content stringlengths 5 1.05M |
|---|
from bisect import bisect_left, bisect_right
while True:
try:
N = int(input())
except EOFError:
break
except ValueError:
error = False
continue
lista = []
for i in range(N):
x, y = list(map(int, input().split()))
for item in range(x, y + 1):
... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ComitteeFunds(scrapy.Item):
# define the fields for your item here like:
funds = scrapy.Field()
member= scrapy.Field()
industry= sc... |
import time
from pynput import mouse, keyboard
from pynput.keyboard import Key, Controller as keyboard_controller, Listener as keyboard_listener
from pynput.mouse import Button, Controller as mouse_controller, Listener as mouse_listener
event_arr = []
is_auto = [False]
def on_press(key):
print(key)
# print(ke... |
# File containing default global values
DEFAULT_TIME_VALUE = "00010101T00:00:00"
TIME_FORMAT = '%Y%m%dT%H:%M:%S' |
import sys
from time import time
from layer import NetLayer
from utils import *
if __name__ == "__main__":
# 解析参数。
if len(sys.argv) != 2:
print("[Error] Device ID expected")
exit(-1)
# 创建主机网络层。
device_id = sys.argv[1]
net = NetLayer(device_id)
print(net)
recv_frame = Fram... |
from os import cpu_count
from multiprocessing import Pool
from functools import partial
import numpy as np
from anndata import AnnData
from pandas import DataFrame
from .utils import transform_input_data, find_mutual_nn, compute_correction
from .utils import svd_internal, find_shared_subspace, get_bio_span, subtract_bi... |
# Used to remove the Red Draco Morph Buff In Leafre : Station in case field/undomorphdarco.py fails
from net.swordie.ms.client.character.skills.temp import CharacterTemporaryStat
if sm.getnOptionByCTS(CharacterTemporaryStat.Morph) == 16:
sm.removeCTS(CharacterTemporaryStat.Morph) |
from .base import *
DEBUG = False
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static', 'dist')
]
WEBPACK_MANIFEST_FILE = os.path.join(BASE_DIR, '../manifest-dist.json')
|
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Cisco.IOS.get_sla_probes
# ---------------------------------------------------------------------
# Copyright (C) 2007-2017 The NOC Project
# See LICENSE for details
# -------------------------------------------------------... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email = 'admin@test.com',
... |
from datetime import datetime
from model import GAN
from sample import generate_real_samples
import tensorflow as tf
# Nombre d'époques
epochs = 1000
# Taille des lots
batch_size = 256
# Taille de l'espace latent
latent_dim = 100
# Taux d'apprentissage du discriminateur
d_learning_rate = 0.0001
# Taux d'apprentissage ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'seconscreen.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form,MainWindow,ocr):
Form... |
import skimage.feature
import matplotlib.pyplot as plt
import numpy as np
def corner_detector(img):
img_gray=0.2989*(img[:,:,0])+0.5870*(img[:,:,1])+0.1140*(img[:,:,2])
img_gray=img_gray.astype(np.uint8)
cimg=skimage.feature.corner_harris(img_gray)
'''
IF THE TEST IMAGE IS BEING USED, THEN THE FEATURE HAS ... |
#MenuTitle: Select all Anchors and Paths
# -*- coding: utf-8 -*-
__doc__="""
Select all Anchors and Paths 90 left in the current glyph.
"""
thisFont = Glyphs.font # frontmost font
thisFontMaster = thisFont.selectedFontMaster # active master
listOfSelectedLayers = thisFont.selectedLayers # active layers of selected g... |
from .mean_vfe import MeanVFE
from .pillar_vfe import PillarVFE, PillarVFE_TANet
from .image_vfe import ImageVFE
from .vfe_template import VFETemplate
__all__ = {
'VFETemplate': VFETemplate,
'MeanVFE': MeanVFE,
'PillarVFE': PillarVFE,
'ImageVFE': ImageVFE,
'PillarVFE_TANet': PillarVFE_TANet
}
|
import numpy as np
def prisoners_dilemma_payoffs(random_state, max_payoff=10):
T = random_state.randint(3, max_payoff)
R = random_state.randint(2, T)
P = random_state.randint(1, R)
S = random_state.randint(P)
payoffs = np.array([[R, S], [T, P]])
return payoffs
def stag_hunt_payoffs(random_st... |
import codecs
# "Moby Words lists by Grady Ward"
# http://www.gutenberg.org/ebooks/3201
# SUMMARISED_FILE = "all_unique_words.txt" # 500k approx
#CODEC = 'Windows-1252'
CODEC = 'utf-8'
SUMMARISED_FILE = "all_unique_words_wikipedia.txt"
# SUMMARISED_FILE = "all_unique_words_wikipedia_AA.txt" # 4.8mil approx
# SUMMAR... |
import copy
import fileinput
from utils import Point
board = {}
for y, line in enumerate(fileinput.input()):
for x, c in enumerate(line.strip()):
board[Point(x, y)] = int(c)
part_1 = 0
for i in range(10000000):
next_state = copy.copy(board)
for pos, val in next_state.items():
next_state... |
"""
These are logic engines for doing tracing.
"""
import typing
from itertools import islice
from covid19sim.epidemiology.symptoms import MODERATE, SEVERE, EXTREMELY_SEVERE
from covid19sim.inference.heavy_jobs import DummyMemManager
from covid19sim.epidemiology.symptoms import STR_TO_SYMPTOMS
if typing.TYPE_CHECKIN... |
from setuptools import setup
import sys
import modifycsf
extra = {}
if sys.version_info >= (3,):
extra["use_2to3"] = True
setup(name="mcsf",
version=modifycsf.version,
description="Port modification wrapper for ConfigServer Security&Firewall",
url="http://github.com/Liamraystanley/modify-csf",
... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import src.constants as const
from src.secrets import DATABASE_URL
logger = const.logger
def init_sessionmaker():
try:
engine = create_engine(DATABASE_URL,
connect_args={'sslmode':... |
#!/usr/bin/env python
'''
II. Modify the 'show ip bgp' exercise from class2. Simplify the program using
the flow-control statements from this class.
>>>> 'show ip bgp' exercise from class2' (for reference) <<<<<
You have the following four lines from 'show ip bgp':
entry1 = "* 1.0.192.0/18 157.130.10.233 0... |
from median_angle import create_median_angle_correction, \
create_target_angle, \
median_angle_correct, \
calc_median_angle_params, \
calc_target_angle
__all__ = ['create_median_angle_correction', \
'create_t... |
from pickle import loads, dumps
import numpy as np
import pandas as pd
from classicML import _cml_precision
from classicML import CLASSICML_LOGGER
from classicML.api.models import BaseModel
from classicML.backend import get_conditional_probability
from classicML.backend import get_dependent_prior_probability
from cla... |
for i in range(11, 100, 2):
print(i) |
# Copyright 2022 NVIDIA 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 to in wr... |
# TODO: revisit ignoring type and write some tests for this, the multi-inheritance in this
# this file is challenging, it should be broken into true mixins.
"""
Constructive Solid Geometry file formats.
"""
import abc
from typing import List
from galaxy import util
from galaxy.datatypes import data
from galaxy.dataty... |
# Generated by Django 2.2.4 on 2020-04-03 04:05
from django.db import migrations
from django.utils import timezone
def populate_score_pb(apps, schema_editor):
User = apps.get_model("omgwords-agent", "User")
ScorePB = apps.get_model("omgwords-agent", "ScorePB")
now = timezone.now()
for user in User.obj... |
# import_export_facebook/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.conf.urls import re_path
from . import views, views_admin
urlpatterns = [
re_path(r'^bulk_retrieve_facebook_photos/$',
views_admin.bulk_retrieve_facebook_photos_view, name='bulk_retrieve_facebo... |
import importlib
def test_version():
assert importlib.metadata.version('dbd') == '0.8.9'
|
import csv
import os
from pymongo import MongoClient
from recipe_extractor import *
from urllib.parse import quote_plus
import conf
client = MongoClient('mongodb://{}:{}@{}'.format(
quote_plus(conf.DATABASE_USER),
quote_plus(conf.DATABASE_PASSWORD),
quote_plus(conf.DATABASE_ADDRESS),
), authSource='saana_... |
import math
from geometry_msgs.msg import Point, Pose
from roomba.util import getHeading
class Frontier:
alpha = 0.75 # Distance to frontier
beta = 0.1 # Size of frontier (decreases cost)
gamma = 0.25 # Angle to frontier
def __init__(self, r: Pose, s: int, d: float, c: Point, p: list):
s... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime, timedelta
from rest_framework.serializers import HyperlinkedIdentityField
from drf_haystack.serializers import HaystackSerializer, HaystackFacetSerializer, HighlighterMixin
from .search_indexes import Mock... |
# Generated by Django 3.2 on 2021-04-30 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('waterspout_api', '0030_auto_20210429_1758'),
]
operations = [
migrations.RemoveIndex(
model_name='calibratedparameter',
... |
""":mod:`megastep.modules` are chunks of functionality that often turn up in megastep environments.
"""
import numpy as np
import torch
from rebar import arrdict
from . import spaces, geometry, cuda, plotting
import matplotlib.pyplot as plt
def to_local_frame(angles, p):
"""Converts a velocity vector in the glo... |
from realsense_utils import RealSenseCamera
import cv2
import preprocessing as pre
import numpy as np
from math import pi
TMP_DEST = "/home/spark/cv-chess/core/vision/tmp/"
def rotate_image(image, angle):
image_center = tuple(np.array(image.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle,... |
n1, n2, n3, n4 = input().split(' ')
n1 = float(n1) * 2
n2 = float(n2) * 3
n3 = float(n3) * 4
n4 = float(n4) * 1
media = (n1 + n2 + n3 + n4) / 10
print(f'Media: {media:.1f}')
if media >= 7:
print('Aluno aprovado.')
elif media < 5:
print('Aluno reprovado.')
else:
print('Aluno em exame.')
exame = float... |
from pygame import *
window = display.set_mode((950,700))
class GameSprite(sprite.Sprite):
def __init__(self,img,x,y,speed,width,height):
super().__init__()
self.image = transform.scale(image.load(img),(width,height))
self.rect = self.image.get_rect()
self.rect.x = x
... |
import select
import socket
import numpy
import numpy as np
import time
import zmq
from urh.dev.gr.AbstractBaseThread import AbstractBaseThread
from urh.util.Logger import logger
class SenderThread(AbstractBaseThread):
MAX_SAMPLES_PER_TRANSMISSION = 65536
def __init__(self, sample_rate, freq, gain, bandwid... |
#!/usr/bin/env python
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in... |
# ----------------------------------------------------------------------------
# Copyright (c) 2020, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------... |
import random
from typing import Any, Iterator, List, Optional, Type
import attr
import numpy as np
from sympy import *
Vector = List[float]
class NnException(Exception):
pass
class Node(object):
def __init__(self, name: str):
self.incoming: List["Edge"] = list()
self.outgoing: List["Edge... |
import toml
import dropbox
with open('config.toml', 'r') as fo:
config = toml.load(fo)
print(config)
def send_to_dropbox(fname):
DBOX_DESTINATION = '/Apps/Raspberry Pie Camera'
with open(fname, 'rb') as fo:
data = fo.read()
try:
res = dbx.files_upload(data, '{}/{}'.format(DBOX_... |
from rich import print
from rich.panel import Panel
from rich.markdown import Markdown
md = Markdown("**Hello**, *World*.")
print(Panel(md))
|
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
NetIpStackInfoEntryType = Enum(
'dynamic',
'invalid',
'manual',
'other',
)
|
"""
Rasterer class implement a differentiable rasterer.
"""
import numpy as np
import tensorflow as tf
from rastering.utils import calibration_matrix
from rastering.utils import project_in_2D
def keep_top_n(meshes, top_n):
"""
Filter a list of meshes keeping only the top `n` wider triangles
"""
def t... |
import os
import pytest
import numpy as np
import pandas as pd
import tensortrade.exchanges as exchanges
from gym.spaces import Box
from tensortrade.features import FeaturePipeline
from tensortrade.features.indicators import TAlibIndicator
from tensortrade.features.scalers import MinMaxNormalizer
path = os.path.dirn... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 14:53:3 2019
@author: Excalibur
Paramater ranges for elasticities
"""
# ----------------------
# Elasticity parameters
# ----------------------
alphaM = (1/3,2)
alphaP = (1, 6)
alphaS = (1/4, 1/2)
alphas = {'alphaM':alphaM, 'alphaP':alphaP, 'alphaS':alphaS}
betaA =... |
import numpy as np
import torch
import random
import time
import math
from fairseq import utils
from fairseq.data import data_utils, LanguagePairDataset
class MaskedLanguagePairDataset(LanguagePairDataset):
""" Wrapper for masked language datasets
(support monolingual and bilingual)
... |
from ._utils import randomWalkFromCSC
__all__ = ['randomWalkFromCSC']
|
#! /usr/bin/env python
print 'v2'
import os
import re
import sys
import imp
import os.path as op
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
# for dprime
from scipy.stats import norm
from math import exp,sqrt
Z = norm.ppf
def gather_experiment_info(exp_name=None, dirs=No... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
#!/usr/bin/env python3
import os
from configparser import ConfigParser
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
def __init__(self, filename):
self.parser = ConfigParser()
self.parser.read(filename)
def database_config(self, password, section='postgresql'):
params = self.parser.ite... |
import unittest
from qupulse.pulses.parameters import ParameterConstraint, ParameterConstraintViolation,\
ParameterNotProvidedException, ParameterConstrainer, ConstantParameter, ConstrainedParameterIsVolatileWarning
from qupulse.pulses.measurement import MeasurementDefiner
class MeasurementDefinerTest(unittest.T... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\J_MARCHAL\workspace\SerialNumberGenerator\src\lsng\hmi\edit_model\edit_model_ui.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
... |
import pickle
import matplotlib.pyplot as plt
(stars,times,xyzuvw,xyzuvw_cov)=pickle.load(open("traceback_save.pkl"))
bp_stars = []
#for i in range(len(stars)):
# X = xyzuvw[i,80,0]
# Y = xyzuvw[i,80,1]
# Z = xyzuvw[i,80,2]
# if (-1900<X and X<-1540) and (2000<Y and Y<2600) and (Z<-20 and Z>-45):
# ... |
import pytest
import asyncio
from cancel_token import CancelToken
from eth.beacon.types.attestation_records import AttestationRecord
from eth.beacon.types.attestation_data import AttestationData
from eth.db.atomic import AtomicDB
from eth.beacon.db.chain import BeaconChainDB
from eth.beacon.types.blocks import BaseB... |
from .h5seis import *
|
from sys import modules
from raser.geometry import R3dDetector
from raser.pyfenics import FenicsCal
from raser.g4particles import Particles
from raser.calcurrent import CalCurrent
from raser.elereadout import Amplifier
from raser.setting import Setting
from raser.model import Material
from raser.model import Av... |
"""Page type: top_service."""
from .page import Page
class TopServicePage(Page):
"""Page type: top_service."""
def get_title(self):
"""Get the title."""
title_cell = self.soup.find('div', {'class': 'mc-right'})
title = title_cell.find('h3')
return title.get_text() if title els... |
'''
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at
most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that
(0 <= i <= n - 2).
Example:
Input - nums = [4,2,3]
Output - true
... |
"""
Simple classes to get info from the ip system utility
"""
from subprocess import check_output as sub
import re
__all__ = ['Devices', 'Routes']
class Devices(object):
""" Network devices from IP """
def __init__(self):
self.ips = {}
self.states = {}
# Get states
for i in s... |
from django.urls import path
from . import views
app_name = 'app_email'
urlpatterns = [
path('', views.email, name='email'),
path('send_email/', views.send_email, name='send_email'),
]
|
'''7、 水仙花数
【问题描述】
打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该
数本身。例如:153 是一个"水仙花数",因为 153=1 的三次方+5 的三次方+3 的三次方。
【输入】
无
【输出】
以列表形式输出所有的水仙花数。
【输出样例】[153, 370, 371, 407]'''
nar = []
for i in range(9):
for j in range(9):
for k in range(9):
if (i*i*i+j*j*j+k*k*k)==(i*100+j*10+k):
if i ... |
from django.db import models
import hashlib
# Create your models here.
def get_upload_path(instance, filename):
return instance.category + '/challenges_{0}/{1}'.format(
hashlib.md5(instance.name.encode('utf-8')).hexdigest(), filename)
class Challenges(models.Model):
name = models.CharField(max_leng... |
from geolite2 import geolite2
import requests
import csv
def get_ip_location(SELF_IP):
reader = geolite2.reader()
location = reader.get(SELF_IP) ## initiate reader, t get
print(type(reader))
print(reader)
print(type(location))
print(location)
print(location.values()) # print key values)
... |
import functions
import matrices
import constants
|
#!/usr/bin/env python
# coding=utf-8
"""
Launches a Python shell with a configured API client ready to go.
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
from argparse import ArgumentParser
from logging import DEBUG, basicConfig, getLogger
from sys import stderr
from six im... |
#!/usr/bin/env python
# coding=utf-8
from eins import road
from eins import statistics
import copy
if __name__ == '__main__':
# some paras
length = 1000
exectime = 100
lanes = 3
vmax = 6
# define cars
car = road.Car()
car1 = road.Car()
car.name = 'No1'
car1.name = 'No2'
car... |
# test that fixed dictionaries cannot be modified
try:
import uerrno
except ImportError:
print("SKIP")
raise SystemExit
# Save a copy of uerrno.errorcode, so we can check later
# that it hasn't been modified.
errorcode_copy = uerrno.errorcode.copy()
try:
uerrno.errorcode.popitem()
except TypeError:
... |
#!/usr/bin/env python3
import sys
import re
def extract(s):
return [int(x) for x in re.findall(r'(-?\d+).?', s)]
def inside(coord, box):
minx, maxx, miny, maxy = box
x, y = coord
return (minx <= x <= maxx) and (miny <= y <= maxy)
def step(pos, v):
x, y = pos
dx, dy = v
x += dx
y += ... |
from zwierzeta.zwierze import Zwierze
class Czlowiek(Zwierze):
def __init__(self, swiat, x=-1, y=-1):
self.sila = 5
self.priorytet = 4
self.obecnySwiat = swiat
if x == -1:
super().__init__(swiat, 5, 4, "aqua")
else:
super().__init__(swiat, 5, 4, "aqua... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
__author__ = "Bannings"
class Solution:
# def myPow(self, x: float, n: int) -> float:
# """
# Exponentiation by squaring using recursion
# """
# def pow(n):
# if n == 0: return 1
# ans = pow(n // 2)
# retu... |
from pathlib import Path
from typing import Iterator, Dict
import argparse
import sys
from resource import getrusage, RUSAGE_SELF
import timeit
from pymusas.taggers.rule_based import USASRuleBasedTagger
from pymusas.lexicon_collection import LexiconCollection
def iter_over_benchmark_data(benchmark_data_file: Path
... |
import os
from kvdroid.jclass.android.os import Environment
def path():
return os.path.dirname(os.path.abspath("__main__"))
def sdcard():
return Environment().getExternalStorageDirectory().toString()
def external_sdcard():
try:
return os.path.join("/storage", os.listdir("/storage")[1])
ex... |
from __future__ import unicode_literals, print_function
import json
from lightdo.parsers import *
from lightdo.logger import logger
arg_parser = ARGParser()
opt = arg_parser.parser()
loc = os.path.dirname(__file__)
############## pre deal action ##############
# wenku login option
if not opt.is_anonymous:
config ... |
nome=input("Nome:\n")
lista_nome=nome.split() #Cada palavra vira um elemento de uma nova lista
print(lista_nome[0],lista_nome[-1]) #O índice 0 pega o primeiro nome e o índice -1 pega o último. |
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restful import Resource
from flask import jsonify
from database.file_handler import fs
from database.db import mongo
from resources.students.student_proposal import curr_user_is_student
import datetime
class ProposalUpload(Resource):
@jwt_r... |
from web3 import Web3
from decouple import config
from pprint import pprint
infura_url = config('INFURA_URL')
print(infura_url, "\n\n")
# HTTPProvider:
w3 = Web3(Web3.HTTPProvider(infura_url))
res = w3.isConnected()
print(res, "\n\n")
# Access latest block
latest_block = w3.eth.get_block('latest')
pprint(latest_bl... |
#This file was originally generated by PyScripter's unitest wizard
import unittest
from gol02 import Gol02
from cell import Cell
def dummy():
""" Dummy function for comparison of the return values """
return
class Gol02Test(unittest.TestCase):
def setUp(self):
pass
def tearDo... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.html import mark_safe
from crispy_forms.helper import FormHelper
from crispy_forms import layout, bootstrap
from mptt.forms import TreeNodeChoiceField
from utils.fields import MultipleChoiceTreeField
from .models import ... |
from bottle import route, run, static_file
import os
@route('/update', method = 'POST')
def hello():
print "hello"
os.system('cd /home/ubuntu/Kyrix/front-end/js && git pull && cat embed/API.js globalVar.js jump.js parameter.js staticLayers.js zoom.js zoomButton.js pageOnLoad.js dynamicLayers.js > embed/all.js ... |
import copy, random, pytest
from src.tree.range_tree import RangeTreeFixed1D
@pytest.mark.parametrize("seed", list(range(100)))
def test_one_sum(seed, lo=-1024, hi=1024):
random.seed(seed)
x = random.randint(lo, hi)
tree = RangeTreeFixed1D([x])
assert tree.get(0, 1) == x
@pytest.mark.parametrize("... |
import os
import logging
import time
from threading import Thread
from navio.pwm import PWM
pi = os.getenv('PI', False)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
T100 = 't100'
SERVO = 'servo'
# map of duty cycle settings in milliseconds which is the
# units expected by the navio PWM module... |
"""
Module for Serialization and Deserialization of KNX Search Response.
Search Requests are used to search for KNX/IP devices within the network.
A search response contains all information of a found device (Name, serial number, supported features.).
It supports an array-style access to the DIBs (use classname as ind... |
# flake8: noqa
# import apis into api package
from xero_python.file.api.files_api import FilesApi
|
import time
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.exceptions import PermissionDenied
from django.conf import settings
from attendees.persons.models import Attendee, Attending
from attendees.person... |
import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from csharp_element import CSharpElement
import csharp_class_method_parser
import csharp_class_member_parser
import csharp_class... |
"""
Generates a unique json file by using the standard python
library, with file.read()
TODO: change the team name
TODO: add the socket function and a __main__ call
"""
import json
import datetime
from time import time
import socket
from inspect import getsource
DATE = datetime.date.isoformat(datetime.date.today())
HA... |
"""validator"""
from .base_validator import Validator
|
# -----------------------------------------------------------------------------
# Copyright (C) 2019-2020 The python-ndn authors
#
# This file is part of python-ndn.
#
# 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 ... |
# https://codeforces.com/problemset/problem/469/A
n = int(input())
little_x = [int(x) for x in input().split()]
little_y = [int(x) for x in input().split()]
concat_list = list(set(little_x[1:] + little_y[1:]))
input_list = list(range(1, n + 1))
if 0 in concat_list:
concat_list.remove(0)
if concat_list == input... |
for i in range (1,6): #perulangan for sebagai inisialisasi dari angka 1 hingga angka yang lebih kecil daripada 6.
print("Ini adalah perulangan ke -", i) #perintah jika looping akan tetap berjalan |
import plistlib
from itertools import chain
import fbuild.builders.c.gcc.darwin as darwin
from fbuild.path import Path
# ------------------------------------------------------------------------------
def _iphone_devroot(simulator):
if simulator:
return Path('/Developer/Platforms/iPhoneSimulator.platform/... |
from functools import reduce
from unittest import TestCase
from matroids.algorithms import kernel_hitting_set, brute_hitting_set
class TestHittingSet(TestCase):
def test_empty_family(self):
family = []
result = kernel_hitting_set(family, set(), 5, 2)
self.assertEqual(result[0], [])
... |
from typing import Tuple, TypeVar, Generic, Any
from abc import ABC, abstractmethod
from .strategy import BaseDatabaseConnection, BaseConnectionPool
from .operator import DatabaseOperator
from ..interface import DataPersistenceLayer
from ... import get_current_mode
T = TypeVar("T")
class DatabaseAccessObject(DataP... |
from django.contrib import admin
from .models import *
# Registrace modelů v administraci aplikace
admin.site.register(Workout)
admin.site.register(WorkoutType) |
#!/usr/bin/python
import noiselib
import numpy as np
from PIL import Image
size = (2000, 400)
nwidth = 5
max_col_ind = 375
noiselib.init(256)
xs = np.arange(0, nwidth, float(nwidth) / size[1])
ys = np.array(map(lambda z: noiselib.simplex_noise2((z, 0)), xs))
ys = (nwidth - xs) * ys
print ys
ys = ys / np.amax(ys)
bb... |
""" Implementation of all available options """
from __future__ import print_function
def train_opts(parser):
# Transformer or Seq2Seq
parser.add_argument('--model-choice', required=True, help="transformer or seq2seq")
# Common training options
group = parser.add_argument_group('Training_options')
... |
from string import Template
import datetime
import netaddr
from graphene.test import Client
from django.test import TestCase
from ipam.models import Aggregate
from netbox_graphql.schema import schema
from netbox_graphql.tests.utils import obj_to_global_id
from netbox_graphql.tests.factories.ipam_factories import Ag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.