content stringlengths 5 1.05M |
|---|
#Python Project. Beginner Level. Level 1
# Dice Rolling game.....
import random
import tkinter as bijoy
root = bijoy.Tk() # main window
root.geometry("750x475") # Resize
root.title('Roll Dice') #title
ll = bijoy.Label(root, text = '', font = ("times new roman",260)) #level to display dice
#Activate button
def roll()... |
import time
from datetime import datetime, date
import boto3
class CE(object):
def __init__(self, credentials=None):
super().__init__()
self.credentials = credentials
c = credentials.get() if credentials is not None else {}
self.ce_client = boto3.client('ce', **c)
@staticmethod
def _get_st... |
'''
This file using geopy library
I found this API before using Yandex
After I understand the Yandex API I focus on it
'''
from flask import Blueprint, current_app
from geopy.geocoders import Nominatim
from geopy import distance
PREFIX = '/geopy'
geopy_lib = Blueprint('geopy_lib', __name__, url_prefix=PREFIX)
geoloca... |
#!/usr/bin/env python3
import config
import binascii
import requests
import logging
from logging.handlers import RotatingFileHandler
from bluepy.btle import UUID, Peripheral, ADDR_TYPE_PUBLIC, DefaultDelegate, Scanner, BTLEInternalError
battery_level = -1
sensor_id = -1
class TempHumDelegate(DefaultDelegate):
def __... |
# coding=utf-8
import pandas as pd
ques_importance = {"I easily adapt to day-to-day changes of my life and manage my responsibilities well.": 0.911,
"I care for things that are important to me, not what is important to others.": 0.868,
"I feel I am a sensible person.": 0.862,
... |
"""Top-level package for geo-prof."""
__author__ = """Shakur"""
__email__ = '[email protected]'
__version__ = '0.0.2'
|
from floodsystem.geo import rivers_with_stations
from floodsystem.geo import stations_by_river
from floodsystem.stationdata import build_station_list
stat = build_station_list()
#from floodsystem import geo
print(len(rivers_with_stations(stat)), "Rivers with one or more stations")
print((sorted(rivers_with_statio... |
import numpy as np
import os
import traceback
import yaml
from edflow.hooks.hook import Hook
from edflow.util import walk, retrieve, contains_key
from edflow.custom_logging import get_logger
class RuntimeInputHook(Hook):
"""Given a textfile reads that at each step and passes the results to
a callback functio... |
class TimedCycle:
def __init__(self, max_frame, ticks, movements, start_frame=0):
self.current_tick = 0
self.max_frame = max_frame
self.frame = start_frame
self.movements = movements
self.max_ticks = ticks
self.config = (max_frame, start_frame, movements, ticks)
... |
"""
Class Features
Name: drv_dataset_hmc_io_static
Author(s): Fabio Delogu ([email protected])
Date: '20200401'
Version: '3.0.0'
"""
#######################################################################################
# Library
import logging
import os
import xarray as xr... |
"""
Created on Nov 6, 2021
@author: reganto
"""
from tornado.web import Application
from tests.base import BaseTest
from database.models import migrator, Thread, Channel
from database.model_factory import Factory
class ChannelTest(BaseTest):
def get_app(self):
return Application()
def setUp(self):
... |
from typing import Union
from record_keeper.module.admin.query import (
get_listeners,
remove_listener,
update_listener,
)
from record_keeper.utilities.message import MessageWrapper
class AdminRelay:
def __init__(self):
self.admin_options = [
"dice",
"help",
... |
# Copyright 2018 Science and Technology Facilities Council
#
# 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... |
import os
import csv
def search_user(userid, guildid):
""" Check if entry exists in database """
if os.path.isfile(f'userdata/{guildid}.csv'):
with open(f'userdata/{guildid}.csv', 'rt') as file:
reader = csv.reader(file)
for row in reader:
if str(userid) in row[0... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
from frappe.model.naming import validate_name
@frappe.whitelist()
def rename_doc(doctype, old, new, force=Fals... |
from arm.logicnode.arm_nodes import *
class MergeNode(ArmLogicTreeNode):
"""Activates the output when at least one connected input is activated.
If multiple inputs are active, the behaviour is specified by the
`Execution Mode` option.
@output Active Input Index: [*Available if Execution Mode is set t... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import numpy as np
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.utils import try_import_torch
torch, nn = try_import_torch()
class DQNTorchModel(TorchModelV2):
"""Extension of standard TorchModelV2 to provide dueling-Q functionality.
"""
def __init__(
self,
... |
def inverse(s):
return "AM" if (s == 'PM') else "PM"
def add_time(start, duration, day=''):
shift_hours, shift_mins = duration.split(':')
start_hour = start.split(' ')[0].split(':')[0]
start_min = start.split(' ')[0].split(':')[1]
start_part = start.split(' ')[1]
# print(f'adding {shift_hours... |
from networkx import MultiDiGraph
from pyformlang.cfg import CFG
from scipy.sparse import dok_matrix
from typing import Set, Tuple
from project.utils.cfg_utils import transform_cfg_to_wcnf, is_wcnf
__all__ = ["matrix_based"]
def matrix_based(cfg: CFG, graph: MultiDiGraph) -> Set[Tuple[int, str, int]]:
"""
... |
#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distri... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""Demo based on the demo mclist.tcl included with tk source distribution."""
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkFont
import re
split_symbol = '|'
settings_content = ""
case_columns = ("name", "instructions")
case_data = [
("ReImgI... |
#!/usr/bin/env python3
import bitstruct
import numpy as np
from bitstruct import *
src = open("input.txt", "r").read()
example = "D2FE28"
example = "38006F45291200"
example = "A0016C880162017C3686B18A3D4780"
example = "9C0141080250320F1802104A08"
# src = example
buf = bytearray.fromhex(src)
literal = 4
# def pa... |
# coding: utf-8
# flake8: noqa
"""
Twitter APIs
Call Twitter APIs.<BR />[Endpoint] https://api.apitore.com/api/23 # noqa: E501
OpenAPI spec version: 0.0.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import apis into sdk packa... |
# -*- coding: utf-8 -*-
import asyncio
import logging
import logging.config
import os
import queue
import random
import re
import shutil
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import discord
from ...core.arguments import get_args
from ...binders import available_formats
from .... |
import sys
def reverse(num):
count = num
result = 0
while count != 0:
n = count % 10
count = count // 10
result = result*10 + n
return result
def firstdigit(num):
while num > 9:
num = num // 10
return num
def lastdigit(num):
return num % 10
line = "121"
re... |
class Identifier:
"""
A class that encapsulates the column names of a dataset for use in Mobipy functions.
...
Attributes
----------
lat_name : str
the latitude column name
lon_name : str
the longitude column name
timestamp : str
the timestamp column name, used in some mobipy function... |
import json
with open('reposfinal') as data_file:
data = json.load(data_file)
i = 0
for repo in data:
i += 1
print "repos = " + str(i)
j = 0
for repo in data:
for commit in repo['commit']:
j+=1
print j
|
import os
import tempfile
from io import StringIO
from django.contrib.gis.geos import MultiPolygon
from django.test import TestCase
from organisations.boundaries.management.commands.boundaryline_import_boundaries import (
Command,
)
from organisations.models import (
DivisionGeography,
OrganisationGeography... |
passagem = 1500
print(passagem)
custo_por_dia = 350
dias = 2
custo_total = passagem * 2 + custo_por_dia * dias
print(custo_total)
print ("O custo de sua passagem será: R$ 3700,00. ")
print ("O custo de sua passagem será: R$", custo_total)
dólar = 5.01
print("O custo de sua passagem será: US$", custo_total/dóla... |
from libai.config import LazyCall
from modeling.moco import MoCo_ViT
from modeling.vit import VisionTransformer
base_encoder = LazyCall(VisionTransformer)(
img_size=224,
patch_size=16,
in_chans=3,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4,
drop_path_rate=0.1,
global_pool=F... |
def remove_every_other(lst):
"""Return a new list of other item.
>>> lst = [1, 2, 3, 4, 5]
>>> remove_every_other(lst)
[1, 3, 5]
This should return a list, not mutate the original:
>>> lst
[1, 2, 3, 4, 5]
"""
return [item for item in lst if lst.index(item) % 2... |
network="lora"
""" LoRa example configuration options """
_MAX_CONNECTION_ATTEMPT_TIME_SEC = 60
""" LoRa-related configuration options """
_DEV_EUI = "<lora-dev-eui>"
_APP_EUI = "<lora-app-eui>"
_APP_KEY = "<lora-app-key>"
from network import LoRa
_LORA_REGION = LoRa.<lora-region>
_LORA_ADR = <lora-adr>
_LORA_DR = <... |
import os
import sys
import unittest
REGRESSION_TEST_DIRNAME = 'regressiontests'
REGRESSION_TEST_DIR = REGRESSION_TEST_DIRNAME
sys.path.insert(0, '../src/')
def load_suite_tests(only=None):
only_module, only_test_case = None, None
if only:
args = only.split(".")
only_module, only_test_case, ... |
from utils import misc
class NetTracker:
def __init__(self):
self.peer_servers_set = set()
def add_peer(self, peer_server):
self.peer_servers_set.add(peer_server)
def remove_peer(self, peer_server):
try:
self.peer_servers_set.remove(peer_server)
except KeyError... |
from banklite.dtypes import BaseCustomer, RetailCustomer, CommercialCustomer
def test_base_customer():
customer = BaseCustomer("1111111111", 11111, "555-555-5555", "[email protected]")
assert customer.customer_id is not None
assert customer.zip == 11111
assert customer.phone == "555-555-5555"
assert... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
import os.path
# The directory containing this file
HERE = os.path.abspath(os.path.dirname(__file__))
# The text of the README file
with open(os.path.join(HERE, "README.md")) as fid:
README = fid.read()
def package_fil... |
from django.contrib import admin
from django.urls import path,include
from django.contrib.auth import views
from django.conf import settings
from django.conf.urls.static import static
from django_registration.backends.one_step.views import RegistrationView
urlpatterns = [
path('admin/', admin.site.urls),
path(... |
"""
Package for the video comment API
"""
|
"""Generate Lights Out puzzle.
Ref: https://github.com/pmneila/Lights-Out
"""
# Standard library imports
from operator import add
from itertools import chain, combinations
from functools import reduce
# Third party imports
import numpy as np
from numpy import eye, hstack, vectorize, vstack, int32
from num... |
#!/usr/bin/env python
# The Notices and Disclaimers for Ocean Worlds Autonomy Testbed for Exploration
# Research and Simulation can be found in README.md in the root directory of
# this repository.
import constants
import math
import copy
from tf.transformations import quaternion_from_euler
from utils import is_shou_... |
# coding: utf-8
"""
Xero Payroll AU
This is the Xero Payroll API for orgs in Australia region. # noqa: E501
OpenAPI spec version: 2.4.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class SettingsTrack... |
from .utils import sorted_by_key
from .station import MonitoringStation
#define the stations with their water level being over the threshold of 0.8
def stations_level_over_threshold(stations, tol):
#create an empty list of tuples
tuples = []
#loop through each station
for station in stations:
... |
from typing import List
import re
import numpy as np
import pandas as pd
from eunjeon import Mecab # Uses mecab for better performance
from sklearn.base import BaseEstimator, TransformerMixin
__all__ = ['ColumnSelector', 'ColumnMerger', 'WordUnifier',
'RegExReplacer', 'DuplicateRemover', 'StopWordRemover'... |
# -*- coding: utf-8 -*-
import scrapy
class KindleTelegramSpider(scrapy.Spider):
name = 'kindle_telegram'
allowed_domains = ['https://www.amazon.com.br/']
start_urls = ['https://www.amazon.com.br/gp/product/B0773XBMB6/']
def parse(self, response):
name = response.xpath('//span[@id="priceblock... |
#!usr/bin/env python
from sprite import *
import universal_var
import timer
import bar
import projectile
class World_camera(object):
world_location = [0, 0] #player position from the origin
original_position = [250, 200]
x = original_position[0]
y = original_position[1]
x_offset = 0
y_of... |
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DATASET_ROOT = os.path.join(PROJECT_ROOT, 'data')
|
import inspect
from remake.operators.base import BaseOperator
class ParameterOperator(BaseOperator):
def __init__(self, name, sources, transform: callable, default_value, helper, dtype="_right"):
super().__init__(name, sources, priority="LAZY", order=1, type="PARALLEL")
self.transform = transform... |
from modeltranslation.translator import translator, TranslationOptions
from .models import MetaTag
class MetaTagTranslationOptions(TranslationOptions):
fields = ('title', 'keywords', 'description')
translator.register(MetaTag, MetaTagTranslationOptions)
|
import logging
import numpy as np
import pandas as pd
from countess.plugins.scoring import BaseScorerPlugin
from countess.plugins.options import Options
from countess.base.constants import WILD_TYPE_VARIANT
from countess.base.utils import log_message
from countess.base.constants import IDENTIFIERS, VARIANTS
options ... |
# Cryptopals
# Set 4 Challenge 25
# Break "Random Access Read/Write" AES CTR
import base64
from Crypto.Cipher import AES
from random import randint
def random_bytes(n):
random_ints = []
for i in range(n):
random_ints.append(randint(0,255))
return bytes(random_ints)
def binary_xOR(byte_code1,byte... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
import imutils
img1 = cv2.imread('qr_code.png',0) # queryImage
img2 = cv2.imread('qr_code_rotated90.jpg',0) # trainImage
img2 = imutils.resize(img2, width=600)
# Initiate SIFT detector
orb = cv2.ORB_create(nfeatures=1000, scoreType=cv... |
# Indic library
import sys
from indicnlp import common
INDIC_NLP_LIB_HOME=r"indic_nlp_library"
INDIC_NLP_RESOURCES=r"indic_nlp_resources"
sys.path.append(r'{}\src'.format(INDIC_NLP_LIB_HOME))
common.set_resources_path(INDIC_NLP_RESOURCES)
from indicnlp.tokenize import indic_tokenize
import torch
from torch.utils.da... |
from model.contact import Contact
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
# fill contact page
self.open_contact_page()
wd.find_element_by_name("firstname").click()
wd.find_element_by_name("first... |
import argparse
import datetime
import json
import logging
import shutil
import sys
import lmdb
from dredis import db
from dredis.keyspace import Keyspace
from dredis.path import Path
logger = logging.getLogger(__name__)
BACKEND = 'lmdb'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-... |
from sortedintersect.intersect import *
|
# -*- coding: utf-8 -*-
from collections import defaultdict
from os.path import dirname
import os
import networkx as nx
""" Given a set of simulation runs and a threshold graph (output from Tills tool
gml2tg) for a arbitrary threshold and weight, generate one gml file with
networkx for each unique complex =... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
... |
"""Test eliminate common subexpr pass"""
from tvm import relay
from tvm.relay.op import register_alter_op_layout
from tvm.relay import ir_pass
def test_simple():
def before():
x = relay.var("x", shape=(1, 16))
y1 = relay.nn.relu(x)
y2 = relay.nn.relu(x)
y1 = relay.add(y1, relay.con... |
# Copyright IBM Corp, 2016
#
# 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, so... |
def intersect(nums1, nums2):
ret_list = []
if (nums1 is None or nums2 is None):
return ret_list
nums1.sort() #Assume already sorted
nums2.sort() #Assume already sorted
i = 0
j = 0
while(i < len(nums1) and j < len(nums2)):
if(nums1[i] == nums2[j]):
... |
"""Detection of country for authors affiliations."""
import requests
from bs4 import BeautifulSoup
# from typing import Union, List, Dict, Any
def get_references_from_hal(hal_id: str):
url = "https://hal.archives-ouvertes.fr/{}/html_references".format(hal_id)
try:
r = requests.get(url)
soup = ... |
import numpy as np
import itertools
def getBasePrefix(prefix):
return prefix.split(":")[0].split("-")[0].split("@")[0].split("#")[0].upper()
def getScopeGroups(trainPrefixes, scopeFname, ligandReceptorOrder=True, considerPairsInsteadMonomer=True):
'''
scope independency will be carried out as pairs of famili... |
import a2s
from tensor_site import auth_tokens
from discord_webhook import DiscordWebhook, DiscordEmbed
import re
from servers.models import Server, PlayerCount
from django.core.management.base import BaseCommand
def send_discord_announce(server, successful):
webhook = DiscordWebhook(url=auth_tokens.Discord_Webh... |
"""
Module defining the class `Emulator`, from which emulators inherit
"""
from abc import ABC, abstractmethod
from typing import Callable
import numpy as np # type: ignore
def raise_not_implemented_error():
raise NotImplementedError()
class BaseEmulator(ABC):
"""
Base class from which emulators shoul... |
##
# This class represents a node within the network
#
import sys
import time
import warnings
from collections import deque
import numpy as np
import tensorflow as tf
from dgp_aepmcm.layers.gp_layer import GPLayer
from dgp_aepmcm.layers.input_layer import InputLayer
from dgp_aepmcm.layers.noise_layer import NoiseLaye... |
from functools import lru_cache
from typing import Dict, Iterable, Set, Tuple
from .interfaces import Conflict, Layer, Match, Tree
from .utils import depth, is_import_allowed, match_submodule
def match_layer(tree: Tree, layer: Layer, module: str) -> Match:
match = Match(module, layer)
for import_ in layer.i... |
import threading
import pexpect
class Connection:
def __init__(self, intro, conn, numb):
self.open = False
self.type = intro
self.connection = conn
self.listening = 1
self.number = int(numb) + 1
self.thread = threading.Thread(target=self.wait)
self.thread.start()
def __str__(self):
string = ""
if(s... |
# encoding: utf-8
"""
@author: gallupliu
@contact: [email protected]
@version: 1.0
@license: Apache Licence
@file: test.py
@time: 2017/12/16 19:15
"""
from data.test import DataSuper
class wikiqa(DataSuper):
def gen_train(self):
print("gen wikiqa!")
def gen_embeddings(self):
print("ge... |
import pytest
from luminos.plugins.bluetooth import (Bluetooth)
instance = None
@pytest.fixture
def bluetooth():
global instance
if instance is None:
instance = Bluetooth()
return instance
class TestBluetooth:
def test_discover_devices(self, bluetooth):
devices = bluetooth.discove... |
from machine.exceptions.machine import MachineError
class UnsupportedResponseTypeError(MachineError):
message = "Client doesn't support required content types"
status_code = 403
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 2011-04-11 10:58:17
###############################################################################
# Copyright (c) 2010, Vadim Shlyakhov
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentatio... |
"""
Created on Mon Feb 26 14:29:11 2018
@author: Christian Bender
@license: MIT-license
This module contains some useful classes and functions for dealing
with linear algebra in python.
Overview:
- class Vector
- function zeroVector(dimension)
- function unitBasisVector(dimension,pos)
- function axpy(scalar,vector1... |
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from flask import Blueprint
import handlers
decodeinvoice_api = Blueprint('decodeinvoice_api', __name__)
@decodeinvoice_api.route('/decodeinvoice', methods=['GET'])
def decodeinvoice_get():
"""
Decode a BOLT-11 compatible Light... |
import pygame, sys
from copy import deepcopy
from pygame.locals import *
from constants import *
setfile = open("settings.txt", 'r')
GAMESIZE = GAMESIZES[int(setfile.readline())]
WINDOWWIDTH = int(800*GAMESIZE)
WINDOWHEIGHT = int(600*GAMESIZE)
SQUARESIZE = int(50*GAMESIZE)
BOARDSIZE = 9
XLMARGIN = int((3/4*WINDOWWIDT... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-10-21 07:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('customercorner', '0004_auto_20171021_0703'),
]
operations = [
migrations.Ad... |
#
# Test if network forward function runs
# Copyright EAVISE
#
import inspect
import pytest
import torch
import lightnet as ln
classification_networks = ['Darknet', 'Darknet19', 'Darknet53', 'MobileDarknet19', 'MobilenetV1', 'MobilenetV2']
anchor_detection_networks = ['DYolo', 'MobilenetYolo', 'MobileYoloV2', 'Mo... |
from .job import Job
from .email_sub import EmailSub
from .user import User
|
#!/usr/bin/env python3
import pyqtgraph as pg
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from pyqtgraph.widgets.PlotWidget import *
from pyqtgraph.imageview import *
from pyqtgraph.widgets.GraphicsLayoutWidget import GraphicsLayoutWidget
from pyqtgraph.graphicsItems.GradientEditorItem import... |
#!/usr/bin/env python
import mock
import os
import socket
import threading
import time
import unittest
from uhppote_rfid import ControllerSocket, SocketConnectionException, SocketTransmitException
class TestControllerSocket(unittest.TestCase):
"""
Tests UHPPOTE socket transmission by emulating the control b... |
from rest_framework import serializers
from .models import Game, Move, Player
from .statements.ifs import STATEMENTS as IF_STATEMENTS
from .statements.thens import STATEMENTS as THEN_STATEMENTS
class MoveSerializer(serializers.ModelSerializer):
"""
Model serializer for Move
"""
if_statement = serial... |
import jsonfile, json
def get_all_data():
reader = jsonfile.JSONFile()
reader.open_file('/home/pi/TrailSafe/Device/temp_data/buffer.data')
return reader.read()
def dequeue():
try:
writer = jsonfile.JSONFile()
writer.open_file('/home/pi/TrailSafe/Device/temp_data/buffer.data')
b... |
# @Rexhino_Kovaci
# This is an extra exercises that I challenged myself with on Google Kickstart 2020 during the online sessions
# This algorithm takes user input and compare the left and right subtree
# this would allow us to maintain a sorted list of numbers
# this program would check if the tree is balanced between ... |
from _group_category import GroupCategorytBackend
from _user_category import UserCategorytBackend
from enums import CategoryEnum
CATEGORY_BACKEND_MAP = {
CategoryEnum.GROUP: GroupCategorytBackend,
CategoryEnum.USER: UserCategorytBackend,
CategoryEnum.OFFICE: UserCategorytBackend,
CategoryEnum.TASK: Use... |
import komand
from .schema import AssignLicenseToUserInput, AssignLicenseToUserOutput, Input, Output, Component
# Custom imports below
import requests
from komand.exceptions import PluginException
class AssignLicenseToUser(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
... |
# Copyright 2016 The Spitfire 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 copy
import optparse
import string
import cStringIO
import StringIO
import sys
import timeit
try:
import spitfire
import spitfire.compiler.... |
# Generated by Django 3.2.9 on 2021-12-02 22:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0009_alter_post_hours'),
]
operations = [
migrations.DeleteModel(
name='Foo',
),
migrations.RemoveField(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
微软的烙饼排序
@Author: AC
2018-4-8
'''
__author__ = 'AC'
##############################################
#------------------import--------------------#
##############################################
import random
import copy
##############################################
#-... |
import logging
from rest_framework.response import Response
from rest_framework.views import exception_handler
logger = logging.getLogger(__name__)
def core_exception_handler(exc, context) -> Response: # type: ignore
logger.error(exc)
logger.error(context)
response = exception_handler(exc, context)
... |
1. CPU COMMUNICATES WITH RAM VIA THE WHAT?
Memory Bus
2. PROCESSOR GETS SPEED BOOST WHEN PROCESSOR ACCESSES NEARBY SEQUENTIAL MEMORY ADDRESSES:
Because of the cache.
3. GIVEN NUMBER 96, CONVERT INTO BINARY, THEN ADD RESULTING DIGITS IN DECIMAL. WHAT IS THE RESULT:
2
4. *TIME* COMPLEXITY OF PERFORMING MAT... |
"""Test metar_parser."""
# 3rd Party
import pytest
from pyiem.util import utc
# Local
import pywwa
from pywwa.workflows import metar_parser
from pywwa.testing import get_example_file
def test_api():
"""Test that we can load things to ignore."""
metar_parser.load_ignorelist()
metar_parser.cleandb()
me... |
import logging
import azure.functions as func
import psycopg2
import os
from datetime import datetime
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import *
def main(msg: func.ServiceBusMessage):
notification_id = int(msg.get_body().decode('utf-8'))
logging.info(
f"Py... |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.models.commondb.status.status_unit_test.py is part of The RAMSTK
# Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing Status module algorithms... |
"""Awox device scanner class"""
import asyncio
import logging
from homeassistant.core import HomeAssistant
from .awoxmeshlight import AwoxMeshLight
# import awoxmeshlight from .awoxmeshlight
from .bluetoothctl import Bluetoothctl
_LOGGER = logging.getLogger(__name__)
START_MAC_ADDRESS = "A4:C1"
class DeviceScanne... |
from amfibious.crawler import AmfibiousCrawler
from amfibious.parser import AmfibiousParser
from amfibious.amfibious_store import AmfiMongo
|
import functools
import importlib
import inspect
import json
import logging
import pprint
import sys
import threading
import time
thread_local = None
logger = logging.getLogger(__name__)
data_logger = logging.getLogger('generic_profiler_data')
WRAPPED = {None, __name__}
ENABLE_CALLER_FRAME_LOG = True
FUNC_NAME_BLACK... |
from panther_base_helpers import gsuite_details_lookup as details_lookup
def rule(event):
if event['id'].get('applicationName') != 'groups_enterprise':
return False
return bool(
details_lookup('moderator_action', ['ban_user_with_moderation'], event))
def title(event):
return 'User [{}] ... |
import json
import allure
from faker import Faker
from requests import Response
class BaseCase:
@allure.step('Get answer')
def get_answer(self, response: Response, name):
try:
response_as_dict = response.json()
except json.decoder.JSONDecodeError:
assert False, f"respo... |
import cv2
import mediapipe as mp
import os
import time
class poseDetector():
def __init__(self,mode= False, upBody =False,smooth = True,detectionCon = 0.5,trackCon=0.5):
self.mode = mode
self.upBody = upBody
self.smooth = smooth
self.d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.