content
stringlengths
0
894k
type
stringclasses
2 values
version = "1.0.0a"
python
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import connection from django.db import IntegrityError from django.utils.text import slugify from django.http import HttpResponse, JsonResponse from build.management.commands.base_build import Command as B...
python
from dataclasses import dataclass @dataclass class FileContent: content: str
python
from itertools import product from .constraints import Validator def all_cut_edge_flips(partition): for edge, index in product(partition.cut_edges, (0, 1)): yield {edge[index]: partition.assignment[edge[1 - index]]} def all_valid_states_one_flip_away(partition, constraints): """Generates all valid ...
python
from ..lab2.TreeNode import TreeNode from ..lab1.Type import Type from ..lab1.Token import Token from ..lab1.Tag import Tag from ..lab2.NodeType import NodeType from TypeException import TypeException from SemanticException import SemanticException class SemanticAnalyzer(object): def __init__(self, symbol_table, ...
python
#!/usr/bin/env python3 -u """ Main Script for training and testing """ import argparse import json import logging import os import pdb import random import sys import time as t from collections import OrderedDict import numpy as np import spacy import torch from torch import nn from torch.optim.lr_scheduler import Red...
python
# Demonstration showing plot of the 5 stations with the highest relative water levels as well as their best fit polynomials import matplotlib.pyplot as plt import matplotlib from datetime import datetime, timedelta from floodsystem.station import MonitoringStation from floodsystem.plot import plot_water_level_with_fit...
python
from sanic import Sanic from sanic_cors import CORS app = Sanic(__name__) CORS(app)
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from progress.bar import ChargingBar from scipy import linalg as LA from .base import ComputationInterface # noinspection PyUnr...
python
from .. import db class Enrollment(db.Model): ''' Model handling the association between a user and the courses they are enrolled in in a many-to-many relationship, with some added data ''' __tablename__ = 'user_courses' user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) course_id ...
python
import sys import os # in order to get __main__ to work, we follow: https://stackoverflow.com/questions/16981921/relative-imports-in-python-3 PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SC...
python
import argparse import sys from typing import Tuple from bxcommon.models.blockchain_peer_info import BlockchainPeerInfo from bxcommon.models.blockchain_protocol import BlockchainProtocol from bxcommon.utils.blockchain_utils.eth import eth_common_constants from bxgateway import log_messages from bxutils import logging ...
python
from setuptools import setup, find_namespace_packages with open("README.md", "r") as fh: long_description = fh.read() setup(name='s3a_decorrelation_toolbox', version='0.2.9', description='Decorrelation algorithm and toolbox for diffuse sound objects and general upmix', long_description=long_desc...
python
# Creative Commons Legal Code # # CC0 1.0 Universal # # CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE # LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN # ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS # INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMON...
python
# BLACK = \033[0;30m # RED = \033[0;31m # GREEN = \033[0;32m # BROWN = \033[0;33m # BLUE = \033[0;34m # PURPLE = \033[0;35m # CYAN = \033[0;36m # YELLOW = \033[1;33m # BOLD = \033[1m # FAINT = \033[2m # ITALIC = \033[3m # UNDERLINE = \033[4m # BLINK = \033[5m # NEGATIVE = \033[7m # CROSSED = \033[9m # END = \033[0m def...
python
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('ct', '0002_auto_20141110_1820'), ] operations = [ migrations.AlterField( model_name='conceptlink', name='relationship', field=models.CharField(default='d...
python
from pytest import mark from ..crunch import crunch @mark.parametrize( "description,uncrunched,crunched", [ ["number primitive", 0, [0]], ["boolean primitive", True, [True]], ["string primitive", "string", ["string"]], ["empty array", [], [[]]], ["single-item array", [...
python
import os path = os.path.dirname(__file__) def get(resource): return os.path.join(path, resource).replace('\\', '/')
python
# Copyright 2021 Adobe. All rights reserved. # This file is licensed to you 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...
python
import os import tempfile from contextlib import contextmanager from collections import OrderedDict from neupy import plots, layers, algorithms from neupy.plots.layer_structure import exclude_layer_from_graph from base import BaseTestCase @contextmanager def reproducible_mktemp(): name = tempfile.mktemp() r...
python
"""Wrapper of the multiprocessing module for multi-GPU training.""" # To avoid duplicating the graph structure for node classification or link prediction # training we recommend using fork() rather than spawn() for multiple GPU training. # However, we need to work around https://github.com/pytorch/pytorch/issues/17199...
python
""" payload_generators.py Copyright 2007 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the ho...
python
from django.http import JsonResponse from django.views.generic.edit import FormView from .forms import ( UploadAttachmentForm, DeleteAttachmentForm ) class FileUploadView(FormView): """Provide a way to show and handle uploaded files in a request.""" form_class = UploadAttachmentForm def upload_file(...
python
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """CSSubmissionCable model""" from __future__ import absolute_import, unicode_literals from datetime import datetime from peewee import DateTimeField, ForeignKeyField from playhouse.fields import ManyToManyField from .base import BaseModel from .challenge_binary_node ...
python
import functools import gc import os import sys import traceback import warnings def is_in_ipython(): "Is the code running in the ipython environment (jupyter including)" program_name = os.path.basename(os.getenv('_', '')) if ('jupyter-notebook' in program_name or # jupyter-notebook 'ipytho...
python
import collections import math import numbers import numpy as np from .. import base from .. import optim from .. import utils __all__ = [ 'LinearRegression', 'LogisticRegression' ] class GLM: """Generalized Linear Model. Parameters: optimizer (optim.Optimizer): The sequential optimizer u...
python
import sys import os import re import shutil import tempfile import subprocess from distutils import dir_util from typing import Any, List, Mapping, Set import pathspec REPLACE_PATTERN = re.compile(r"#\[(\w+)\]#") HELP = """ Usage: netbeansify <input directory> [options] Available Options: --help ...
python
from __future__ import annotations import pathlib from contextlib import contextmanager from typing import Any, Iterable, Iterator, Union from alembic import command from alembic.config import Config from dcp import Storage from dcp.storage.base import DatabaseStorageClass from sqlalchemy.engine import Result from sq...
python
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython """ from random import randint # pip install prototools from prototools import int_input, text_align, textbox from prototools.colorize import * LIMITE, MIN, MAX, intentos = 5, 1, 10, 0 NUMERO_ALEATORIO = randint(MIN, MAX) textbox( cyan("ADIVINA EL NUME...
python
# -*- coding:utf-8 -*- from xml.dom import minidom from xlrd import open_workbook import json import re jdict = {} axls = open_workbook('student.xls') sheet1 = axls.sheet_by_name('student') for i in range(3): sign = str(sheet1.cell(i,0).value) jdict[sign] = [] for j in range(1,5): if j...
python
import os import pytest from analyzer.ResultsCollector.PytestResults import PytestResult pytest_version = 'pytest-6.2.5' @pytest.fixture(scope='module') def data(data_dir): return os.path.join(data_dir, 'PytestResults') @pytest.fixture(scope='module') def happy_day(data): with open(os.path.join(data, 'hap...
python
# -*- coding: utf-8 -*- import plotly.graph_objs as go def draw(x1, y1, x2, y2, x3, y3, safety_factor, flag=None, x4=None, y4=None, x5=None, y5=None, x6=None, y6=None, x7=None, y7=None, x8=None, y8=None, x9=None, y...
python
''' Created on 24 Nov 2015 @author: wnm24546 ''' from scipy.constants import c, h, k, pi from scipy.optimize import curve_fit from collections import OrderedDict import numpy as np from Lucky.LuckyExceptions import BadModelStateException #k is kb class CalculationService(object): def __init__(self, pp): ...
python
from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User from .models import Employee, CostCenter, Unity class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSe...
python
import numpy as np import astropy.constants as cst import astropy.units as u def blackbody(wave, T): ''' Blacbody function Parameters ---------- wave : float Wavelength(s) in micron T : float Temperature in Kelvin Results ------- bb_spectrum : float Black...
python
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. import json import sys import re import traceback from os.path import expanduser import os import urllib from uforge.objects.uforge import * im...
python
import argparse import yaml from train_eval.evaluator import Evaluator import os # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", help="Config file with dataset parameters", required=True) parser.add_argument("-r", "--data_root", help="Root directory with data", required=True)...
python
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from users.models import super_table, teacher_table, student_table from users.serializers import SuperSerializer, TeacherSerializer, Stude...
python
"""Represents a tether from one actor to another""" from nari.types.event.base import Event from nari.types.actor import Actor from nari.types.event import Type class NetworkTether(Event): """Network tether event""" __id__ = Type.networktether.value def handle_params(self): self.source_actor = Act...
python
from flask import Flask, Blueprint, request from flask_bcrypt import Bcrypt from flask_cors import CORS from api.models import db from api.email import mail import os app = Flask(__name__) CORS(app) app.config.from_object(os.environ["APP_SETTINGS"]) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(...
python
from tkinter import * from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfilename from os.path import basename from tkinter.messagebox import askokcancel, askyesno from tkinter import PhotoImage # functions = Functions() class Frontend(): activefile = 'unactive' def __ini...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create COMSOL compatible color encodings for the CET perceptually uniform colour maps available at: http://peterkovesi.com/projects/colourmaps/ To install to COMSOL, copy the unzipped tsv files to the comsol\data\colormap directory Works at least for COMSOL 4.2a. Cre...
python
import ipaddress import os.path from unittest import TestCase from unittest.mock import MagicMock, patch from parameterized import parameterized from salt.exceptions import CommandExecutionError import yaml import metalk8s_network from tests.unit import mixins from tests.unit import utils YAML_TESTS_FILE = os.path...
python
import torch.nn as nn from .losses import get_loss from ..architectures import get_backbone from .wrapper import Wrapper class SimpleClassifierWrapper(Wrapper): def __init__(self, wrapper_config): super().__init__() self.backbone = None self.classifier = None self._init_modules(wra...
python
# -*- coding: utf-8 -*- # # Project: silx (originally pyFAI) # https://github.com/silx-kit/silx # # Copyright (C) 2012-2017 European Synchrotron Radiation Facility, Grenoble, France # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docume...
python
#!/usr/bin/env python3 import random def emit_test_one(max_len_list,len_cmd_min,len_cmd_max,no_exception): header = ''' #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "DoublyLinkedList.h" #include <list> #include <stdexcept> using namespace std; ''' ''' Test cases ...
python
import numpy as np from tqdm import tqdm LOOP_SIZE = 10000000 SEED = [0, 1, 0] def monty_hall(typed): doors = SEED np.random.shuffle(doors) opted_3 = np.random.randint(0, 3) if not typed: result = doors[opted_3] return result else: for i in range(3): if i != o...
python
CARDINALITA = 10 lista_numeri = [] somma = 0.0 contatore = 0 while contatore < CARDINALITA: numero = input('inserisci un numero ') print "iterazione ", contatore lista_numeri += [numero] somma += float(numero) contatore += 1 media = somma / CARDINALITA varianza2 = 0.0 contatore = 0 while contato...
python
from utils import test_execution COUNT = 8000 @test_execution('with context manager') def with_context_manager(): def runner(): for _ in range(COUNT): with open('test.txt', 'r') as file: content = file.read() return runner @test_execution('without context manager') def ...
python
import tensorflow as tf import cv2 import numpy as np IMG_SIZE=(224,224) Model=tf.keras.models.load_model ('Ensamble_Model(Ori).h5') path='C:/Users/mariotiara/Desktop/GUI/Sampel/ffc04fed30e6_(0)_Normal.jpeg' img=tf.keras.preprocessing.image.load_img(path,target_size=IMG_SIZE) x = tf.keras.preprocessing.i...
python
#!/usr/bin/env python __all__=['configstruc', 'loadpdb', 'loadstruc', 'molecule', 'protein', 'ligand', 'lipid'] from loadstruc import (FetchPDB, Loadstruc)
python
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # 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 applic...
python
import argparse as ag import ast import csv import datetime from ebooklib import epub import feedparser import json import logging from termcolor import colored logging.basicConfig(filename='logs.log', level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - ' '%(me...
python
# ---------------------------------------------------------------------------- # meh # Copyright (c) 2021 TreeCaptcha # # 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, in...
python
# -*- coding: utf-8 -*- # Copyright 2011 Fanficdownloader 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 # # Unless require...
python
from collections import namedtuple import csv import gzip from os.path import abspath, join import subprocess from growser.app import db, log from growser.db import from_sqlalchemy_table from growser.models import Recommendation from growser.cmdr import DomainEvent, Handles from growser.commands.recommendations impor...
python
# 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, software # distributed under t...
python
from json import decoder, loads from os import getenv from re import findall, search from nfu.expand_bus.network import http_get from nfu.expand_bus.ticket import get_alipay_url from nfu.nfu_error import NFUError def get_bus_schedule(route_id: int, date: list) -> dict: """ 若日期在车票预售期内,获取班车时刻表。 - 字段说明 ...
python
import os import sys import argparse import requests import flask import json import re import yaml import shutil import mmh3 from munch import Munch, munchify from flask import render_template, redirect, url_for, send_from_directory from markupsafe import escape def log(*args, **kwargs): print(*args, **kwargs, ...
python
from .models import Electricity from django.http import HttpResponse from django.utils import timezone from django.views.generic import View import datetime import json class get_json(View): """ Returns list of timestamp-consumption pairs. """ def get(self, request, *args, **kwargs): time_start = tim...
python
# utility packages import os from tqdm import tqdm import csv # math and support packages from scipy import ndimage import numpy as np import pandas as pd # image processing packages import cv2 import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split from random import shuff...
python
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Modifications made by Cloudera are: # Copyright (c) 2016 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A cop...
python
import CollectionsManager from UserController.UserCommand import UserCommandClass # ==================================== UserCommandAddNewDuck Class =================================# class UserCommandAddNewDuck(UserCommandClass): component = None component_index = 0 component_selected = None ...
python
import numpy as np import ctypes as C import cv2 libmog = C.cdll.LoadLibrary('libmog2.so') def getfg(img): (rows, cols) = (img.shape[0], img.shape[1]) res = np.zeros(dtype=np.uint8, shape=(rows, cols)) libmog.getfg(img.shape[0], img.shape[1], img.ctypes.data_as(C.POINTER(C.c_ubyte))...
python
# coding: utf-8 """ Camunda BPM REST API OpenApi Spec for Camunda BPM REST API. # noqa: E501 The version of the OpenAPI document: 7.13.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from openapi_client.configuration import Configuration clas...
python
import multiprocessing import time from functools import wraps def logging_decorator(f): @wraps(f) def wrapper(*args, **kwds): print('Entering decorator') result=f(*args, **kwds) print('Exiting decorator') return result return wrapper @logging_decorator def compute_squares(number):...
python
from setuptools import setup setup( name='nlzss', author='magical', license='MIT', packages=['nlzss'] )
python
# coding: utf-8 #!/usr/bin/python import sys, getopt, time import operator import pickle import numpy as np #for euclidean distance import pandas as pd # to read the actual dataset from numpy import zeros, sum as np_sum, add as np_add, concatenate, repeat as np_repeat, array, float32 as REAL, empty, ones, memmap ...
python
# # PySNMP MIB module ELTEX-MES-eltMacNotification-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-eltMacNotification-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:47:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pyt...
python
from abc import ABC class AbstractDiscriminantStrategy(ABC): def calculate_discriminant(self, a, b, c): pass
python
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # 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 applicabl...
python
import pandas as pd import numpy as np UTIL_SCORING = {'player': { 'assists': 2, 'kills': 3, 'deaths': -1, 'total cs': 0.02, # 'games_not_played': 20 }, ...
python
""" Business logic for the orchestration operations. """ from http import HTTPStatus import bson import requests from shipyard_cli.errors import StatusError class CraneService(): """Service for orchestration operations.""" def __init__(self, url: str, port: str): self.base_url = url + ':' + port ...
python
# -*- coding: utf-8 -*- """ Created on Tue Aug 21 16:20:46 2018 @author: Arvinder Shinh """ import tensorflow as tf from tensorflow import saved_model as sm import DevnagriLipiDataGenerator import DevnagriLipiDataVerifier SerializedImgContainer, Labels = DevnagriLipiDataGenerator.DevnagriData() Classfy_Inputs=tf.p...
python
from . import settings from django.conf import settings from django.core.exceptions import ObjectDoesNotExist if hasattr(settings, 'SALES_MODEL_FROM') and hasattr(settings, 'SALES_MODEL_IMPORT'): User = getattr(__import__(settings.SALES_MODEL_FROM, fromlist=[settings.SALES_MODEL_IMPORT]), settings.SALES_MODEL_IMPO...
python
from datetime import datetime from unittest import TestCase import jsons from jsons import DeserializationError class TestPrimitive(TestCase): def test_dump_str(self): self.assertEqual('some string', jsons.dump('some string')) def test_dump_int(self): self.assertEqual(123, jsons.dump(123)) ...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 Tong LI <tongli.bioinfo@protonmail.com> # # Distributed under terms of the BSD-3 license. """ """ import fire from zarr import consolidate_metadata from pathlib import Path import zarr def main(file_in): stem = Path(file_in).st...
python
# coding=utf-8 # Copyright 2018 The TensorFlow Datasets Authors. # # 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 appl...
python
# coding: utf-8 ########################################################################## # NSAp - Copyright (C) CEA, 2019 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for det...
python
import codecs import numpy as np import copy import time import random import json import multiprocessing import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import os import joblib entities2id = {} relations2id = {} relation_tph = {} relation_hpt = {} ...
python
# -*- coding: utf-8 -*- # encoding: utf-8 # /run.py """ Tic-Toc-Tpe API ------------------------------------------------------------------------ App for production ------------------------------------------------------------------------ """ import os ...
python
from Tkinter import * root = Tk() root.title("kaki") root.resizable(0,0) points = [] tag = "line" c = Canvas(root, bg="white", width=1280, height= 720) def make_dot(x, y, xmax, ymax): dot = c.create_oval(x, y, xmax, ymax, fill="black") def point(event): x = event.x - 2 y = event.y - 2 o = 4 do...
python
# # Catalog creation history: # # catalog creation requires one to set the RESULTS_VERS environment variable to the correct reduction # # DR11 catalog created using 'python make_rcsample.py -o /work/bovy/data/bovy/apogee/apogee-rc-DR11.fits --addl-logg-cut --rmdups' # rmdups was added after the fact because this option...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-09-15 09:15 from django.db import migrations, models import django.db.models.deletion import wagtail.core.models class Migration(migrations.Migration): dependencies = [ ("wagtailcore", "0028_merge"), ("torchbox", "0067_auto_20160906_16...
python
n=int(input('no of primes to be generated : ')) counter=0 n1=2 while True: is_prime=True for i in range(2,n1//2+1): if n1%i==0: is_prime=False break if is_prime==True: print(n1) counter=counter+1 if counter==n: break n1=n1+1
python
# -*- encoding: utf-8 -*- """Main application window Contains : - menubar with File, Edit - statusbar displaying cursor position on the scene - NodeEditorWidget instance containing a graphics view and the scene """ import os import json from PyQt5.QtWidgets import QMainWindow, QAction, QFileDialog, QLabel,...
python
import dgl import networkx as nx # create a graph g_nx = nx.petersen_graph() g_dgl = dgl.DGLGraph(g_nx) import matplotlib.pyplot as plt plt.subplot(121) nx.draw(g_nx, with_labels=True) plt.subplot(122) nx.draw(g_dgl.to_networkx(), with_labels=True) plt.show() # add edges and nodes into graph import dgl import torc...
python
#!/usr/bin/env python3 import base64 import sys from pprint import pformat from nullroute.irc import Frame class SaslMechanism(object): def __init__(self): self.step = 0 self.inbuf = b"" def do_step(self, inbuf): return None def feed_input(self, inbuf): self.inbuf += inbuf...
python
"""Config flow for nVent RAYCHEM SENZ.""" import logging from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN class OAuth2FlowHandler( config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN ): """Config flow to handle SENZ OAuth2 authentication.""" DOMAIN = DO...
python
# -*- encoding: utf-8 -*- # # Copyright 2012 Martin Zimmermann <info@posativ.org>. All rights reserved. # License: BSD Style, 2 clauses -- see LICENSE. # # Provide a homogenous interface to Templating Engines like Jinja2 import abc class AbstractEnvironment(object): """Generic interface for python templating eng...
python
import pandas as pd import torch def get_covariates(cov_name, split): """ get a list of strutured covariates as a pytorch tensor split by train/val/test input: - cov_name = 'Male' - split = 'train', 'val' or 'test' Here we're mostly interested in gender so our covaraite is male...
python
# -*- coding: utf-8 -*- """ Defines the unit tests for the :mod:`colour.plotting.section` module. """ import unittest from matplotlib.pyplot import Axes, Figure from colour.geometry import primitive_cube from colour.models import RGB_COLOURSPACE_sRGB, RGB_to_XYZ from colour.plotting import (plot_visible_spectrum_sect...
python
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^dashboard$', views.dashboard, name="dashboard"), url(r'^properties$', views.properties, name="properties"), url(r'^add_property$', views.add_property, name="add_property"), ...
python
import sys import os import cv2 images_path = sys.argv[1] thumbnail_size = 300 thumbnails_path = os.path.join(images_path, "thumbnails") event_name = os.path.basename(images_path) if not os.path.isdir(thumbnails_path): os.mkdir(thumbnails_path) images = os.listdir(images_path) yml_line = "gallery:\n" for ind,...
python
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder)==0: return None tn=TreeNode(preorder[0]) l=[] r=[] for i in preorder: if i<preorder[0]: l.append(i) elif i>preorder[0]: ...
python
from onboarding_project.celery import app from squad_pantry_app.models import PerformanceMetrics @app.task def calc_performance_metrics(): PerformanceMetrics.create_avg_performance_metrics()
python
""" Creates components from JSON files. This provides an easy way for adding custom components without mucking around with blenders API. Of course, for more advanced tools it is necessary to create more complex UI's, but if you just want a component with a couple twiddleable numbers, bools and vecs, a JSON component ca...
python
#!/usr/bin/env python3 import os import re import sys import errno import subprocess import json import glob IMPORTPREFIX="github.com/kentik/" REPOROOT=os.path.basename(os.getcwd()) SRCDIR="staging" TGTDIR="proto_go" PACKAGE="^(package .*);" # # Attributes pertinent to building the go code to serve proto types # f...
python
#!/usr/bin/env python3 import sys import time import automationhat time.sleep(0.1) # Short pause after ads1015 class creation recommended try: from PIL import Image, ImageFont, ImageDraw except ImportError: print("""This example requires PIL. Install with: sudo apt install python{v}-pil """.format(v="" if sy...
python
"""Application credentials platform for the Honeywell Lyric integration.""" from homeassistant.components.application_credentials import ( AuthorizationServer, ClientCredential, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from .api import LyricLoca...
python