content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
import os
import argparse
import logging
SCRIPT_PATH = os.path.abspath(__file__)
FORMAT = '[%(asctime)s] %(levelname)s %(message)s'
l = logging.getLogger()
lh = logging.StreamHandler()
lh.setFormatter(logging.Formatter(FORMAT))
l.addHandler(lh)
l.setLevel(logging.INFO)
debug = l.debug
info = l.i... |
from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
#print(os.environ["OMP_NUM_THREADS"])
from quspin.basis import spin_basis_1d
from quspin.operators import hamiltonian
from quspin.tools.evolution import expm_multiply_parallel
from ... |
import torch
class Config:
IMGS_PATH = '/home/data'
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
N_DOMAINS = 11
N_CLASSES = 2
IMG_SIZE = 224
BATCH_SIZE = 32
EPOCHS = 10000
LEARNING_RATE = 0.001
WEIGHT_DECAY = 0.000000001
MOMENTUM = 0.9 |
"""
Tests The functions in PGComp/Matrixtools.py
"""
import pytest
import numpy
import os
from spHNF_manip.matrix_tools import *
def test_create_nxn_matrices():
assert 3 == len(create_nxn_matrices(1))
assert 81 == len(create_nxn_matrices(2))
def test_det_is_n():
assert 1 == det_is_n(1, [[1, 0, 0], [0, 1, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: Niv Drory (drory@astro.as.utexas.edu)
# @Filename: tiledb.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import itertools
import astropy
import cycler
import matplotlib.pyplot as plt
import numpy
from matplotlib import animation... |
# -*- coding: utf-8 -*-
import datetime
import re
import time
import traceback
import base64
import response_data
from dateutil.relativedelta import relativedelta
from lxml import etree
from base_request_param import mix_current_time
if __name__ == '__main__':
import sys
sys.path.append('../../../')
sys.... |
#The MIT License (MIT)
#
#Copyright (c) 2014-2015 Bohdan Danishevsky ( dbn@aminis.com.ua )
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the... |
# -*- coding: utf-8 -*-
# Copyright 2017 Tecnativa - Jairo Llopis
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools import safe_eval
class MassMailingList(models.Model):
_inherit = "mail.mass_mailing.list"
dynamic = fields.Boolean(
... |
#!/usr/bin/env python
# Copyright (c) 2019 Daniel Hammer. 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 re... |
#!/usr/bin/python
# coding=utf-8
# 公众号:testerzhang
__author__ = 'testerzhang'
import time
import traceback
from appium import webdriver
from selenium.common.exceptions import NoSuchElementException
from tqdm import tqdm
import parse
from loguru import logger
import config
logger.add(config.MIAO_LOG)
def wait_time... |
# Builtin modules
from __future__ import annotations
from typing import List, Union, Tuple
# Third party modules
# Local modules
# Program
class Levels:
levels:List[ Tuple[int, str, str] ] = [
(100, "DISABLED", "DIS"),
(60, "CRITICAL", "CRI"),
(50, "ERROR", "ERR"),
(40, "WARNING", "WAR"),
(30, "INFO", "INF")... |
import ecs
class Manager:
def __init__(self):
"""A Manager keeps track of all Entities, Components, and Systems
A Manager contains the 'database' for all entity/component connections
as well as call the process function for Systems that are
assigned to it.
"""
sel... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnaly... |
#import SimpleCV
from SimpleCV import *
import time
time_start = time.clock()
tic = time_start
img = Image('IMG_3080.JPG')
toc = time.clock()
delta_t = (toc-tic)
print " %f s to open image" % delta_t
tic=toc
blue_distance = img.hueDistance(Color.BLUE).invert().threshold(210)
toc = time.clock()
delta_t = (toc-t... |
# This program reads in a text file from a prompt on the command line and outputs every second line of the text file
# John Dunne 2019-03-14
# This program is adapted from the extra reading I completed here: https://stackoverflow.com/questions/30551945/how-do-i-get-python-to-read-only-every-other-line-from-a-file-that-... |
import pandas as pd
import os
from tqdm import tqdm
import pickle
import torch
import dgl
import networkx as nx
import matplotlib.pyplot as plt
def draw_dgl(G):
nx_G = G.to_networkx()
nx.draw(nx_G, with_labels=True)
plt.show()
class Pipeline:
def __init__(self, ratio, root):
sel... |
from asyncio import open_connection
from contextlib import closing
from pyiced import (
Align, container, IcedApp, image, ImageHandle, Length, Settings,
text, WindowSettings,
)
class ImageExample(IcedApp):
def __init__(self):
self.__handle = None
class settings(Settings):
class windo... |
import logging
import time
logger = logging.getLogger(__name__.rsplit(".")[-1])
class RS485:
import serial
baud = 9600
enabled = True
master = None
port = None
ser = None
timeLastTx = 0
def __init__(self, master):
self.master = master
classname = self.__class__.__na... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Neighborhood(models.Model... |
"""
Remove missing values from one or more dataframes.
"""
from tasrif.processing_pipeline import ProcessingOperator
from tasrif.processing_pipeline.validators import InputsAreDataFramesValidatorMixin
class DropFeaturesOperator(InputsAreDataFramesValidatorMixin, ProcessingOperator):
"""
Examples
--------... |
# Copyright 2016-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import sys
from awsglue.transforms import Join
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
glu... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli... |
import cv2
import numpy as np
import os
def stack_dataset_examples(directory):
l = []
for item in os.listdir(directory):
if not item.startswith('.'):
l.append(item)
l = sorted(l)
images = []
for li in l:
li = directory+"/"+li
temp = cv2.imread(li)
... |
from django import template
from django.contrib.contenttypes.models import ContentType
from ..models import Comment
from ..forms import CommentForm
register = template.Library()
@register.simple_tag
def get_comment_count(obj):
content_type = ContentType.objects.get_for_model(obj)
return Comment.ob... |
"""Tables for User, Password, Comments, Friends and Posts
Revision ID: 3d6c688278ae
Revises:
Create Date: 2019-10-08 15:19:44.799296
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3d6c688278ae'
down_revision = None
branch_labels = None
depends_on = None
de... |
# Generated by Django 3.0.6 on 2020-07-22 18:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('survey', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='question',
options={'ordering': ('sur... |
# _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2018/6/17.
"""
from sqlalchemy import Column, Integer, String, ForeignKey
from app.models.base import Base
from app.models.image import Image
__author__ = 'Allen7D'
class Theme2Product(Base):
__tablename__ = 'theme_product'
theme_id = Column(Integer, ForeignKey(... |
"""
mcpython - a minecraft clone written in python licenced under the MIT-licence
(https://github.com/mcpython4-coding/core)
Contributors: uuk, xkcdjerry (inactive)
Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence
Original game "minecraft" by Mojang Studios (www.m... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
'''
记录每个节点的最大路径值,
返回节点所在最大路径值时, 1: 只能选取一侧的值; 2: 小于0的值不进行选择
'''
... |
# -*- coding: utf-8 -*-
"""FlyBase database models."""
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
import pybel.dsl
from .constants import MODULE_NAME
Base = declarative_base()
FLY_GENE_TABLE_NAME = f'{MODULE_NAME}_flyGene'
class FlyGene(Base): # type: ... |
import torch
import torch.nn as nn
import torch.distributions as dists
import numpy as np
def difference_function(x, model):
d = torch.zeros_like(x)
orig_out = model(x).squeeze()
for i in range(x.size(1)):
x_pert = x.clone()
x_pert[:, i] = 1. - x[:, i]
delta = model(x_pert).squeeze... |
#!/usr/bin/env python
from __future__ import print_function
import pcapy
# import os
import sys
import subprocess # use commandline
import requests # whois
import re
from netaddr import valid_ipv4, valid_mac
import os
# import platform # socket alternative to get hostname
import socket
"""
[kevin@Tardis test]$ .... |
import torch
from torch import nn
class CalibrationWrapper(nn.Module):
def __init__(self):
super().__init__()
self.start_indexes = []
self.end_indexes = []
self.models = nn.ModuleList([])
def add_model(self, model, start_index, end_index):
self.models.append(model)
... |
import os
import sys
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'sitecomber_article_tests'))
sys.path.append(BASE_DIR)
from sitecomber_article_tests.utils import get_misspelled_words, simplify_word
from sitecomber_article_tests.dictionary import core_dictionary
lang = "en"
def test_word(wo... |
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
class Painter():
def __init__(self, figsize = (12, 8)):
plt.rcParams['font.sans-serif'] = ['serif']
sns.set(context="paper", style="ticks",
font=... |
from typing import Union
import aiohttp
from utils.exceptions import NotAllowedStatusException
class HTTP:
@staticmethod
async def get(
url: str,
params: dict = None,
json: bool = False,
status: int = None,
**kwargs,
) -> Union[str, dict]:
async with aiohttp... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
Data Structures :: LRU Cache
"""
class ListNode:
def __init__(self, key, value, prev=None, next=None):
"""A node in a doubly-linked list-based LRU cache.
:param key : Key by which to access nodes.
:param value : Value accessed by key.
:param pre... |
# PROJECT : kungfucms
# TIME : 19-2-11 上午11:31
# AUTHOR : Younger Shen
# EMAIL : younger.x.shen@gmail.com
# CELL : 13811754531
# WECHAT : 13811754531
# https://github.com/youngershen/
from django.core.mail import send_mail
from django.utils.translation import ugettext as _
from django.utils import timezone
from django... |
from .feature_pyramid_net import *
from .polar_head import *
from .stage_backbone import *
|
__all__ = ["BasicStream"]
class BasicStream:
def __init__(self, stream_name: str = None) -> None:
self.name = stream_name
self._next_stream = None
def input(self, data, *args, **kwargs):
"""
read data from buffer
:param data: data that move in the stream
:retur... |
import fbe
import proto
from proto import proto
from unittest import TestCase
class TestCreate(TestCase):
def test_create_and_access(self):
# Create a new account using FBE model into the FBE stream
writer = proto.AccountModel(fbe.WriteBuffer())
self.assertEqual(writer.model.fbe_offset, 4... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
"""Chromium presubmit script for src/tools/ios.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 10:56:21 2020
Create plots of time series with example sources.
@author: rouhinen
"""
import numpy as np
from numpy.linalg import norm
from numpy.random import randn
from scipy import signal, stats
import matplotlib.pyplot as plt
import glob
from fidelityOpMinimal imp... |
from agent import Agent
from random import random, sample
from itertools import combinations
from math import comb
# from mission import Mission
class Evolver(Agent):
'''
Maintains probabilities of all possible worlds.
Calculates the probabilty of each player being a spy from set of worlds.
World p... |
import unittest
import jamband
class TestMain(unittest.TestCase):
def test_pigeons(self):
msg = "My brain has degenerated today so much that I’m listening to pigeons playing ping pong enthusiastically"
match = jamband.refersToJamBand(msg)
self.assertTrue(match)
def test_phish(self):
... |
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import sys
import classifier as c
from plotDecBoundaries import plotDecBoundaries
def error_rate(classifications, true_classifications):
if (np.shape(classifications) != np.shape(true_classifications)):
raise RuntimeError("Size not equ... |
#////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
# Name :
# Author : Avi
# Revision : $Revision: #10 $
#
# Copyright 2009-2020 ECMWF.
# This software is licensed under the terms of the Apache Licence version 2.0
# which can be obtained at http://www.apache.org/licenses/LIC... |
## ===============================================================================
## Authors: AFRL/RQQA
## Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
##
## Copyright (c) 2017 Government of the United State of America, as represented by
## the Secretary of t... |
from datetime import timedelta
import time
import unittest
from cockroach import util
class RetryTest(unittest.TestCase):
def test_retry(self):
opts = util.RetryOptions(timedelta(microseconds=10), timedelta(seconds=1), 2, 10)
retries = [0]
def fn():
retries[0] += 1
... |
"""
Generator based data loader for Cloud38 and L8CCA clouds segmentation datasets.
If you plan on using this implementation, please cite our work:
@INPROCEEDINGS{Grabowski2021IGARSS,
author={Grabowski, Bartosz and Ziaja, Maciej and Kawulok, Michal
and Nalepa, Jakub},
booktitle={IGARSS 2021 - 2021 IEEE International G... |
# Copyright 2018 The TensorFlow Authors.
#
# 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 ... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... |
import os
from pathlib import Path
import click
import palm.project_setup_utils as project_setup_utils
def test_has_env(tmp_path):
os.chdir(tmp_path)
assert not project_setup_utils.has_env()
Path('.env').touch()
assert project_setup_utils.has_env()
def test_optionally_create_env(tmp_path, monkeypat... |
# Copyright 2021 Google LLC
#
# 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, ... |
from django.db import models
class Government(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Agency(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Department(models.Model):
nam... |
import numpy
import pandas
from scipy import stats
def df_accepted(df, key, include=None, exclude=None):
if include is None:
if exclude is None:
return df
return df[~df[key].isin(exclude)]
if exclude is None:
return df[df[key].isin(include)]
return df[df[key].isin(include) & ~df[key].isin(exclu... |
#!/usr/bin/env python3
# Foundations of Python Network Programming, Third Edition
# https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter01/search4.py
import socket
from urllib.parse import quote_plus
request_text = """\
GET /maps/api/geocode/json?address={}&sensor=false HTTP/1.1\r\n\
Host: maps.google.com:80\r\... |
asciiArt = '''
__________ __ .__ _________ .__ .__ __
\______ \___.__._/ |_| |__ ____ ____ \_ ___ \_____ | | ____ __ __| | _____ _/ |_ ___________
| ___< | |\ __\ | \ / _ \ / \ / \ \/\__ \ | | _/ ___\| ... |
#! Code voor een ASN betaalrekening
from os import path
from typing import Dict, Optional, Tuple
from beancount.core import data, number, position
from beangulp.importers import csvbase
import csv as pycsv
import re
pycsv.register_dialect("asnbankdialect", delimiter=",")
class Importer(csvbase.Importer):
encodi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ilsgateway', '0002_auto_20160104_1600'),
]
operations = [
migrations.CreateModel(
... |
# -*- coding: utf-8 -*-
# Scrapy settings for liferay project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest... |
'''[skope-rules](https://github.com/scikit-learn-contrib/skope-rules) (based on [this implementation](https://github.com/scikit-learn-contrib/skope-rules))
'''
from .skope_rules import SkopeRules
from .rule import Rule, replace_feature_name
__all__ = ['SkopeRules', 'Rule']
|
import kernelwidget
import bufferswidget
import displaywidget
import newdialog
import stylesheet
import settings
import icons
import utils
import pygpuip
import os
from PySide import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, path, settings = None):
super(MainWindow, self).__init... |
# Copyright 2018 AimBrain Ltd.
# 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 agree... |
class Snake:
def __init__(self, width=600, height=400):
self.width = width
self.height = height
def xml(self):
return """
<script type="application/processing">
var width = %s;
var height = %s;
var x = width/2;
var y = height/2;
var vx = 2;
var vy = 0;
void setup() {
size(width,heig... |
"""
Viewsets for users app
"""
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, mixins, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from kaznet.apps.main.mixins... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 25-01-2011
@author: fearless-spider
'''
import urllib2, sys, time, random
import BaseHTTPServer
import csv
from BeautifulSoup import BeautifulSoup
from htmlentitydefs import name2codepoint as n2cp
import re
def substitute_entity(match):
ent = match.group... |
import inspect
import os
import unittest
import pytest
from approvaltests.approvals import verify_all
from approvaltests.reporters.generic_diff_reporter_factory import (
GenericDiffReporterFactory,
)
from mockito import mock, when, unstub, ANY
from robot.utils import WINDOWS
from selenium import webdriver
from Se... |
#############################################################################
# Transport properties of solvent-permeable hard spheres #
# The basic theory is based on Riest et al. Soft Matter (2015) #
# and simulation data from Abade et al. (2012) #
# ... |
from mediaman.core.clients.multi import abstract
from mediaman.core.clients.multi import methods
def gen_all(gen):
try:
result = next(gen)
yield result
while True:
result = gen.send(True)
yield result
except StopIteration:
pass
class Multiclient(abstr... |
#coding:utf-8
# 自定义异常类
class CustomError(Exception):
def __init__(self, ErrorInfo):
self.errorinfo = ErrorInfo
Exception.__init__(self, ErrorInfo)
def __str__(self):
return self.errorinfo
|
from azure.core.exceptions import HttpResponseError
from msrest import Serializer
import pytest
import time
import json
from kubernetes import client
from common.kubernetes_crd_utility import watch_crd_instance
from common.kubernetes_pod_utility import (
watch_pod_status,
get_pod_logs,
get_pod_logs_since_s... |
from subprocess import Popen
from shlex import split
class ProcessUtil():
def __init__(self):
super().__init__()
self.train_process = None
self.evaluate_process = None
self.tensorboard_process = None
def execute_training(self):
self.train_process = Popen(split(cmd))
... |
import setuptools
from dict_tiny import version
VERSION = version.__version__
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name=version.name,
version=VERSION,
author="louie",
author_email="louiehan1015@gmail.com",
description=version.DESCRIPTION,
long_... |
import copy
import json
import torch
from mmf.common.sample import Sample
from mmf.datasets.mmf_dataset import MMFDataset
class MMIMDbFeaturesDataset(MMFDataset):
def __init__(self, config, dataset_type, imdb_file_index, *args, **kwargs):
super().__init__(
"mmimdb", config, dataset_type, imd... |
from django.conf.urls import url
from tax import views
urlpatterns = [
url(r'^auth/', views.auth, name='tax_auth'),
url(r'^search/', views.search, name='tax_search'),
]
|
""" Module to perfome command line operation in the services."""
from fabric.api import run, cd
from fabric.context_managers import settings, hide
def execute_cmd_in_node(node, user, passwd, cmd):
with hide('everything'):
with settings(host_string='%s@%s' % (user, node), password=password,
... |
from modules.constants import (
NAV_BAR_TOP,
)
#################################
# Front panel navigation buttons
#################################
class NavButton(object):
def __init__(self, g_vars, fill, font):
self.nav_bar_top = NAV_BAR_TOP
self.font = font
self.fill = fill
... |
from typing import (
TYPE_CHECKING,
Sequence,
)
import numpy as np
from ...helper import typename
if TYPE_CHECKING:
from ...types import (
DocumentArrayIndexType,
)
class DelItemMixin:
"""Provide help function to enable advanced indexing in `__delitem__`"""
def __delitem__(self, in... |
from __future__ import absolute_import
import abc
from copy import deepcopy
import time
from enum import Enum
import six
from simpleflow.base import Submittable
from simpleflow.history import History
from . import futures
from .activity import Activity
if False:
from typing import Optional, Any, Dict, Union, ... |
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.conf import settings
from django_comments.abstracts import CommentAbstractModel
from mptt.models import MPTTModel, TreeForeignKey
from diventi.core.models import PromotableModel
class DiventiComment(MPTTModel, ... |
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import gui.motion_player as mp
class HmaUi(object):
DEFAULT_WIDTH = 1600
DEFAULT_HEIGHT = 1200
"""
this class makes ui for main window and connect ui signals to event handlers of main window
custom event handlers in main window must be impleme... |
'''Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso, mostre:
A) Quantos números foram digitados.
B) A lista de valores, ordenada de forma decrescente.
C) Se o valor 5 foi digitado e está ou não na lista.'''
numero = list()
while True:
n = int(input("Digite um valor: "))
if n not ... |
"""Defines actions that may be associated with flows packets."""
# System imports
from enum import IntEnum
from math import ceil
# Local source tree imports
from pyof.foundation.base import GenericStruct
from pyof.foundation.basic_types import (
FixedTypeList, Pad, UBInt8, UBInt16, UBInt32)
from pyof.v0x04.common.... |
import os
from tool.model import GetModelInfo
GIANT_SETTING = {
"BASE_DIR": os.path.dirname(os.path.realpath(__file__)), # 这个是必不可少的
"TEST_FILES": ["gaintstar_api.json"],
"DATA_FILES": {"default": "./dataTable/data.xlsx"},
"PARAMETRIC_CLASS": [GetModelInfo],
"REMOTE": False,
"DEBUG": True,
}
|
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.screenmanager import Screen
class ChangeLevelScreen(Screen):
game_screen = ObjectProperty(None)
stars_img = StringProperty('')
|
import pytest
@pytest.fixture()
def valid_spelled_content_pack(pack):
"""
Create a pack with valid spelled content.
"""
for i in range(3):
pack.create_release_notes(
version=f"release-note-{i}",
content="\n#### Scripts\n##### ScriptName\n- Added a feature"
)
... |
"""A package for client"""
# pylint: skip-file
__all__ = [
'demo_client'
]
|
import numpy as np
import matplotlib.pyplot as plt
n, t1, t2, t3, t4, t5, t6, t7, t8 = np.genfromtxt('python/statisch.txt', unpack=True)
plt.plot(5*n-5, t1, 'bo', markersize=1, label=r'$T_1$,\;Messing (breit)')
plt.plot(5*n-5, t4, 'ro', markersize=1, label=r'$T_4$,\;Messing (schmal)')
plt.plot(5*n-5, t5, 'ko', markers... |
# -*- coding: utf-8 -*-
from mamonsu.plugins.pgsql.plugin import PgsqlPlugin as Plugin
from .pool import Pooler
import time
class PgHealth(Plugin):
DEFAULT_CONFIG = {'uptime': str(60 * 10), 'cache': str(80)}
def run(self, zbx):
start_time = time.time()
Pooler.query('select 1 as health')
... |
import os
import pathlib
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from fnmatch import fnmatch
from glob import glob
from typing import List, Optional
from urllib.parse import urlparse
from collection_manager.entities.exceptions import MissingValueCollectionError
class Col... |
# coding: utf-8
"""
AVM
This is api for AVM (automated valuation machine) # noqa: E501
The version of the OpenAPI document: 1.0.0
Contact: info@enbisys.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class FloorLevel(object):
"""NOTE... |
import numpy as np
import os
from tqdm import tqdm
from absl import flags, app
from code.utils.calculate_cds import get_cds
from code.utils.csv_util import read_features
def confusion_matrix_test(features_dir, matrix_dir):
validate_dict = read_features(features_dir, "validate")
# 混淆矩阵
confusion_matrix =... |
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Color,Rectangle
class Colored_layout(BoxLayout):
def __init__(self, l_color=(0.7, 0, 0, 1), **kw):
super().__init__(**kw)
self.padding="10dp"
with self.canvas.before:
Color(*l_color)
self.rect=Rectangl... |
from enum import IntEnum
class Language(IntEnum):
IPA = 0
ENG = 1
CHN = 2
GER = 3
|
from django.forms import ModelForm
from .models import Profile
class AddData(ModelForm):
class Meta:
model = Profile
fields = '__all__' |
"""Console script for pyfmt."""
import sys
import click
from .pyfmt import fmt
@click.command()
@click.argument("fmt_folder")
@click.option("--folder", help="The folder to format")
def main(folder: str, fmt_folder: str):
"""Console script for pyfmt."""
click.echo("Formating ... ")
click.ec... |
from pytpp.tools.helpers.date_converter import from_date_string
from pytpp.properties.response_objects.dataclasses import certificate
class Certificate:
@staticmethod
def Certificate(response_object: dict):
if not isinstance(response_object, dict):
response_object = {}
return cert... |
import math
import time
start_time = time.time()
data = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[100000000000000,-90000000000000]]
prediction_x_value = 90
start_m = -100
start_c = -20
acuracy_for_m = 0.00001
acuracy_for_c = 0.00001
step_size = 0.01
acceptible_error = 0.1
def calculate_error(m,c,data):
total_error_squa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.