content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# $Id: devices/k2510.py | Rev 42 | 2019/01/10 07:31:01 clu_wrk $
# xDevs.com Keithley 2510 TEC SMU module
# Copyright (c) 2012-2019, xDevs.com
#
# Python 2.7 | RPi3
# Project maintainers:
# o Tsemenko Ilya (@)
# https://xdevs.com/guide/teckit
#
import os.path
import sys
import time
import f... |
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# Example:
# Input: nums = [1,2,3]
# Output:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
class Solution(object):
def subset... |
# Copyright (c) 2013, TZCODE SRL and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr, flt, date_diff, nowdate
def execute(filters=None):
return get_columns(filters), get_data(filters)
def get_colu... |
import datetime
import requests
import json
class Client:
def __init__(self, token=None):
self.token = token
if self.token is None:
self.authenticate()
def authenticate(self):
client_id = input("client id> ")
client_secret = input("client secret> ")
auth = requests.auth.HTTPBasicAuth(client_id, client... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 12:52:50 2018
@author: notic
"""
#==============================================================================
#First Frame Acquisition
#==============================================================================
def firstframe(begin):
import cv2
f... |
# from PyQt5 import QtGui, QtCore, uic
# from PyQt5 import QtWidgets
# from PyQt5.QtWidgets import QMainWindow, QApplication
#
#
# class Overlay(QMainWindow):
# def __init__(self):
# QMainWindow.__init__(self)
# self.setWindowFlags(
# QtCore.Qt.WindowStaysOnTopHint |
# ... |
from p3ui import *
import asyncio
from imageio import imread
import p3ui.skia as skia
import numpy as np
repeat_x = 100
repeat_y = 10
base = imread('image.png')
# minions = np.concatenate((minions, np.ones((minions.shape[0], minions.shape[1], 1)) * 255.), axis=2)
rgba = np.zeros((base.shape[0] * repeat_y, base.shape[... |
from typing import List
from pydantic import BaseModel
import datetime
class CreateProjectResponse(BaseModel):
project_arn: str = None
class DeleteProjectResponse(BaseModel):
project_status: str = None
class OutputConfig(BaseModel):
S3Bucket: str = None
S3KeyPrefix: str = None
class S3Object(Bas... |
from ..app import run_futura
def main():
run_futura()
|
import socket
from threading import Thread, active_count
import queue
import sys
import time
from functools import wraps
class ServerConnectError(OSError):
pass
def show_run_state(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Creat a Thread {}'.format(args[0].__class__))
fun_r... |
# -*- coding: utf-8 -*-
def bucket_sort(nums, ascending=True):
'''
桶排序算法
Note
----
- 时间复杂度O(m+n),m为桶的个数(nums的最大值+1),n为待排序数的个数
- 缺点:
* 需要事先知道最大最小值
* 浪费空间(桶的个数受最大值影响极大)
* 小数点和负数处理麻烦(可通过转化成正整数再排序)
- 优点: 时间复杂度低
Parameters
----------
nums : list
待排... |
import os
from django.conf import settings
from django.template import Engine
from django_tenants.test.cases import TenantTestCase
class TenantCachedLoaderTestCase(TenantTestCase):
@classmethod
def setUpClass(cls):
test_app_root = settings.TENANT_APPS_DIR
settings.MULTITENANT_TEMPLATE_DIRS =... |
# encoding: utf-8
from itertools import groupby
from datetime import datetime
import json
from dateutil.tz import tzlocal
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.templ... |
import sys
import os
import grequests
import requests
from datetime import datetime
import json
import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid
import ssl
import env
import db_commands
MAX_PAGES = 20
DB_PATH = './testDB.db'
HUUTONET_A... |
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox as mBox
import lneMenu
import nmInterface as nmitf
import dpInterface as dpitf
import urlInterface as urlitf
class interface:
# 这是爬虫的界面
def __init__(self):
self.root = tk.Tk()
self.width = 495 # 图形界面的宽
self.h... |
# -*- coding: UTF-8 -*-
'''
Contains basic interfaces for graph data structures.
@todo: This is planned to be replaced by pygraph
Created on 05.10.2010
@author: SIGIESEC
'''
class Node(object):
def get_id(self):
raise NotImplementedError(self.__class__)
class LabelledNode(Node):
def get_label(self... |
from packet import Packet
packet = Packet('192.168.31.48')
print(packet.sendCmd('get_prop', ['power'])) |
"""
Base classes for various parts of rabbitpy
"""
import logging
try:
import queue
except ImportError:
import Queue as queue
import socket
import threading
import time
from pamqp import specification
from rabbitpy import exceptions
from rabbitpy import utils
LOGGER = logging.getLogger(__name__)
class AMQ... |
import pytest
from rpg_namer import RPGItems
def test_random():
item = RPGItems().random_item()
assert item != ''
def test_random_helm():
item = RPGItems('helmet').random_item()
assert item != ''
def test_random_body():
item = RPGItems('body').random_item()
assert item != ''
def test_ran... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... |
from django.apps import AppConfig
class CanteenModelConfig(AppConfig):
name = 'canteen_model'
|
#!/usr/bin/python
import os
import re
import json
import seismometer.input
import seismometer.message
#-----------------------------------------------------------------------------
class MessengerReader(seismometer.input.Reader):
'''
Network reader accepting JSON and Graphite-like messages.
This reader ... |
import datashader.transfer_functions as tf
import numpy as np
import scipy.stats as stats
from datashader.colors import rgb
from datashader.utils import ngjit
from sklearn.cluster import KMeans as KMEANS
from xarray import DataArray
def color_values(agg, color_key, alpha=255):
def _convert_color(c):
r, g,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from argument.argument import argument
class argnet( argument ):
def __init__( self ):
super().__init__()
self.parser.add_argument( '--networkaddr', help='network address' )
self.parser.add_argument( '--mult... |
import logging
from google.cloud import bigquery
from pytest import fixture
class BigQueryClientChecker:
def __init__(self, bq_client: bigquery.Client, expected_data_sets: set):
self.__bq_client = bq_client
logging.info("Project is: {}".format(self.__bq_client.project))
self.__expected_d... |
#
# CORE
# Copyright (c)2011-2014 the Boeing Company.
# See the LICENSE file included in this distribution.
#
# author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
#
from core.netns import nodes
from xml.dom.minidom import parse
from xmlutils import *
class CoreDocumentParser0(object):
def __init__(self, sess... |
from ...bs_node import BSNode
from ...bs_node.field import BSNodeField
from ...bs_node.iterable import BSNodeIterable
from ...bs_reference.iter import BSReferenceIter
from ...bs_reference.child import BSReferenceChild
from ...bs_reference.link import BSReferenceLink
class Rule(BSNode):
_tag_name = 'rule'
de... |
from functools import partial
from jaxrk.reduce.lincomb import LinearReduce
from .rkhs import FiniteVec
from .core.typing import Array
from .utilities import cv
import jax.numpy as np, jax.scipy as sp
from typing import Any
from jaxrk.rkhs import Cov_regul
import jax
__log2pi_half = np.log(2. * np.pi) / 2
def mvgau... |
"""
Python wrapper around `thpronun` (https://github.com/tlwg/thpronun)
Many thanks to P' Thep and P' Ott
"""
import os
import subprocess
from ast import literal_eval
# install thpronun to /usr/local/bin
url = 'https://github.com/airesearch-in-th/kora/releases/download/v0.7/thpronun.tar'
os.system(f'curl -L {url} | t... |
#!/usr/bin/env python3
import argparse
from pathlib import Path
from typing import Iterator
import tensorflow_datasets as tfds
import tqdm
def extract_wikipedia(tf_data) -> Iterator[str]:
in_paragraph: bool = False
for wiki in tqdm.tqdm(tf_data.as_numpy_iterator()):
for text in wiki['text'].decode(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class BusinessBankAccountInfo(object):
def __init__(self):
self._business_bank_account_name = None
self._business_bank_card_no = None
self._business_bank_name = None
sel... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-02 15:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0005_auto_20160502_0301'),
]
operations = ... |
"""
Checks for renovate configuration
"""
import json
import os
from pytest_repo_health import health_metadata
from . import get_file_content
from .utils import file_exists
MODULE_DICT_KEY = "renovate"
LAST_PR_QUERY = """
query searchRepos($filter: String!) {
search(query: $filter, type: ISSUE, last: 1) {
nod... |
import numpy as np
import matplotlib.pyplot as plt
import time
from mnist import MNIST
from sklearn.neighbors import KDTree
#show_digit displays an image rendering of a 28x28 numpy array
def show_digit(img):
plt.axis('off')
plt.imshow(img.reshape((28,28)), cmap=plt.cm.gray)
plt.show()
return
#vis_imag... |
import unittest
from tests.utilities import BaseTest
from accessors import user_accessor
from ddt import ddt, data, unpack
from mock import patch, MagicMock
import time
@ddt
class UserAccessorTest(BaseTest):
import_route = 'accessors.user_accessor'
def setUp(self):
self.s3_accessor = self.add_patcher... |
class PeakFinder:
def __init__(self, threshold):
self.threshold = threshold
self.last = 0
self.name = f'nrm_peak{threshold}'
def is_peak(self, value):
difference = value - self.last
previous = self.last
self.last = value
if difference > (self.threshold ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot pour répondre aux messages Telegram.
Ce programme est dédié au domaine public sous licence MIT.
Ce bot utilise la classe Updater pour gérer le bot.
Usage:
Example Echobot Basic.
"""
import logging
from os import environ
from flask import Flask
from datetim... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Filename: dockerfile_augmenter.py
import os, sys, re, tempfile, subprocess, time
import pobs_templates
import logging
from optparse import OptionParser, OptionGroup
__version__ = "0.1"
OPTIONS = None
def parse_options():
usage = r'usage: python3 %prog [options] -f /path... |
"""
tests for the generate_payments generator and loanpart iterator
"""
from unittest.mock import MagicMock
import pytest
from mortgage_scenarios.core import PaymentData
from mortgage_scenarios.core import generate_payments, LoanPartIterator
def input_dict():
yield {'amount_boy': 100,
'fv': 20,
... |
import requests
import os.path
import time
import datetime
from gtmetrix import settings
from gtmetrix.exceptions import *
from gtmetrix.utils import (validate_email,
validate_api_key)
__all__ = ['GTmetrixInterface',]
class _TestObject(object):
"""GTmetrix Test representation."""
... |
# Generated by Django 2.2.4 on 2019-09-04 23:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('visits', '0006_auto_20190902_0228'),
]
operations = [
migrations.AlterField(
model_name='visit',
name='percentage_ev... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import unittest
from converters.iot_topic_converter import IoTTopicConverter
class TestTopicConverter(unittest.TestCase):
def setUp(self):
self.job_name = "test_job"
self.protocol = "... |
import argparse
def run_game(starting_numbers, stop):
last_turns = {}
for i, n in enumerate(starting_numbers[:-1]):
last_turns[n] = i + 1
previous = starting_numbers[-1]
for turn in range(len(starting_numbers) + 1, stop + 1):
previous_turn = turn - 1
if previous not in last... |
"""
==================
Two-class AdaBoost
==================
This example fits an AdaBoosted decision stump on a non-linearly separable
classification dataset composed of two "Gaussian quantiles" clusters
(see :func:`sklearn.datasets.make_gaussian_quantiles`) and plots the decision
boundary and decision scores. The di... |
#! /usr/bin/env python3
from mule_local.JobGeneration import *
from mule.InfoError import *
import glob
import os
import re
import sys
class JobData(InfoError):
"""
Load all available data within job directory.
This data in includes
a) All .pickle files within the directory
b) All [MULE] prefixed output i... |
#! /usr/bin/env python
"""Build cython extensions.
isort:skip_file
"""
import multiprocessing
import os
from pathlib import Path
from typing import List
from setuptools import Distribution, Extension # type: ignore
from Cython.Build import cythonize # type: ignore
from Cython.Distutils.build_ext import new_build_ex... |
# Divide two integers without using multiplication, division and mod operator.
# If it is overflow, return MAX_INT.
class Solution:
# @param {integer} dividend
# @param {integer} divisor
# @return {integer}
def divide(self, dividend, divisor):
isNeg = False
if dividend < 0:
... |
# Copyright (c) 2018, Toby Slight. All rights reserved.
# ISC License (ISCL) - see LICENSE file for details.
from .__main__ import pick
from .event import Event
name = "cpick"
|
# Standard Library
import logging
from functools import wraps
# Third Party
import mixingboard
import requests
from chassis.models import Token, User
from flask import Blueprint, request, jsonify
from jinja2 import TemplateNotFound
# Local
api = Blueprint('api', __name__)
def requiresToken(fn):
@wraps(fn)
... |
# Membership Operators:
# Algorithms develop and become optimized over time as a result of constant evolution and the need to
# find the most efficient solutions for underlying problems in different domains.
# These Operators cand be used with any iterable data structure in Python, including Strings, Lists, and Tupl... |
""" Package Initialization file. """ |
import functools
import six
import json
import pandas as pd
from bigorm.database import Base
import sqlalchemy as sa
import google.api_core.exceptions
from google.cloud.bigquery import job as bigquery_job
from google.cloud.bigquery.dbapi.cursor import job, exceptions
from bigorm.database import DatabaseContext
from ... |
from os.path import dirname, join
import numpy as np
from crocoddyl import loadTalos
from crocoddyl.locomotion import ContactSequenceWrapper
from multicontact_api import ContactSequenceHumanoid
MUSCOD_CS_OUTPUT_FILENAME = join(dirname(__file__), "data/test_locomotion.xml")
CONTACT_SEQUENCE_XML_TAG = "contact_sequence... |
#
# Copyright (c) 2017 Intel Corporation
#
# 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 t... |
#Imports necessários
import time
import os
from datetime import datetime
#Imports do selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import e... |
#!/usr/bin/env python3
import os.path as path
import sys
import asyncio
import time
cur_dir = path.dirname(path.abspath(__file__))
sys.path.append(path.join(cur_dir, '..'))
from avio.api_handler import ApiHandler
from avio.application import make_app, run_app
from avio.json_api_client import JsonApiClient
class Sa... |
"""
Nikto Python Library
written By: Umar Farook
Nikto Command: perl nikto.pl -h <host> -p port> -o <report_namae>
"""
import subprocess
class RoboNikto(object):
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self,nikto_path):
self.nikto_path = nikto_path
def run_nikto(self,host,port,export_repor... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.okex3 import okex3
class okcoin(okex3):
def describe(self):
return self.deep_extend(super(okcoin, self).describe()... |
from datetime import datetime
class Pessoa:
def falar(self):
print('Luiz está Falando')
# criando uma classe usando o metodo especial do python
class Pessoa1:
ano_nascimento = int(datetime.strftime(datetime.now(), '%Y'))
# ano_nascimento = 2020
def __init__(self, nome, idade, comendo=False,... |
# Example
# %%
from ipyccmd import display_ccmd, DisplayType
from ipyccmd import md_print
import numpy as np
r = 5
h = 20
volume = np.pi * r**2 * h
"---".md()
"## Using `display_ccmd()` or curse `.md()`".md(dtype=DisplayType.MARKDOWN)
"<hr>".md(dtype=DisplayType.HTML)
"""Thus we have calculated the **volum... |
import os
import sys
import acconeer.exptool as et
def main():
parser = et.utils.ExampleArgumentParser()
parser.add_argument("-o", "--output-file", type=str, required=True)
parser.add_argument("-l", "--limit-frames", type=int)
args = parser.parse_args()
et.utils.config_logging(args)
if os.pa... |
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QMdiSubWindow, QTableWidgetItem
from .histogram_ui import HistGraphicalUI, HistListUI
class HistGraphical(QMdiSubWindow, HistGraphicalUI):
"""The HistGraphical class implements a graphical representation of the image histogram."""
def __i... |
import numpy as np
from skimage.transform import resize
import rawpy
from keras.models import Sequential
from keras.preprocessing import image
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import preprocess_input
from keras.applications.imagenet_utils import decode_predictions
from k... |
#!/usr/bin/python2.7
# Copyright 2010 Google Inc. 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 cv2 as cv
import numpy as np
class CoordinatesGenerator:
KEY_RESET = ord("r")
KEY_QUIT = ord("q")
def __init__(self, input_media, output):
self.output = output
self.caption = input_media
self.color = (0, 0, 255) # colour is Red
try:
self.image = cv.imr... |
# coding:utf-8
import hashlib
import inspect
import logging
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, csc_matrix
from sklearn.model_selection import train_test_split, StratifiedKFold, KFold, GroupKFold
from .cache import Cache, numpy_buffer
from .utils.main import idx, concat
logger... |
import PikaStdLib
import STM32G0
time = STM32G0.Time()
uart = STM32G0.UART()
uart.init()
uart.setId(1)
uart.setBaudRate(115200)
uart.enable()
while True:
time.sleep_ms(500)
readBuff = uart.read(2)
print('read 2 char:')
print(readBuff)
|
# Copyright 2018-2019 DeepMind Technologies Limited and 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
"""
evoke app.code module
"""
|
"""Add transactions table
Revision ID: e9d0a38b9f1f
Revises: 1d4bf3ad7e05
Create Date: 2021-09-07 12:10:04.635207
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e9d0a38b9f1f"
down_revision = "1d4bf3ad7e05"
branch_labels = None
depends_on = None
def upgrade(... |
# -*- coding: utf-8 -*-
"""Top-level package for Subprocess Manager."""
__author__ = """Daniele Turato"""
__email__ = 'daniele.turato@siav.it'
__version__ = '0.1.0'
from .subprocess_manager import SubprocessManager
|
from .crawlerCaptcha import *
from .crawler import *
from .crawlerMath import *
__all__ = []
__all__.extend(crawlerCaptcha.__all__)
__all__.extend(crawler.__all__)
__all__.extend(crawlerMath.__all__) |
#!/usr/bin/env python
import logging
import pytest
import random
import unittest
from tests.ops import add, blow_up, blow_up2
from jack import ManagerRegistry
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(process)d %(message)s')
log = logging.getLogger(__name__)
class Test(unittest.TestC... |
from typing import Tuple
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorcross.utils import dataset_split
from tensorflow.keras.layers import TextVectorization
from tensorflow.keras.models import Sequential
np.random.seed(0)
tf.random.set_seed(0)
class IMDB:
def __init_... |
# terrascript/snowflake/r.py
# Automatically generated by tools/makecode.py ()
import warnings
warnings.warn(
"using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2
)
import terrascript
class snowflake_account_grant(terrascript.Resource):
pass
class snowflake_api_integration(terrascri... |
import cv2
def init(xres, yres):
print(cv2.__version__)
print("starting vision")
# change this number to set the camera being used
cap = cv2.VideoCapture(0)
cap.set(3, xres)
cap.set(4, yres)
return cap
|
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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... |
import struct
from .method import Method
from .method import Header
from .method import Body
from .heartbeat import HeartBeat
_FRAME_HEADER_SIZE = 7
_FRAME_END_SIZE = 1
_FRAME_END = b'\xce'
_FRAME_METHOD = 1
_FRAME_HEADER = 2
_FRAME_BODY = 3
_FRAME_HEARTBEAT = 8
class InvalidFrameError(Exception):
pass
def r... |
#Built with python 3.8. I can only confirm it works on that.
#setting up files
mugs = open("png.txt","r")
installer = open("Mug Installer.event","w")
#going through each line of png.txt to generate installer
line = mugs.readline()
while line:
#grab the mug name
mug = line.split(".")
#write labels and incbi... |
#!/usr/bin/env python
import matplotlib
matplotlib.rcParams['legend.fancybox'] = True
import matplotlib.pyplot as plt
import numpy as np
#data
x = [1, 2, 3, 4]
#define some data
#x = [1, 2, 3, 4, 5]
pellet4java = [1.491, 1.628, 3.502, 5.285]
pellet4android = [1.646, 4.968, 7.597, 13.590]
#error data
pellet4java_err... |
################################################################################
# #
# ____ _ #
# | _ \ ___ __| |_ __ _ _ _ __ ___ ... |
class DS():
def __init__(self, ins_matrix, con_ver, mst, v_a, v_b):
self.Insidence_Matrix = ins_matrix
self.mst = mst
self.con_ver = con_ver
self.set = []
def get_edge(a, b):
for i in range(len(self.Insidence_Matrix[0])):
if (self.Insidence_Ma... |
"""Extracts a slice and lines from a 2-dimensional wedge case.
Usage:
python ./extract_rans_data.py $case --timestep latest \\
--radial-extension 0.09 --axial-extension 0.15 --x-res 90 --y-res 150 \\
--output-dir "."
Assumes:
- Axial direction is the Z axis.
"""
import json
import os
import argparse
i... |
def agent_clean(agent_pos, clean_status):
if agent_pos == "A" and clean_status[0] == 0:
# agent_pos="B"
print("A is clean")
print("Moving agent to position B")
return "B"
if agent_pos == "A" and clean_status[0] == 1:
clean_status[0] = 0
print("Cleaning position A"... |
from setuptools import setup
from subprocess import check_output
#The following two functions were taken from the repo: https://github.com/pyfidelity/setuptools-git-version/blob/master/setuptools_git_version.py
def format_version(version, fmt='{tag}.{commitcount}'):
parts = version.split('-')
if len(parts) == ... |
from django.db import models
from django.contrib.auth.models import User
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
class Common(models.Model):
created_date = models.DateTimeField(auto_now_add=True, blank=True)
modified_date = models.DateTimeField(auto_now=True, blank=Tr... |
'''
ASTEROIDS: Rotating Polygons
A great way to create polygon shapes is to use a list of angles
and a corresponding list of radii (plural of radius).
Below, a polygon object specifies the center of the polygon
at x,y and uses a list of angles and radii extending from
the central point to draw a triangle.
This is a u... |
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from aws import Action as BaseAction
from aws import BaseARN
service_name = 'Amazon Glacier'
prefix = 'glacier'
class Action(BaseAction):
def __init__(self, action=None):
sup = super(Action... |
"""HA Cli docker object."""
import logging
from ..const import ENV_TIME
from ..coresys import CoreSysAttributes
from .interface import DockerInterface
_LOGGER: logging.Logger = logging.getLogger(__name__)
MULTICAST_DOCKER_NAME: str = "oppio_multicast"
class DockerMulticast(DockerInterface, CoreSysAttributes):
... |
import os
from subprocess import call # nosec
from tempfile import NamedTemporaryFile
from typing import List
from tilecloud import Tile
class OptiPNG:
def __init__(self, options: List[str], arg0: str = "/usr/bin/optipng"):
self.args = [arg0, "-q"] + list(options)
def __call__(self, tile: Tile) -> ... |
# Copyright Alexander Malahov 2018.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import unohelper
# noinspection PyUnresolvedReferences
from com.sun.star.task import XJobExecutor
import l... |
import socket
def form_ring(members):
sorted_binary_ring = sorted([socket.inet_aton(member) for member in members])
print(sorted_binary_ring)
sorted_ip_ring = [socket.inet_ntoa(node) for node in sorted_binary_ring]
print(sorted_ip_ring)
return sorted_ip_ring
def get_neighbour(members,... |
from .base import Action
from xml.etree import ElementTree
import requests
import sys
class Info(Action):
name = 'info'
aliases = []
description = 'Get information about a Roku device'
arguments = {
'ip': {
'help': 'IP address of Roku device',
},
}
@staticmethod
... |
import pandas as pd
import numpy as np
def splitter(sourcefile, targetfile):
df = pd.read_csv(sourcefile, header=None)
b = df[np.mod(np.arange(df.index.size), 4) == 0]
b.to_csv(targetfile)
if __name__ == '__main__':
#splitter('suicide_rate_1985_2016.csv', 'suicide_rate_1985_2016_one_fourth.csv')
... |
import pygame
class Image():
black = (0,0,0)
white = (255,255,255)
def __init__(self, imageSource, root, x = 0, y = 0):
self.imageSource = imageSource
self.image = None
self.x = x
self.y = y
self.hide = True
# pygame display object
self.root = root
... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2021 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
#!/usr/local/bin/python
# coding: utf-8
from enum import Enum
import sys
class ErrorLevel(Enum):
low = 0
normal = 1
high = 2
critical = 3
def raise_error(error: Exception or str, level: ErrorLevel = ErrorLevel.normal):
if isinstance(error, Exception):
print(type(error).__name__, '(' + level.name + '):', err... |
class Config:
################ 模型部分
num_classes = 2 # 类别数量, (不包括背景)
backbone = 'resnet50'# backbone 使用的骨架网络
lr = 1e-3
batch_size = 8
gradient_accumulation=4
device='cuda:0'
clip_value = 100
loss_alpha = 1.
loss_beta = 0.2
loss_gamma = 1.
pretrained=False
deconv_wit... |
# test_sfwebui.py
import unittest
import cherrypy
from cherrypy.test import helper
from spiderfoot import SpiderFootHelpers
from sflib import SpiderFoot
from sfwebui import SpiderFootWebUi
class TestSpiderFootWebUiRoutes(helper.CPWebCase):
@staticmethod
def setup_server():
default_config = {
... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="UUGame",
version="1.0.0",
author="Group D",
description="UUGame for 1DL251",
long_description=long_description,
long_description_content_type="text/markdown",
pac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.