content
stringlengths
5
1.05M
import os import argparse import pickle import numpy as np import mxnet as mx import cv2 from tqdm import tqdm def load_mx_rec(rec_path, save_path, write_img=True): if not os.path.isdir(save_path + "/images"): os.makedirs(save_path + "images") imgrec = mx.recordio.MXIndexedRecordIO( os.path.jo...
from ovos_plugin_common_play.ocp import MediaType, PlaybackType from ovos_workshop.skills.common_play import OVOSCommonPlaybackSkill, \ ocp_search, ocp_featured_media import requests import bs4 from ovos_utils.parse import fuzzy_match import random class PobreTVSkill(OVOSCommonPlaybackSkill): def __init__(sel...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: cs3/sharing/ocm/v1beta1/resources.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _...
# -*- coding: utf-8 -*- """ Autor: André Pacheco Email: pacheco.comp@gmail.com Script to prepare data to train, validate and test NCT dataset """ import sys sys.path.insert(0,'../../..') # including the path to deep-tasks folder from constants import RAUG_PATH sys.path.insert(0,RAUG_PATH) import os from raug.utils.lo...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import sys def f_gold(arr, n, A, B, C): for i in range(n): arr[i] = (A * arr[i] * arr[i] + B * arr[i] + C) ind...
from django.contrib.auth.models import User from haystack.query import SearchQuerySet MAX_QUERY_LENGTH = 100 def do_user_search(data, num_results=None): """ User search logic. Returns a tuple of (User, [User suggestions]). User can be None, and suggestions can be empty on error. :param data: Form d...
""" Advent of code 2021 day 05 / 1 """ import math from os import path import re class Code(object): def __init__(self, lines): self.lines = lines def solve(self): print(self.lines) dim = {} cnt = 0 xa, xb, ya, yb = -1, -1, -1, -1 for line in self.lines: ...
import pynput import pyperclip as pp import time import random, string from pynput import keyboard import socket HOST = '0.0.0.0' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) CLIENTS_LIST = [] print("Setting up this computer as a client.....
# -*- coding: utf-8 -*- # Copyright (c) 2019, Hardik Gadesha and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class ProductQuery(Document): pass @frappe.whitelist(allow_guest=True) def getProductQuery(...
# Generated by Django 3.1.1 on 2020-10-18 07:27 from django.db import migrations import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('photos', '0001_initial'), ] operations = [ migrations.AddField( model_name='photo...
#!/usr/bin/env python # Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Generates the swarming_bot.zip archive for the bot. Unlike the other scripts, this file can be run stand-alone to generate a sw...
import os def main(): """Prints info about qconfig""" print("qconfig enterprise available at - https://www.qsonlabs.com")
from sympy import Rational, eye, simplify, zeros from transition import func def get_N(): P = zeros(19, 19) for i in range(19): for j in range(19): if func(i, j) == r"\frac{1}{6}": P[i, j] = Rational(1, 6) elif func(i, j) == r"\frac{1}{2}": ...
from collections import defaultdict from typing import Any, Dict, Iterable, List, Optional, Tuple import networkx as nx import structlog from eth_utils import is_checksum_address, to_checksum_address from networkx import DiGraph from pathfinding_service.config import ( DEFAULT_SETTLE_TO_REVEAL_TIMEOUT_RATIO, ...
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. 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 requir...
# # Copyright (c) Microsoft Corporation. # All rights reserved. # # This code is licensed under the MIT License. # # 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, inclu...
import numpy as np regions = np.array(range(128)).reshape(8,-1) region_names = ['Virginia','California','Oregon','Ireland','Sao Paulo','Singapore','Sydney','Tokyo'] args.all = True driver.add_pipeline('', [ Filter(Service, GossipService), Filter(Event, [SyncStarted, SyncCompleted, DuplicatedUnit]), Gossip...
""" Copyright 2020 The OneFlow 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 applicable law or agr...
""" @Time : 2019/1/9 15:27 @Author : Sam @Project : IEC101 @FileName: MessageHandle.py @Software: PyCharm @Blog : https://blog.muumlover.com """
""" In this example we change the layer of the straight """ import gdsfactory as gf @gf.cell def wg(layer=(2, 0), **kwargs): return gf.components.straight(layer=layer, **kwargs) if __name__ == "__main__": c = wg() c.show()
from django.forms import * from softdelete.models import * import logging class ChangeSetForm(ModelForm): class Meta: model = ChangeSet exclude = ('content_type', 'object_id',)
from rdflib import Graph from rdflib.term import Literal, URIRef from rdflib.namespace import RDF, OWL, split_uri import click import json import sys RDF_TYPE = RDF["type"] OWL_SAME_AS = OWL["sameAs"] def get_stats(graph): def init(): r = {} r["elems"] = {} r["types"] = {} return ...
# Copyright 2015 Antiun Ingeniería, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Verify email at signup", "summary": "Force uninvited users to use a good email for signup", "version": "12.0.1.0.1", "category": "Authentication", "website": "https://github.com/O...
from domain.repositories import DebtRepository from domain.useCases import PayDebtPart from infra.controllers.contracts import HttpRequest, HttpResponse from infra.controllers.contracts.ValidatorDecorator import validate from infra.controllers.errors import NotFoundError from infra.controllers.validators import PayDebt...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from requests.exceptions import HTTPError class TaskNotFoundError(HTTPError): """任务不存在。""" class TaskError(HTTPError): """分析任务出错。""" class TimeoutError(Exception): """分析任务超时。"""
import random import numpy as np from TableGeneration.Distribution import Distribution import time ''' The code for generating 4 categories of tables consists of several small pieces e.g. types of borders, irregular/regular headers and transformations. We define header_categories which has two possiblities: 1. Regu...
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.views.generic.dates import ArchiveIndexView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView from django.core.serializers.json import ...
product = input() sugar = input() number_of_drinks = int(input()) price = 0 if product == "Espresso": if sugar == "Without": price = 0.90 elif sugar == "Normal": price = 1.00 elif sugar == "Extra": price = 1.20 elif product == "Cappuccino": if sugar == "Without": price ...
#!/usr/bin/env python import argparse import commands import json import time class ASAVpn(): def __init__(self, firewall, ignore_list, community_string): self.firewall = firewall self.ignore_list = ignore_list self.cmd = 'snmpwalk -v1 -c%s %s 1.3.6.1.4.1.9.9.392.1.3.21.1.10' % (community_s...
#!/bin/python3 def binod(): print('binod')
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from typing import Optional from torch import Tensor import math from utils import get_clones from models.depatch_embed import build_patch_embeds class Transformer(nn.Module): """ Transformer compu...
from ply import yacc import src.lexer as lexer import src.syntaxTree as node class Parser(object): def __init__(self): self.lexer = lexer.Lexer() self.lexer.build() tokens = lexer.Lexer.tokens precedence = ( ('left', 'ADD', 'SUB'), ('left', 'MUL', 'DIV'), ('left',...
from fastapi import FastAPI from api import api_router app = FastAPI() app.include_router(api_router)
from .prob_utils import *
from generate import * from pudzu.charts import * # generate d3 html df = pd.read_html("https://en.wikipedia.org/wiki/List_of_countries_by_intentional_homicide_rate")[2] COL = df.columns[0] df[COL] = df[COL].apply(lambda x: x.replace("†","") if isinstance(x, str) else x) rates = df.set_index(COL).Rate X = 2 COUNTR...
from configparser import ConfigParser from azure.mgmt.policyinsights import PolicyInsightsClient from mop2.utils.configuration import OPERATIONSPATH, CONFVARIABLES from mop2.utils.files import change_dir class PolicyDefinitionInsightScope: def __init__(self, operations_path=OPERATIONSPATH, config_variables=CON...
# import the necessary packages from matplotlib import pyplot as plt import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path to the image") args = vars(ap.parse_args()) # load the image, convert it to ...
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.9.1+dev # kernelspec: # display_name: Python [conda env:core_acc] * # language: python # nam...
class Solution: def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: left = max(A, E) right = max(...
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/incorrect-regex/problem # Difficulty: Easy # Max Score: 20 # Language: Python # ======================== # Solution # ======================== import re for _ in range(int(input()))...
import heapq # initialize a heap myheap = [] heapq.heapify(myheap) def get_data(item): heapq.heappush(myheap, item) get_data(2) get_data(-1) get_data(-100) print myheap
""" NAME: plotting_functions.py AUTHOR: Bronwyn Reichardt Chu Swinburne 2021 EMAIL: <breichardtchu@swin.edu.au> PURPOSE: To hold useful plotting functions Written on MacOS Mojave 10.14.5, with Python 3.7 FUNCTIONS INLCUDED: get_rc_params chen_et_al_2010 murray_et_al_2011 davies_et_al_2019 ...
# write a program that contains a list of authors # print out authors in the list # modify the program that so that the program checks # to see whether the author is male or female # male and females are stored in separate lists # add an author to the list of authors, but their gender is unknown
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2021, Tyler Gates <tgates81@gmail.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' --- module: spectrum_mode...
"""Support for controlling Sisyphus Kinetic Art Tables.""" import asyncio import logging import voluptuous as vol from homeassistant.const import ( CONF_HOST, CONF_NAME, EVENT_HOMEASSISTANT_STOP ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import pytest from cryptography.exceptions import InternalError from cry...
#!/usr/bin/env python3 import pathlib import re import subprocess import sys import pyagentx # Updater class that set OID values class HwMonTable(pyagentx.Updater): def __init__(self, *args, **kwargs): self.sensors = list() p = pathlib.Path('/sys/class/hwmon') for x in p.iterdir(): ...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2021 Linh Pham # api.wwdt.me is released under the terms of the Apache License 2.0 """Locations Models""" from typing import List, Optional from pydantic import BaseModel, conint, Field # region Location Models class Location(BaseModel): """Location Information""" ...
import numpy as np import heapq from pdb import set_trace as bp # TODO: # - [collapse] at the edges, use the full tile class CollapseContradiction(Exception): """ Raised when a pixel has no possible state to collapse into. """ def __init__(self, x, y): Exception.__init__(self) self._x = x ...
from rest_framework import viewsets from .models import DemoModel from .serializers import DemoModelSerializer class DemoModelViewset(viewsets.ModelViewSet): queryset = DemoModel.objects.all() serializer_class = DemoModelSerializer
# # PySNMP MIB module HUAWEI-MODULE-INFO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-MODULE-INFO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:35:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
x = [0,1,2,3,4,5,6] specific_route = '40.91.216.117/32' ips = ['40.91.216.117', '40.127.198.46', '137.117.45.133', '52.179.213.230', '40.85.250.63', '51.140.44.69', '65.52.206.156'] def ip_list(): outputip = [] for y in x: outputip.append('10.{}.1.42'.format(st...
# Copyright 2019 Google 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 to in writing, ...
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup( name="aioredis-models", version="3.0.0", description="Model Redis data structures", long_description=README, long_description_content_type="text/markdown"...
#pylint: disable=consider-using-f-string from pathlib import Path from subprocess import CalledProcessError import shlex import sys from yt_dlp import main as yt_dlp_main class SysExitSignal(Exception): ''' Signals a sys.exit() call ''' def __init__(self, exit_code, *args, **kwargs): self.exit_cod...
from PythonQt import QtGui from PythonQt.QtGui import QVector3D as Vec from PythonQt.QtGui import QGroupBox, QVBoxLayout, QPushButton import rexviewer as r #componenthandlers don't necessarily need to be naali modules, #but this one needs to listen to update events to do mouse hover tricks import circuits #should be...
[ [S, 1, 1], [MS, [2,3], [1,2], 50], [Num, [4,5], [2,5]], [S, 6, 0], [S, 7, 5] ]
import copy # Solution using recursion def get_subsets_a(setz, index=None): if index is None: index = len(setz) - 1 if index == -1: return [[]] old_subs = get_subsets_a(setz, index - 1) new_subs = [] item = setz[index] for val in old_subs: new_subs.append(val) ...
import streamlit as st import onnxruntime from torchvision import transforms from model_inference import lab_to_rgb, get_input_tensor, to_numpy import torch ort_session = onnxruntime.InferenceSession("generator.onnx") st.title("Colorize One-Piece Manga using Pix2Pix GAN.") st.write( "I am a anime fan but the epis...
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup( name = 'walnut', version = '0.2', url = 'https://github.com/c0ding/walnut', download_url = 'https://github.com/c0ding/walnut/archive/master.zip', author = 'Martin Simon', author_email = 'me@martinsimon.me', license = 'Apache ...
from py_grader.docker_tools.code_runner import CodeRunner, delete_docker_images
from stack import Stack def main(): """ Example Stack() usage """ stack = Stack() stack.push("apple") stack.push("pear") stack.push("banana") print(stack.peek()) print(stack.pop()) print(stack.pop()) print(stack.pop()) if __name__ == "__main__": main()
""" Command line interface to Gopher Airtime's HTTP APIs. """ import click import gopherairtime_cli.load class GopherAirtimeCliContext(object): def __init__(self): self.token = None @click.group(name="gopherairtime-cli") @click.version_option() @click.option('--token', '-t', help='Gopher Airtime Auth ...
#!/usr/bin/env python3 import os import sys import math import pandas as pd import numpy as np from dataclasses import dataclass def is_empty_file(fpath): return False if os.path.isfile(fpath) and os.path.getsize(fpath) > 0 else True base_dir = os.getcwd() exp_code = sys.argv[1] boost_mode = sys.argv[2] base_dir...
def clean_text(text): text = text.replace('\n', ' ') return text def get_entities_from_tuple(words, embeddings, ner, trans_prob): import gcn_ner.utils as utils sentence = utils.aux.create_full_sentence(words) A_fw, A_bw, tags, X = utils.aux.create_graph_from_sentence_and_word_vectors(sentence, em...
import plistlib class Manifest: def __init__(self, manifest): self.manifest = plistlib.loads(manifest) self.version = self.fetch_version() self.buildid = self.fetch_buildid() self.supported_devices = self.fetch_supported_devices() def fetch_buildid(self): return self.manifest[...
"""This module manages the tests for the authentication app.""" from django.test import TestCase
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ListTagsRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is...
from geo_joyplot.core import get_plot_df
# -*- coding: utf-8 -*- # # This file is 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 w...
import numpy as np V = np.array([0,0,0,0,0]) reward = np.array([0,0,0,0,1]) gamma = 1/2 left = np.array([[0.5,0.5,0,0,0],[1/3,2/3,0,0,0],[0,1/3,2/3,0,0],[0,0,1/3,2/3,0],[0,0,0,1/3,2/3]]) right = np.array([[2/3,1/3,0,0,0],[0,2/3,1/3,0,0],[0,0,2/3,1/3,0],[0,0,0,2/3,1/3],[0,0,0,0.5,0.5]]) stay = np.array([[0.5,0.5,0,0,0],...
''' This is the main entry point for the Sinbad library. Use the various connect*(...) methods to instantiate a data source. See the full documentation for more details on usage. ''' from jsonpath_rw import parse from zipfile import ZipFile, BadZipfile import urllib.parse import random import json import io import os...
# -*- coding: UTF-8 -*- # 初始化各数据结构 resource_cnt = 3 Available = [3, 3, 2] # 可利用各资源总数 Max = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]] # 各进程最大需求资源数 Allocation = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]] # 已分配各进程的资源数 Need = [[7, 4, 3], [1, 2, 2], [6, 0, 0], [0, 1, 1], [4, 3, 1]] # 各进程尚需的资...
import unittest from gdl.csv_writer import CsvWriter class CsvWriterTest(unittest.TestCase): @staticmethod def test_write_to_string_without_header(): assert '''Donald,Duck\r\nDolly,Duck\r\n''' == CsvWriter().as_csv_string([["Donald", "Duck"], ["Dolly", "Duck"]]) @staticmethod def test_write_...
"""Sphinx configuration file for an LSST stack package. This configuration only affects single-package Sphinx documentation builds. """ from documenteer.sphinxconfig.stackconf import build_package_configs import lsst.integration.test.reporting _g = globals() _g.update(build_package_configs( project_name='integr...
from distutils.core import setup setup( name='kissanime_dl', version='0.1dev', url='https://github.com/myh1000/kissanime-dl', author='Michael Huang', author_email='myh1000@gmail.com', packages=['kissanime_dl',], license='Creative Commons Attribution-Noncommercial-Share Alike license', l...
import unittest from pyquilted.quilted.detail import * class MockDetail(Detail): def __init__(self): pass class TestDetail(unittest.TestCase): def setUp(self): self.mock = MockDetail() def test_detail(self): self.assertTrue(hasattr(self.mock, 'serialize')) def test_detail_l...
from random import randint import time print('-'*40) print('JOGAR NA MEGA SENA'.center(40)) print('-'*40) num = int(input('Quantos jogos você quer que eu sorteie? ')) mega = [] print(' SORTEANDO OS NÚMEROS '.center(40, '#')) for i in range(num): jogo = [] while len(jogo)<6: sorteio = randint(1,60) ...
#!/usr/bin/env python2 from Crypto.Util.number import long_to_bytes from gmpy import invert c = 1255175567548994333354127249819818045465945247845837131555195957666457804964737798922879950261797144969862733084307639446180846553263783795441744889429182840206420204888831259981242375650511761656242096228176660519527148720...
#! /usr/bin/env python __author__ = 'Jiri' import bitstring import math #################################################################### # Base Class for Converting Decagon Data from raw data to SI Units # # Expand this class for other sensors or data loggers # ######################################...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data_ingestion', '0021_auto_20160321_1212'), ] operations = [ migrations.AlterField( model_name='collectiontable...
import sys import h5py from time import time import os import numpy as np import signal from decimal import Decimal # debug = False debug = True # Debug = False Debug = True def db(t,v=''): if debug == True: print(t,v) def Db(t,v=''): if Debug == True: print(t,v) def loadDataSet(fileName, da...
from django.test import TestCase from django.core.urlresolvers import resolve from django.http import HttpRequest from django.contrib.auth.models import User from store.models import Store from store.views import home_page # Create your tests here. class HomePageTest(TestCase): def test_home_page_url_and_view(...
import sys sys.path.append('..\\') import numpy as np import matplotlib.pyplot as plt import pdb from itertools import combinations from scipy.special import comb from loan_functions import * ### Define the parameters of the test ### nLoans = 3 a = 100.0 max_iters = 9000 ndec = 2 # Note to Patrick: # Since you'll wan...
from httpx import URL from httpx.exceptions import InvalidURL import pytest def test_idna_url(): url = URL("http://中国.icom.museum:80/") assert url == URL("http://xn--fiqs8s.icom.museum:80/") assert url.host == "xn--fiqs8s.icom.museum" def test_url(): url = URL("https://example.org:123/path/to/somewh...
################################################################################ # Copyright (c) 2015 IBM Corporation # # 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...
def compare_nmi_matrices(tgans, extra_datasets = None, include_true_data = True, n_q_bins = 40, ncol = None, nrow = None, average_method = "arithmetic", subplot_title_true_dataset = "True dataset", subplot_titles_tgans = None, subplot_titles_extra_datasets = None, fig...
import matplotlib.pyplot as plt Partition = 'Holidays', 'Eating_Out', 'Shopping', 'Groceries' sizes = [250, 100, 300, 200] fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=Partition, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') plt.show()
import filecmp import logging import os import pytest import subprocess from unittest import mock from triphecta import distances, tasks, utils this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, "data", "tasks") def test_pheno_constraints_template(): options = mock.Mock() ...
# Shamelessly stolen from stack overflow # https://stackoverflow.com/questions/41752946/replacing-a-character-from-a-certain-index def replace_str_index(text,index=0,replacement=''): return '%s%s%s'%(text[:index],replacement,text[index+1:]) def create_addr_list(addr, bitmask): for i, bit in enumerate(bitmask)...
import numpy as np import torch import cv2 def bbox_flip(bboxes, img_shape, direction='horizontal'): """Flip bboxes horizontally or vertically. Args: bboxes (Tensor): Shape (..., 4*k) img_shape (tuple): Image shape. direction (str): Flip direction, options are "horizontal", "vertical"...
from django import forms from .models import productDetails, productPath, productSuggestions, Manufacturer, Category class productForm(forms.ModelForm): class Meta: model = productDetails fields ="__all__" labels ={ 'Product Name':'Name of Product', } def __init__(se...
# colors cl_black = (0, 0, 0) cl_white = (255, 255, 255) cl_red = (255, 0, 0) cl_green = (0, 255, 0) cl_blue = (0, 0, 255) cl_off_black = (30, 30, 30) size = SC_WIDTH, SC_HEIGHT = 1024, 640 FPS = 120 PADDLE_SPEED = 300 / FPS
from django.db import models from django.conf import settings from django.db import models from django.db.models import Q from items.models import Item from django.db.models.signals import post_save from django.dispatch import receiver class ThreadManager(models.Manager): # returns a list that contains all the c...
from django.conf.urls.i18n import i18n_patterns from django.urls import include, path, re_path from django.utils.translation import gettext_lazy as _ from django.views.generic import TemplateView view = TemplateView.as_view(template_name='dummy.html') urlpatterns = [ path('not-prefixed/', view, name='not-prefixed...
""" Generated by 'django-admin startproject' using Django 3.2.7. """ from pathlib import Path from decouple import config import os from datetime import timedelta import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = config('SECRET_KEY') PRIVATE_KEY_PATH, PRIVATE_KEY = BASE_DIR/"keys/...
import traceback from sqlalchemy.exc import IntegrityError class Usuario(object): def __init__(self, *args, **kwargs): self.codigo = kwargs.get("codigo", None) self.nome = kwargs.get("nome", None) self.email = kwargs.get("email", None) self.senha = kwargs.get("senha", None) ...
#!/usr/bin/env python import subprocess ##Input file ### General Inputs ### ## Temperature # Import numpy array of temperatures Temperature = '0,25,50,75,100,125,150,175,200,225,250,275,300' ## Pressure # Only set up for single pressure values Pressure = '1' ## Method # Only one method is accepted cu...
def calculate_average(team: list): avg = 0 for i in team: avg += i[1].ratings.highest_sr return round(float(avg) / len(team)) class MatchMaking: def __init__(self, ow_members, members): self.members = members tup = [] for i in range(0, len(members)): tup.app...
import unittest from solutions.elementary.right_to_left import my_solution class TestSolution(unittest.TestCase): def test_solution(self): self.assertEqual(my_solution(('left', 'right', 'left', 'stop')), 'left,left,left,stop') self.assertEqual(my_solution(('bright aright', 'ok')), 'bleft aleft,o...