content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ An example *.py file. Some examples of coding in a *.py file as opposed to a Jupyter notebook file. These examples are meant to be viewed in the Spyder IDE. The concept of cells as used below is specific to Spyder. """ #%% This is a cell similar to a Jupyter notebook cell. # You can run t...
#-*- coding:utf-8 -*- import threading import bisect import random import logging import sched import time try: import queue except ImportError: import Queue as queue from .base import BaseObject,EMPTY_LIST,DAY_FINALIZE_TICK from .utils import now2next,TList from .macro_command_queue import mcq_stub class S...
""" Color Directives There are many different way to specify color; we support all of the color formats below and will convert between the different color formats. """ from math import atan2, cos, exp, pi, radians, sin, sqrt from mathics.builtin.colors.color_internals import convert_color from mathics.builtin.base...
from openmm_systems.test_systems._legacy_all import *
# -*- coding: utf-8 -*- from guizero import App, Box, Text, ButtonGroup, TextBox, Combo, PushButton, info from math import pi, sqrt def update_txt_value(): if btn_duct_type.value == "okrągły": txt_size_value.value = "Średnica:" else: txt_size_value.value = "Długość boku:" flow_unit...
# -*- encoding: utf-8 -*- from django.contrib.auth.decorators import login_required from djongo import models from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404 from django.utils.translation import activate from cliente.forms import ClienteForm, ClienteTodosForm from cliente.models import...
#-*- coding: utf-8 -*- #文章类 class Article(object): def __init__(self, id, title, content, author, tags, catagory, date, url): self.id = id self.title = title self.content = content self.author = author self.tags = tags self.catagory = catagory self.date = date...
import autodisc as ad import os def test_twodmatrixcppnneatevolution(): dir_path = os.path.dirname(os.path.realpath(__file__)) ################################################################ # normal evolution evo_config = ad.cppn.TwoDMatrixCCPNNEATEvolution.default_config() evo_config.neat_co...
def interlock(s1,s2,s3): if len(s1)!=len(s2): return False elif len(s3)!=2*len(s1): return False else: for i in range(len(s1)): if s1[i]!=s3[2*i] or s2[i]!=s3[2*i+1]: return False return True s1=raw_input('s1:') s2=raw_input('s2:') s3...
import argparse import random from PIL import ImageFont, Image, ImageDraw parser = argparse.ArgumentParser(description='Generate a desktop background using random characters and colors.') def size(s): defaults = { '4k': (3840, 2160), '2k': (2048, 1080), '1440p': (2560, 1440), '10...
from ...error import GraphQLError from .base import ValidationRule class UniqueOperationNames(ValidationRule): __slots__ = 'known_operation_names', def __init__(self, context): super(UniqueOperationNames, self).__init__(context) self.known_operation_names = {} def enter_OperationDefiniti...
""" spectrum_overload Setup.py My first attempt at a setup.py file. It is based off A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Licensed under the MIT Licence # To use a consistent encoding import codecs import os # Alway...
# This work is based on original code developed and copyrighted by TNO 2020. # Subsequent contributions are licensed to you by the developers of such code and are # made available to the Project under one or several contributor license agreements. # # This work is licensed to you under the Apache License, Version 2...
####################### #Pytest fixture test sample ####################### import pytest, time, logging from selenium import webdriver #logging.basicConfig(format = u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.DEBUG) logging.basicConfig(filename="sample.log", level=log...
import scrapy import math import urllib.parse as urlparse from urllib.parse import parse_qs from mergedeep import merge import urllib.request import os from opencage.geocoder import OpenCageGeocode import subprocess class RoutesSpider(scrapy.Spider): # Remember to set it first by `export OPENCAGE_API_KEY=XXXXX` ...
from django.shortcuts import render_to_response, HttpResponse, render, redirect, get_list_or_404 from django.template import RequestContext import json, httplib, urllib from project.models import Projects def index(request): data = { "projects" : get_list_or_404(Projects.objects.all().order_by("-submit_date")...
""" In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minu...
# Import a specific function from a module from random import randrange from math import fsum, remainder, sqrt # multiple functions can be imported from module. Thi is achieved by separating functions by a comma ',' # Example: from os import times, system rand_num = randrange(1, 100) print('Random number bet...
# coding: utf-8 """ This module contains various helpers for migrations testing. """ import os from django import VERSION MIGRATION_NAME = 'test' def makemigrations(): from django.core.management import call_command from django.core.management.commands.makemigrations import Command from django.db.migra...
import random import asyncio import aiohttp import json from discord import Game from discord.ext.commands import Bot # Jolts token TOKEN = 'NTY0NjQ4Nzk2NjQyODY5MjQ4.XKrCew.ZoFF0FF_m0wDUMNmB2DZGs_pPuw' # Possible starts for a comman BOT_PREFIX = ("!", "?") # Create instant of discord bot that we call "client" with our...
import traceback import logging try: import multiprocessing except ImportError: multiprocessing = None class MultiprocessHelper: """ An small framework for running heavy operations as multi-processes. MultiprocessHelper uses a map-reduce architecture, where multiple read workers perform the mappi...
import os import time import jwt import requests from cryptography.hazmat.backends import default_backend def print_github_token(): app_id = os.environ['DEPLOY_APP_ID'] cert_str = os.environ['DEPLOY_APP_PRIVATE_KEY'] cert_bytes = cert_str.encode() private_key = default_backend().load_pem_private_key(...
#!/usr/bin/env python3 # Copyright 2018 Stefan Kroboth # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distributed except ...
#find all movies details from imdb_task_1 import movies import requests,pprint from bs4 import BeautifulSoup url = "https://www.imdb.com/title/tt0066763/" def scrape_movie_details(movie_url): Total_detail_list = [] page = requests.get(movie_url) soup = BeautifulSoup(page.text,"html.parser") # print(soup) #...
import numpy as np n = 8 # Create a nxn matrix filled with 0 matrix = np.zeros((n, n), dtype=int) # fill 1 with alternate rows and column matrix[::2, 1::2] = 1 matrix[1::2, ::2] = 1 # Print the checkerboard pattern for i in range(n): for j in range(n): print(matrix[i][j], end=" ") print()
from base_classes.base_scraper import BaseScraper class IssuePage(BaseScraper): url_root = 'https://atomicavenue.com/atomic' def __init__(self, url_to_scrape): super(IssuePage, self).__init__(url_to_scrape) def get_current_for_sale(self): sellers = [] condition = "" for ...
from qutip.solver.options import SolverOdeOptions from qutip.solver.sesolve import SeSolver from qutip.solver.mesolve import MeSolver from qutip.solver.solver_base import Solver import qutip import numpy as np from numpy.testing import assert_allclose import pytest class TestIntegratorCte(): _analytical_se = lamb...
#!/usr/bin/env python import xml.etree.ElementTree as ET class tailf_webui(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def webui_schematics_panels_panel_name(self, **kwargs): """Auto Generated Code ""...
import asyncio import hashlib from os import linesep from typing import Sequence from aiofile import async_open from aiofiles import os as aio from ..common import run DEFAULT_BUFFER_SIZE = 100 * 1024 * 1024 async def _getsize_by_reading(filepath: str, chunk_size: int = DEFAULT_BUFFER_SIZE) -> int: """ Sim...
""" Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. """ from __future__ import division, absolute_import, print_function import sys import itertools import numpy as np im...
import datetime from os.path import dirname, join import pandas as pd from scipy.signal import savgol_filter from bokeh.io import curdoc from bokeh.layouts import column, row from bokeh.models import ColumnDataSource, DataRange1d, Select from bokeh.palettes import Blues4 from bokeh.plotting import figure STATISTICS ...
#MenuTitle: Delete Diagonal Nodes Between Extremes # -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals __doc__=""" Good for cleaning TTF curve. It removes Diagonal Node Between Extremes, after placing the current outline in the background. """ import GlyphsApp import math f = Gly...
import timeit import numpy as np durations = timeit.repeat( 'a["b"]', repeat=10 ** 6, number=1, setup="a = {'b': 3, 'c': 4, 'd': 5}" ) mul = 10 ** -7 print( "mean = {:0.1f} * 10^-7, std={:0.1f} * 10^-7".format( np.mean(durations) / mul, np.std(durations) / mul ) ) print("min ...
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import re from recipe_engine import recipe_api class CommitPositionApi(recipe_api.RecipeApi): """Recipe module providing commit position pars...
from calendar import timegm from flask_login import UserMixin, login_user from datetime import datetime import flask_socketio as sio from .Permissions import Permissions from .Token import Token from .database import Database from .Room import Room, ROOMS from .Logger import Logger from .. import config from .Layout i...
import os import sys import math """ Score: 1 full point. Well done! Notes: ------- First of all, your work is correct. I noticed you forked instead of cloning. It's actually more efficient to clone though there is something to learn from cloning. Docstrings: - typically, we would write the title on the first line ...
import os import json import threading import time from Qt import QtCore, QtGui, QtWidgets from pype.vendor import ftrack_api from pypeapp import style from pype.ftrack import FtrackServer, credentials from . import login_dialog from pype import api as pype log = pype.Logger().get_logger("FtrackModule", "ftrack") ...
#!/usr/bin/env python import random import numpy as np import pandas as pd import six def mmm(data, method= "mean/median/mode"): """Multivariate Imputation by Mean, median or mode ---------- data: Pandas data frame Data to impute. method : could be Mean,Median,Mode RETURNS ...
"""Classes to track inputs/outputs of modeling protocols. See also :class:`modelcif.protocol.Step`. """ class Data(object): """Some part of the system that is input or output by part of the modeling protocol. Usually a subclass is passed to :class:`modelcif.protocol.Step` to describe the...
# Authors: CommPy contributors # License: BSD 3-Clause from __future__ import division # Python 2 compatibility from numpy import arange, log10 from numpy.random import seed from numpy.testing import run_module_suite, dec, assert_allclose from commpy.channels import MIMOFlatChannel, SISOFlatChannel from commpy.modu...
# # 794. Valid Tic-Tac-Toe State # # Q: https://leetcode.com/problems/valid-tic-tac-toe-state/ # A: https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/117603/Javascript-Python3-C%2B%2B-Concise-solutions # from typing import List class Solution: def validTicTacToe(self, A: List[str], winX = False, winO ...
import os import sys import time import logging try: import py_modelica as pym print 'Found py_modelica in virtual python environment' except ImportError as err: print err.message print 'Use META virtual python environment' from optparse import OptionParser parser = OptionParser() pars...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-24 18:47 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0029_chart_slug'), ] operations = [ migrations.RemoveField( mod...
from django.conf.urls import re_path from . import views urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^search/', views.search_results, name='search'), re_path(r'^location/(?P<location>\w+)/', views.image_location, name='location'), ]
#!/usr/bin/env python """ .. module:: workbench :synopsis: Experiments in Python. .. moduleauthor:: Steve Knipmeyer <steve@modelrelief.org> """ # https://nikolak.com/pyqt-qt-designer-getting-started/ from PyQt5 import QtWidgets # Import the PyQt4 module we'll need import os import sys ...
"""Functions for formatting messages. This module allows for messages to be consistently formatted by message type. Some message types are always printed, while others are only printed if verbose mode is enabled. By default, error, warning, and success messages are always printed while info and debug messages are not...
# coding: utf-8 """ Healthbot APIs API interface for Healthbot application # noqa: E501 OpenAPI spec version: 1.0.0 Contact: healthbot-hackers@juniper.net Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class SshKeyProfil...
import numpy as np import cv2 import os.path from argparse import ArgumentParser import torch import torch.nn.functional as F from torch.autograd import Variable import sys sys.path.append("./correlation_package/build/lib.linux-x86_64-3.6") import cscdnet class DataInfo: def __init__(self): self.width = 1...
import torch from nlstruct.torch_utils import multi_dim_triu def masked_flip(x, mask, dim_x=-2): flipped_x = torch.zeros_like(x) flipped_x[mask] = x.flip(dim_x)[mask.flip(-1)] return flipped_x IMPOSSIBLE = -100000 # def logdotexp(log_A, B): # # log_A: 2 * N_samples * N_tags # # B: 2 * N_tags * N...
""" This module provides WebIDE related functionality """ import logging import zipfile import os from ..hana_ml_utils import DirectoryHandler logger = logging.getLogger(__name__) #pylint: disable=invalid-name class WebIDEDeployer(object): """ This class provides WebIDE deployer related functionality. ...
#! /usr/bin/env python # _*_ coding:utf-8 _*_ from common import Event def singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @singleton class CommonEvent(objec...
import sys import pandas as pd import sqlite3 import os def processRegionalLoad(dbName): dirname = os.path.dirname(__file__) regionData = pd.read_csv(os.path.join(dirname,"input/regions.csv"), sep=";") regionIDs = regionData["ID"].values # For progressbar cnt = 0 length = len(regio...
import re import sys import math class Token: def __init__(self, type, value): self.type = type self.value = value ans = 0 functions = { "ans": lambda p: ans, "exit": lambda p: sys.exit(0), "mean": lambda numbers: float(sum(numbers)) / max(len(numbers), 1), "sum": lambda numbers: ...
import subprocess lines = open ("topology.txt", "r").readlines() res = [str.strip().split("<- is \"wired\" to ->") for str in lines] iFaceList = {} #extract the node names and the used eth interfaces from the file for s in res: for x in s: if x == "": continue t = x.strip().split(" ")...
import time, heapq import numpy as np import numpy.ma as ma import gdspy as gp class GdsMap: def __init__(self, cell, grid_size, buffer=None, layers=None, precision=0.001): start_time = time.time() self.grid_size = grid_size if layers is None: lay...
#!/usr/bin/python # Filename: __init__.py # Author: David Taylor (@Prooffreader) from chorogrid.Colorbin import Colorbin from chorogrid.Chorogrid import Chorogrid from chorogrid.plotting import plot from zipcodes_df import zipcodes
from datetime import timedelta from typing import List from http import HTTPStatus from cachetools import TTLCache, cached from azure.core import MatchConditions from azure.cosmos import ContainerProxy from azure.cosmos.exceptions import CosmosResourceNotFoundError, \ CosmosAccessCon...
"""Graphical procedures for GPR data.""" import numpy as np import math import matplotlib.pyplot as plt from matplotlib import cm from ...gis.raster import RectifyTif class PLT: def show(self): """Display the current plot.""" plt.show() def save(self, outpath): """Sa...
from flask import render_template, g, request, jsonify, current_app from info import db, constants from info.utils.common import user_login from info.modules.profile import profile_blu from info.libs.image_storage import storage from info.models import Category, News from info.utils.response_code import RET @profile...
from odoo import tools, models, fields class AccountArVatLine(models.Model): """ Modelo base para nuevos reportes argentinos de iva. La idea es que estas lineas tenga todos los datos necesarios y que frente a cambios en odoo, los mismos sean abosrvidos por este cubo y no se requieran cambios en los ...
from IPython.core.display import Markdown, display import numpy as np def printmd(string:str): ''' Markdown printout in Jupyter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ prints a ``string`` that contains markdown (or more precisely, can contain markdown) in Jupyter cell output ''' display(Markdown(string)...
import os import sys import json import requests class OpenWeatherAPI(object): """ Performs requests to the OpenWeather API Service. Documentation : https://openweathermap.org/api # NOTE: - Add more features to this API - Publish to PyPi """ def __init__(self, key, headers=None...
import warnings from unittest import TestCase import numpy as np import tensorflow as tf import uncertainty_wizard as uwiz from uncertainty_wizard.internal_utils import UncertaintyWizardWarning class EnsembleFunctionalTest(TestCase): @staticmethod def _dummy_stochastic_classifier(): model = uwiz.mod...
import discord import os import asyncio from datetime import datetime from discord.ext import tasks, commands from discord.utils import get client = commands.Bot(command_prefix='.') client.remove_command('help') TOKEN = os.getenv("TOKEN") @client.event async def on_ready(): print('Started {0.user}'.format(client)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------- # test_spaceAfterComma.py # # test for spaceAfterComma rule # ---------------------------------------------------------------- # copyright (c) 2014 - Domen Ipavec # Distributed under The MIT License, see L...
import unittest import os from exm.conf import settings class TestGetSetting(unittest.TestCase): """ Test get config """ def test_getenv_setting_path(self): self.assertEqual(os.getenv('SETTING_PATH') != '', True) def test_get_CELERY_PATH(self): self.assertEqual(settings.CELERY_P...
larg = float(input('largura da parede:')) alt = float(input('altura da parede:')) area = larg * alt print('sua parede tem a dimensão de {} x {} e sua Área é de {}m². '.format(larg, alt, area, )) tinta = area / 2 print('para pintar essa area de tinta voce precisará de {}L de tinta.'.format(tinta, ))
from django.urls import path from .views import UserRegisterView, UserPostView, UserListView, UserUpdateView from django.contrib.auth import views from evileg_core.decorators import recaptcha app_name = 'users' urlpatterns = [ path('', UserListView.as_view(), name='users-list'), path('register/', recaptcha(UserR...
from flask import Flask from flask_restful import Resource, Api from firebase import firebase import json import os.path import urllib.parse import requests app = Flask(__name__) api = Api(app) google_places = {} firebase_url = "" firebase_name = "" firebase = firebase.FirebaseApplication(firebase_url, None) class G...
import datetime from django.test import TestCase from django.contrib.auth.models import User from addressbook.models import Address, Country from .models import Invoice class InvoiceTestCase(TestCase): def setUp(self): usr = User.objects.create(username='test', first_na...
# # PySNMP MIB module HUAWEI-NAT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-NAT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:35:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
import unittest from hwt.interfaces.utils import addClkRstn, propagateClkRstn from hwt.simulator.simTestCase import SimTestCase from hwt.synthesizer.param import Param from hwt.synthesizer.unit import Unit from hwtLib.amba.axis import AxiStream, axis_recieve_bytes, axis_send_bytes from hwtLib.amba.axis_comp.strformat_...
import math import logging from datetime import date nTypes = {0: "Nordic Event", 1: "Nordic Main Header", 2: "Nordic Macroseismic Header", 3: "Nordic Comment Header", 5: "Nordic Error Header", 6: "Nordic Waveform Header", 8: "Nordic Phase Data"} class values(): maxInt = 9223372036854775807 def validat...
import streamlit as st import pandas as pd import base64 import os import datetime import sqlalchemy as sa from pathlib import Path import psycopg2 #creating sql alchemy engine engine = sa.create_engine('postgresql://xiamtznyktfwmk:c4218e192fc96997efcc66e19d80352dfed962907d9a19e76b297fce47197227@ec2-54-224-120-186.com...
from sys import platform from cffi import FFI def initialize_dynamic_lib(): if platform.startswith('darwin'): prefix = 'lib' ext = 'dylib' elif platform.startswith('win32'): prefix = '' ext = 'dll' elif platform.startswith('linux'): prefix = 'lib' ext = 'so...
# Author: Eric Bezzam # Date: July 15, 2016 import numpy as np from .doa import DOA class MUSIC(DOA): """ Class to apply MUltiple SIgnal Classication (MUSIC) direction-of-arrival (DoA) for a particular microphone array. .. note:: Run locate_source() to apply the MUSIC algorithm. Parameters ...
#! /usr/bin/env python # -*- coding: utf-8 -*- import gunicorn.util from gunicorn.app.wsgiapp import WSGIApplication class TWSGIAPP(WSGIApplication): def init(self, parser, opts, args): print(self.cfg) self.app_uri = ".app:app" args = [self.app_uri] super(TWSGIAPP, s...
import datetime import webbrowser import dateutil.rrule from .compat import quote_plus from .utils import indent # What. name = 'Fresno.py' description = 'The Fresno Python User Group' # Where. location = 'Bitwise Industries' address = ''' 700 Van Ness Ave Fresno, CA ''' map = 'https://www.google.com/maps?q={0}'.f...
# -*- coding: utf-8 -*- """ ------------------------------------------------- @File : test_wangge.py Description : @Author : pchaos date: 18-4-1 ------------------------------------------------- Change Activity: 18-4-1: @Contact : p19992003#gmail.com -----------------...
w #import stuff #little bit about general stuff grid = [ [1,2,3], [4,5,6], [7,8,9], ['a','b','c','d'] ] ''' try: asdasd except dividedbyzero except invalidvalue ''' ########## ''' mode = 'r' # read # mode = 'w' # write, can create files # mode = 'a' # append only # mode = 'r+'# read & write f =...
import numpy as np def mask_np(array, null_val): if np.isnan(null_val): return (~np.isnan(null_val)).astype('float32') else: return np.not_equal(array, null_val).astype('float32') def masked_mape_np(y_true, y_pred, null_val=np.nan): with np.errstate(divide='ignore', invalid='i...
"""empty message Revision ID: 130e75eac0f7 Revises: None Create Date: 2017-04-14 17:51:12.533272 """ # revision identifiers, used by Alembic. revision = '130e75eac0f7' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! #...
import zarrdump from zarrdump.core import dump, _open_with_xarray_or_zarr from click.testing import CliRunner import fsspec import pytest import numpy as np import xarray as xr import zarr def test_version(): assert zarrdump.__version__ == "0.2.2" @pytest.fixture() def tmp_xarray_ds(tmpdir): def write_ds_t...
#Leia um valor de massa em libras e apresente-o convertido em quilogramas. #A formula de conversao eh: K=L*0.45 , #Sendo K a massa em quilogramas e L a massa em libras. l=float(input("Informe a massa em libras: ")) k=l*0.45 print(f"O peso convertido em KG eh {k}")
from absl import app import jax from jax._src.numpy.lax_numpy import argsort import jax.numpy as jnp from jaxopt import implicit_diff from jaxopt import linear_solve from jaxopt import OptaxSolver, GradientDescent from matplotlib.pyplot import vlines import optax from sklearn import datasets from sklearn import model_s...
from typing import Union from inject import autoparams from loaders.database import DatabaseProvider from models.student.StudentModel import StudentModel, UpdateStudentModel from infrastructure.students.repo.StudentRepository import StudentRepository class MongoDBStudentRepository(StudentRepository): @autoparam...
import re import dotenv import requests import os from model import utils # sets cities and times for weather report # return true if time_input is valid 24hr time, else return false def valid_time(time_input) -> bool: pattern = re.compile(r'((([0-1]\d)|(2[0-3])):[0-5]\d)|24:00') if pattern.match(time_inpu...
from django.conf.urls import url,include from Weatherstack import views app_name = 'Weatherstack' urlpatterns =[ url(r'^batch/$',views.batch,name='batch'), url(r'^time-series/$',views.time_series, name='time-series'), url(r'^ current/$',views.current,name='current'), ]
# Generated by Django 3.1.7 on 2021-03-21 12:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pic', '0003_auto_20210321_1429'), ] operations = [ migrations.CreateModel( name='Image', ...
# MODELS GESTION TOMA DATOS from django.db import models #from matrix_field import MatrixField # Create your models here. # CREAR UNA CLASE POR CADA TABLA DE NUESTRA BASE DE DATOS class Participantes(models.Model): nombre=models.CharField(max_length=30) apellido=models.CharField(max_length=30) fechaNac=models.D...
import unittest import mock import uiza from uiza.api_resources.storage import Storage from uiza.exceptions import ( BadRequestError, UnauthorizedError, NotFoundError, UnprocessableError, InternalServerError, ServiceUnavailableError, ClientError, ServerError, ClientException ) cla...
import sqlite3 import db_init def insert_dummy_data(conn): cur = conn.cursor() #records or rows in a list records = [(1, 'chair', 100, 'living room chairs', "1.jpg"), (2, 'table', 200, 'living room table', "2.jpg") ] #insert multiple records in a single query cur.executemany('INS...
from manimlib.imports import * from old_projects.eoc.chapter2 import Car, MoveCar class CircleScene(PiCreatureScene): CONFIG = { "radius": 1.5, "stroke_color": WHITE, "fill_color": BLUE_E, "fill_opacity": 0.75, "radial_line_color": MAROON_B, "outer_ring_color": GREE...
#!/usr/bin/env python3 """ Sums the contributions for all candidates in each race by election year (mayor, city council, city attorney) and writes it to /src/assets/candidates/{year}/campaign_race_totals.json as a JSON object. The keys are "mayor", "city council", and "city attorney" respectively. The key "last update...
# TODO: To be removed, replaced by CurrencyUnitsCalculation import locale from calculate_anything.calculation.base import _Calculation from calculate_anything.query.result import QueryResult from calculate_anything.constants import FLAGS class CurrencyCalculation(_Calculation): def __init__(self, value=None, err...
import pytest, requests_mock, subprocess, tarfile, os, json, shutil from components.update import update from components.cron import cron from components.movies import movies from components.updateip import updateip #~@pytest.mark.skip(reason="this is how you skip tests") with open('config.json', 'r') as config_file:...
import BaseHTTPServer import threading import requests from nose.plugins.attrib import attr from tests.checks.common import AgentCheckTest class HttpServerThread(threading.Thread): def __init__(self, data): super(HttpServerThread, self).__init__() self.done = False self.hostname = 'localho...
from typing import Tuple import torch import torch.nn as nn from colossalai.amp.naive_amp import NaiveAMPModel from colossalai.logging import get_dist_logger from colossalai.zero.sharded_model.sharded_model_v2 import ShardedModelV2 from colossalai.zero.sharded_optim.sharded_optim_v2 import ShardedOptimizerV2 from torc...
from collections.abc import Iterable from typing import Any from django.db.models.query import QuerySet def is_query_set(value: Any) -> bool: """Gets whether the specified value is a :see:QuerySet.""" return isinstance(value, QuerySet) def is_sql(value: Any) -> bool: """Gets whether the specified valu...
import uuid from django.db import models from django.utils.translation import ugettext_lazy as _ class Job(models.Model): access_token = models.CharField( max_length=255, help_text=_( "Used to authenticate as the user on Reddit", ), ) refresh_token = models.CharField...