content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import unittest
import os
import spreadsheet
from Exceptions import *
from Cell import Cell
class ReadTests(unittest.TestCase):
def setUp(self):
spreadsheet.spreadsheet = {}
def test_read_command__malformatted_arg(self):
with self.assertRaises(InputException):
spreadsheet.read_c... | python |
# -*- coding: utf-8 -*-
"""INK system utilities module.
"""
from base64 import b64encode
import hashlib
import sys
from ink.sys.config import CONF
def verbose_print(msg: str):
"""
Verbose Printer.
Print called message if verbose mode is on.
"""
if CONF.debug.verbose and CONF.debug.verbose_leve... | python |
import discord
import asyncio
import MyClient
from threading import Thread
print("Discord.py Voice Recorder POC")
DISCORD_TOKEN = ""
client = MyClient.MyClient()
client.run(DISCORD_TOKEN)
| python |
import asyncio
import copy
import functools
from contextlib import contextmanager
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
List,
Optional,
Reversible,
Tuple,
Type,
TypeVar,
Union,
)
from telethon.client.updates import EventBuilderDict
from tele... | python |
# -*- coding: utf-8 -*-
""" Manifest Decorator Tests
"""
from django.urls import reverse
from tests.base import ManifestTestCase
class DecoratorTests(ManifestTestCase):
"""Tests for :mod:`decorators <manifest.decorators>`.
"""
def test_secure_required(self):
"""Should redirect to secured versio... | python |
# Operadores aritmeticos
22 + 22 # Suma
22 - 2 # Resta
22 / 2 # Divison
22 // 2 # Divison entera
22 * 2 # Multiplicacion
22 % 2 # Modulo
22 ** 2 # Exponente
# Operadores de asignacion
numero = 0
numero += 2
numero -= 1
numero *= 9
numero /= 3
# Operadores de comparacion
numero1 = 5
numero2 = 3
print(numero1 ==... | python |
from sqlalchemy import *
import testbase
class SingleInheritanceTest(testbase.AssertMixin):
def setUpAll(self):
metadata = BoundMetaData(testbase.db)
global employees_table
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
... | python |
import pytest
from hypothesis import given
from tests.strategies import med_ints, small_floats
from tinytorch import module
class ModuleA1(module.Module):
def __init__(self):
super().__init__()
self.p1 = module.Parameter(5)
self.non_param = 10
self.a = ModuleA2()
self.b = ... | python |
import sys
sys.path.append('../')
from pycore.tikzeng import *
import math
network = []
f = open("./arch_yolov3.txt", "r")
for x in f:
layer = {}
input_1 = x.split()
layer["id"] = input_1[0]
layer["type"] = input_1[1]
if("->" in x):
input_2 = x.split("->")[1].split()
layer["height... | python |
import os
from mkmapi.exceptions import MissingEnvVar
def _get_env_var(key):
try:
return os.environ[key]
except KeyError:
raise MissingEnvVar(key)
def get_mkm_app_token():
return _get_env_var('MKM_APP_TOKEN')
def get_mkm_app_secret():
return _get_env_var('MKM_APP_SECRET')
def ge... | python |
import argparse
import uuid
import sys
import socket
import eventlet
import eventlet.event
import eventlet.greenpool
from localtunnel import util
from localtunnel import protocol
from localtunnel import __version__
def open_proxy_backend(backend, target, name, client, use_ssl=False, ssl_opts=None):
proxy = event... | python |
# MP3
import selenium
import pygame
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('c:/Users/wmarc/OneDrive/Documentos/UNIVESP/Curso em Video/Desafio_021.mp3')
pygame.mixer.music.play()
pygame.event.wait() | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import argparse
import os.path
import re
import sys
import tarfile
import os
import datetime
import math
import random, string
import base64
import json
import time
from time import sleep
from time i... | python |
#
# Copyright (c) SAS Institute, Inc.
#
# 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, di... | python |
from magicbot import StateMachine, state, timed_state
from components.cargo import CargoManipulator, Height
from components.vision import Vision
class CargoManager(StateMachine):
cargo_component: CargoManipulator
vision: Vision
def on_disable(self):
self.done()
def intake_floor(self, force... | python |
import os
import pandas
import geopandas
from shapely.geometry import Polygon, LineString
from shared import print_
geopandas.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
COLUMNS_TO_DROP = ["Description"]
def generate_regions(**kwargs):
print_("GENERATE REGIONS", title=True)
print_("Parameters... | python |
# -*- coding: utf-8 -*-
import unittest
from copy import deepcopy
from openregistry.lots.core.tests.base import snitch
from openregistry.lots.bargain.tests.base import (
LotContentWebTest
)
from openregistry.lots.core.tests.blanks.json_data import test_loki_item_data
from openregistry.lots.bargain.tests.blanks.it... | python |
# -*- coding: utf-8 -*-
import re
from datetime import timedelta
from django.contrib.auth.models import Group
from django.contrib.auth import authenticate
from django.core.validators import EMPTY_VALUES
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext_lazy a... | python |
import unittest
from tests.refactor.utils import RefactorTestCase
from unimport.constants import PY38_PLUS
class TypingTestCase(RefactorTestCase):
include_star_import = True
@unittest.skipIf(
not PY38_PLUS, "This feature is only available for python 3.8."
)
def test_type_comments(self):
... | python |
# Copyright 2012 Google Inc. All Rights Reserved.
"""Simulator state rules for the build system.
Contains the following rules:
compile_simstate
"""
__author__ = 'benvanik@google.com (Ben Vanik)'
import io
import json
import os
import sys
import anvil.async
from anvil.context import RuleContext
from anvil.rule imp... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 14:32:57 2020
@author: Administrator
"""
"""
回文字符串是指一个字符串从左到右与从右到左遍历得到的序列是相同的.例如"abcba"就是回文字符串,而"abcab"则不是回文字符串.
"""
def AddSym2Str(s):
if len(s) == 0:
return '*'
return ('*' + s[0] + AddSym2Str(s[1:]))
def GetPalLen(i , s):
lens... | python |
from bson import ObjectId
from db.db import Database
from db.security import crypt
import datetime
class Users(Database):
_id: str
name: str
cpf: str
email: str
phone_number: int
created_at: str
updated_at: str
def __init__(self):
super().__init__()
def create_user(self, ... | python |
binomski_slovar = {(1, 1): 1}
for n in range(2, 101):
for r in range(n + 1):
if r == 0:
binomski_slovar[(n, r)] = 1
elif r == 1:
binomski_slovar[(n, r)] = n
elif r == n:
binomski_slovar[(n, r)] = binomski_slovar[(n - 1, r - 1)]
else:
... | python |
# -*- coding: utf-8 -*-
'''
@Time : 4/20/2022 4:36 PM
@Author : dong.yachao
''' | python |
'''Crie uma classe para implementar uma conta corrente.
A classe deve possuir os seguintes atributos: número da conta,
nome do correntista e saldo. Os métodos são os seguintes:
alterarNome, depósito e saque; No construtor, saldo é opcional,
com valor default zero e os demais atributos são obrigatórios.'''
class ... | python |
from dataclasses import dataclass
from bindings.csw.abstract_coordinate_system_type import AbstractCoordinateSystemType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class ObliqueCartesianCstype(AbstractCoordinateSystemType):
"""A two- or three-dimensional coordinate system with straight axes that
... | python |
from dataclasses import dataclass, field
from typing import Optional
from serde import deserialize
from metaphor.common.filter import DatasetFilter
from metaphor.snowflake.auth import SnowflakeAuthConfig
from metaphor.snowflake.utils import DEFAULT_THREAD_POOL_SIZE
@deserialize
@dataclass
class SnowflakeRunConfig(S... | python |
# -*- coding: utf-8 -*-
#####################################################################
# Peach - Python para Inteligência Computacional
# José Alexandre Nalon
#
# Este arquivo: demo07.py
# Demonstração e teste, Mapeamento de uma função não linear.
################################################################... | python |
from django.conf.urls import url
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.home_teamlead),
url(r'^index_teamlead$', views.index_teamlead, name='index_teamlead'),
url(r'^holidays_teamlead$', views.holidays_teamlead, name='... | python |
from base64 import b64decode
from zlib import decompress
from os import system
inputFile = "handcrafted-pyc.py_bc552f58fe2709225ca0768c131dd14934a47305"
magicHeader = b"\x03\xf3\x0d\x0a\xfb\x1c\x32\x59"
outputPycFile = "dump.pyc"
outputSrcFile = "output.py"
uncompyleExe = "uncompyle6"
code = 'eJyNVktv00AQXm/eL0igiaFA... | python |
import numpy as np
from scipy.signal import find_peaks
import os
import pycst_ctrl
class PyCstDataAnalyser:
""" Used to analyse data exported by CST"""
def __init__(self, opts):
# Initialize attributes
# Polarization indicator
self.pol_ind = opts.get('pol_ind', 'lin_dir')
#... | python |
# -*- coding:utf-8 -*-
"""
@description:
"""
import os
import sys
import numpy as np
import torch
from jiwer import wer
import sacrebleu
sys.path.append('..')
import config
from data_reader import load_word_dict
from seq2seq_model import Seq2SeqModel
from utils.logger import logger
device = torch.device("cuda" if t... | python |
# Copyright 2016, 2017 John J. Rofrano. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | python |
"""Helper neural network training module."""
from collections import OrderedDict
from pathlib import Path
from time import time
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from ..datasets import IMAGE_SHAPES, get_loader
from ..models import fit_to_dataset, get_model
from ..mod... | python |
from PyQt5 import QtWidgets
from otter.OListView import OListView
class TemplatesTab(QtWidgets.QWidget):
"""
List of recent file that show on the MainWindow
"""
def __init__(self, parent):
super().__init__(parent)
main_layout = QtWidgets.QVBoxLayout()
main_layout.setContentsM... | python |
import string
def alphabetSubsequence(s):
seen = -1
for i in s:
index = string.ascii_lowercase.find(i)
if index > seen:
seen = index
else:
return False
return True
s = "effg"
print(alphabetSubsequence(s))
| python |
import os
import sys
import inspect
import string
import numpy as np
PycQED_py3_dir = "D:\\Github\\PycQED_py3"
AssemblerDir = PycQED_py3_dir + \
"\\instrument_drivers\\physical_instruments\\_controlbox"
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()... | python |
val = input().split()
a, b, c = val
a = float(a)
b = float(b)
c = float(c)
if a < (a+b) and b < (c+a) and c < (a+b):
per = a + b + c
print('Area = %.2f' %per)
| python |
import pandas
import numpy
import filepaths
import utils
def fetch_ng_inflation_cpi():
stats_metadata = utils.read_stats_metadata()
url = stats_metadata['NG']['inflation']['CPI']['url']
tmp_filepath = utils.download_file(url)
df = pandas.read_excel(tmp_filepath, sheet_name='Table1', header=None)
... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import datetime
UNIQUE_REDIS_KEY_PREFIX = 'celery_unique'
class UniqueTaskMixin(object):
abstract = True
unique_key = None
redis_client = None
def apply_asyn... | python |
from . import hist, quality
| python |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Node.js st module Directory Traversal''',
"description": '''A directory traversal vulnerability in the st module before 0.2.5 for Node.js allows remote attackers to read arbitrary files via a %2e%2e (e... | python |
__copyright__ = "Copyright 2015 Contributing Entities"
__license__ = """
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 re... | python |
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.matcher import Matcher, PhraseMatcher
from spacy.tokens import Span
import string
from nltk.corpus import stopwords
import pandas as pd
def phrase_template():
'''
This function returns a list of all the possible technical terms that has high possibilit... | python |
# Import the agent class
#from .agenttemplate import AgentTemplate
| python |
# Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
# SPDX-License-Identifier: MIT
"""
Contains functions specific to decoding and processing inference results for YOLO V3 Tiny models.
"""
import cv2
import numpy as np
def iou(box1: list, box2: list):
"""
Calculates the intersection-over-union... | python |
from xml.etree.ElementTree import tostring
from f1_telemetry.server import get_telemetry
from kusto.ingest import ingest_kusto
from datetime import datetime
batch_freq_high = 9 # 20 cars per packet * batch_freq_high(x) packets
batch_freq_low = 2
ingest_cartelemetrydataCnt = 0
ingest_cartelemetryBuffer = ""
ingest_ses... | python |
"""Integration test for pytype."""
from __future__ import print_function
import csv
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
from pytype import config
from pytype import main as main_module
from pytype import utils
from pytype.pyi import parser
from pytype.py... | python |
#!/usr/bin/env python
import argparse
def main(args):
"""
This is some doc
"""
print(args)
def sub_function():
"""
Here is some doc about this sub function
"""
pass
def parse_arguments():
parser = argparse.ArgumentParser(description="")
parser.add_argument("-t", "--type", d... | python |
while (True):
print("mohammed uddin made changes")
print(":D")
| python |
# logic.py to be
import random
global actual_score
def start_game():
# declaring an empty list then
# appending 4 list each with four
# elements as 0.
mat = []
for i in range(4):
mat.append([0] * 4)
# calling the function to add
# a new 2 in grid after every step
add_new_2(ma... | python |
import os
from flask import request, render_template, redirect, session, Blueprint, flash, jsonify, abort, send_from_directory
from werkzeug.utils import secure_filename
import indieweb_utils
from bs4 import BeautifulSoup
import requests
from config import ENDPOINT_URL, TWITTER_BEARER_TOKEN, UPLOAD_FOLDER, MEDIA_ENDP... | python |
"""Docstring for varnet.py
Normalized U-Net implemetnation for unrolled block network.
"""
import math
from typing import List, Tuple
import fastmri
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastmri.data import transforms
from unet import MHUnet
from att_unet import AttUnet
class Nor... | python |
import pygame
import numpy as np
from time import sleep
class GameOfLife:
def __init__(self):
pygame.init()
self.size = 800
self.divisions = 100
self.length = self.size // self.divisions
self.screen = pygame.display.set_mode((self.size, self.size))
self.fps = 120
... | python |
import numpy as np
import torch
import torchvision
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.manifold import TSNE
import os
from .model import resnet
from PIL import ImageFilter
import random
def adjust_learning_rate(args, optimizer, epoch, lr):
# if args.cosine:
# eta_min = l... | python |
x = int(input())
if x % 2 == 0:
y = x + 1
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
else:
y = x
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
y = y + 2
print(y)
| python |
from datetime import datetime
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http... | python |
# https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
p, res = x, 0
while p:
res = res * 10 + p % 10
p = int(p/10)
return res == x | python |
import numpy as np
import multiprocessing
import xgboost as xgb # requires xgboost package, installed e.g. via 'pip install xgboost'
class XGBoost:
def __init__(self, train_loader, val_loader, x_shape, dim_out, args):
self.args = args
self.dim_out = dim_out
if args.regression:
... | python |
import os
import time
# 请求用户输入要循环开关闭的网卡名称
eth_name = input('请输入要循环启用关闭的网卡名称:')
# 记录循环次数
i = 1
while True:
# 关闭指定网卡
os.popen('ifconfig ' + eth_name + ' down')
print(eth_name + '网卡关闭了')
# 休眠5S
time.sleep(5)
# 开启指定网卡
os.popen('ifconfig ' + eth_name + ' up')
print(eth_name + '网卡开启了')
# ... | python |
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title,
size=(400, 200))
self.Move((800, 250))
#self.Centre()
def main():
app = wx.App()
ex = Example(None, title='M2I & MQL - Moving Wind')
... | python |
"""
This file defines common tags to use in templates
"""
from django import template
from django.contrib import messages
from django.template.defaultfilters import safe
register = template.Library()
@register.filter(name="make_spaces")
def make_spaces(in_string: str) -> str:
"""
This filter takes a... | python |
import json
from google.protobuf import json_format
from services.doubler.doubler_pb2 import Number
def build_request_from_dict(d, request):
json_str = json.dumps(d)
return json_format.Parse(json_str, request)
def build_request_from_file(filename, request):
with open(filename) as f:
json_str = ... | python |
from .convLSTM import StConvLSTM
from .GRU import StGRU
from .additive import StAdditive
from .LSTM import StLSTM
| python |
#!/usr/bin/env python
"""
Example of a telnet application that displays a dialog window.
"""
from __future__ import unicode_literals
from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.shortcuts.dialogs import yes_no_dialog
from prompt_toolkit.eventloop import From, get_event_loop
import... | python |
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def contruindo_relatorio(service, creds, SAMPLE_SPREADSHEET_ID, lista):
# Quantidade Ped... | python |
'''
Created on Jan 6, 2016
@author: T0157129
'''
import logging
import logging.config
from Items.PotionObject import PotionObject
class MyCharacter:
'''
This class represents a basic character.
Attributes:
int HP : represents the Health Points of the character.
If HP==0 the chara... | python |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
ans = []
for intv in sorted(intervals,... | python |
from __future__ import division
import os,time,cv2
import scipy.io as sio
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
from numpy import *
import scipy.linalg
from copy import copy, deepcopy
def lrelu(x):
return tf.maximum(x*0.2,x)
def identity_initializer():
def _initiali... | python |
import tweepy
from tweepy.parsers import JSONParser
# This class creates an instance of the Twitter API
class API(object):
# Initiates the API
def __init__(self):
# Keys for Twitter API (maybe reading it from a .txt)
self.consumer_key = 'EfbgNEMgmXNSweNDcWmoaSwm0'
self.consumer_secret ... | python |
# coding=utf-8
import threading, time, re, os, sys, json, random
try:
import requests
except ImportError:
print '---------------------------------------------------'
print '[*] pip install requests'
print ' [-] you need to install requests Module'
sys.exit()
'''
\ \ / /__ _ ... | python |
"""
methods for processing mapping results in SAM/BAM format
def parse_deltas(sam_file, ...):
parse a sam/bam file into dicts of coverage changes by position
def deltas_to_cov(cov_deltas, x_max=None, nan_for_zero=True):
convert coverage deltas into coverage array
class SAMFlag(IntFlag):
class for dec... | python |
"""
Module for requesting to URL and get page's html code from there,
download media files, check that the request if correct, page in RNC exists.
"""
__all__ = (
'get_htmls', 'is_request_correct', 'download_docs'
)
import asyncio
import logging
import time
from typing import List, Optional, Tuple, Union
import ... | python |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2013-2014 Alex Forencich
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... | python |
from maskcnn import training_aux_wrapper
from sys import argv
def main():
dataset, image_subset, neuron_subset, seed, arch_name, opt_name = argv[1:]
training_aux_wrapper.train_one_wrapper(dataset, image_subset, neuron_subset, int(seed), arch_name, opt_name)
if __name__ == '__main__':
main()
| python |
import numpy
import unittest
import sycomore
from sycomore.units import *
class TestBloch(unittest.TestCase):
def test_pulse(self):
M = sycomore.bloch.pulse(47*deg, 23*deg)
numpy.testing.assert_almost_equal(
M,
[[ 0.95145043, 0.11437562, 0.28576266, 0. ],
... | python |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from project.tweets.views import TweetsViewset
router = DefaultRouter()
router.register(r"tweets", TweetsViewset, basename="tweets")
urlpatterns = [
path("", include(router.urls)),
]
| python |
import random
import names
import csv
from django.template.defaultfilters import slugify
from orcamentos.crm.models import Customer, Person, PhonePerson
from orcamentos.utils.lists import COMPANY_LIST
from orcamentos.utils.gen_random_values import (
gen_cpf,
gen_digits,
gen_phone,
gen_rg,
)
from orcamen... | python |
from urllib.request import urlopen
def get_page_3(url):
pagina = urlopen(url)
codigoHtml = pagina.read().decode('utf')
pagina.close()
return codigoHtml
def get_next_target(website):
start_link= website.find('<a href')
if (start_link) != -1:
start_quote= website.find('"',start_link... | python |
/home/runner/.cache/pip/pool/cf/51/25/b749cb02a5396340ce9fda7fffc4272d66af9443a947242291d6202aba | python |
def proc():
str = input()
fp = open('./dict/person.dic', mode='rt', encoding='utf-8')
while True:
line = fp.readline()
if not line:
break
if str in line:
return
fp.close()
fp = open('./dict/person.dic', mode='at', encoding='utf-8')
fp.write('\n%s/... | python |
import numpy as np
import libs.state_node as STTREE
class HillClimbing:
def __init__(self, initialPuzzle, answerPuzzle, k):
self.totalExpansions = 0
self.k = k
self.answerPuzzle = answerPuzzle.puzzle
self.frontier = []
self.frontier.append(
(
ST... | python |
# Generated by Django 3.1.13 on 2021-09-28 03:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('property', '0010_auto_20210928_0430'),
]
operations = [
migrations.AlterField(
model_name='property',
name='propert... | python |
from supermarket import Supermarket
from Markov import Get_Entry
entry = Get_Entry()
lidl = Supermarket(name='LIDL', entry = entry)
while lidl.is_open():
# increase the time of the supermarket by one minute
# generate new customers at their initial location
# repeat from step 1
lidl.add_new_cust... | python |
"""
Timeseries plots with error bands
=================================
_thumb: .5, .45
"""
import seaborn as sns
sns.set(style="darkgrid")
# Load an example dataset with long-form data
fmri = sns.load_dataset("fmri")
# Plot the responses for different events and regions
sns.lineplot(x="timepoint", y="signal",
... | python |
from typing import Literal, Any, List, Dict
from flask_sqlalchemy import SQLAlchemy
from base64 import b32encode
from flask import session
from globals import *
import xml.etree.ElementTree as ET
import sqlite3
import secrets
import random
import error
import re
import os
db = SQLAlchemy(app)
Role = Literal['s', 'u'... | python |
import bitwise as bw
class TestStackPointer:
def test_StackPointer(self):
up = bw.wire.Wire()
down = bw.wire.Wire()
clock = bw.wire.Wire()
output_bus = bw.wire.Bus16()
a = bw.processor.StackPointer(up, down, clock, output_bus)
clock.value = 0
clock.value =... | python |
from django.db import models
class Suggestion(models.Model):
name = models.CharField(max_length=100, unique=True)
class ImageTag(models.Model):
game = models.CharField(max_length=100)
image = models.CharField(max_length=50)
tag = models.CharField(max_length=200)
class Favorite(models.Model):
u... | python |
"""
byceps.blueprints.site.core.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from typing import Optional
from flask import g, url_for
from .... import config
from ....services.party im... | python |
from .qtscraper import *
from ._version import __version__
def setup(app):
from .qtgallery import setup
return setup(app)
| python |
# -*- coding: utf-8 -*-
# Copyright 2012 Google Inc. 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 require... | python |
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
class VGG19(Sequential):
def __init__(self):
super().__init__()
self.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(224, 224, 3), padding='same', a... | python |
import sys
import time
import numpy as np
import pandas as pd
import datetime as dt
import multiprocessing as mp
class MultiProcessingFunctions:
""" This static functions in this class enable multi-processing"""
def __init__(self):
pass
@staticmethod
def lin_parts(num_atoms, num_threads):
""" This function... | python |
#!/usr/bin/python3
# ============================================================================
# Airbnb Configuration module, for use in web scraping and analytics
# ============================================================================
import logging
import os
import configparser
import sys
from bnb_kanpora.m... | python |
import _hgdb
class DebugSymbolTableException(Exception):
def __init__(self, what):
super().__init__(what)
# wrapper class
class DebugSymbolTable:
def __init__(self, filename):
self.db = _hgdb.init_debug_db(filename)
def store_variable(self, id_: int, value: str, is_rtl: bool = True):
... | python |
#This program takes a csv file of financial data as input and produces
#a statistical report stored to a csv file and printed to the terminal.
#The input file must contain a series of months with corresponding profits
#and losses. The output report includes the total number of months analyzed,
#the net total amount of ... | python |
import numpy as np
import tensorflow as tf
import time
# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="output/model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_de... | python |
#!/usr/bin/env python2
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import datetime
import optparse
import os
import re
import sys
import urlparse
import gclient_utils
import subprocess2
USAGE = ... | python |
# -*- coding: utf-8 -*-
"""
MagicTelecomAPILib.Models.Account
This file was automatically generated by APIMATIC v2.0 on 06/22/2016
"""
from MagicTelecomAPILib.APIHelper import APIHelper
class Account(object):
"""Implementation of the 'Account' model.
TODO: type model description here.
... | python |
# Linear regression on iris dataset
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = os.path.join(os.environ["PYPROBML"], "figures")
def save_fig(fname): plt.savefig(os.path.join(figdir, fname))
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn import datasets... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.