content
stringlengths
0
894k
type
stringclasses
2 values
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
python
#!flask/bin/python from farm import app if __name__ == "__main__": app.run(host='0.0.0.0', port=8001, debug=True)
python
import datetime def prev_month_range(when = None): """Return (previous month's start date, previous month's end date).""" if not when: # Default to today. when = datetime.datetime.today() # Find previous month: http://stackoverflow.com/a/9725093/564514 # Find today. first = datetime...
python
''' example code to join dataframes merge_by_FIPS doesn't need to be it's own file; it's just calling .join on two data frames ''' from deaths import death_sample from vaccines import vaccine_sample def merge_by_FIPS(desired_date): # get dataframes with FIPS as indices deaths_df = death_sample(desired_date) ...
python
# Generated by Django 3.1.2 on 2020-11-10 14:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('userauth', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='fccProfil...
python
import json import time, os import requests from datetime import datetime from PIL import Image from PIL.ExifTags import TAGS def download_img(url, basepath, filename): with open(f'{basepath}/{filename}.jpg', "wb") as file: res = requests.get(url) file.write(res.content) def download_movi...
python
#! /usr/bin/env python from datetime import datetime import hb_config # import MySQLdb import pymysql.cursors import pymysql.converters as conv # import pymysql.constants as const from pymysql.constants import FIELD_TYPE import hb_output_settings as output_settings import hb_queries import hb_templates as templates im...
python
from accuracy2 import MyClassifier1 ob=MyClassifier1() print(ob.predict())
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Source: https://github.com/simplegadget512/Truecolor # MIT License # Copyright (c) 2017 Albert Freeman # 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 t...
python
import os from charge.repository import Repository if __name__ == '__main__': test_data_dir = os.path.realpath( os.path.join(__file__, '..', 'cross_validation_data')) out_file = 'cross_validation_repository.zip' repo = Repository.create_from(test_data_dir, min_shell=0, max_shell...
python
import unittest from typing import List import utils # https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 def round_up_to_power_of_2(v): v -= 1 v |= v >> 1 v |= v >> 2 v |= v >> 4 v |= v >> 8 v |= v >> 16 return v + 1 # O(n) space. Segment tree array. class NumArray: ...
python
# Generated by Django 3.0.8 on 2020-08-12 16:14 from django.db import migrations, models import utils.delete.managers import utils.postgres.managers class Migration(migrations.Migration): dependencies = [ ('definitions', '0008_auto_20200810_0520'), ] operations = [ migrations.AlterModel...
python
from typing import Any, Optional from baserow.core.models import Application, TrashEntry, Group from baserow.core.registries import application_type_registry from baserow.core.signals import application_created, group_restored from baserow.core.trash.registries import TrashableItemType, trash_item_type_registry clas...
python
""" NetEvo for Python ================= NetEvo is a computing framework designed to allow researchers to investigate evolutionary aspects of dynamical complex networks. It provides functionality to easily simulate dynamical networks with both nodes and edges states, and includes optimization methods...
python
# Generated by Django 3.2.8 on 2021-11-02 22:22 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('tasks', '0009_alter_task_task_description'), ] operations = [ ]
python
from processes.models import Workflow import factory from faker import Factory as FakerFactory from .owned_model_factory import OwnedModelFactory from .run_environment_factory import RunEnvironmentFactory faker = FakerFactory.create() class WorkflowFactory(OwnedModelFactory): class Meta: m...
python
""" """ from .utils import install_issubclass_patch __version__ = "0.10.2" install_issubclass_patch()
python
import torch.nn as nn from .fcn import FCNHead def build_segmentor(opt): n_class = opt.n_class # channels = [18, 36, 72, 144] channels = [128] classifier = FCNHead( sum(channels), sum(channels), n_class, num_convs=1, kernel_size=1 ) return classifier def...
python
############################################################################## # Copyright (c) 2016 HUAWEI TECHNOLOGIES CO.,LTD and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
python
from collections import defaultdict from typing import Optional import ether.topology from ether.core import Node, Connection DockerRegistry = Node('registry') class Topology(ether.topology.Topology): def __init__(self, incoming_graph_data=None, **attr): super().__init__(incoming_graph_data, **attr) ...
python
import os from collections import Counter from datetime import datetime import matplotlib.pyplot as plt import pandas as pd def process_logfile(log_file) -> list: with open(log_file, mode='r', encoding='utf-8') as file: lines = file.readlines() return [line.split(" : ")[0] for line in lines] if __n...
python
from instagrapi import Client import requests import json username = "USERNAME" password = "PASSWORD" def instagram_json(): response = requests.get(f"https://www.instagram.com/{username}/?__a=1") data = response.json() data1 = json.dumps(data) data2 = json.loads(data1) followers = data2[...
python
# Modules from termenu import PlainMenu # Initialize our menu menu = PlainMenu() # Main option list @menu.option("Check out GitHub!") def check_github(): print("You selected 'Check out GitHub!'.") @menu.option("Read some documentation!") def read_docs(): print("You selected 'Read some documentation!'.") @me...
python
# -*- coding: utf-8 -*- """ Provides the Action class as part of the PokerNowLogConverter data model""" from dataclasses import dataclass from player import Player @dataclass class Action: """ The Action class represents a single action made by a player in the active phase of the game. Args: player ...
python
from calc import calculate_reverse_polish_notation print( calculate_reverse_polish_notation(input().split(' ')) )
python
# -*- coding: utf-8 -*- """Functions to load and write datasets.""" __all__ = [ "load_airline", "load_arrow_head", "load_gunpoint", "load_basic_motions", "load_osuleaf", "load_italy_power_demand", "load_japanese_vowels", "load_longley", "load_lynx", "load_shampoo_sales", "lo...
python
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
python
from raybot import config from raybot.model import db, POI, Location from raybot.bot import bot from raybot.util import h, get_user, get_map, pack_ids, uncap, tr import csv import re import os import random import logging from typing import List, Tuple from datetime import datetime from aiogram import types from aiogra...
python
import numpy as np import math from keras.initializers import RandomUniform from keras.models import model_from_json from keras.models import Sequential from keras.layers import Dense, Flatten, Input, Lambda, Activation from keras.layers.merge import concatenate from keras.models import Sequential, Model from keras.opt...
python
# ***************************************************************************** # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
python
# Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’. # Example 1: # Input: [2, 1, 5, 1, 3, 2], k=3 # Output: 9 # Explanation: Subarray with maximum sum is [5, 1, 3]. # Example 2: # Input: [2, 3, 4, 1, 5], k=2 # Output: 7 # Explanation: Subarra...
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python
import tkinter as tk from tkinter import * from tkinter import filedialog from tkinter import messagebox from Bio import Entrez import os doubleBackSlash = r'/ '[0] class Script1: def __init__(self): self.a_InputCSVFileName = "" self.b_OutputPATH = "" self.c_OutputFileName...
python
import torch import torch.nn as nn import torch.optim as optim import numpy as np class DeepModel(nn.Module): def __init__( self, num_states, num_actions, ): super(DeepModel, self).__init__() self.conv1 = nn.Conv2d(1,20,(1,1)) self.conv2 = nn.Conv2d(1,20,(1,7...
python
import logging import traceback lgr = logging.getLogger('datalad.revolution.create') _tb = [t[2] for t in traceback.extract_stack()] if '_generate_extension_api' not in _tb: # pragma: no cover lgr.warn( "The module 'datalad_revolution.revcreate' is deprecated. " 'The `RevCreate` class can be impo...
python
# coding: utf-8 # Written by Lucas W. for Python 3.7.0 """Initialisation""" from time import time from threading import Timer from copy import deepcopy from random import choice name = "Terminal Chess (by Lucas W. 2019)" board_template = [ #standard setup ['wR','wN','wB','wQ','wK','wB','wN','wR'], ['wP','wP','wP','wP'...
python
from hubcheck.pageobjects.widgets.item_list_item import ItemListItem from hubcheck.pageobjects.basepageelement import TextReadOnly, Link class TagsBrowseResultsRow1(ItemListItem): def __init__(self, owner, locatordict={}, row_number=0): super(TagsBrowseResultsRow1,self).__init__(owner,locatordict,row_num...
python
import argparse import csv import sqlite3 import sys import random import time import sys import math #c.execute(UPDATE {} SET member=? WHERE callsign LIKE ? find_parent_sql = "SELECT * FROM orgs WHERE parentcallsign LIKE ?" org_insert_sql = "INSERT INTO orgs VALUES(?,?,?)" def update_org_id(table): return "UPDA...
python
import logging import time from celery import shared_task from django.db import transaction from pontoon.checks.utils import ( bulk_run_checks, get_translations, ) log = logging.getLogger(__name__) @shared_task(bind=True) def check_translations(self, translations_pks): """ Run checks on translatio...
python
from datetime import datetime import pytest from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from optuna.storages.rdb.models import BaseModel from optuna.storages.rdb.models import StudyModel from optuna.storages.rdb.models import StudySystemAttributeMod...
python
from typing import Any, Dict, Iterator, List, Optional from loguru import logger from pydantic import Field from ..metadata_source import ColumnMetadata from .external_metadata_source import ( ExternalMetadataSource, ExternalMetadataSourceException, ) try: import boto3 import botocore from mypy_b...
python
from django.conf.urls import patterns, include, url #from polls import views from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_angularjs_rest.views.home', name='home'), # url(r'^django_angularjs_rest/', include('django_angularjs_rest.foo.urls...
python
from vk import VKAPI class Photos(VKAPI): method_class = 'photos' def __init__(self, access_token=''): super(Photos, self).__init__(access_token=access_token) def confirm_tag(self, **params): self.set_method('confirmTag') return self.send(params) def copy(self, **params)...
python
from setuptools import setup, find_packages from distutils.util import convert_path long_description =""" # Virtual Pi The easiest way to use this package is to install using pip3 for python 3 ```bash $ sudo pip3 install VPi ``` To use the mock or virtual pi just type the following at the beginning of your script....
python
# Concatenate strings in a (nested) list # 1. concatenate strings in a non-nested list # 2. list are themselves lists def concat_str(string_list): """ Concatenate all the strings in a possibly-nested list of strings @param str|list(str|list(...)) string_list: this string list. @rtype: str >>> lis...
python
from __future__ import absolute_import, unicode_literals import os from setuptools import find_packages, setup version = __import__('logtailer').__version__ def read(fname): # read the contents of a text file return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="django-logtai...
python
##TODO: move this to a common location from db_password import DB_PASSWORD DB_ENGINE = "postgresql_psycopg2" DB_NAME = "testdb"# "ConceptNet" DB_HOST = "localhost" # or whatever server it's on DB_PORT = "5432" # or whatever port it's on DB_USER = "pat" # change this to your PostgreSQL username DB_SCHEMA...
python
from flask import Blueprint from flask import request from flask import jsonify from dock.common.exceptions import AppBaseException blueprint = Blueprint('transaction', __name__, url_prefix='/transaction') class Provision(object): def __init__(self): pass @classmethod def create(cls, p): ...
python
#!/usr/bin/env python3 import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import learn2learn as l2l from learn2learn.data.transforms import NWays, KShots, LoadData, RemapLabels def pairwise_distances_logits(a, b): n = a....
python
"""Shared pytest fixtures.""" import os import re import unittest.mock as mock from http.server import HTTPServer import pytest from pywemo import SubscriptionRegistry @pytest.fixture(scope='module') def vcr_config(): """VCR Configuration.""" def scrub_identifiers(response): body = response['body'...
python
import json import pickle import sqlite3 import time import pandas as pd from old.src.Model.Redis_connecter import RedisConn def picklify(df): dt_bytes = pickle.dumps(df) return dt_bytes def res_depicklify_to_list(): r = RedisConn().r db = sqlite3.connect("t0419.db") res = [] count = r.scar...
python
""" gcae.py PyTorch-Lightning Module Definition for the No-Language Latent Actions GELU Conditional Auto-Encoding (GCAE) Model. """ from pathlib import Path from typing import Any, List, Tuple import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim...
python
# Sample file to deploy Cubes slicer as a WSGI application import sys import os.path import ConfigParser CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) CONFIG_PATH = os.path.join(CURRENT_DIR, "slicer.ini") try: config = ConfigParser.SafeConfigParser() config.read(CONFIG_PATH) except Exception as e...
python
# # PySNMP MIB module ADAPTECSCSI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADAPTECSCSI-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:13:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
python
import requests, zipfile, io, subprocess, os, sys from datetime import datetime from dotenv import load_dotenv load_dotenv() ZIP_FILE_URL = os.getenv('ZIP_FILE_URL') if not ZIP_FILE_URL: sys.exit('Error getting zip file url from env') try: r = requests.get(ZIP_FILE_URL) except: sys.exit('Error getting fi...
python
from behave import then @then("The response status is {response_status:d}") def check_response_status(context, response_status): assert context.status == response_status
python
import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.models import Model, Sequential from tensorflow.keras.layers import Layer from tensorflow.keras.layers import (Input, Concatenate, Dense, Activation, BatchNormalization, Reshape, Dropout, ...
python
import os import sys import dicom import numpy as np # import SimpleITK as sitk from matplotlib import use use("Qt4Agg") from matplotlib import pyplot as plt from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.patches import Polygon from...
python
import os import torch import shutil import pickle import numpy as np from tqdm import tqdm from pathlib import Path from torch.utils.data import Dataset class P3B3(Dataset): """P3B3 Synthetic Dataset. Args: root: str Root directory of dataset where CANDLE loads P3B3 data. part...
python
# -*- coding: utf-8 -*- """ Natural Convection heat transfer calculation based on Churchill and Chu correlation """ def Churchill_Chu(D, rhof, Prf, kf, betaf, alphaf, muf, Ts, Tinf): """ Natural Convection heat transfer calculation based on Churchill and Chu correlation :param D: [m] Pipe inside di...
python
import functools import numpy as np import unittest from scipy.stats import kendalltau, pearsonr, spearmanr from sacrerouge.data import Metrics from sacrerouge.stats import convert_to_matrices, summary_level_corr, system_level_corr, global_corr, \ bootstrap_system_sample, bootstrap_input_sample, bootstrap_both_sam...
python
from argparse import ArgumentParser def parse_args(): parser = ArgumentParser(description="An auto downloader and uploader for TikTok videos.") parser.add_argument("user") parser.add_argument( "--no-delete", action="store_false", help="don't delete files when done" ) parser.add_argument( ...
python
from random import randint from lotto import getLotto from wc.wc import WC def getBoard(width=5, height=5, extra=75 - 5 * 5): lotto = getLotto(width, height, extra) board = [[lotto.draw() for _ in range(width)] for __ in range(height)] # TODO free spaces return Board(board, width, height) def transpose(board): r...
python
from infra.controllers.contracts.http import HttpRequest from cerberus import Validator from infra.controllers.validators.ports import CerberusErrors, PayloadValidator from utils.result import Error, Ok, Result class AddNewDebtValidator(PayloadValidator): def __init__(self) -> None: self.schema = { ...
python
# Generated by Django 2.2.13 on 2020-10-27 04:49 from django.db import migrations import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ("navigation", "0002_remove_pri_sec_footer_navs"), ] operations = [ migrations.AddField( ...
python
# Copyright 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://www.apache.org/licenses/LICENSE-2.0 # # or in the "l...
python
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
python
# -*- coding: utf-8 -*- """ Created on Tue Oct 4 22:53:41 2016 @author: midhununnikrishnan """ import numpy as np import combinatorics as cb def sumofdigits(G,k=1)->int: """find + of digits """ su = 0 while G > 0: if k == 1: su += (G%10) else: su += (G%...
python
from lacore.adf.persist import make_adf from lacore.archive import restore_archive as _restore_archive from lacli.nice import with_low_priority from lacli.hash import HashIO def archive_handle(docs): h = HashIO() make_adf(docs, out=h) return h.getvalue().encode('hex') restore_archive = with_low_priority(...
python
import pandas as pd def find_related_cols_by_name(dataframe_list, relationship_dict=None): # dataframe_list # List of pandas dataframe objects # # relationship_dict # This is an existing relationship_dict. If None, a new # relationship_dict should be created ### # Studen...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 5 10:15:25 2021 @author: lenakilian """ import pandas as pd import copy as cp import geopandas as gpd wd = r'/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis/' years = list(range(2007, 2018, 2)) geog = 'MSOA' yr = 2015 dict_cat = 'c...
python
""" Provides helping function for issues. """ import copy from json import JSONDecodeError from math import ceil from typing import Optional, List, Collection, Dict import arrow from pyramid.request import Request from slugify import slugify from dbas.database import DBDiscussionSession from dbas.database.discussion_...
python
# Generated by Django 3.0.7 on 2020-07-12 09:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin_app', '0004_order_arsip'), ] operations = [ migrations.AddField( model_name='order', name='p1_a', ...
python
import torch import torch.nn as nn from torchvision import models from torchvision import transforms from bench_press.models.modules.spatial_softmax import SpatialSoftmax pretrained_model_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, ...
python
import arcade import math import random import settings # default window SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = "WeFly X Charlie" BULLET_SPEED = 2 Score = 0 INSTRUCTIONS_PAGE_0 = 0 INSTRUCTIONS_PAGE_1 = 1 GAME_RUNNING = 2 GAME_OVER = 3 WIN = 4 position_y_1 = 600 position_y_2 = 0 # default boss' propert...
python
from Crypto.Cipher import AES import base64 import hashlib def jm_sha256(data): sha256 = hashlib.sha256() sha256.update(data.encode("utf-8")) res = sha256.digest() # print("sha256加密结果:", res) return res def pkcs7padding(text): bs = AES.block_size length = len(text) ...
python
import os import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration DEBUG = False DOMAIN_NAME = "deeptipandey.site" AWS_STORAGE_BUCKET_NAME = AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME", "") AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID", "") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_AC...
python
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' print("Задача 1") for i in range(1, 6): print(i, 0) i += 1 ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. ''' print("Задача 2") count = 0 for i in ran...
python
#coding=utf-8 import os, re, sys import json import datetime from openpyxl import load_workbook def parse_cell_value(value): #布尔类型 if isinstance(value, bool): return value #int类型 if isinstance(value, int): return value #float类型 if isinstance(value, float): return value ...
python
import os.path from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from PIL import Image import random import util.util as util import numpy as np class ConditionalDataset(BaseDataset): """ This dataset class can load unaligned/unpaired datasets with classes. ...
python
import json import urlparse import sys def handle(req): """handle a request to the function Args: req (str): request body """ sys.stderr.write(req) qs = urlparse.parse_qs(req) if "user_name" in qs: if not qs["user_name"][0] == "slackbot": emoticons = "" ...
python
import numpy as np import matplotlib.pyplot as plt class PlotDrawer: @staticmethod def draw(mfcc_data): PlotDrawer.__prepare_plot(mfcc_data) plt.show() # plt.close() @staticmethod def save(filename, mfcc_data): PlotDrawer.__prepare_plot(mfcc_data) plt.savefig(...
python
import datetime import io import operator import os import re from zipfile import ZipFile # def make_entry(entry): # if isinstance(entry, Entry): # return entry # mtime = os.path.getmtime(entry) # return Entry(entry, mtime) # handlers = { # ".zip": (lambda x: None) # } # class DirectoryHand...
python
# Copyright (c) 2014 Rackspace Hosting # 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 req...
python
#!/usr/bin/python import random import math import shelve import os #initialize constants STARTING_AMOUNT = 1000 MAX_BETS = 10000 #ROUND_LIMIT = 500000 ROUND_LIMIT = 5000 #whether or not to give verbose terminal output for each round of gambling #note: with short rounds, terminal output becomes a significant bottlenec...
python
# Copyright 2016 Ericsson AB. # # 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...
python
import mfclient import mf_connect import csv import time projSummary = "MFProjectSummary" storeSummary = "MFStoreSummary" timestr = time.strftime("%Y%m%d-%H%M%S") with open(projSummary+timestr+".csv", 'ab') as f: header = ["project","allocation","usage"] writer = csv.writer(f) writer.writerow(header) ...
python
from flask import jsonify, request, abort, Blueprint from ..auth0 import auth from ..auth0.authManagementAPI import * from datetime import * from ..db.models import * api = Blueprint('api', __name__) # build Auth0 Management API builder = Auth0ManagementAPIBuilder() auth0api = builder.load_base_url(). \ load_acce...
python
from _collections import deque def solution(): people = deque() while True: name = input() if name == 'End': print(f'{len(people)} people remaining.') break elif name == 'Paid': while people: popped_person = people.popleft() ...
python
from numpywren import compiler, frontend, exceptions import unittest import astor import ast import inspect def F1(a: int, b: int) -> int: return a//b def F2(a: float, b: int) -> float: return a + b def F3(a: float, b: int) -> float: c = a + b d = log(c) e = ceiling(d) return c def F4(a:...
python
from datetime import date from new_movies import movies_directory from new_movies.configuration import UNLIMITED_WATCHING_START_DATE, UNLIMITED_WATCHING_END_DATE from new_movies.exceptions import NoCreditsForMovieRent, MovieNotFound, ViewsLimitReached from new_movies.movie import Movie from new_movies.rented_movie imp...
python
################################################################################ # # Implementation of angular additive margin softmax loss. # # Adapted from: https://github.com/clovaai/voxceleb_trainer/blob/master/loss/aamsoftmax.py # # Author(s): Nik Vaessen ###########################################################...
python
#!/usr/bin/env python import os import sqlite3 from datetime import datetime from getpass import getuser from bashhistory import db_connection class SQL: COLUMNS = [ "command", "at", "host", "pwd", "user", "exit_code", "pid", "sequence", ] CREATE_COMMANDS: str = """ DROP TA...
python
import numpy as np import pandas as pd def print_matrix(matrix): pd.set_option('display.max_rows', len(matrix)) print() print(matrix) def normalize(matrix): return matrix.div(matrix.sum(axis=1), axis=0) def generate_matrix(data): key_set = set(data.keys()) for edges in data.values(): ...
python
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse class NegativeTargets(Client): """Amazon Advertising API for Sponsored Display Documentation: https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi#/Negative%20targeting This API enables programmatic access ...
python
from vpython import * scene.title = "VPython: Draw a sphere" sphere() # using defaults #see http://www.vpython.org/contents/docs/defaults.html
python
# -*- coding: utf-8 -*- import requests #resp = requests.post("http://localhost:5000/predict", json={"raw_text":"how do you stop war?"}) # resp_prod = requests.post("http://213.159.215.173:5000/get_summary", json={"raw_text":"A significant number of executives from 151 financial institutions in 33 countries say that ...
python
# Generated by Django 3.2.6 on 2021-09-01 20:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('produtos', '0004_ajuste_produtos'), ] operations = [ migrations.CreateModel( name='Fornecedor',...
python
import os dirpath = os.pardir import sys sys.path.append(dirpath) import torch.utils.model_zoo as model_zoo from torch.autograd import Variable from torch.optim import lr_scheduler import resnet_epi_fcr import resnet_vanilla import resnet_SNR import resnet_se from common.data_reader import BatchImageGenerator from c...
python
from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from .models import ( Cart, Item ) from .serializers import ( CartSerializerDefault, CartSerializerPOST, ItemSerializerDefault, ItemSerializerPOST ) class CartViewSet(ModelViewSet): ...
python