content stringlengths 5 1.05M |
|---|
from __future__ import annotations
from textwrap import dedent
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
from pandas.util._decorators import doc
from pandas.util._validators import validate_bool_kwarg
from dtoolkit._typing import SeriesOrFrame
from dtoolkit.accessor._util import get_mas... |
# Meta / Dialog / Closable
# Display a #dialog having a close button, and detect when it's closed. #meta
# ---
from h2o_wave import main, app, Q, ui
@app('/demo')
async def serve(q: Q):
if not q.client.initialized:
# Create an empty meta_card to hold the dialog
q.page['meta'] = ui.meta_card(box=''... |
from dataset_specifications.housing import HousingSet
class HouseAgeSet(HousingSet):
def __init__(self):
super().__init__()
self.name = "house_age"
self.x_dim = 2
# Modified version of the California house price dataset (housing)
# Predict house age only from coordinates o... |
import pickle
import os
import time
from enum import Enum
from .. import config
class Status(Enum):
""" Enum containing all statuses Ricecooker can have
Steps:
INIT: Ricecooker process has been started
CONSTRUCT_CHANNEL: Ricecooker is ready to call sushi chef's construct_channel me... |
from PyQt6.QtWidgets import (
QMainWindow,
QTreeWidgetItem,
QWidget
)
from PyQt6.QtGui import (
QIcon
)
from .mainwindow_ui import Ui_MainWindow
from .defmodules import WIDGETS_DEFAULT
from .symmetric import WIDGETS_SYMMETRIC
from .asymmetric import WIDGETS_ASYMMETRIC
from .cryptotools import WIDGETS_... |
def fileInput(mainFilePath, inputFilePath):
with open(inputFilePath, 'a') as file:
file.write('\n')
with open(mainFilePath) as file:
script = "fileOpenAsInput = open('"+inputFilePath+"')\n"
line = file.readline()
while line != '':
if "fileInput" in line:
... |
"""Plotting referendum results in pandas.
In short, we want to make beautiful map to report results of a referendum. In
some way, we would like to depict results with something similar to the maps
that you can find here:
https://github.com/x-datascience-datacamp/datacamp-assignment-pandas/blob/main/example_map.png
To... |
import bson.json_util
import json
import math
import numpy
import pymongo
import scipy.linalg
import sys
import time
from findNodes import run as find_nodes
from neighborhood import run as get_neighborhood
class Cache:
def __init__(self, radius, namefield, host, db, coll):
self.radius = radius
se... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 14:51:15 2021
@author: crtjur
"""
# from tkinter import *
import tkinter as tk
# class GPIO(tk.Frame):
# """Each GPIO class draws a Tkinter frame containing:
# - A Label to show the GPIO Port Name
# - A data direction spin box to select pin as input or out... |
# -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# 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 la... |
# test_utils.py
"""Tests for rom_operator_inference.utils.py."""
import pytest
import numpy as np
from scipy import linalg as la
import rom_operator_inference as roi
# utils.lstsq_reg() -----------------------------------------------------------
def _test_lstq_reg_single(k,d,r):
"""Do one test of utils.lstsq_re... |
"""
Setup for different kinds of Goldair climate devices
"""
from . import DOMAIN
from .const import (
CONF_CLIMATE,
CONF_DEVICE_ID,
CONF_TYPE,
CONF_TYPE_AUTO,
CONF_TYPE_DEHUMIDIFIER,
CONF_TYPE_FAN,
CONF_TYPE_GECO_HEATER,
CONF_TYPE_GPCV_HEATER,
CONF_TYPE_GPPH_HEATER,
)
from .dehumidi... |
#!/usr/bin/env python
# Import modules
import numpy as np
import sklearn
from sklearn.preprocessing import LabelEncoder
import pickle
from sensor_stick.srv import GetNormals
from sensor_stick.features import compute_color_histograms
from sensor_stick.features import compute_normal_histograms
from visualization_msgs.ms... |
from collections import deque
class ZigzagIterator2:
"""
@param: vecs: a list of 1d vectors
"""
def __init__(self, vecs):
# do intialization if necessary
self.queue = [deque(vector) for vector in vecs]
"""
@return: An integer
"""
def next(self):
# write your co... |
import re
ranks = {
'S': -1,
'G': -2,
'F': -3,
'O': -4,
'P': -5
}
class KrakenTaxon:
__slots__ = ('percent', 'cum_reads', 'unique_reads', 'rank', 'taxid', 'name', 'indent', 'parent')
def __init__(self, percent, cum_reads, unique_reads, rank, taxid, name, indent):
self.percent ... |
"""Shows some basic dispatch examples."""
# Local package imports
from lhrhost.messaging.dispatch import Dispatcher
from lhrhost.messaging.presentation import Message, MessagePrinter
def print_dispatcher(dispatcher):
"""Print some deserializations."""
messages = [
Message('e', 123),
Message('... |
# Using batch size 4 instead of 1024 decreases runtime from 35 secs to 4 secs.
# Standard Library
import os
import shutil
import time
from datetime import datetime
# Third Party
import mxnet as mx
import pytest
from mxnet import autograd, gluon, init
from mxnet.gluon import nn
from mxnet.gluon.data.vision import data... |
import math
import money
class adpackmoney:
def __init__(self, bal, advert):
self.advert = advert
self.balance = bal
class adpack:
def __init__(self, worth, course, args):
self.worth = worth
self.course = course
self.args = args
self.earning = adpackmoney(0.0, ... |
import os
from pytest_shutil import env, run
TEMP_NAME = 'JUNK123_456_789'
def test_set_env_ok_if_exists():
ev = os.environ[TEMP_NAME] = 'junk_name'
try:
with env.set_env(TEMP_NAME, 'anything'):
out = run.run('env', capture_stdout=True)
for o in out.split('\n'):
... |
def summation(num):
return sum(xrange(1, num + 1))
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-20 23:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import portfolio.models
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
from Rationale_Analysis.models.rationale_extractors.base_rationale_extractor import RationaleExtractor
from allennlp.models.model import Model
import math
import numpy as np
@Model.register("max_length")
class MaxLengthRationaleExtractor(RationaleExtractor) :
def __init__(self, max_length_ratio: float) :
s... |
from wand.contrib.linux import get_hostname
from wand.apps.relations.kafka_relation_base import KafkaRelationBase
__all__ = [
"KafkaSRURLNotSetError",
"KafkaSchemaRegistryRelation",
"KafkaSchemaRegistryProvidesRelation",
"KafkaSchemaRegistryRequiresRelation",
]
class KafkaSRURLNotSetError(Exception):... |
#-*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
import sys, os.path
pkg_dir = os.path.dirname(os.path.realpath(__file__)) + '/../../'
sys.path.append(pkg_dir)
from scipy.stats import t
from collections import Counter
from MPBNP import *
np.set_printoptions(suppress=True)
... |
"proto_ts_library.bzl provides the proto_ts_library rule"
load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "JSModuleInfo")
def _proto_ts_library_impl(ctx):
"""
Implementation for proto_ts_library rule
Args:
ctx: the rule context object
Returns:
list of providers
... |
import unittest
from mock import MagicMock
import bilby
class TestPymultinest(unittest.TestCase):
def setUp(self):
self.likelihood = MagicMock()
self.priors = bilby.core.prior.PriorDict(
dict(a=bilby.core.prior.Uniform(0, 1), b=bilby.core.prior.Uniform(0, 1))
)
self.p... |
def return_cst():
return 1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Using the new (beta) MovieStim2 to play a video file.
Requires:
* vlc, matching your python bitness
* pip install python-vlc
"""
from __future__ import absolute_import, division
from psychopy import visual, core, event, data, logging, monitors
fro... |
from dataclasses import dataclass, asdict
from enum import Enum, auto
from typing import Type
import torch
import wandb
from datargs import argsclass
from torch import nn, Tensor
from preprocessor_meta import Preprocessor, filter_sig_meta
from gw_data import *
from models import HyperParameters, ModelManager
class ... |
from hsm.api.openstack import wsgi
from hsm.api.views import versions as views_versions
VERSIONS = {
"v1.0": {
"id": "v1.0",
"status": "CURRENT",
"updated": "2012-01-04T11:33:21Z",
"links": [
{
"rel": "describedby",
"type": "application/p... |
from urllib.parse import urlparse
import os
from archive_api.models import DataSet, MeasurementVariable, Site, Person, Plot, Author
from django.urls import resolve
from django.db import transaction
from rest_framework import serializers
from rest_framework.reverse import reverse
class StringToIntReadOnlyField(seri... |
#q.no.1
year=int(input("enter a year to check it is leap year or not:"))
if year%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
#q.no.2
length=int(input("enter length:"))
breadth=int(input("enter breadth:"))
def dimensions(l,b):
if l==b:
return("dimensions of squa... |
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from base.dependency.dependency_if import ModuleGrouper
from base.modules_if import ModuleListSupply
from commons.configurator import Configurator
from commons.config_util import ClassLoader
import logging
import sys
config_module_list_supply = ModuleListSupply()
config_... |
####
# EECS1015: Lab 5
# Name: Mahfuz Rahman
# Student ID: 217847518
# Email: [email protected]
####
import random
names = ("Masha", "Kevin", "Ruigang", "Vlad", "Ramesh", \
"Aditi", "Caroline", "Panos", "Chuck", "Grani", \
"Rutha", "Stan", "Qiong", "Alexi", "Carlos")
cities = ("Toronto", "Ottawa", "H... |
from .views import ProductViewSet, UserAPIView
from django.urls import path
urlpatterns = [
path('products', ProductViewSet.as_view({
'get': 'getAllProducts',
'post': 'postProduct'
})),
path('products/<str:pk>', ProductViewSet.as_view({
'get': 'getProduct',
'put': 'updatePro... |
# -*- coding: utf-8 -*-
"""This is a module demonstrating a script
A collection of functions that print 'script'.
Example:
This is an example that exemplifies in the ``Example`` section::
$ python script.py
New Section.
Attributes:
module_variable (str): A variable mentioned in the ``Attributes`` se... |
import torch
import torch.optim as optim
from sketch import SketchAlgorithm
import torch.nn.functional as F
import logging
import bagua.torch_api as bagua
from bagua.torch_api.algorithms import gradient_allreduce
USE_SKETCH = True
sketch_biases = False
def main():
torch.manual_seed(42)
torch.cuda.set_device(b... |
#vim: fileencoding=utf8
from __future__ import division, print_function
import sys, os.path, codecs, traceback
from rays import *
from rays.compat import *
from .base import *
import pytest
class TestEmbpy(Base): # {{{
def template(self, name):
return os.path.join(self.TEST_DIR, "templates", name)
... |
'''
Classifier : K Nearest Neighbour
DataSet : Inbuilt Winne Predictor Dataset
Features : Alcohol, Malic acid , Ash, Alcalinity of ash , Magnesium ,Total phenols , Flavanoids ,
: Nonflavanoid phenols , Proanthocyanins , Color intensity, Hue , OD280/OD315 of diluted wines, Proline.
Labels : Class... |
from __future__ import print_function
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import healpy as hp
from scipy.stats import binned_statistic
from ipywidgets import widgets
from IPython.display import display
import time
# LSST libraries, MAF metrics
import lsst.sims.maf.slicer... |
class IdentifierManager(object):
def __init__(self, start_id = 0):
self.next_id = start_id
def next(self):
self.next_id += 1
return self.next_id - 1
def next_n(self, n):
ret = xrange(self.next_id, self.next_id + n)
self.next_id += n
return ret
def get_... |
# Copyright 2019 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... |
from .anvilGoogleAuth import *
|
import pytest
from fileDownloader import FileDownloader
import requests
import os
from customErrors import DirectoryNotFoundError
import logging
from zipfile import ZipFile
class TestFileDownloader:
def test_validUrl(self, tmpdir):
with pytest.raises(requests.exceptions.MissingSchema):
FileDow... |
import discord
from discord.ext import commands
import cogs
import settings
import random
bot = commands.Bot(command_prefix='=')
bot.add_cog(cogs.Moderation(bot))
bot.add_cog(cogs.Fun(bot))
bot.add_cog(cogs.Utility(bot))
@bot.event
async def on_ready():
activity = discord.Activity(name=bot.command_... |
daftar = ['jeruk','mangga','apel']
while True:
cari = raw_input('Cari BUah : ')
if not cari:
print "selesai"
break
if cari in daftar:
print "Ditemukan pada index ke ",
print 1+ daftar.index(cari)
else:
print "tidak ketemu"
|
import os
import requests
import logging
import json
from time import time
from glob import glob
from .file_system_cache import FileSystemCache
DEFAULT_ENDPOINT = 'https://pangeabio.io'
logger = logging.getLogger('pangea_api') # Same name as calling module
logger.addHandler(logging.NullHandler()) # No output unle... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/billing/budgets_v1beta1/proto/budget_model.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.proto... |
# ABC167B - Easy Linear Programming
def main():
# input
A, B, C, K = map(int, input().split())
# compute
kotae = A+(K-A)*0-(K-A-B)
# output
print(kotae)
if __name__ == '__main__':
main()
|
import re
import asyncio
import sys
import os
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from utils import *
from instaloader import Profile
from pyrogram import Client, filters
from config import Config
chat_idd = int(Config.chat_idd)
USER = Config.USER
OWNER = Config.OWNER
HOME_TEXT = Con... |
# 查票类,目的是将查到的票输出到文件,让用户选票
import json
import re
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning # 忽略 Warning 用
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # 忽略 Warning 用
class Crawl:
def __init__(self, departure_date, from_station_chs, to_station_... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Ben Kurtovic <[email protected]>
#
# 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 ... |
from datetime import datetime
from unittest.mock import patch
import pytz
from django.core.management import call_command
from django.test import TestCase
from registrations.models import JembiSubmission
class JembiSubmitEventsTests(TestCase):
@patch("registrations.management.commands.jembi_submit_events.push_t... |
from __future__ import print_function, absolute_import
from .image import ImageSoftmaxEngine, ImageTripletEngine
from .image import ImageTripletEngine_DG, ImageQAConvEngine
from .video import VideoSoftmaxEngine, VideoTripletEngine
from .engine import Engine
|
################################################################################
#
# This file implements the interface of different kinds of
# data modules.
#
# Author(s): Nik Vaessen
################################################################################
from abc import abstractmethod, ABCMeta
from typing i... |
'''
Created on 15 Sep 2017
@author: gavin
'''
from .basehandler import TcpHandler
class netbios(TcpHandler):
NAME = "NetBIOS Session"
DESCRIPTION = '''Responds to NetBIOS session requests. To be used along side SMB handler.'''
CONFIG = {}
def __init__(self, *args):
'''
Constructor... |
# Generated by Django 3.2.5 on 2021-08-14 10:16
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
import wagtail.contrib.routable_page.models
import wagtail.core.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('blog',... |
# Copyright © 2021 Dar Gilboa, Ari Pakman and Thibault Vatter
# This file is part of the mdma library and licensed under the terms of the MIT license.
# For a copy, see the LICENSE file in the root directory.
from mdma import fit
import torch as t
import numpy as np
from experiments.UCI.gas import GAS
from experiment... |
import argparse
from io import StringIO
import os
from pathlib import Path
import time
import gym
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from utils.annealing import Step, TReciprocal, ExponentialDecay
from utils.logger import Logger
from utils.path import get_run_path
from util... |
import locale
import warnings
from django.test import TestCase
from django_celery_beat.models import DAYS
import snitch
from snitch.models import Event
from snitch.schedules.models import Schedule
from snitch.schedules.tasks import clean_scheduled_tasks, execute_schedule_task
from tests.app.events import (
ACTIVA... |
from ...hek.defs.swat import *
|
from event_model import unpack_event_page
from qtpy.QtGui import QStandardItemModel, QStandardItem
from qtpy.QtWidgets import QTableView, QWidget, QVBoxLayout
class BaselineModel(QStandardItemModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setHorizontalHeaderLab... |
# Author info:
# Github | rlyonheart
# Twitter| rly0nheart
# Instagram | rlyonheart
#import color module
import termcolor
from termcolor import colored,cprint
# import the random module
import random
# import the time module(not that important)
import time
# import sys module(using this to terminate the program)
im... |
from src.harness.agentThread import AgentThread
class DefaultName(AgentThread):
def __init__(self, config, motion_config):
super(DefaultName, self).__init__(config, motion_config)
def initialize_vars(self):
self.locals = {}
self.locals['added'] = False
self.locals['finalsum']... |
#!/usr/bin/env python3
from linkedlist import LinkedList, Node
import random
random.seed(42)
class IntersectingLinkedList(LinkedList):
def __init__(self, data_a: list, data_b: list):
self.head_a = self.__build_list(data_a)
self.head_b = self.__build_list(data_b)
self.intersect()
def... |
"""
Based on Scipy's cookbook:
http://scipy-cookbook.readthedocs.io/items/bundle_adjustment.html
"""
import math
import sys
import logging
from functools import lru_cache
import numpy as np
import quaternion
from scipy.sparse import lil_matrix
from scipy.optimize import least_squares
from visnav.algo ... |
import json
from typing import TYPE_CHECKING, Type, TypedDict, cast
import jwt
import requests
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.utils import timezone
from requests.auth import HTTPBasicAuth
if TYPE_CHECKING:
... |
import json
import logging
class FwtSpec:
def __init__(self, spec_json):
try:
spec_json_obj = json.load(spec_json)
self.column_names = spec_json_obj['ColumnNames']
self.offsets = spec_json_obj['Offsets']
self.include_header = spec_json_obj['IncludeHeader']
... |
"""
Database Initialization and storage handling module.
See docs for how to set up the database.
Logging messages to a log file is not needed here as this is run directly
as a command-line script. The detailed creation of places might be good to
move to a log file with only summary level data printed to the console.... |
"""
Work on hashtags
"""
import re
HASHTAG_PATTERN=re.compile(r'(^|\s)#([^\d\s]\w+\b)')
def extract_hashtags(content):
"""
Extract twitter-like hashtags from a given content
"""
return [
matches[1]
for matches in HASHTAG_PATTERN.findall(content)
]
|
# -*- coding: utf-8 -*-
"""
This script calculates SEMA score between two AMRs
"""
import argparse
import codecs
import logging
from amr import AMR
class Sema:
"""
SEMA: an Extended Semantic Metric Evaluation for AMR.
"""
def __init__(self):
"""
Constructor. Initiates the variables
... |
try:
import Tkinter as tk
import tkMessageBox as tkmb
except ImportError:
import tkinter as tk
from tkinter import messagebox as tkmb
def show_error(title, message):
root = tk.Tk()
root.withdraw()
tkmb.showerror(title=title, message=message)
def show_message(title, message):
root = t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tools for the impurity caluclation plugin and its workflows
"""
#use print('message') instead of print 'message' in python 2.7 as well:
from __future__ import print_function
# redefine raw_input for python 3/2.7 compatilbility
from __future__ import absolute_import
fr... |
from functools import wraps
from os import PathLike
from typing import Callable, Union
__all__ = [
'read_lines', 'read_json'
]
def read_lines(path: str, *, filter_empty=True):
from typing import List
def decorator(func: Callable[..., List[str]]):
@wraps(func)
def wrapper(*args, **kwargs)... |
import datetime
import unittest
import genetic
def get_fitness(genes):
return genes.count(1)
def display(candidate, startTime):
timeDiff = datetime.datetime.now() - startTime
print(
"{0}...{1}\t{2:3.2f}\t{3}".format(
"".join(map(str, candidate.Genes[:15])),
"".join(map(s... |
# -*- coding: utf-8 -*-
r"""
Bending of focusing mirror
--------------------------
Uses :mod:`shadow` backend.
File: `\\examples\\withShadow\\04_06\\05_VFM_bending.py`
Pictures at the sample position,
:ref:`type 1 of global normalization<globalNorm>`
+---------+---------+---------+---------+
| |VFMR1| | |VFMR2| | |V... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mikhail Kyosev <[email protected]>
# License: BSD - 2-caluse
from __future__ import print_function
from collections import OrderedDict
import re
import glob
import time
import os
import datetime
import functools
import curses
from subprocess import Popen, PIPE
... |
import logging
import click
from bson.json_util import dumps
from flask.cli import with_appcontext
from scout.commands.utils import builds_option
from scout.export.gene import export_genes
from scout.server.extensions import store
from .utils import build_option, json_option
LOG = logging.getLogger(__name__)
@cli... |
from setuptools import setup, find_packages, Extension
from io import open
from os import path
import pathlib
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# automatically captured required modules for install_requires i... |
""" The Flask Server for the PWA """
import sys
import os
import requests
import cv2
import socket
import numpy as np
import logging
from sys import stdout
from utils import *
from camera import Camera
from flask import Flask, session, render_template, request, url_for, flash, redirect, jsonify, Response
from flask_s... |
import calendar
import copy
import datetime
import time
from django.conf import settings
from django.db.models.signals import post_save
from django.contrib import auth
from django.contrib.auth.models import User
COOKIE_USER_DATA_KEY = '_UD'
COOKIE_USER_DATA_TS_KEY = '_UDT'
# Defaults to 4 hours in seconds
COOKIE_USE... |
#!/usr/bin/python
# poll the AWS Trusted Advisor for resource limits and posts an SNS message to a topic with AZ and resource information
# Import the SDK
import boto3
import uuid
import json
import ec2Limits
import rdsLimits
import cloudformationLimits
import ConfigParser
# Instantiate a new client for AWS Support AP... |
from colorama import Fore, init
init(autoreset=True)
def leiaint(numero_inteiro):
"""
:param numero_inteiro: Número inteiro digitado
:return: int(param) else ERROR
"""
while True:
try:
return int(numero_inteiro)
except Exception:
print(Fore.RED + 'ERRO! Digi... |
import numpy as np
import math
import sys
#
# this run control defines 8 parameters, with total number of expected instances
# of 1 * 1 * 1 * 1 = 1
#
# fidelity levels, 1 * 1 * 1 = 1
f_rxtr = 0
f_fc = 2
f_loc = 0
# reactor params, 1 = 1
n_rxtr = 1
r_t_f = 1.0
r_th_pu = 1.0
# supplier params, 3 = 3
r_s_th = 0.08 # ... |
/home/runner/.cache/pip/pool/f6/94/02/3149708d154718ac19c6fc1de1b5b9a7ef6fed55dc7e510b1089878358 |
import torch
import torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(self,input_channels, output_channels):
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(input_channels, output_channels, 3, stride = 1, padding=1),
... |
from django.db import models
from apps.base.models import Timestampable
class Transaction(Timestampable):
address = models.CharField(max_length=255)
vhost = models.CharField(max_length=255, default='default')
agent_ping_time = models.DateTimeField(blank=True)
time_avg = models.FloatField(default=999, ... |
class Log:
@staticmethod
def log(message, app, type = 'INFO'):
app.logger.info(message)
return 'LOG:' + message
@staticmethod
def info(message, app):
_message = ' >> ' + message
app.logger.info(_message)
return _message
@staticmethod
def debug(message, ... |
# -*- coding: utf-8 -*-
"""Plots and EDA_v1
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Y0k-MwXaSWQIZ64sOD2wDa14P3xRNZTe
"""
!pip install yfinance
import pandas_datareader as web
from pandas_datareader import data as pdr
import yfinance as yfin
im... |
#!/usr/bin/python
# coding=utf-8
import numpy as np
import pytest
import socket
from http.server import HTTPServer
from threading import Thread
from app import MyHandler
from service import MNIST
@pytest.fixture(scope="session")
def mnist_class():
return MNIST()
@pytest.fixture(scope='session')
def port_num... |
#! usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import logging
import re
from concurrent.futures import ThreadPoolExecutor
from typing import Optional
import sqlalchemy.sql
import whois_alt
from sqlalchemy import select, insert
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.dialects.postgre... |
# -*- coding: utf-8 -*-
'''
Bandidos estocásticos: introducción, algoritmos y experimentos
TFG Informática
Sección 7.1
Figuras 3, 4 y 5
Autor: Marcos Herrero Agustín
'''
import scipy.stats as stats
import matplotlib.pyplot as plt
import numpy as np
def regretEFFavsFirst(n,m,arms,gaps):
rwds = 2*[0... |
# Generated by Django 2.0.5 on 2018-05-06 16:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('patients', '0004_auto_20180506_1612'),
]
operations = [
migrations.AlterField(
model_name='patient',
name='profile_i... |
import os
import logging
from abc import ABCMeta, abstractmethod
from pyfasta import Fasta, FastaRecord
from pyfasta.fasta import FastaNotFound
from .helpers import fasta_filepath
from .helpers import supported_build
from .helpers import parse_build
from .md5 import calculate_md5
from .. import SUPPORTED_BUILDS
fro... |
import django
import wagtail
from wagtail_storages import backends, utils
HOOK_ORDER = getattr(
django.conf.settings,
'WAGTAIL_STORAGES_DOCUMENT_HOOK_ORDER',
100
)
@wagtail.core.hooks.register('before_serve_document', order=HOOK_ORDER)
def serve_document_from_s3(document, request):
# Skip this hook... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... |
"""init"""
NAME = "test01"
|
# 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, software
# d... |
#!/usr/bin/env python
"""
_SiblingSubscriptionsComplete_
Oracle implementation of Subscription.SiblingSubscriptionsComplete
"""
from WMCore.WMBS.MySQL.Subscriptions.SiblingSubscriptionsComplete import \
SiblingSubscriptionsComplete as SiblingCompleteMySQL
class SiblingSubscriptionsComplete(SiblingCompleteMySQL):... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import re
from pathlib import Path
from typing import List
class _MarkdownLink:
"""Handle to a markdown link, for easy existence test ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.