content
stringlengths
0
894k
type
stringclasses
2 values
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """ Read Signature Test - All this does is read the signature from the chip to check connectivity! """ import board import busio import pwmio import adafruit_avrprog spi = busio.SPI(board.SCK, board.MOSI, board.MISO) avrpro...
python
from django.urls import path from rest_framework_simplejwt.views import ( TokenRefreshView, ) from social_network.views import RegisterView, PostView, LikeView, DislikeView, LoginView, UserActivityView, \ AnalyticsView, PostListView app_name = 'sn' urlpatterns = [ path('api/user/register/', RegisterView....
python
""" Module to test the StackToken class. """ from pymarkdown.stack_token import StackToken def test_stack_token_equal(): """ Test to make sure two equal StackToken instances are equal. """ # Arrange token1 = StackToken("type1", extra_data="extra1") token2 = StackToken("type1", extra_data="ext...
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from distutils.spawn import find_executable from distutils import sysconfig, log import setuptools import setuptools.command.build_py import setuptools.command.develop im...
python
available = "$AVAILABLE$" randomized = "$RANDOMIZED$" hashstring = "$HASHSTRING$" rand_ord = '$RANDORD$' from random import randint as rand def get_sum(value): sums = 0 for k, v in enumerate(value): sums += ord(v)+k return sums def get_activation(request): if not request[0] in randomized or len(request) <= ...
python
'''Creates the wires and part objects''' import FreeCAD import Mesh import lithophane_utils from utils.resource_utils import iconPath from boolean_mesh import BooleanMesh from boolean_mesh import ViewProviderBooleanMesh from create_geometry_base import CreateGeometryBase class ProcessingParameters(object): def ...
python
import pytest from yaml_loader import load_yaml_file from template_loader import load_template @pytest.fixture def values(): """ Loads values for the test template. """ return load_yaml_file('tests/data/values.yaml') @pytest.fixture def template(): """ Gets the template object for the test template...
python
# -*- coding: utf-8 -*- ########################################################### # Elasticsearch Snack 1.1 # # A brief example case indexing recipes with Elasticsearch, # Python and Docker containers # # Copyright 2020 Borja González Seoane # # Contact: borja.gseoane@udc.es #########################################...
python
def match(candidate, job): return candidate["min_salary"] * 9 <= job["max_salary"] * 10
python
from django.conf import settings from django.contrib.auth import get_user_model from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from model_utils.models import TimeStampedModel from producto.models import Producto User = get_user_model() class Order(TimeStampedModel...
python
def isLetter(c): return c >= "A" and c <= "Z" or c >= "a" and c <= "z" def plusOut(s,word): i = 0 value = "" booboo = False while i < len(s) - len(word) + 1: test = s[i:i + len(word)] if test == word: value += test booboo = True elif booboo == False: ...
python
""" This module handles all interactions with Twitter. """ import logging import tweepy from hockeygamebot.helpers import arguments, utils from hockeygamebot.models.hashtag import Hashtag def get_api(): """ Returns an Authorized session of the Tweepy API. Input: None Output: tweep...
python
''' This script elaborates more advanced operations on DataFrames. ''' import pandas as pnd import numpy as npy # Create a DataFrame: dict = {'Col1': [0, 0, 1, 0, 1, 1], 'Col2': ['A', 'B', 'C', 'D', 'E', 'F'], 'Col3': npy.random.randint(1,10,6)} dFrame = pnd.DataFrame(dict) print('The DataFrame is: \n', dFra...
python
"""Module extracts ORB features from an input image and writes to .npz file. All code lifted from openSfM; namely files io.py, features.py and detect_features.py""" import os import cv2 import numpy as np def detect_features(img, nfeat, hahog_params=None): """ Extracts ORB features from image :param img...
python
from enum import Enum class TimeValidity(Enum): DAY = (0,) GOOD_TILL_CANCEL = (1,) class Order: def __init__(self, instrument_code): self.instrumentCode = instrument_code def to_json(self): # replace ' with " for Trading212 compatibility return self.__dict__.__str__().replac...
python
"""Test the LinearSystemComp.""" import unittest import numpy as np import openmdao.api as om from openmdao.utils.assert_utils import assert_near_equal class TestLinearSystemComp(unittest.TestCase): """Test the LinearSystemComp class with a 3x3 linear system.""" def test_basic(self): """Check agai...
python
import datetime import json from itertools import count import scipy.io import numpy as np import pandas as pd import h5py from graphcnn.helper import * import graphcnn.setup.helper import graphcnn.setup as setup import math from math import radians, cos, sin, asin, sqrt from scipy import stats from tqdm import tqd...
python
from math import sqrt def spiral_factor(x): return 1-1/sqrt(1+(91/90000)*x**2) file = open("spiral_array.h", "w") print("const float spiral_factor[] = { 0.0", end='', file=file) for x in range(1, 101): print(",", end='\n', file=file) print(spiral_factor(x), end='', file=file) print("};", end='\n', file...
python
import os def post_register_types(root_module): root_module.add_include('"ns3/network-module.h"')
python
import redis from django.conf import settings from .models import Product # connect to redis r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) class Recommender(object): def get_product_key(self, id): return 'produ...
python
import logging import os from lightwood.encoders.image.helpers.nn import NnEncoderHelper import torch class NnAutoEncoder: def __init__(self, is_target=False): self._model = None self._pytorch_wrapper = torch.FloatTensor self._prepared = False def prepare_encoder(self, priming_data):...
python
# -*- coding: utf-8 -*- """ sphinx.directives.code ~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import codecs import sys from difflib import unified_diff from docutils import nodes from docutils.parsers.rst import ...
python
# -*- coding: utf-8 -*- """ SQLpie License (MIT License) Copyright (c) 2011-2016 André Lessa, http://sqlpie.com See LICENSE file. """ from flask import g import json import sqlpie import os class Document(object): __tablename = "documents" STATE = "state" IS_NOT_INDEXED = 0 IS_INDEXED = 1 PARSER...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- import proc_criatividade as criatividade from dao.cenario import Cenario from dao.perssonagem import Perssonagem from dao.objeto import Objeto from dao.transporte import Transporte from dao.missao import Missao from...
python
from kernel.local_alignment_kernel import LocalAlignmentKernel from kernel.spectrum_kernel import SpectrumKernel, SumSpectrumKernel from kernel.substring_kernel import SubstringKernel from kernel.base_kernel import KernelIPImplicit, KernelIPExplicit, SumKernelIPExplicit __all__ = ["LocalAlignmentKernel", "SpectrumKern...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import sys import argparse import logging import json import importlib import base64 from .common import enable_multi_thread, enable_multi_phase from .constants import ModuleName, ClassName, ClassArgs, AdvisorModuleName, AdvisorClassNa...
python
# Copyright 2020 Louis Richard # # 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 writin...
python
# import dependencies import os import json import struct import time import requests import numpy as np import binascii import datetime import datetime as dt from datetime import date from flask import Flask, Response, request, redirect, url_for, escape, jsonify, make_response from flask_mongoengine import MongoEngine...
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 # d...
python
# vim:set et ts=4 sw=4: import logging class FileLogger(object): """ This becomes a File Like object that can be be written to. But instead of actually writing to a file it writes to a logger object Example: #Redirect stdout and stderr to a logging object import sys from file_logger import ...
python
# Copyright 2014 - Rackspace # # 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, ...
python
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from tksugar import Generator count = 1 def button(button, tag): global count child = Generator(r"samples\yml\multiwindow_child.yml").get_manager() ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4...
python
import numpy from scipy.ndimage import shift from skimage.exposure import rescale_intensity from aydin.features.groups.translations import TranslationFeatures from aydin.io.datasets import camera def n(image): return rescale_intensity( image.astype(numpy.float32), in_range='image', out_range=(0, 1) )...
python
numberlist = [1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numberlist: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") else: print(str(number) + "th")
python
# -*- coding: utf-8 -*- import inspect import io import os import numpy as np import pytest import pytoshop from pytoshop import enums from pytoshop import layers DATA_PATH = os.path.join(os.path.dirname(__file__), 'psd_files') def test_futz_with_channel_image_data(): filename = os.path.join(DATA_PATH, 'g...
python
from abc import ABC, abstractmethod from typing import List from evobench import Benchmark from evobench.model import Solution class HillClimber(ABC): def __init__(self, benchmark: Benchmark): self.benchmark = benchmark @abstractmethod def __call__(self, solution: Solution, **kwargs) -> Solutio...
python
# coding=utf-8 from urllib2 import URLError, HTTPError import urllib2 import json import logging from api_exception import APIError from common.config import configs from common.util import Util # from appName.route.neutron_api import list_ports_by_nobind # from appName.route.neutron_api import list_network # from appN...
python
import os import torch import torchvision.transforms as transforms import torchvision.datasets as datasets def load_dataset(data_root, dataset_name, trans): if dataset_name == 'mnist': return datasets.MNIST( root=data_root, train=True, transform=trans, downl...
python
from typing import Union, Optional, List, Dict from torch_geometric.typing import OptPairTensor, Adj, OptTensor, Size, PairTensor import torch from torch import Tensor from torch_geometric.nn import GINEConv as BaseGINEConv, GINConv as BaseGINConv, LEConv as BaseLEConv from torch.nn import Sequential, Linear, ReLU fro...
python
import argparse, logging, math, filepattern, time, queue from bfio import BioReader, BioWriter import pathlib from preadator import ProcessManager logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') # length/width of the chunk each _m...
python
#!/usr/bin/env python import os, sys import string import argparse import re parser = argparse.ArgumentParser(description=""" creates mut file from snpEFF vcf """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--vcf', metavar = '<file.vcf>', required=True, help="""VCF file. <REQUIRED>\n\n""") ...
python
""" Django settings for Journal project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ ...
python
#!/usr/bin/env python import os, sys, subprocess, argparse, re, logging, errno import mymm parser = argparse.ArgumentParser(description = "This program takes a .pqr file (MEAD format only for now, meaning no chain field!) and writes a CRG and PDB file from it.", prog = sys.argv[0]) parser.add_argument('--pqr', metav...
python
""" This code was generated by Codezu. Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. """ from mozurestsdk.mozuclient import default as default_client from mozurestsdk.mozuurl import MozuUrl; from mozurestsdk.urllocation import UrlLocation from mozure...
python
import os import os.path as osp import pickle import sys import time project_root = os.path.abspath ( os.path.join ( os.path.dirname ( __file__ ), '..', '..' ) ) if __name__ == '__main__': if project_root not in sys.path: sys.path.append ( project_root ) import coloredlogs, logging logger = logging.getLog...
python
# ---------------------------------------------------------------------- # AdministrativeDomain REST API # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- ...
python
import torchvision.transforms as transforms import numpy as np import h5py, os, random, math, torch import os import torch.utils.data as data import cv2 from PIL import Image import csv def get_csv_content(path): # if not path.endswith('.csv'): raise ValueError(f"Wrong path, Got {path}") ...
python
# import the libraries import googlemaps import json from GoogleMapsAPIKey import get_my_key # Define the API Key. API_KEY = get_my_key() # Define the Client gmaps = googlemaps.Client(key = API_KEY) # Define Parameters # Method One Place ID: 'place_id:ChIJ7-bxRDmr3oARawtVV_lGLtw' ...
python
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
python
from internos.taskapp.celery import app import json import pytz import httplib import datetime from django.utils import timezone from time import mktime from internos.backends.utils import get_data @app.task def sync_partner_data(): from internos.etools.models import PartnerOrganization partners = get_data('...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import DomoticzAPI as dom from test_all import (WIDTH_LABEL, FILE, TEST, H2, CRLF, SUFFIX) def main(): print(FILE) print("{:{}<{}}: {}".format("Test script", SUFFIX, WIDTH_LABEL, __file__)) print(FILE) server = dom.Server() print(CRLF) print(TEST...
python
from unittest import TestCase from algotrader.app.backtest_runner import BacktestRunner from algotrader.trading.config import Config, load_from_yaml from algotrader.trading.context import ApplicationContext from tests import test_override class StrategyPersistenceTest(TestCase): start_date = 19930101 intrim_...
python
def ajuda(com): help(com) def titulo(msg, cor=0): tam = len(msg) + 4 print('-' * tam) print(f' {msg}') print('-' * tam) comando = '' while True: titulo('SISTEMA DE AJUDA PyHELP') comando = str(input('Funca ou Biblioteca > ')) if comando.upper() == 'FIM': break else: ...
python
from src.core.models import TimestampedModel from src.users.managers import UserManager from src.users.validators import ( validate_unique_username, validate_username_valid_characters_only, ) from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.util...
python
from django import forms from django.core.exceptions import ValidationError from grandchallenge.publications.models import ( Publication, identifier_validator, ) from grandchallenge.publications.utils import get_identifier_csl class PublicationForm(forms.ModelForm): def clean_identifier(self): id...
python
class MorseCode(): def __init__(self): self.__dic_plain = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'-...
python
# -*- coding: utf-8 -*- ############################################################################ # # Copyright © 2013, 2014 OnlineGroups.net and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany th...
python
from .emojipedia import Emojipedia, Emoji
python
import re import ssl from retrying import retry import urllib.request wordlist_re = re.compile( r'<a href="/wordlist/(\w+.shtml)" target="_top">\w+</a><BR>') wordlist_name_re = re.compile( r'<h1 class=body-title__title>(.+?)</h1>') words_re = re.compile( r'<div class=wordlist-item>([\w -\\\']+?)</div>') ...
python
"""This module contains the general information for AdaptorHostEthIf ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class AdaptorHostEthIfConsts: IF_TYPE_VIRTUAL = "virtual" MAC_AUTO = "AUTO" UPLINK_PORT_0 = "0" ...
python
from PyQt5.QtGui import QImage from PIL import Image import numpy as np def numpyQImage(image): qImg = QImage() if image.dtype == np.uint8: if len(image.shape) == 2: channels = 1 height, width = image.shape bytesPerLine = channels * width qImg ...
python
#Copyright (c) 2014 Samsung Electronics Co., Ltd 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 # # Unle...
python
from src import Camera, Tracer, World, Stereo
python
import pygame import random import time import sys pygame.init() # definicion de colores blanco = pygame.Color(255,255,255) negro = pygame.Color(0,0,0) rojo = pygame.Color(255,0,0) rojo_o = pygame.Color(100,0,0) gris = pygame.Color(200,200,200) verde = pygame.Color(0,250,100) verde_o = pygame.Color(0,150,50) morado = ...
python
# 要添加一个新单元,输入 '# %%' # 要添加一个新的标记单元,输入 '# %% [markdown]' # %% import numpy as np from matplotlib import pyplot as plt import os from matplotlib import font_manager import matplotlib as mpl zhfont1 = font_manager.FontProperties(fname='SimHei.ttf') from mpl_toolkits.axes_grid1 import make_axes_locatable import pandas as ...
python
# Corrigido print('Exercício 010') print() # Bloco de entrada carteira = float(input('Informe quanto você tem na sua carteira: ')) print() # Bloco de cálculo dólar = carteira / 5.47 # Bloco de saída print('Você pode comprar $ {:.2f} dólares com R$ {} reais na carteira.'.format( dólar, carteira)) print()
python
""" Write an iterative function iterPower(base, exp) that calculates the exponential baseexp by simply using successive multiplication. For example, iterPower(base, exp) should compute baseexp by multiplying base times itself exp times. Write such a function below. This function should take in two values - base can be...
python
from SuperSafety.Utils.utils import limit_phi, load_conf from SuperSafety.Supervisor.Dynamics import run_dynamics_update import numpy as np from matplotlib import pyplot as plt import numpy as np from numba import njit class Modes: def __init__(self, conf) -> None: self.time_step = conf.kernel_time_st...
python
import math import re from threading import Thread import serial from ...LightSkin import ForwardModel, LightSkin, EventHook class ArduinoConnectorForwardModel(ForwardModel): """ Connects to an Arduino running the Arduino Connector Script on the given port with the given baudrate Parses the input in a n...
python
# ------------------------------------------------------------------------------- # 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/licens...
python
import numpy as np from numpy.testing import assert_equal from terrapin.flow_direction import aread8, convert_d8_directions test_sets = [ # source: # http://resources.arcgis.com/en/help/main/10.1/index.html#//009z00000051000000 # lower right corner of flow accumulation array is 2 in url but it should be 1...
python
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
python
# Copyright 2019 Adobe # All Rights Reserved. # # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. If you have received this file from a source other than Adobe, # then your use, modification, or distribution of it ...
python
import os import sys from time import sleep # Logo do programa! print('-' * 41) print(' Calculadora Simples Version 1.0') print('-' * 41) print(' Seja bem-vindo!') print('-' * 41) sleep(3) os.system('clear') # Valores para usar na Opção! n1 = int(input('1# Digite um valor: ')) n2 = int(input('2# Digit...
python
from __future__ import division import os, time, scipy.io import tensorflow as tf import numpy as np from PIL import Image tf.logging.set_verbosity(tf.logging.INFO) # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from dataset import SID_dataset as SID_dataset from network import Netowrk as Netowrk ############### ## Data #...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse from hoppy.timing.timing import EventFits __author__ = 'Teruaki Enoto' __date__ = '2020 September 5' __version__ = '0.01' def get_parser(): """ Creates a new argument parser. """ usage = """ plot event fits file (PULSE_PHASE) """ pa...
python
from django.apps import AppConfig class MainConfig(AppConfig): name = 'main' SOCIALS = { 'vk': 'https://vk.com/goto_msk', 'instagram': 'https://www.instagram.com/goto_goto_goto/', 'facebook': 'https://www.facebook.com/GoToCampPage/', 'telegram': 'https://t.me/goto_channel' }
python
''' Based on https://stackoverflow.com/questions/44164749/how-does-keras-handle-multilabel-classification ''' import warnings try: from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import SGD def keras_fit(T, Y, **kwargs): if Y.ndim == 1: ...
python
from z3 import Implies import numpy as np from z3 import Implies from quavl.lib.expressions.qbit import Qbits from quavl.lib.models.circuit import Circuit, Method from quavl.lib.operations.gates import Rx, Rz, V, CNOT, V_dag def repair_toffoli(): # Initialize circuit a, b, c = Qbits(['a', 'b', 'c']) n =...
python
from . import Base from sqlalchemy import Column, String, Integer, Enum as EnumCol, Date, ForeignKey from sqlalchemy.orm import relationship from enum import Enum class TaskType(Enum): Note = "Note" Task = "Task" class Task(Base): __tablename__ = "task" id = Column(Integer, primary_key=True, autoin...
python
"""Core Module ============== This module includes the abstraction of a Simulation Model and the definition of a Path. """ from .base_model import BaseModel, ModelState from .path import Path
python
import pulp from graphviz import Digraph from discord import Embed, File from tabulate import tabulate import math import ada.emoji from ada.result_message import ResultMessage from ada.breadcrumbs import Breadcrumbs class HelpResult: def __str__(self): return """ ADA is a bot for the videogame Satisfact...
python
import numpy import dask.dataframe as dd import operator import collections import re import logging #logging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s', level=logging.NONE) # build successor relation and edges among concepts def successor(concepts,c1,c2): return c1 < c2 an...
python
import io, csv from flask import ( Blueprint, render_template, request, redirect, url_for, make_response, session, ) from helpers.hubspot import create_client from helpers.session import SessionKey from auth import auth_required from hubspot.crm import ObjectType from hubspot.crm.contacts im...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import importlib import os import sys from io import StringIO from PySide2.QtCore import Qt from PySide2.QtGui import QKeyEvent from PySide2.QtWidgets import QWidget, QMessageBox from tensorflow.keras.models import Model, load_model from MnistClassifier.Ui_MainWidget im...
python
# DESCQA galaxy catalog interface. This defines the GalaxyCatalog base class # and, on import, registers all of the available catalog readers. Convenience # functions are defined that enable automatic detection of the appropriate # catalog type. # Note: right now we are working with galaxy properties as floats, with #...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import getopt import sys from _datetime import datetime from fmc_rest_client import FMCRestClient from fmc_rest_client.resources import * logging.basicConfig(level=logging.INFO) fmc_server_url = None username = None password = None obj_types = [] obj_name_prefix = None...
python
from django.shortcuts import render from .models import Portfolio def portfolio(request): portfolios = Portfolio.objects return render(request, 'portfolio/portfolio.html', {'portfolios': portfolios})
python
from ...config import LennyBotSourceConfig from .isource import ISource from ..github import GitHubService import re import requests class GithubSource(ISource): def __init__(self, name, config: LennyBotSourceConfig, github: GitHubService) -> None: self._name = name self._github = github ...
python
# -*- coding: utf-8; -*- """ Gui implementation for gui created via qt-designer. """ __author__ = "Christoph G. Keller" __copyright__ = "Copyright 2017" __credits__ = [""] __license__ = "MIT" __version__ = "2.0.0" __maintainer__ = "Christoph G. Keller" __email__ = "christoph.g.keller@gmail.com" __status__ ...
python
from flask_restful import Resource, reqparse, abort from flask import request from lista.models.service_model import ServiceModel from lista.schemas.service_schema import ServiceSchema class ServiceResource(Resource): parser = reqparse.RequestParser() parser.add_argument('name', type=st...
python
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from PIL import Image, ImageDraw import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path import seaborn as sns import tqdm class DetectionDataset(Dataset)...
python
def _repr(mat,notes,dFrame): from shutil import get_terminal_size as gts old = None d0,d1 = mat.dim feats = mat.features ind_level = mat.index.level col_place_holder = mat.DISPLAY_OPTIONS["col_place_holder"] row_place_holder = mat.DISPLAY_OPTIONS["row_place_holder"] left_seperator ...
python
import numpy as np import tensorflow as tf tensor_2d = np.array([(1, 2, 3, 4), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)]) print(tensor_2d) print(tensor_2d[2][3]) print(tensor_2d[0:2, 0:2]) matrix1 = np.array([(2, 2, 2), (2, 2, 2), (2, 2, 2)], dtype='int32') matrix2 = np.array([(1, 1, 1), (1, 1, 1), (1, 1, 1)], ...
python
# Generated by Django 4.0.1 on 2022-01-06 14:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('verzelapp', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='modulo', name='app_label', ), ...
python
from . HaarClassifierFunctions import faceFinder as fd from . HaarClassifierFunctions import haarTraining as tr from . HaarClassifierFunctions import boundingBoxes as bd import cv2 import os import numpy as np def classifierceleb(path): test_img = cv2.imread(path) print(test_img) face_detected,...
python
"""Simple watcher that prints wikipedia changes as they occur.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import pprint import argparse import pywikibot import requests import sseclient from googleapiclient import errors as google_api_er...
python
#programa ainda não finalizado n = [] for c in range(0, 5): valor = int(input('Digite um valor: ')) if c == 0 or valor > n[-1]: n.append(valor) print('Valor adicionado ao final da lista.') else: pos = 0 while pos < len(n): if valor <= n[pos]: #TypeError ...
python
from collections import defaultdict from typing import List, Any, Set, Tuple, Iterable import pandas as pd def printUniqueTokens(series: pd.Series): unique_series = series.unique() token_count = {} for a in unique_series: tokens = a.split(' ') for t in tokens: if t not in toke...
python
from django.conf import settings import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('auth', '0011_update_proxy_permis...
python