text stringlengths 2 999k |
|---|
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/lib/validators.py
__version__='3.5.33'
__doc__="""Standard verifying functions used by attrmap."""
import sys, codecs
from reportlab.lib.utils import isSeq, isByte... |
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import colorsys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from measurements.name_prompt import NamePrompt
sys.path.... |
from dydx3 import Client
from web3 import Web3
from rich import print
from rich.table import Table
from dydx3.constants import API_HOST_MAINNET, POSITION_STATUS_OPEN
from connect import client
#check if can access API
marketData = client.public.get_markets().data
open_positions = client.private.get_positions(
... |
import os
import struct
import numpy as np
import theano
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
def load_mnist(path, kind='train'):
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
... |
import FWCore.ParameterSet.Config as cms
source = cms.Source("EmptySource")
from GeneratorInterface.Hydjet2Interface.hydjet2DefaultParameters_cff import *
generator = cms.EDFilter("Hydjet2GeneratorFilter",
collisionParametersRHIC200GeV,
qgpParametersRHIC,
hydjet2Parameters,
fNhsel = cms.int32(2), # Flag to incl... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 23:02:37 2019
@author: yoelr
"""
__all__ = []
from lazypkg import LazyPkg
LazyPkg(__name__, ['process_settings', 'chemicals', 'system', 'units']) |
#
# PySNMP MIB module CISCOSB-GVRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-GVRP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:22:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence, PackedSequence
from stanza.models.common.biaffine import BiaffineScorer
from stanza.models.common.hlstm import HighwayLSTM
from stanza.models.co... |
"""appart.payments URL Configuration"""
from django.urls import path, include
from rest_framework_nested import routers
from payments import api
router = routers.DefaultRouter()
router.register("service", api.ServiceViewSet, basename='Service')
router.register("service_wop", api.ServiceWithoutPagination, basename='s... |
class Solution:
# @param {integer[]} gas
# @param {integer[]} cost
# @return {integer}
def canCompleteCircuit(self, gas, cost):
if not gas:
return -1
start = 0
l = len(gas)
while start < l:
x = 0
for i in range(l):
diff ... |
# Copyright (c) 2020 Jarret Dyrbye
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php
import os
import time
import mmap
PIXEL_RECORD_BIT_SIZE = 12
BITS_PER_BYTE = 8
WIDTH = 1024
HEIGHT = 1024
class ArtDb(object):
def __init__(... |
from django.db import models
from api.users.models import User
class DailyLog(models.Model):
user = models.ForeignKey(User)
date = models.DateField(auto_now_add=True)
dream_diary = models.TextField(null=True, blank=True)
chimp_management = models.TextField(null=True, blank=True)
def __str__(sel... |
#!/usr/bin/env python
# encoding: utf-8
import io
import argparse
import logging
import string
import twitter_nlp.python.twokenize as twk
from backports import csv
from dateutil.parser import parse
from Levenshtein import jaro_winkler
from utils import import_config, set_log_config
class ScheduleMatcher(object):
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Valiant Systems and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestMembers(unittest.TestCase):
pass
|
# coding=utf-8
from mock import patch, call, MagicMock
from django.conf import settings
from django.test import TestCase
from algoliasearch_django import AlgoliaIndex
from algoliasearch_django import algolia_engine
from algoliasearch_django.models import AlgoliaIndexError
from .models import User, Website, Example
... |
"""
Django settings for Sericulture project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from dja... |
# Copyright 2001 by Gavin E. Crooks. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit test for Des"""
import unittest
from Bio.SCOP import Des
class DesTests(unittes... |
import os
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from mapgwm.obs import preprocess_obs
from mapgwm.swflows import aggregrate_values_to_stress_periods, preprocess_flows, combine_measured_estimated_values
@pytest.fixture()
def obsdata():
return pd.DataFrame({'datetime': ['2001... |
#!/usr/bin/env python
import os
from setuptools import setup
PKG_NAME = "mendeley2calibre"
author = "Nikos Koukis"
author_email = "nickkouk@gmail.com"
# Utility function to read the README file.
# Used for the long_description.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
... |
# Copyright 2016 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... |
# Copyright (c) 2010 OpenStack Foundation
#
# 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 ... |
import psutil
import datetime
def main():
print("___________________________SYSTEM INFORMATION___________________________\n")
print("############ CPU ############")
cpu_percent()
cpu_count()
cpu_freq()
print("\n############ MEMORY ############")
memory()
print("\n############ DISK #####... |
import pytest
from django.core.management import call_command, CommandError
from apps.reviews.factories import UserFactory, SelfReviewFactory, ReviewFactory
from apps.reviews.models import SelfReview, Review
def test_send_email_edgecase(running_interval, mailoutbox):
with pytest.raises(CommandError) as excinfo:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ScheduleConfigItem(object):
def __init__(self):
self._config_name = None
self._date = None
self._id = None
@property
def config_name(self):
return self._c... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... |
# --------------
# Import the required Libraries
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import calendar
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
# Generate a line chart that visualizes the readings in the months
def line_chart(df,period,... |
'''
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Outp... |
#!/usr/bin/env python
# coding: utf8
"""
This package provides tools for downloading model from network
using remote storage abstraction.
Examples:
```python
>>> provider = MyProviderImplementation()
>>> provider.get('/path/to/local/storage', params)
```
"""
from abc import ABC, abstract... |
import asposepdfcloud
from asposepdfcloud.apis.pdf_api import PdfApi
from asposepdfcloud.rest import ApiException
from pprint import pprint
pdf_api_client = asposepdfcloud.api_client.ApiClient("b125f13bf6b76ed81ee990142d841195",
"78946fb4-3bd4-4d3e-b309-f9e2ff9ac6f9")
temp_folder = ''
test_data_path=''
pdf... |
import asyncio
import signal
import logging
try:
import uvloop
except ImportError:
uvloop = None
from src.introducer import Introducer
from src.server.outbound_message import NodeType
from src.server.server import ChiaServer
from src.util.config import load_config_cli, load_config
from src.util.default_root i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `src` package."""
import pytest
import nyuki
from nyuki.geotiff_resampler import resampler
import dhash
import os
@pytest.mark.usefixtures('small_image')
@pytest.mark.parametrize("resolution", [0.12, 0.24])
def test_image_resampler(small_image, resolution... |
from print_models import make_helado as mh
mh('Chocolate', 'Grajea')
mh('Mango', 'Chocolate', 'Nueces', 'Lechera') |
# -*- coding: utf-8 -*-
"""ThreatConnect TI Email """
from tcex.tcex_ti.mappings.group.tcex_ti_group import Group
class Email(Group):
"""Unique API calls for Email API Endpoints"""
def __init__(self, tcex, name, to, from_addr, subject, body, header, owner=None, **kwargs):
"""Initialize Class Properti... |
import asyncio
import json
import logging
import re
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from discord import ActivityType, Spotify, Game, Streaming, CustomActivity, Activity, Member, User
from homeassistant.components.notify import PLATFORM_SCHEMA
from homeassistant.const impor... |
list1 = [['Akriti', 41], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39], ['Tina', 37.2]]
second_low_grades = []
|
from flask import Flask
from website.config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
from website.main.routes import main
app.register_blueprint(main)
return app |
#
# Tests for the Casadi Algebraic Solver class
#
import casadi
import pybamm
import unittest
import numpy as np
from scipy.optimize import least_squares
import tests
class TestCasadiAlgebraicSolver(unittest.TestCase):
def test_algebraic_solver_init(self):
solver = pybamm.CasadiAlgebraicSolver(tol=1e-4)
... |
#!/bin/env python
# Example program for viewing a 360 photosphere in a virtual reality headset
import os
from textwrap import dedent
import numpy
from OpenGL.GL import * # @UnusedWildImport # this comment squelches IDE warnings
from OpenGL.GL.shaders import compileShader, compileProgram
from PIL import Ima... |
"""\
wxHyperlinkCtrl widget configuration
@copyright: 2014-2016 Carsten Grohmann
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
config = {
'wxklass': 'wxHyperlinkCtrl',
'supported_by': ('wx28', 'wx3'),
'style_defs': {
'wxHL_ALIGN_LEFT': {
'desc': _('Align the... |
from rest_framework import generics, status
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .serializers import *
from .models import Transaction
from rest_framework.views import... |
from __future__ import division
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf
import numpy as np
import time
import os
import cv2
import kmodel
from utils import transparentOverlay
os.environ['KERAS_BACKEND'] = 'tensorflow'
print(tf.__version__)
config = tf.ConfigProto(log_device_... |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
import functools
from preparers import FormRecognizerPreparer
from preparers import GlobalClientPreparer as _GlobalClientPreparer
from asyn... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "django_sample.users"
verbose_name = _("Users")
def ready(self):
try:
import django_sample.users.signals # noqa F401
except ImportError:
p... |
from collections import Counter
def solution(A):
A_counter = Counter(A)
for key, value in A_counter.items():
if value % 2 != 0:
return key |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read/write functionality for JP2OpenJPEG driver.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
############... |
# -*- coding: utf-8 -*-
# Copyright © 2018 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
"""
Python API for MPS neural network backend
"""
from __future__ import print_funct... |
"""
Escreva um programa que converta uma temperatura,
digitando em graus Celsius e converta para graus Fahrenheit.
"""
celsius = int(input('Digite a temperatura: '))
fahrenheit = (celsius / 5) * 9 + 32
Kelvin = celsius + 273
print(f'A temperatura {celsius}°C em Fahrenheit é {fahrenheit}°F')
print(f'E em Kevin fica {Kel... |
# Generated by Django 3.2.4 on 2021-06-22 08:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('events', '0001_initial')... |
# """ This module will scrape match data from RIOT API then format and filter it for data analysis
# #NOTE: USE THIS MODULE ONLY FOR THE FIRST TIME YOU HAVE INSTALL THE PROGRAM OR IF YOU HAVE DELETED THE LOCAL DATA FILES
# #NOTE: DON'T FORGET TO ADD YOUR RIOT API KEY IN .env FILE
# #NOTE: PLEASE BE CAREF... |
# yapf: disable
import warnings
import numpy as np
from garage.np import (concat_tensor_dict_list, explained_variance_1d,
pad_batch_array, pad_tensor,
stack_and_pad_tensor_dict_list, stack_tensor_dict_list)
# yapf: enable
data = [
dict(obs=[1, 1, 1], act=[2, 2, 2], ... |
"""
Base/mixin classes for the spatial backend database operations and the
`SpatialRefSys` model the backend.
"""
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class BaseSpatialOperations(object):
"""
This module holds t... |
# Copyright 2016-2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
#!/usr/bin/env python3
import unittest
from helper import cheat_output
#from textreplacer import TextReplacer
# Test locally
import sys
sys.path.append('../textreplacer/')
from textreplacer import TextReplacer
class TestMarkCase2(unittest.TestCase):
def setUp(self):
patterns = [
r"^\d+$",
... |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import recipe_api
class FirebaseApi(recipe_api.RecipeApi):
"""Provides utilities to upload docs to Firebase.
This API only works on... |
#!C:\Program Files\Python25\python.exe
from os.path import abspath
from sys import prefix
from sys import argv
if len(argv) >= 2 and argv[1] == "-install":
create_shortcut(abspath(prefix + '/pythonw.exe'), 'Generates random lorem ipsum text', abspath(get_special_folder_path('CSIDL_COMMON_PROGRAMS') + '/Lorem Ipsum G... |
"""
This file offers the methods to automatically retrieve the graph odepb400.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: object_detection/protos/input_reader.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.... |
"""
pit_remove.py
Implementation of algorithm described by Planchon(2001)
Created by JL, Oct 2015
"""
import numpy
import landlab
from landlab import Component, FieldError
from landlab.grid.base import BAD_INDEX_VALUE
class PitRemove(Component):
def __init__(self, input_grid):
self._grid = input_grid
(self... |
from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, in_data, out_attributes, user_options, num_cores,
out_path):
import os
from genomicode import filelib
from genomicode import... |
from __future__ import division
from __future__ import print_function
import json
import random
import cv2
import numpy as np
from helpers import preprocessor
class FilePaths:
""" Filenames and paths to data """
fnCharList = '../model/charList.txt'
fnWordCharList = '../model/wordCharList.txt'
fnCor... |
"""Asynchronous client for the PVOutput API."""
from .models import Status, System
from .pvoutput import PVOutput
from .exceptions import (
PVOutputAuthenticationError,
PVOutputConnectionError,
PVOutputError,
PVOutputNoDataError,
)
__all__ = [
"PVOutput",
"PVOutputAuthenticationError",
"PVO... |
# -*- coding: utf-8 -*-
"""
x tools for easy work
"""
|
# -*- coding: utf-8; -*-
#
# @file __init__.py
# @brief
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2016-09-01
# @copyright Copyright (c) 2016 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
"""
coll-gate application initialisation
"""
# Application Config for startup and more...
default_app_config = ... |
import time
from unittest import mock
import pytest
from pytest import approx
from redbucket.data import RateLimit, Zone
from redbucket.in_memory import InMemoryRateLimiter
T0 = 123.4
@pytest.fixture
def mock_time(monkeypatch):
mtime = mock.Mock(name='time', wraps=time)
monkeypatch.setattr('redbucket.in_me... |
import pytest
from PJ.application import Application
__author__ = 'Max'
@pytest.fixture(scope="session", autouse=True)# run all tests in one session.
def app(request):
global fixture
fixture = Application()
request.addfinalizer(fixture.destroy)
return fixture
# ID = 1
def test_with_valid_login_and_p... |
""" Maximum Sum of a Circular Sub-array: A circular sub-array is when you connect the last element to first
We have to find sum among all sub arrays, circular and normal"""
"""Solution: """
def max_circular_sum(a) -> int:
n = len(a)
res = a[0]
for i in range(n):
curr_max = a[i]
curr_... |
#!/usr/bin/env python
import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
Arguments:
x -- A scalar or numpy array.
Return:
s -- sigmoid(x)
"""
inverse = 1+np.exp(np.negative(x))
s = 1 / inverse
return s
def sigmoid_grad(s):
"""
... |
'''
09.12 - Use the 2x16 LCD screen with the PCF8574 I2C backpack (software I2C)
This sketch shows how to display text in a 2X16 LCD display. This display uses
the PCF8574 I2C backpack instead of the native parallel connection to save on pins.
Components
----------
- ESP32
- 2x16 LCD (such as the HD44780) wi... |
# coding=utf-8
# Copyright 2019-present CNRS, Facebook Inc. and the HuggingFace Inc. team.
#
# 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 random
import numpy as np
import pandas as pd
import tensorflow as tf
import re
import time
from sklearn import preprocessing
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('num_gpus', 4, "How many GPUs to use.")
k = 10
epochs = 10000
display_step = 10
learning_rate = 0.03
batch_size = 250
trai... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import binascii
import argparse
import re
# raw_input doesn't exist in Python 3
try:
raw_input
except NameError:
raw_input = input
PROMPT_TEXT = "I agree to be careful"
WARNING_TEXT = """
USE THIS SOFTWARE AT YOUR OWN DISCRETION. THIS... |
import importlib
import numpy as np
from game import MTD_Game
from utils import *
__author__ = "Sailik Sengupta"
class Strategy:
def __init__(self, game_to_play=MTD_Game(), gamma=0.5):
self.game = game_to_play
self.DISCOUNT_FACTOR = gamma
self.lib = importlib.import_module('gurobi')
... |
__author__ = "Hangi,Kim"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
""" IBM LoadLeveler job adaptor implementation
reference for pbs job adaptor & sge job adaptor implementation
Hangi, Kim hgkim@kisti.re.kr
"""
import saga.utils.pty_shell
import saga.url as surl
import sa... |
import hashlib
import pickle
import json
import redis
import requests
from crawler import school_announcements_crawler as sac_crawler
from utils import error_code
from utils import config
from utils.config import REDIS_URL
red_string = redis.StrictRedis.from_url(
url=REDIS_URL, db=4, charset="utf-8", decode_resp... |
# coding:utf-8
import random
import string
from flanker.addresslib import address
from mock import patch
from nose.tools import assert_equal, assert_not_equal
from nose.tools import nottest
from ... import skip_if_asked
DOMAIN = '@hotmail.com'
SAMPLE_MX = 'mx0.hotmail.com'
@nottest
def mock_exchanger_lookup(arg, ... |
#!/usr/bin/python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': '',
'author': 'Christopher Woodall',
'url': '',
'download_url': '',
'author_email': 'chris@cwoodall.com',
'version': '0.1',
'install_requires': ['nose'... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... |
from graphql.language.location import SourceLocation as L
from graphql.validation.rules import UniqueInputFieldNames
from .utils import expect_fails_rule, expect_passes_rule
def duplicate_field(name, l1, l2):
return {
'message': UniqueInputFieldNames.duplicate_input_field_message(name),
'location... |
import re
import pandas as pd
import numpy as np
import os,sys, yaml, csv
import logging
logger = logging.getLogger(__name__)
from omniconverter import Converter #todoooooooooooooooo
def stata_to_statistics(study_name, input_csv, input_path, output_path, input_path_de=""):
filereader = pd.read_csv(input_csv, del... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
# -*- coding: utf-8 -*
import serial
import time
import threading
# 打开串口
ser = serial.Serial("/dev/ttyAMA0", 9600)
ser.flushInput()
def read_data():
count=ser.inWaiting()
if count:
recv=ser.read(count)
data=int(str(binascii.b2a_hex(s.read(n))))
print('recv data:',recv)
de... |
from rest_framework import status
from rest_framework.views import exception_handler as drf_exception_handler
from django.http import JsonResponse
def default_handler(exc, context):
# https://www.django-rest-framework.org/api-guide/exceptions/
# Call REST framework's default exception handler first,
# to ... |
from sys import argv
script, name = argv
quest = input("What is your quest? ")
print(f"{name} your quest is to {quest}.")
|
class Solution:
def findTilt(self, root: TreeNode) -> int:
total_tilt = 0
def valueSum(node):
nonlocal total_tilt
if not node:
return 0
left_sum = valueSum(node.left)
right_sum = valueSum(node.right)
tilt = abs(left_sum -... |
# Copyright (C) 2015 Twitter, Inc.
"""Container for all enum values used by the Ads API SDK."""
def enum(**enums):
return type('Enum', (), enums)
TRANSFORM = enum(
TIME=0,
BOOL=1,
INT=2,
LIST=3,
OBJECT=4
)
AGE_BUCKET = enum(
AGE_13_TO_24='AGE_13_TO_24',
AGE_13_TO_34='AGE_13_TO_34',... |
# Import our libs
from numpy import exp, array, random, dot
# Define our data
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
# Use our lib
random.seed(1)
# We do maths
synaptic_weights = 2 * random.random((3, 1)) - 1
for iteration in r... |
""" Pagermaid Plugins AutoReplySticker """
# ______ _
# | ___ \ | |
# | |_/ /__ _ __ | |_ __ _ ___ ___ _ __ ___
# | __/ _ \ '_ \| __/ _` |/ __/ _ \ '_ \ / _ \
# | | | __/ | | | || (_| | (_| __/ | | | __/
# \_| \___|_| |_|\__\__,_|\___\___|_| |_|\___|
#
from os import mkdir
from os.p... |
"""djangoTutorial URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... |
#!/usr/bin/env python
# import required libraries
import sys
import numpy as np
from pyrf.devices.thinkrf import WSA
from pyrf.util import read_data_and_context
from pyrf.numpy_util import compute_fft
from pyrf.connectors.twisted_async import TwistedConnector
from twisted.internet import reactor, defer
import twisted... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import subprocess
import sys
# from mpl_toolkits.mplot3d import axes3d, Axes3D
def getDefName(definition):
if definition == 1:
return "d(x,y) = max {K(x|y*),K(y|x*)} / max{K(x), K(y)}"
elif definition == 2:
retu... |
# -*- coding: utf-8 -*-
import numpy as np
import torch
from torch import nn
from kbcr.kernels import GaussianKernel
from kbcr.models import NeuralKB
from kbcr.models.reasoning import SimpleHoppy
from kbcr.reformulators import SymbolicReformulator
import pytest
@pytest.mark.light
def test_masking_v1():
nb_ent... |
import os
import sys
import traceback
from textgrid import TextGrid, IntervalTier
from aligner.corpus import load_text, parse_transcription
from aligner.g2p.generator import PhonetisaurusDictionaryGenerator
from aligner.corpus import Corpus
from aligner.models import G2PModel
from aligner.dictionary import check_bra... |
"""
Keeps a reference to a rgb and depth images (given an id). keeps data on disk or ram depending on need
date : 2017-23-03
"""
__author__ = "Mathieu Garon"
__version__ = "0.0.1"
import numpngw
import os
import numpy as np
from PIL import Image
class Frame:
def __init__(self, rgb, depth, id):
... |
from django.contrib.auth import get_user_model
from django.test import TestCase
User = get_user_model()
class BaseTestCase(TestCase):
test_user = None
test_admin = None
@classmethod
def setUpClass(cls):
super().setUpClass()
# Create usual user.
cls.password = User.objects.mak... |
visParamdB = {
'bands': ['HH', 'HV', 'HHHV_ratio'],
'min': [-20, -25, 1],
'max': [0, -5, 15],
'gamma': 1.1}
visParamPow = {
'bands': ['HH', 'HV', 'HHHV_ratio'],
'min': [0, 0, 1],
'max': [0.5, 0.15, 15],
'gamma': 1.1}
visParamRFDI = {'min':0.25, 'max':1, 'palette':['#105e1e', '#f... |
#!/usr/bin/env python
from random import randint
from naivepyrunner import Runner, QueueMode
from helloworldtask import HelloWorld
if __name__ == "__main__":
runner = Runner(mode=Runner.Mode.SHARED_QUEUE, queue_mode=QueueMode.FIFO)
for i in range(60):
runner.add_task(HelloWorld(hw=i, pause_center=rand... |
#!/usr/bin/python
# Copyright 2021 Northern.tech AS
#
# 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 ap... |
# generates a 3D maze schematic in a csv file.
# for use on command line.
# parameters are the x, y, and z dimensions of the maze and the filename.csv in that order
import sys, random, csv
# P - positive, N - negative
class Cell:
def __init__(self):
self.wallPX = True
self.wallNX = True
se... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-27 12:17
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depende... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.