content stringlengths 5 1.05M |
|---|
from django.core.management.base import BaseCommand
from django.utils import timezone
from web.tasks import Start
import os,logging
log = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Starts the crawler'
def handle(self, *args, **kwargs):
if not os.path.exists('crawler.pid'):
from web.tasks i... |
import unittest
import torch
import torchaudio.kaldi_io as kio
import common_utils
class Test_KaldiIO(unittest.TestCase):
data1 = [[1, 2, 3], [11, 12, 13], [21, 22, 23]]
data2 = [[31, 32, 33], [41, 42, 43], [51, 52, 53]]
def _test_helper(self, file_name, expected_data, fn, expected_dtype):
""" ... |
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open('README.md','r',encoding='utf-8-sig') as f:
readme = f.read()
setup(
name='pytemperature',
version='1.1',
packages=['pytemperature'],
url='https://github.com/wannaphong/pytemperature',
license='MIT',
author='Wannapho... |
# Nov 17th '19
# Time: O(n)
# Space: O(1)
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
min_a = self.min_count(A[0], A, B)
return min_a if min_a!=-1 else self.min_count(B[0], A, B)
def min_count(self, el, A, B):
"""
Number of ways to convert a... |
n = int(input("Digite um número inteiro: "))
a = b = 0
repete = False
while n > 0:
b = a
a = n % 10
n = n // 10
if b == a:
repete = True
if repete:
print("sim")
else:
print("não")
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
"""
*Bitwise Exponential*
"""
from dataclasses import dataclass
import jax.numpy as jnp
from ._operator import Exponential
__all__ = ["BitwiseExponential"]
@dataclass
class BitwiseExponential(
Exponential,
):
operator = jnp.exp2
|
# A dictionary containing the letter to digit phone keypad mappings.
KEYPAD = {
'A': '2', 'B': '2', 'C': '2', 'D': '3', 'E': '3',
'F': '3', 'G': '4', 'H': '4', 'I': '4', 'J': '5',
'K': '5', 'L': '5', 'M': '6', 'N': '6', 'O': '6',
'P': '7', 'Q': '7', 'R': '7', 'S': '7', 'T': '8',
'U': '8', 'V': '8', ... |
# Import installed packages
from flask import Flask, jsonify
# Import app code
app = Flask(__name__)
# After creating the app, so that cors can import it
from app import cors
@app.route("/api/")
def root():
return jsonify({"message": "Hello World"})
if __name__ == "__main__":
app.run(debug=True, host="0.0.0... |
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if len(data) == 0:
return 0
lo = 0
hi = len(data) - 1
while(lo < hi):
mid = lo + (hi-lo)//2
if data[mid] >= k:
hi = mid
el... |
import logging
import os
import threading
import time
class Poll(threading.Thread):
"""This class polls the YAML plugin file for changes"""
def __init__(self, EfetchPluginManager, interval=3):
self._interval = interval
self._last_timestamp = 0
self._plugin_manager = EfetchPluginManage... |
class BestModelBean():
def __init__(self, score, model_path):
self.score = score
self.model_path = model_path
class ScoreModel:
def __init__(self, name, bigger_better=True, best_num=1, description=None):
self.name = name
from collections import namedtuple
# self.best_sc... |
import argparse
import gym
import torch
from torch import nn
from torch import optim
from prl.agents import A2CAgent
from prl.callbacks import TrainingLogger, ValidationLogger
from prl.environments import Environment
from prl.function_approximators import PytorchFA
from prl.function_approximators.pytorch_nn import Po... |
#!/Users/scoffman/.virtualenvs/oldschool/bin/python
"""
let us get some cloud INFOrmation.
requires Python2.x right now
would like to add
"""
# list available environments and their status
# leverages cloudformation
import re
import os
import sys
import time
import fnmatch
import argparse
import subprocess
from glob ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
# Parameter für die Übertragungsfunktion
A0 = 1e5
f_un = 3e6
# f_3_db = f_un/A0
f_3_db = 1.2e6
wd1 = 2*np.pi*f_3_db
wd2 = 2*np.pi*4e6
GB ... |
from work.auxiliary import data_functions
import os
import cv2
import numpy as np
import shutil
import logging
from work.auxiliary import decorators
from work.segmentation.segmentation import SegmentationSingle
import matplotlib.pyplot as plt
logger = logging.getLogger(__name__)
logger_decorator = decorators.Logger_... |
# Generated by Django 3.1.1 on 2020-10-27 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('validator', '0024_auto_20200923_1532'),
]
operations = [
migrations.CreateModel(
name='Statistics',
fields=[
... |
from flask import Flask, send_file
import os
import string
# `entrypoint` is not defined in app.yaml, so App Engine will look for an app
# called `app` in this file.
app = Flask(__name__)
if __name__ == '__main__':
# This is used when running locally only.
app.run(host='127.0.0.1', port=8080, debug=True)
# F... |
import logging
import os.path as op
import os, glob
import zipfile
from time import sleep
from .pyand import ADB
from AndroidRunner.util import ConfigError
logger = logging.getLogger(__name__)
class AdbError(Exception):
"""Raised when there's an error with ADB"""
pass
class ConnectionError(Exception):
... |
"""Test that backtraces can follow cross-object tail calls"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestCrossObjectTailCalls(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.... |
import cups
from printer import Printer
class System:
def __init__(self):
self.connection = cups.Connection()
def printer(self):
if (self.connection.getDefault()):
return Printer(self.connection, self.connection.getDefault())
return None
def has_printer(self):
... |
#!/usr/bin/env python
import unittest
from ct.client.db import cert_desc
from ct.crypto import cert
CERT = cert.Certificate.from_der_file("ct/crypto/testdata/google_cert.der")
class CertificateDescriptionTest(unittest.TestCase):
def test_from_cert(self):
desc = cert_desc.CertificateDescription.from_cert(CER... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Name: FFmpeg Image Generation and Overlay
Author: Cody Hill
Date Created: April 2, 2021
Last Modified: April 2, 2021
Licensed under the GNU General Public License Version 3 (GNU GPL v3),
available at: https://www.gnu.org/licenses/gpl-3.0.txt
(C) 2021 Cody Hill
"""
... |
#!/usr/bin/env python
from typing import Callable, Generator, Iterable
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import BernoulliNB
imp... |
# down vote
def send_email(user, pwd, recipient, subject, body):
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\... |
# This sample demonstrates how to register a DXL service to receive Request
# messages and send Response messages back to an invoking client.
from __future__ import absolute_import
from __future__ import print_function
import logging
import os
import sys
from dxlclient.callbacks import RequestCallback
from dxlclient.... |
from django.conf.urls import url
from homepage import views
urlpatterns = [
url('^$', views.home, name='home_page'),
]
|
# -*- coding: utf-8 -*-
#
# test_xlsm_nwm.py
# pangaea
#
# Author : Alan D Snow, 2017.
# License: BSD 3-Clause
from os import path
from numpy.testing import assert_almost_equal
import pandas as pd
from affine import Affine
import pytest
import xarray as xr
import pangaea as pa
from .conftest import compare_proj... |
import ipaddress
from flask_redis import FlaskRedis
from redis.exceptions import LockError
from .db_utils import DBUtils
import docker
class RedisUtils:
def __init__(self, app, user_id=0):
self.redis_client = FlaskRedis(app)
self.key = 'ctfd_whale_lock-' + str(user_id)
self.lock = None
... |
# coding: utf-8
from enum import Enum
class Mark(Enum):
D = "底分型"
G = "顶分型"
class Direction(Enum):
Up = "向上"
Down = "向下"
class Freq(Enum):
F1 = "1分钟"
F5 = "5分钟"
F15 = "15分钟"
F30 = "30分钟"
F60 = "60分钟"
D = "日线"
W = "周线"
M = "月线"
class Signals(Enum):
Other = "Other~... |
import csv
import logging
from django.db import transaction
from postcode_api.models import LocalAuthority
from postcode_api.utils import ZipExtractor
log = logging.getLogger(__name__)
class LocalAuthoritiesImporter(object):
def __init__(self):
self.graph = None
def import_local_authorities(self... |
from sequana import databases
import os
import glob
import pytest
import pytest_timeout
import requests
def network_available():
try:
res = requests.request("GET", "https://github.com", timeout=5)
return True
except requests.ConnectTimeout:
return False
except err:
raise er... |
import asyncio
import messages
from downloader import BLOCK_SIZE
TIMEOUT = 30 # timeout for read operation when reading bytes
CHUNK_SIZE = 10*1024 # max threshold for bytes to read at a time
# This class represents the communication between the client and the peer.
# It follows the bittorrent protocol.
class ClientP... |
from elementtree.SimpleXMLWriter import XMLWriter
from django.http import HttpResponse
from StringIO import StringIO
def get_fail_response(message="", status=1):
result = StringIO()
xml = XMLWriter(result, 'utf-8')
xml.start("result", status=str(status), message = message)
xml.end()
return HttpResp... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from core.serializers import CustomTokenObtainPairSerializer
from core.model_views.plan_views import PlanListCreateAPIView, PlanRetrieveUpdateDestroyAPIView
TOKEN_OBTAIN_PAIR = 'token-obtain-pair'
TOKEN_REFRE... |
"""metrodeclaracion URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
+-------------------------------------------------
@Author: cc
@Contact: yaochen@xjh.com
@Site: http://www.xjh.com
@Project: sobookscrawler
@File: base_mongo_da.py
@Version:
@Time: 2019/5/23 10:22
@Description: T... |
import json
import hmac
import hashlib
import zlib
import binascii
import logging
import asyncio
import aiohttp
import config
from utils import L,D,EX,W,E
import utils
class Uploader(object):
def __init__(self, server):
self.server = server
self.limitlog = utils.NotTooOften(600)
@asyncio.cor... |
from setuptools import setup
import setup_pyjstools
import setup_pyjswidgets
__VERSION__='0.8.1'
packages=setup_pyjstools.packages+setup_pyjswidgets.packages
package_data=dict(setup_pyjstools.package_data.items()+setup_pyjswidgets.package_data.items())
entry_points=dict(setup_pyjstools.entry_points.items()+setup_pyjsw... |
# encoding: utf-8
import numpy as np
import torch
from datasets.BaseDataset import BaseDataset
import os
import cv2
class NYUv2(BaseDataset):
def __init__(self, setting, split_name, preprocess=None,
file_length=None):
super(NYUv2, self).__init__(setting, split_name, preprocess, file_length... |
class QueryBuilder(object):
def __init__(self, cube, **kwargs):
super(QueryBuilder, self).__init__()
self.cube = cube
self.path = [[] for _ in range(cube.get_dimension())]
self.precision = [0 for _ in range(cube.get_dimension())]
self.timeframe = [None, None]
if kwar... |
# Get data for the sounding
df = WyomingUpperAir.request_data(datetime(1999, 5, 3, 12), 'OUN')
# Calculate the ideal surface parcel path
sounding['profile'] = mpcalc.parcel_profile(sounding['pressure'],
sounding['temperature'][0],
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import unittest
from unittest.mock import call, create_autospec, MagicMock, Mock, patch
from hbmqtt.client import MQTTClient
from frischen.spdrl20 import (
BlockEnd, BlockStart, Counter, DistantSignal, Element, MQTTDispatcher, OuterButton, Route, Sign... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from sklearn import linear_model
first = list(map(int, str.split(input(), " ")))
m, n = first[0], first[1]
data = [list(float(x) for x in input().split()) for i in range(n)]
x = [[item[i] for i in range(m)] for item in data]
y = [item[-1] for item... |
# -*- coding: utf-8 -*-
import wx
import ukbiobank
class M_AM_B(wx.Frame, ukbiobank.ukbio):
pass
class SelectVariablesFrame(wx.Frame, ukbiobank.ukbio):
__metaclass__ = M_AM_B
def __init__(self, parent, ukb):
super().__init__(parent=parent, title="UKBiobank-tools checkbox")
panel = wx.... |
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
# Create your views here.
from django.views.decorators.cache import cache_page
from services.about.about_service import AboutService
@cache_page(300)
def index(request):
return render(request, 'photo/index.html')
|
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import ctypes
from .base import SMLM
import numpy as np
import numpy.ctypeslib as ctl
class PostProcess:
def __init__(self, smlmlib):
self.lib = smlmlib
# CDLL_EXPORT void NearestNeighborDriftEstimate(const Vector3f * xyI, const int *spotFrameNum,... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
# You can run this module directly with:
# twistd -ny emailserver.tac
"""
A toy email server.
"""
from __future__ import print_function
from zope.interface import implementer
from twisted.internet import defer
from twisted.mail import smtp
f... |
from django.urls import path
from . import views
app_name = "rooms"
urlpatterns = [
path("<int:pk>", views.room_detail, name="detail")
] |
import subprocess
if __name__ == '__main__':
subprocess.Popen(["python", "main.py", "--mode", "train", "--game", "hexus", "--board_level", "\"#EB00A2\""], shell=False)
subprocess.Popen(["python", "main.py", "--mode", "train", "--game", "hexus", "--board_level", "\"#0D2EFF\""], shell=False)
subprocess.Popen... |
"""
Library folder for implementations of the `presalytics.story.components.WidgetBase` class
"""
|
"""
An imperative-looking notation for Effectful code.
See :func:`do`.
"""
from __future__ import print_function
import sys
import types
from . import Effect, Func
from ._utils import wraps
def do(f):
"""
A decorator which allows you to use ``do`` notation in your functions, for
imperative-looking co... |
import typing
import sys
import math
def solve(n: int, s: int, k: int) -> typing.NoReturn:
g = math.gcd(n, k)
if s % g:
print(-1)
return
s //= g
k //= g
n //= g
x = pow(k, -1, n)
c = -s * x % n
print(c)
def main() -> typing.NoReturn:
t = int(input())
for _ in range(t):
n, s, k ... |
import os
import re
class HTMLTestMixin:
def check_link_for_symbol(self, html, pairs):
"""make sure that in the html source, the given symbols has expected links around it"""
for symbol, expected_link in pairs:
self.assertEqual(link_for_text(html, symbol), expected_link)
def link_for_... |
from .jsonb import * # NOQA
|
print('====== DESAFIO 78 ======')
lista = list()
cont = 0
for c in range(1,3):
lista.append(int(input('Digite um número: ')))
print(f'O maior número digitado foi: {max(lista)} na posição {lista.index(max(lista))}')
print(f'O menor número digitado foi: {min(lista)} na posição {lista.index(min(lista))}') |
from app import app
from flask import request, jsonify, render_template
from app.engine.rank import get_top_docs as gtp
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/result", methods=["GET", "POST"])
def result():
# query = request.args.get('q')
# algo = request... |
#FARENHEIT PARA CELSIUS
#DESAFIO 08
print('DESAFIO 08')
farenheit = float(input('Digite a temperatura em farenheit: '))
celsius = 5/9 * (farenheit - 32 )
print('A sua temperatura em farenheit é {}° para celsius é {:.2f}°C'.format(farenheit,celsius))
|
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
from collections import OrderedDict
from typing import Dict, List, Union
from enum import Enum
class ConfigBaseMeta(type):
def annotations_and_defaults(cls):
annotations = OrderedDict()
defaults = {}
for base i... |
# -*- coding: utf-8 -*-
'''
:codauthor: :email:`Mike Place <mp@saltstack.com>`
'''
# Import Python libs
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../... |
import subprocess
import sys
import os
import math
# This code is meant to manage running multiple instances of my KMCLib codes at the same time,
# in the name of time efficiency
resultDir = os.environ.get('RESULTS')
if resultDir == None :
print ("WARNING! $RESULTS not set! Attempt to write results will fail!\n")
... |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2017, ARM Limited and contributors.
#
# 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
#
# ... |
import sys
import os
__all__ = []
__version__ = '0.0.1'
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.' + '/CryptoVinaigrette'))) |
"""
Nudge Position
==============
Position adjustments determine how to arrange geoms that would otherwise
occupy the same space.
``position_nudge()`` is generally useful for adjusting the position of
items on discrete scales by a small amount.
See
`position_nudge() <https://jetbrains.github.io/... |
from tir import Webapp
import unittest
class TMSA330(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGATMS','06/11/2020','T1','M SP 03 ','43')
inst.oHelper.Program('TMSA330')
inst.oHelper.AddParameter("MV_CDHISAP", "", "0... |
import io
from minio import Minio
from connectors.storageABC import __StorageABC
from connectors.util import pack_obj, unpack_obj
class MinIOConnector(__StorageABC):
'Connect to MinIO'
def __init__(self, url, secret):
'init MinIO connector'
## check args
value_error = ValueError(... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root):
def get_paths(node, prev):
# build the result partially... |
# This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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 rights to use, copy, ... |
"""
Sets the downlink status for an ASDP
"""
import os.path as op
import argparse
import logging
from jewel.asdpdb import (
ASDPDB, DownlinkStatus,
)
from utils import logger as OWLSlogger
def set_downlink_status(dbfile, asdpid, status):
logger.info('Loading ASDPDB...')
asdpdb = ASDPDB(dbfile)
asdpdb.... |
# -*- coding: utf-8 -*-
import json
import sys
import subprocess
import time
import threading
import requests
from datetime import datetime
import config_api
from alert import GuardianAlert, AlertException
# TODO:
# from contacts import contacts
import spark_checker
# TODO:
# start application concurrently
def ... |
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
from bacon.all import *
|
from flask import Flask, render_template, Markup, redirect, url_for, flash
import os
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'secret string')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
user = {
'username': 'Miracle Wong',
'bio': 'A boy who loves moives and music... |
# Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ri... |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import List, Generic, NamedTuple, TypeVar
_INPUT = TypeVar('_INPUT', tuple)
_OUTPUT = TypeVar('_OUTPUT', tuple)
class Network(Generic[_INPUT, _OUTPUT]):
def __init__(self, layers: List[Layer]):
self.layers = layers
self.ross = N... |
import itertools
import pytest
import torch
import pytorch_testing_utils as ptu
from .marks import skip_if_cuda_not_available
def test_assert_tensor_dtype_equal(subtests):
dtypes = (
torch.float32,
torch.float64,
torch.float16,
torch.uint8,
torch.int8,
torch.int1... |
"""
Parameters for reading and plotting thermal flux
"""
import os
import yaml
import pprint
from copy import deepcopy
from .default import default_parameters
class Parameters:
def __init__(self, par_set=None):
if par_set is not None:
self.set(par_set)
else:
self.set(defaul... |
# Generated by Django 3.0.1 on 2020-01-12 23:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Hashtag',
fie... |
# Generated by Django 3.2.5 on 2021-07-27 12:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mentorhome', '0003_trainer_trainer_photo'),
]
operations = [
migrations.DeleteModel(
name='Course',
),
]
|
# Generated by Django 3.1.5 on 2021-01-22 09:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("trucks", "0003_auto_20210121_1053"),
]
operations = [
migrations.AddField(
model_name="truck",
name="city",
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 5 10:52:46 2021
@author: SethHarden
"""
class Solution:
def totalNQueens(n):
def is_not_under_attack(row, col):
return not (rows[col] or hill[row - col] or dale[row + col])
def place_queen(row, col):
rows[col] = 1
... |
# -*- coding: utf-8 -*-
# from mmvae_hub.hyperopt.search_spaces.base_search_spaces import base_search_spaces
from sklearn.model_selection import ParameterGrid
from mmvae_hub.hyperopt.search_spaces.search_spaces import *
from mmvae_hub.leomed_utils.launch_jobs import launch_leomed_jobs
# for search_space in [sp_iwmopg... |
#!/usr/bin/env python3
import asyncio
import logging
import os
import sys
# from dotenv import load_dotenv
from pprint import pprint
from urllib.parse import urlparse
from sqlalchemy import func
from botcommands.poll_results import get_poll_result
from botcommands.jokes import get_joke
from botcommands.tldr import ge... |
from django.db.models.query import Prefetch
from guardian.core import ObjectPermissionChecker
class ObjectPermissionCheckerViewSetMixin:
"""add a ObjectPermissionChecker based on the accessing user to the serializer context."""
def get_serializer_context(self):
context = super().get_serializer_contex... |
import pytest
pytestmark = pytest.mark.django_db
def test_is_blocked_filter_lookup_choices(is_blocked_filter):
is_blocked_lookup_choices = is_blocked_filter.lookup_choices
assert is_blocked_lookup_choices == [('1', 'Yes'), ('0', 'No')]
def test_is_blocked_filter_get_non_blocked_users(request_mock, is_bloc... |
from kivymd.uix.toolbar import MDToolbar
from kivy.clock import Clock
class Toolbar(MDToolbar):
def __init__(self,**kw):
super(Toolbar,self).__init__(**kw)
Clock.schedule_once(self.ui)
def ui(self,*a):
self.ids.label_title.markup=True
self.ids.label_title.font_name='fonts/title' |
from __future__ import annotations
from enum import Enum
from json.decoder import JSONDecodeError
from typing import Any
from requests import Session
from ikea_api.constants import Constants
from ikea_api.errors import GraphqlError, IkeaApiError, UnauthorizedError
class Method(Enum):
POST = "POST"
GET = "G... |
from django import forms
from .models import *
class LocationForm(forms.ModelForm):
class Meta:
model = Location
fields = '__all__'
class DeviceTypeForm(forms.ModelForm):
class Meta:
model = DeviceType
fields = '__all__'
class DeviceForm(forms.ModelForm):
class Meta:
... |
import smart_imports
smart_imports.all()
@dext_jinja2.jinjaglobal
def sorted_recipients(recipients_ids, accounts):
recipients = [accounts[recipient_id] for recipient_id in recipients_ids]
recipients.sort(key=lambda account: account.nick_verbose)
return recipients
@dext_jinja2.jinjaglobal
def new_messa... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import torch
import random
from frameworks.evaluating.base import BaseEvaluator
from tqdm import tqdm
import pickle
class FrameEvaluator(BaseEvaluator)... |
import radforest
def test_sphere():
"""There should be real test here"""
assert 1 == 1 |
"""
Definition of forms.
"""
import uuid
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from ckeditor.widgets import CKEditorWidget
from blog.models import BlogPost, MediaItem, Profile
from django.contrib.auth.forms import User... |
import numpy as np
import logging
def accuracy(y_real, y_pred):
y_real = np.array(y_real)
y_pred = y_pred.argmax(axis=1)
out = sum(y_real == y_pred) / len(y_real)
baseline = sum(y_real == np.random.choice(y_real, size=len(y_real), replace=True)) / len(y_real)
logging.debug("ACCURACY: " + str(round... |
#!/usr/bin/env python3
"""
Class to organize and extract data from an fMRI settings file.
Created 8/20/2020 by Benjamin Velie.
veliebm@gmail.com
"""
from pathlib import Path
from copy import deepcopy
class Settings():
"""
Class to organize data extracted from an fMRI settings file.
Parameters
--... |
default_app_config = 'dual_rocks.web.apps.WebConfig'
|
from cocotask import CocoBaseWorker
import time
class TestWorker(CocoBaseWorker):
def process(self, body):
print(self._config["MQ_TYPE"])
print("Test Action: [%d] Received %r" % (self._seq, body))
time.sleep(5)
print("Test Action: [%d] Done" % self._seq)
|
"""
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Status: Accepted (Your runtime b... |
"""
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://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompan... |
from aws_cdk import core as cdk
from aws_cdk import aws_iam as iam
from aws_cdk import aws_eks as eks
from aws_cdk import aws_ec2 as ec2
import yaml
class K8SContainerStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kw... |
from collections import defaultdict
from aocd.models import Puzzle
def solve_puzzle_one(input_array):
counter, ingredients, allergens, possible_allergens = get_data(input_array)
c = 0
for i in ingredients:
if not possible_allergens[i]:
c += counter[i]
print(c)
def get_data(inpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.