content stringlengths 5 1.05M |
|---|
import config
from app import make_app
import pytest
from sqlalchemy import create_engine, MetaData
@pytest.yield_fixture
def app():
create_db(config.SQLA_URI)
autoapi_app = make_app()
yield autoapi_app
drop_db(config.SQLA_URI)
def create_db(sqlalchemy_uri):
CREATE_TABLE_SQL = """
CREAT... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-23 15:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
output_file = None
indent = 0
assign_operators = ['=', '*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=', '|=']
temp_var_count = 0
operator_mappings = {
'!' : 'not',
'||' : 'or',
'&&' : 'and',
}
internal_functions = ['printf', ]
def generate_unique_tempname():
global temp_var_count
temp_var_count += 1
... |
# -*- coding: utf-8 -*-
import json
import logging
from beer_garden.api.http.authorization import authenticated, Permissions
from beer_garden.api.http.base_handler import BaseHandler
class PermissionsAPI(BaseHandler):
logger = logging.getLogger(__name__)
@authenticated(permissions=[Permissions.LOCAL_ADMIN]... |
import pathlib
from argparse import ArgumentParser
import torch
import torchaudio
from torchaudio.prototype.pipelines import EMFORMER_RNNT_BASE_LIBRISPEECH
def cli_main():
parser = ArgumentParser()
parser.add_argument(
"--librispeech_path",
type=pathlib.Path,
required=True,
he... |
# Python - 2.7.6
Test.describe('Basic tests')
Test.assert_equals(year_days(0), '0 has 366 days')
Test.assert_equals(year_days(-64), '-64 has 366 days')
Test.assert_equals(year_days(2016), '2016 has 366 days')
Test.assert_equals(year_days(1974), '1974 has 365 days')
Test.assert_equals(year_days(-10), '-10 has 365 days'... |
#!/usr/bin/env python
# coding:utf-8
import math
import logging
import torch
from torch.optim import Optimizer
from torch.optim import lr_scheduler as lrs
class LRSchedulerWorker(object):
def __init__(self, log_type, logger=None):
super(LRSchedulerWorker, self).__init__()
self.log_level = log_type... |
print('Accessing private members in Class:')
print('-'*35)
class Human():
# Private var
__privateVar = "this is __private variable"
# Constructor method
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 19:54:16 2020
@author: tobia
"""
import spacy
import pandas as pd
import numpy as np
import nltk
from nltk.stem import SnowballStemmer
from spacy.lang.es import Spanish
nltk.download('wordnet')
spacy.load("es_core_news_md")
nltk.download('stopwords')... |
#!/usr/bin/env python3
"""
Author : shv <shv@email.arizona.edu>
Date : 2021-11-16
Purpose: Run length encoding
"""
import argparse
import os
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description="", forma... |
class StopRequest:
stop_id = 0
components = []
def __init__(self, stop_id, components=[]):
self.stop_id = stop_id
self.components = components |
from typing import TYPE_CHECKING, Optional
from requests import Session
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
if TYPE_CHECKING:
from requests import PreparedRequest # pylint: disable=ungrouped-imports
class TimeoutAdapter(HTTPAdapter):
""" Adds a default timeout to r... |
import tensorflow as tf
from tensorflow import keras
# # Helper libraries
import numpy as np
import math
import pathlib as path
from PIL import Image
import random
print(tf.__version__)
# Helper function to display digit images
MODEL_FILE = "mnist.h5"
def pre_process():
def _process(p):
return np.asfa... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import sys
import os
import pytest
import pandas as pd
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import json_to_excel.json_to_excel as source_code
def test_create_sample_json():
count=1
test_json = source_code.create_sample_json(count=count)
assert isinstance(test_js... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Demo script showin... |
from hypothesis_auto import auto_pytest_magic
from streamdeck_ui import api
auto_pytest_magic(api.set_button_command)
auto_pytest_magic(api.get_button_command)
auto_pytest_magic(api.set_button_switch_page)
auto_pytest_magic(api.get_button_switch_page)
auto_pytest_magic(api.set_button_keys)
auto_pytest_magic(api.get_b... |
import unittest
import json
from dataclasses import dataclass, field
from rlbottraining.history.metric import Metric
from .utils.example_metrics import ExampleMetric, ExampleMetric2
class MetricsTest(unittest.TestCase):
def test_dataclass(self):
"""
Just make sure we understand Data Classes pro... |
# Font recognition for the two (2) puzzles that have invoked it so far (2021 Day 13 and ... that one with the flying points from 2018?)
from typing import Set, Tuple
# Yes, this was generated by trawling through github for various inputs for day 13 and running them
# No, it might not have all the possible letters tha... |
"""
Copyright (c) 2020 Tyler Cone
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, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub... |
from unittest.mock import call
from .. import service
from ..models import File
def test_stat():
file = service.stat("somefile")
assert isinstance(file, File)
def test_ls(mocker, settings):
def list_of_files(path):
assert path == "/data/subdir/somedir"
return ["file1", "file2", "file3"... |
import re
import setuptools
import pathlib
WORK_DIR = pathlib.Path(__file__).parent
with open("README.md", "r") as fh:
long_description = fh.read()
def get_version():
"""
Read version
:return: str
"""
txt = (WORK_DIR / 'aiomanybots' / '__init__.py').read_text('utf-8')
try:
retur... |
#Python program for stem plot
#with Amplitude = 5 units
import numpy as np
import scipy as sy
from matplotlib import pyplot as plt
t = np.arange(0,1,0.01)
#frequency = 2 Hz
f = 2
#Amplitude of sine wave = 1
PI = 22/7
a = np.sin(2*PI*2*t)
a = 5*a;
#plt.stem(t,a,linefmt='grey',markerfmt='C',bottom =0.0)
pl... |
import json, inspect
from helper.User import User
from helper.cEmbed import granted_msg, denied_msg
from helper.GitHub import GitHub
from helper.cLog import elog
from helper.Algorithm import Algorithm
from cDatabase.DB_Algorithm import DB_Algorithm
config = json.load(open('config.json', 'r'))
path = __file__.split(co... |
# coding: utf-8
"""
Apteco API
An API to allow access to Apteco Marketing Suite resources # noqa: E501
The version of the OpenAPI document: v2
Contact: support@apteco.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class AudienceExportDe... |
from datetime import date
from messaging.messaging_system import db
from messaging.models import DatabaseModel
from messaging.models.users import User
class Message(DatabaseModel):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
sender = db.Column(db.ForeignKey(User.id), nullable=... |
"""Store Aisle Monitor"""
"""
Copyright (c) 2018 Intel 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, including
without limitation the rights to use, copy, ... |
import discord
from discord.ext import commands
from PIL import Image
import inspect
import random
import io
def random_color():
color = ('#%06x' % random.randint(8, 0xFFFFFF))
color = int(color[1:], 16)
color = discord.Color(value=color)
return color
class Utility:
'''Useful commands to make yo... |
import keyboard, pyautogui, pygame
pygame.init()
appVersion = 'python_pygame_gui_template'
dev = False
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0,255,0)
darkblue = (21,35,45)
lightblue = (22,48,66)
t... |
import asyncio
from ..pool import ConnectionPool, ClosedPool, EmptyPool
from .aioconnection import AIOLDAPConnection
MYPY = False
if MYPY:
from ..ldapclient import LDAPClient
class AIOPoolContextManager:
def __init__(self, pool, *args, **kwargs):
self.pool = pool
self.__conn = None
as... |
""" Bases for sqlalchemy data models """
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Union
from sqlalchemy import Column, text
from sqlalchemy.schema import PrimaryKeyConstraint
from sqlalchemy.sql.base import ImmutableColumnCollection
from sqlalchemy.sql.elements import Bin... |
from machine import Pin
try:
import usocket as socket
except:
import socket
# Set this with the corresponding pin of your board.
led_gpio = 2
led = Pin(led_gpio, Pin.OUT)
web_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
web_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
web_server.bind... |
def threeSum(nums):
res = set()
nums.sort()
for i in range(len(nums)-2):
target = -(nums[i])
left = i + 1
right = len(nums)-1
while left < right:
sum = nums[left] + nums[right]
if sum == target:
res.add((nums[i],nums[left],nums[right]))
left += 1
elif sum ... |
# -*- coding: utf-8 -*-
import glob
import json
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import np_utils, plot_model
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
imp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tong Zhang <zhangt@frib.msu.edu>
# 2016-10-16 20:20:57 PM EDT
#
from flame import Machine
import numpy as np
import matplotlib.pyplot as plt
lat_fid = open('test.lat', 'r')
m = Machine(lat_fid)
## all BPMs and Correctors (both horizontal and vertical)
bpm_ids, cor_ids =... |
#!/usr/bin/python3
import io
from bot.bot import Bot
from bot.handler import MessageHandler, NewChatMembersHandler
from bot.types import Format
class Myteam():
def __init__(self, token, chat):
self.token = token
self.bot = Bot(token=self.token, api_url_base='https://api.internal.myteam.mail.ru/bot... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2010 OpenStack 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... |
from model.group import Group
__author__ = "Grzegorz Holak"
testdata = [
Group(name="nazwa1", footer="stopka1", header="naglowek1"),
Group(name="nazwa2", header="naglowek2", footer="stopka2")
]
|
""" Calculate properties for BpForms modeled in Bouhaddou et al., PLoS Comput Biol, 2018.
This example uses both the Python API and the JSON REST API
Bouhaddou M, Barrette AM, Stern AD, Koch RJ, DiStefano MS, Riesel EA, Santos LC, Tan AL, Mertz AE & Birtwistle MR.
A mechanistic pan-cancer pathway model informed by mu... |
from spanet.network.jet_reconstruction import JetReconstructionModel
from spanet.dataset import JetReconstructionDataset
from spanet.options import Options
|
import os, requests, logging
def send_metric(measurement, tags, values, num_retries=0, must_succeed=False):
url = os.environ.get("DPP_INFLUXDB_URL")
db = os.environ.get("DPP_INFLUXDB_DB")
if tags and url and db:
line_tags = ",".join(["{}={}".format(k, v) for k, v in tags.items()])
line_valu... |
import modulo_restaurante as mr
minha_cozinha = mr.Restaurante(
nome_restaurante='pão com ovo',
tipo_cozinha='normal'
)
minha_cozinha.descrição_restaurante()
minha_cozinha.restaurante_aberto() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module implements the interface to Denon AVR receivers.
:copyright: (c) 2016 by Oliver Goetz.
:license: MIT, see LICENSE for more details.
"""
import logging
import time
from typing import Callable, Dict, List, Optional
import attr
import httpx
from .decorato... |
# coding:utf-8
###############################
# python代码加密与License控制例子
# 这是需要License控制的脚本
###############################
import socket, fcntl, datetime, os, struct
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import time
class Get_License(object):
def __init__(self):
super(Get... |
import random
import math
import numpy as np
from GraphEngine import GraphicEngine
class FourierTransform:
def __init__(self, input_signal_vector):
self.number_of_data = len(input_signal_vector)
self.number_of_transform = int(self.number_of_data / 2)
self.input_signal_vector = input_signa... |
# Generic imports
from pathlib import Path
from math import log2, ceil
import numpy as np
# FPGA-specific imports
from msdsl import MixedSignalModel, VerilogGenerator, sum_op, clamp_op, to_uint, to_sint
from msdsl.expr.expr import array, concatenate
from msdsl.expr.extras import if_
from msdsl.expr.format import SIntF... |
from itertools import cycle
import dwave_networkx as dwnx
import networkx as nx
from matplotlib import pyplot as plt
from matplotlib.cm import get_cmap
from placeandroute.tilebased.heuristic import Constraint
def create(w):
ret = dwnx.chimera_graph(w, w)
return ret, dwnx.chimera_layout(ret)
def cnf_to_con... |
# coding=utf-8
# Copyright 2015 Brave Labs sp. z o.o.
# All rights reserved.
#
# This source code and all resulting intermediate files are CONFIDENTIAL and
# PROPRIETY TRADE SECRETS of Brave Labs sp. z o.o.
# Use is subject to license terms. See NOTICE file of this project for details.
# from celery import shared_task
... |
from model.board import Board, Location, NumberAssignmentError
from model.evaluator import Evaluator
from itertools import permutations
class Result:
complete = False
solution = Board()
success = False
class Solver:
def __init__(self):
self._debut_board = Board()
self._result = Result... |
from matplotlib import pyplot as plt
import tensorflow as tf
import numpy as np
#hyper params
lr = 0.1
epochs = 100
x_train = np.linspace(-1, 1,101)
y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
def model(X,w):
return tf.multiply(X,w)... |
"""
Trellis Histogram
-----------------
This example shows how to make a basic trellis histogram.
https://vega.github.io/vega-lite/examples/trellis_bar_histogram.html
"""
# category: histograms
import altair as alt
from vega_datasets import data
source = data.cars()
(
alt.Chart(source)
.mark_bar()
.encode... |
from ..converter import Converter
from ..oval_node import restore_dict_to_tree
from .client_html_output import ClientHtmlOutput
from .client_json_input import ClientJsonInput
START_OF_FILE_NAME = 'graph-of-'
class JsonToHtml(ClientHtmlOutput, ClientJsonInput):
def __init__(self, args):
super().__init__(a... |
"""Ensemble module."""
import numpy as np
from tqdm import tqdm
from .parser import Parser
from ..utils.metrics import timing
from .conformation import Conformation
from .transform import Transform
class Ensemble:
"""Default class for Ensemble."""
def __init__(
self,
base_conformation: Confor... |
'''
The MIT License (MIT)
Copyright (c) 2014 Stefan Lohmaier
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, including without limitation the rights to
use, copy, modify, mer... |
from frowns import Smiles
from frowns import Smarts
mol = Smiles.smilin("CCN")
pattern = Smarts.compile("CCN")
# simple match
match = pattern.match(mol)
assert match
index = 1
for path in match:
print "match", index
print "\tatoms", path.atoms
print "\tbond", path.bonds
index = index + 1
print "*"*33... |
#
# (c) Copyright 2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017-2018 SUSE 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-... |
import json
from qc_bot.qc_bot import bot
from qc_bot import bot_commands, bot_events
# Modules bot_commands, bot_events are imported
# just to run the code in them
if __name__ == "__main__":
config = None
with open("config.json", "r") as config_file:
config = json.load(config_file)
discord_api_... |
#!/bin/python
from os import path
from shutil import copyfile, copy
from io import open
import fnmatch
import os
resxfiles = "oem_files.conf"
corpconf = "oem.properties"
rcconf = "oem_resources.conf"
src = path.abspath("resources")
dst = path.abspath("..\..")
resx=[]
def getResx(dir, resx):
for root, dirs, files... |
"""
Get records from the table
returns dict if `dictionary is True`
==> https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-cursor.html
"""
import json
from mysql.connector import Error as mysqlError
from typing import List
from helperFunc import getRecordsCount
# get all records
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 10:29:38 2017
@author: neh69
"""
import os
import sys
import numpy as np
import pandas as pd
import lmfit as lm
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from PyQt5 import QtCore, QtWidgets
import visionplot_widgets
... |
import random
import time
import cPickle
import numpy as np
import subprocess as sub
class Optimizer(object):
def __init__(self, pop, selection_func, mutation_func, evaluation_func, num_rand_inds=1):
self.pop = pop
self.select = selection_func
self.mutate = mutation_func
self.evalu... |
import re
import struct
import unicodedata
from .regex import (
EMAIL_REGEX,
EMOJI_REGEX,
HASHTAG_REGEX,
MULTIWHITESPACE_REGEX,
NON_ALNUMWHITESPACE_REGEX,
TELEGRAM_LINK_REGEX,
URL_REGEX,
)
def add_surrogate(text):
return ''.join(
# SMP -> Surrogate Pairs (Telegram offsets are ... |
from skimage.measure import compare_ssim
import imutils
import cv2
imageA = cv2.imread("images/t.png")
imageB = cv2.imread("images/t1.png")
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff... |
class MicroarrayModule:
def __init__(self, owner):
self.owner = owner
def get_parameter_set(self):
return self.owner.get_parameter_set()
def get_m_query_id(self):
return self.owner.get_m_query_id()
def get_t_metadata(self):
return self.owner.get... |
class MessageBus(object):
def __init__(self):
self.handlers = {}
def register_handler(self, event, handler):
if event in self.handlers:
self.handlers[event].append(handler)
else:
self.handlers[event] = [handler]
def fire_event(self, event, **params):
... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... |
"""
Slack Bot Commands Loader
"""
import os
from ebr_trackerbot import module_loader
module_loader.load(os.path.dirname(__file__), "ebr_trackerbot.storage")
|
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from cowpy import cow
import json
import sys
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
parsed_qs = parse_qs(parsed_path.query)
... |
#!/usr/bin/python
def stringWrap(toWrap):
'''
@param {String} toWrap
@return ""toWrap""
Ie, if you call
print(self.stringWrap('mesh'));
> "\"mesh\""
'''
if not toWrap:
return '""'
return '"\\"' + toWrap + '\\""'
def numWrap(toWrap):
return str(toWrap);
##Note: this... |
from django.apps import AppConfig
class PagesConfig(AppConfig):
name = 'glitter.pages'
label = 'glitter_pages'
verbose_name = 'Pages'
def ready(self):
super().ready()
from . import listeners # noqa
|
"""
Recursive Digit
We define super digit of an integer x using the following rules:
If x has only 1 digit, then its super digit is x.
Otherwise, the super digit of x is equal to the super digit of the sum of the digits of x.
For example, the super digit of x will be calculated as:
super_digit(9875) 9+8+7+5 = 29... |
"""The tests for the litejet component."""
import logging
from openpeerpower.components import light
from openpeerpower.components.light import ATTR_BRIGHTNESS
from openpeerpower.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from . import async_init_integration
_LOGGER = logging.getLogger(__name__)
... |
import random
import threading
import time
try:
import Queue
except:
import queue as Queue
class producer:
def __init__(self):
self.food = ["ham", "soup", "salad"]
self.nexttime = 0
def run(self):
global q
while (time.clock() < 10):
if (self.nexttime < tim... |
"""
JSON and meta-data blocks, primarily used for SEO purposes.
"""
import json
from django import forms
from django.utils.translation import ugettext_lazy as _
from wagtail.core import blocks
from coderedcms import schema
from .base_blocks import MultiSelectBlock
class OpenHoursValue(blocks.StructValue):
"""
... |
from argparse import (
ArgumentParser,
Namespace,
_SubParsersAction,
)
import logging
import pathlib
import rlp
from eth_utils import ValidationError
from eth.abc import ChainAPI
from eth.db.atomic import AtomicDB
from eth.db.backends.level import LevelDB
from eth.exceptions import HeaderNotFound
from et... |
__author__ = 'Andreas M. Wahl'
from autosim.SimulationAutomator import SimulationAutomator
from configurator.ranges.RangeGenerator import RangeGenerator
from configurator.visualization.Plotter import Plotter
from configurator.persistence.PersistenceManager import PersistenceManager
import yaml
from configurator.util.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 6 11:35:30 2020
@author: christian
"""
import speaknspell
import matplotlib.pyplot as plt
import numpy as np
from scipy.io.wavfile import read
plt.style.use('paper')
data = read("./Voice Recordings/Short _a_.wav")
y = data[1][:, 0]
x = np.arang... |
from django.contrib.auth.models import User
from django.db import models
from Cinema.models import Movie
class Comment(models.Model):
user=models.ForeignKey(User,on_delete=models.SET_NULL,null=True)
movie=models.ForeignKey(Movie,on_delete=models.CASCADE)
text=models.CharField(max_length=200)
date_cre... |
tot = barato = contamil = contador = 0
baratonome = ''
while True:
nome = str(input('Informe o nome do produto: '))
preco = float(input('Informe o preço do produto: R$'))
contador += 1
if contador == 1 or preco < barato:
barato = preco
baratonome = nome
tot += preco
if preco > 10... |
import pandas as pd
import os
from upload_dados import *
import seaborn as sns
import matplotlib.pyplot as plt
os.system('cls')
#3. Existem correlações entre as características de um anúncio e seu faturamento?
# a. Quais? Explique
# filtrando todos os dados somente dos anuncios alugados
data_df = data_df.loc[data_d... |
"""
* Copyright 2009 Mark Renouf
*
* 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, s... |
"""
models/one_d.py
Author: Ankit Gupta
Implementations of the core DenseNet model
This module contains helper functions that define a DenseNet computational graph in Keras.
Note that these functions are not immediately usable for classification, as the outputs
are not softmaxed, and the functions have not been wrap... |
from django.shortcuts import redirect
from django.http import HttpResponse
from django.template import loader
def index(request):
if request.user.is_authenticated:
user = request.user
context = {
'user': user,
}
template = loader.get_template('patienthistory/home.html'... |
from sparksampling.core.job.base_job import BaseJob
from pyspark.sql import DataFrame
class BasicStatisticsJob(BaseJob):
def __init__(self, *args, **kwargs):
super(BasicStatisticsJob, self).__init__()
def _statistics(self, df: DataFrame, *args, **kwargs) -> dict:
self.logger.info("Generating ... |
# Copyright (c) 2020 the Eclipse BaSyx Authors
#
# This program and the accompanying materials are made available under the terms of the MIT License, available in
# the LICENSE file of this project.
#
# SPDX-License-Identifier: MIT
"""
Module for the creation of an example :class:`~aas.model.submodel.Submodel` template... |
from selenium import webdriver
from selenium.webdriver.support.select import Select
from bs4 import BeautifulSoup
import re
import Course
#Functions
def remove_html_tags(string):
return re.sub(r'<[^<]+?>', '', string)
# Place asterisk in course name and convert to upper
def prep_course(course_name):
g = re.match(r... |
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import (
url_changes
)
url = 'https://selenium.dunossauro.live/aula_10_c.html'
browser = Firefox()
browser.get(url)
wdw = WebDriverWait(browser, 10)
link = browser.f... |
# -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
import logging
from .base_swfilter import BaseSWFilter
class NormSWFilter(BaseSWFilter):
"""
...
"""
__logger = logging.... |
# SPDX-License-Identifier: Apache-2.0
from onnx import onnx_pb as onnx_proto
from ...common._registration import register_converter, register_shape_calculator
from ...common.utils import check_input_and_output_numbers
from ...common.data_types import *
def convert_sparkml_vector_indexer(scope, operator, container):
... |
"""
All constants, imports and functions.
by Bobobert
"""
### Imports
import matplotlib.pyplot as plt
import numpy as np
from abc import ABC
from math import ceil, floor
FLOAT_DEFT = np.float32
UINT_DEFT = np.uint8
INT_DEFT = np.int32 |
from typing import *
@overload
def date_range(start: Literal["2000-01-01"], periods: int):
"""
usage.xarray: 27
"""
...
@overload
def date_range(start: Literal["1999-01-05"], periods: int):
"""
usage.xarray: 1
"""
...
@overload
def date_range(start: Literal["2000-02-01"], periods: ... |
# GUI reader side: like pipes-gui1, but make root window and mainloop explicit
from tkinter import *
from PP4E.Gui.Tools.guiStreams import redirectedGuiShellCmd
def launch():
redirectedGuiShellCmd('python -u pipe-nongui.py')
window = Tk()
Button(window, text='GO!', command=launch).pack()
window.mainloo... |
from . import builtin
|
import requests
import json
parameters = {
# 'address' : '19.108914019118583, 72.86535472954193'
'address' : '19.1067657, 72.8639412'
}
response = requests.get("https://plus.codes/api", params=parameters)
r = json.loads(response.text)
print(r['plus_code']['global_code'])
|
import argparse
import pprint
from typing import Any
import torch
from transformers import AutoTokenizer, BartForConditionalGeneration
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
def pretty_convert(x: Any) -> Any:
if isinstance(x, torch.Tensor):
return x.tolist()
else:
... |
"""
fs.appdirfs
===========
A collection of filesystems that map to application specific locations.
These classes abstract away the different requirements for user data across platforms,
which vary in their conventions. They are all subclasses of :class:`fs.osfs.OSFS`,
all that differs from `OSFS` is the constructor ... |
#!/usr/bin/env python3
import re
import urllib.request
import os
from dockerfile_parse import DockerfileParser
from whalelinter.app import App
from whalelinter.utils import DockerfileCommand
class Parser(DockerfileParser):
def __init__(self, filename):
DockerfileParser.__init__(self, cache_content=True)... |
import six
import json
import threading
from rdflib import URIRef, BNode, Literal, Namespace
from rdflib.namespace import RDF, XSD
from ckanext.dcat.profiles import RDFProfile, VCARD, DCAT, DCT, FOAF, SKOS, ADMS, SPDX, LOCN, GSP
from ckanext.dcat.utils import resource_uri, url_quote
from ckan.plugins import toolkit as ... |
import numpy as np
class Problem:
def __init__(self):
self.states = []
def p(self, s, next_s, action):
return 0
def r(self, s, next_s, action):
return 0
def a(self, s):
return []
def value_iteration(problem, gamma=0.9, theta=0.001):
value = np.zeros(len(proble... |
from ceci import PipelineStage
from descformats import TextFile, HDFFile, YamlFile
import subprocess
import os
# This class runs the python3 version of BPZ from the command line
class BPZpipeStage1(PipelineStage):
"""Pipeline stage to run the BPZpy3 version of BPZ
The inputs and outputs are named in the as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.