content stringlengths 5 1.05M |
|---|
import os
import time
from boto3 import Session
from botocore.exceptions import ValidationError, ClientError, \
ParamValidationError, WaiterError
from .exceptions import EmptyStackName, DeployFailed, TemplateNotSpecified, \
TemplateValidationError, EmptyChangeSet, UpdateStackError, \
StackDoesntExist, Sta... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import time... |
from ._42 import _42
|
import pytest
import numpydoc.validate
import numpydoc.tests
validate_one = numpydoc.validate.validate
class GoodDocStrings:
"""
Collection of good doc strings.
This class contains a lot of docstrings that should pass the validation
script without any errors.
See Also
--------
AnotherC... |
from unittest import TestCase
from main import find_missed_num
class MissingNumberTestCase(TestCase):
def test_without_first(self):
numbers = [2, 3]
self.assertEqual(find_missed_num(numbers), 1)
def test_without_last(self):
numbers = [1, 2]
self.assertEqual(find_missed_num(nu... |
#!/usr/bin/python
# Python has class str to represent and deal with string
first_name = "Sanjeev"
last_name = 'Jaiswal'
nick_name = '''Jassi'''
address = """ Mailing Address right?
if so, it's Hyderabad, Madhapur.
Pin: 500081"""
mobile_num = 9618961800
print("First Name:", first_name)
print("First Name... |
import enolib
input = '''
fieldset:
entry = entry value
other = other value
'''.strip()
entry = enolib.parse(input).fieldset().entry('entry')
def test_required_string_value_returns_the_value():
assert entry.required_string_value() == 'entry value'
def test_required_string_value_touches_the_fieldset_itself():
... |
"""
CLI for gpip utility.
"""
# AVAILABLE COMMANDS
META_COMMANDS = [
"get",
"install",
"version"
]
from .cli import main |
'''
@Author danielvallejo237
'''
import json
import numpy as np
import re
import stanza
from spacy_stanza import StanzaLanguage
import unidecode
import random
NLPProc=None
JSONOBJ=None
with open("recipes_full_v2.json") as jsonFile:
jsonObject = json.load(jsonFile)
JSONOBJ=jsonObject
jsonFile.... |
from telethon import TelegramClient
import time
from telethon import sync, events
from json2table import convert
import requests
import json
import array
from datetime import datetime
import re
import io
api_id = 54245
api_hash = "452452452"
session = "NameOfSession"
client = TelegramClient(session, ap... |
"""Support for Somfy Covers."""
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASS_BLIND,
DEVICE_CLASS_SHUTTER,
CoverEntity,
)
from homeassistant.const import STATE_CLOSED, STATE_OPEN
from homeassistant.helpers import config_validation as cv, entity_platfor... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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... |
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import *
CONF_UPDATE_INSTANT = "update_instant"
CONF_MAPPING = 'mapping'
CONF_CONTROL_PARAMS = 'params'
CONF_CLOUD = 'update_from_cloud'
CONF_MODEL = 'model'
CONF_SENSOR_PROPERTY = "sensor_property"
CONF_SENSOR_UNIT ... |
"""
This module provides an API for tracking
*data lineage* -- the history of how a given result was created, including the
versions of original source data and the various steps run in the *data pipeline*
to produce the final result.
The basic idea is that your workflow is a sequence of *pipeline steps*::
---... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 19 12:36:25 2022
@author: fatimamh
"""
import os
import pandas as pd
from nltk.tokenize import sent_tokenize
'''----------------------------------------------------------------
'''
def get_folders(root):
folders = list(filter(lambda x: os.path... |
import threading
import time
from random import random
class Proxy:
def __init__(self, object, object_pool):
self._object = object
self._object_pool = object_pool
def __enter__(self):
return self._object
def __exit__(self, exc_type, exc_val, exc_tb):
self._object_pool._rel... |
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from Analytics.app import create_app
import sqlalchemy
sql = 'mysql+pymysql'
psql = 'postgresql+psycopg2'
app = create_app()
db_uri = '%s://%s:%s@%s/' % (psql, app.config['DB_USERNAME'], app.config['DB_PASSWORD'], app.confi... |
import tensorflow as tf
from mlp import mlp_layer
"""
An MLP generator
"""
def generator_head(dimZ, dimH, n_layers, name):
fc_layer_sizes = [dimZ] + [dimH for i in range(n_layers)]
layers = []
N_layers = len(fc_layer_sizes) - 1
for i in range(N_layers):
d_in = fc_layer_sizes[i]
d_out = fc_layer_size... |
from unittest import TestCase
from app import create_app
from config import HEADERS
app = create_app("testing")
class BaseTest(TestCase):
"""Base class which is inherited by all system test classes."""
request_headers = HEADERS
@classmethod
def setUpClass(cls):
pass
def... |
# Copyright 2016 Brocade Communications Systems, Inc.
# 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 ... |
__version__ = '4.0.0.r1'
|
import os
import xml.etree.ElementTree as ET
import shutil
import ntpath
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import argparse
import csv
import unidecode
import collections
fileDir = os.path.dirname(os.path.abspath(__file__))
parentDir = os.path.dirname(fileDir)
def trim_... |
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import numpy as np
import common.utils as utils
class MyDataset(Dataset):
def __init__(self, shuffle_seed=0, i... |
# Copyright (c) 2020. Robin Thibaut, Ghent University
import os
import subprocess
import time
import uuid
import warnings
from os.path import join as jp
from loguru import logger
from pysgems.utils.sgutils import joinlist
class Sgems:
def __init__(
self,
project_name: str = "sgems_test",
... |
# https://www.hackerrank.com/challenges/computing-the-correlation
import pytest
def pearson_correlation(x,y):
n = len(x)
sxy = 0
sx = 0
sy = 0
sx2 = 0
sy2 = 0
for xi,yi in zip(x,y):
sxy += xi*yi
sx += xi
sy += yi
sx2 += pow(xi,2)
sy2 += pow(yi,2)
... |
import os
from pandas.testing import assert_frame_equal
import pandas as pd
import numpy as np
from yaetos.pandas_utils import load_csvs, load_df, save_pandas_local
# TODO: check to remove .reset_index(drop=True), using assert_frame_equal(d1, d2, check_index_type=False) instead
def test_load_csvs():
# Test multip... |
import psi4
import XC_Inversion
import matplotlib.pyplot as plt
import libcubeprop
import numpy as np
if __name__ == "__main__":
psi4.set_num_threads(3)
psi4.set_memory('4 GB')
functional = 'svwn'
basis = "cc-pvdz"
vxc_basis = None
ortho_basis = False
svd = 1e-5
opt_method="trust-krylov"
method = "WuYangMN"
... |
from planetmint.backend.tarantool.transaction import tools
|
"""
@author: magician
@date: 2019/11/25
@file: method_demo.py
"""
import math
class MyClass:
"""
MyClass
"""
def method(self):
return 'instance method called', self
@classmethod
def classmethod(cls):
return 'class method called', cls
@staticmethod
def stat... |
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
from glob import glob
from os.path import join, relpath, splitext, dirname, basename
import numpy as np
from pylab import *
from skimage.color.colorconv import rgb2gray, gray2rgb
from skimage.transform._geometr... |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
import sys
import argparse
import colorsys
import re
# def _get_colors(num_colors):
# colors=[]
# for i in np.arange(0., 360., 360. / num_colors):
# hue = i/360.
# lightness = (50 + np.r... |
"""
EmailManager - a helper class to login, search for, and delete emails.
"""
import email
import htmlentitydefs
import imaplib
import quopri
import re
import time
import types
from seleniumbase.config import settings
class EmailManager:
""" A helper class to interface with an Email account. These imap methods
... |
import komand
from .schema import GetSubdomainsInput, GetSubdomainsOutput
# Custom imports below
class GetSubdomains(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="get_subdomains",
description="Get subdomains https://api.passivetotal.org/api/docs/#... |
# Copyright 2019 Verily Life Sciences 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
# -*- coding: utf-8 -*-
"""Download data from Florida Automated Weather Network (FAWN)."""
import mando
import pandas as pd
try:
from mando.rst_text_formatter import RSTHelpFormatter as HelpFormatter
except ImportError:
from argparse import RawTextHelpFormatter as HelpFormatter
import xarray as xr
from tsto... |
import core
import lang
def loadAll():
return [core.loadAll(), lang.loadAll()]
|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import Activity
from botbuilder.schema.teams import (
NotificationInfo,
TeamsChannelData,
TeamInfo,
TeamsMeetingInfo,
)
def teams_get_channel_data(activity: Activity) -> TeamsChannelDa... |
# -*- coding: utf-8 -*-
# Created by apple on 2017/2/21.
from datetime import datetime
from ..log import log
class Date:
@staticmethod
def time2datetime(t) -> datetime:
"""
时间戳转datetime
:param t: 1970开始的秒数
:return:
"""
if t:
try:
ret... |
r'''
Author : PiKaChu_wcg
Date : 2021-10-05 14:27:47
LastEditors : PiKachu_wcg
LastEditTime : 2022-01-05 15:19:22
FilePath : \pikachu_wcgd:\blog\md.py
'''
import os
from datetime import datetime
import argparse
import time
datetime.now().strftime('%Y-%m-%d')
def get_args():
parser = argparse.Arg... |
import numpy as np
from .activation import ActivationFunc
class ReLU(ActivationFunc):
"""Relu activation function
"""
def __init__(self):
super().__init__()
def forward(self, x):
"""forward pass
"""
out = np.maximum(0, x)
self.f_val = out
return out
... |
# Generated by Django 3.1.13 on 2022-03-24 09:10
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('predictions_manager', '0005_auto_20220318_1531'),
]
operations = [
migrations.RemoveField(
mod... |
#!/usr/bin/env python3
from lxml import etree
from urllib.request import urlopen
#Constants
#NS sets up various XML namespaces and loads them
#into a dictionary for reference later.
NS = dict(md="urn:oasis:names:tc:SAML:2.0:metadata",
ds='http://www.w3.org/2000/09/xmldsig#',
mdui="urn:oasis:names:... |
import json
import logging
import math
import random
import time
from datetime import datetime
from pgoapi.utilities import f2i
from s2sphere import CellId, LatLng
from pokedata import Pokedata, parse_map
logger = logging.getLogger(__name__)
REQ_SLEEP = 1
MAX_NUM_RETRIES = 10
#Constants for Hex Grid
#Gap between v... |
import FWCore.ParameterSet.Config as cms
from RecoVertex.BeamSpotProducer.BeamSpotFakeConditionsEarly10TeVCollision_cfi import *
|
import math
from math import sqrt
from math import e as exp
import seaborn as sns
import statsmodels.api as sm
import random
from scipy import optimize
import pandas as pd
import numpy as np
from scipy.ndimage.filters import gaussian_filter, median_filter
class River:
def __init__(self):
self.error = 0
... |
'''
Author: jianzhnie
Date: 2021-11-10 18:22:22
LastEditTime: 2022-02-25 18:58:03
LastEditors: jianzhnie
Description:
'''
import torch
import torch.nn as nn
from torch import Tensor
from torchvision import models
class ImageEncoder(nn.Module):
def __init__(self, is_require_grad=True):
super(ImageEncoder... |
import pandas as pd
messages=pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\t',names=['label','message'])
#clean data and preprocessing
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
from sklearn.ensembl... |
from cv2 import cv2 as cv
import time
from datetime import datetime
import os
from absl import app, flags, logging
from absl.flags import FLAGS
flags.DEFINE_string(
'url', 'rtsp://192.168.100.10/h264/ch1/main/av_stream', 'url for rtsp source')
flags.DEFINE_boolean('dnot_show', False, 'show rtsp stream in window')
... |
import pyautogui
class GUI_INTERFACE():
def __init__(self):
pass
def keywrite(self, *args, **kwargs):
pyautogui.typewrite(list(args), interval=kwargs.get("delay", 0.1))
def write(self, msg):
pyautogui.typewrite(msg)
|
# test the LDS problem class
import jax.numpy as np
import jax.random as random
import tigerforecast
import matplotlib.pyplot as plt
from tigerforecast.utils.random import generate_key
def test_lds_time_series(steps=1000, show_plot=False, verbose=False):
T = steps
n, m, d = 5, 3, 10
problem = tigerforeca... |
from setuptools import setup, find_packages
import django_monitor
setup(
name = 'django-monitor',
version = django_monitor.__version__,
description = "Django app to moderate model objects",
long_description = open("README.rst").read(),
install_requires = [
"django >= 1.9",
],
clas... |
import numpy as np
rbf_human_params = {
't1_blood': 1.55,
'max_perfusion_value': 600,
}
rbf_rat_params = {
't1_blood': 1.14,
'max_perfusion_value': 1000
}
rbf_params = {
'human': rbf_human_params,
'rat': rbf_rat_params
}
def pwi(data):
"""Create a profusion weighted image from a dicom... |
''' Made by Guilherme Moreira, used on the twitter account @RedditHotNews '''
import praw, twitter
from keys import *
from datetime import datetime
api = twitter.Api(consumer_key = consumer_key,
consumer_secret = consumer_secret,
access_token_key = access_token_key,
... |
"""
mslib.msui.multilayers
~~~~~~~~~~~~~~~~~~~
This module contains classes for object oriented managing of WMS layers.
Improves upon the old method of loading each layer on UI changes,
the layers are all persistent and fully functional without requiring user input.
This file is part of mss.
... |
from FBAnalyzer import FBAnalyzer
from utils import get_root_path_from_input
from models import FriendMetric
if __name__ == '__main__':
fb_analyzer = FBAnalyzer(root_path=get_root_path_from_input())
# fb_analyzer = FBAnalyzer.get_pickle_instance("../FBAnalyzer.pkl")
top_10_friends_tuple = fb_analyzer.sort... |
def get_fib(position):
if position < 0:
raise Exception('Position out of bounds, cannot be less than zero.')
if position == 0 or position == 1:
return position
else:
return get_fib(position - 1) + get_fib(position - 2)
# Test cases
print get_fib(9)
print get_fib(11)
print get_fib(... |
#!/usr/bin/env python2
#***************************************************************************
#
# Copyright (c) 2015 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#... |
import numpy as np
import unittest
import chainer.testing as testing
import chainer.testing.condition as condition
from chainer import functions as F
from mkldnn import switch
class TestSoftmaxCrossEntropy(unittest.TestCase):
def setUp(self):
self.x_2d = np.random.rand(2, 3).astype('f')
self.label... |
from firedrake import *
from firedrake.petsc import PETSc
from argparse import ArgumentParser
import sys
parser = ArgumentParser(description="""Linear gravity wave system.""",
add_help=False)
parser.add_argument("--refinements",
default=4,
type=int,
... |
default_app_config = 'demo.periods.apps.PeriodsConfig'
|
def extractBcnovelsCom(item):
'''
Parser for 'bcnovels.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if 'Manga' in item['tags']:
return None
tagmap = [
('When the Protagonist of a Fanfiction', ... |
import htcondor
import os
import shutil
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
from .conf import *
from .dagman import DAGMan
JobStatus = [
"NONE",
"IDLE",
"RUNNING",
"REMOVED",
"COMPLETED",
"HELD",
"TRANSFERRING_OUTPUT",
"SUSPEN... |
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
%matplotlib inline
np.random.seed(1)
X, Y = load_plana... |
# Copyright © 2021 Province of British Columbia
#
# 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 agr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('users', '0013_userprofile_timezone'),
]
operations = [
migrations.AddF... |
# Taiwo Kareem
# 05/04/2018 04:09 AM
import sys
import requests
import re
import time
import os
import json
from urllib.parse import urljoin # Python3
if len(sys.argv) != 2:
sys.exit('Usage: python %s "<config_filename>"' % __file__)
config_file = sys.argv[1]
config = {}
if os.path.isfile(config_file):
with ope... |
import gobject
import logging
import os
import traceback
from glob import glob
# Victron packages
from ve_utils import exit_on_error
from delegates.base import SystemCalcDelegate
class RelayState(SystemCalcDelegate):
RELAY_GLOB = '/dev/gpio/relay_*'
FUNCTION_ALARM = 0
FUNCTION_MANUAL = 2
FUNCTION_BMS_STOPCHARGE ... |
"""
Projet de session IFT780
Date:
Authors: Alexandre Turpin, Quentin Levieux and Adrien Verdier
License: Opensource, free to use
Other: This class is used to create our different transforms to
modify ou dataset (for data augmentation for exemple)
"""
import torchvision.transforms as transforms
class DataTra... |
#!/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... |
# Copyright 2018 qyou@nlpr.ia.ac.cn
import os
from deeppavlov.core.common.registry import register
from deeppavlov.core.models.component import Component
@register('segment')
class Segment(Component):
def __init__(self,
user_dict_path=None,
vocab=None,
**kwargs)... |
#!/usr/bin/python
import re
import smbus
import logging
# ===========================================================================
# Adafruit_I2C Class
# ===========================================================================
logger = logging.getLogger(__name__)
class Adafruit_I2C(object):
def __init__(se... |
"""
Calculate light propagation through optical fibers.
For full documentation see <https://ofiber.readthedocs.io>
Info about calculating simple optical fibers parameters::
help(ofiber.basics)
Info about modes and other characteristics of cylindrical fibers::
help(ofiber.cylinder_step)
Info about material... |
from nesbi.core import Nesbi
def get_monitoring_interfaces(device):
monitoring_interfaces = list()
interfaces_list = device.get('interface_list')
for interface in interfaces_list:
if device.get(interface).get('description') == "##UPLINK##":
monitoring_interfaces.append(interface)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Sn1pebot
#
# Initialization
#
# Sn1pebot Module Initialization
#
# Copyright (c) 2014 Geoffrey "GEOFBOT" Mon (User:Sn1per)
# Distributed under the MIT License
#
# Requires Pywikibot framework (core version)
import pywikibot
from sn1pebot.templatedata import *
from sn1pebo... |
from . import _init_playingwithfusion
from .version import version as __version__
# autogenerated by 'robotpy-build create-imports playingwithfusion playingwithfusion._playingwithfusion'
from ._playingwithfusion import CANVenom, TMD37003, TimeOfFlight
__all__ = ["CANVenom", "TMD37003", "TimeOfFlight"]
del _init_play... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, DateField, IntegerField, DecimalField, TextAreaField
from wtforms.validators import DataRequired
class DbestParametersForm(FlaskForm):
#selecting time series
dataset_name = SelectField('Dataset', choices=[("NASA/GIMMS/3GV0", ... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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... |
from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.dispatch import receiver
from django.utils.functional import cached_property
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from phonenumber_field.modelfiel... |
#!/usr/bin/env/python
"""
Usage:
prepare_data_train.py [options]
Options:
-h --help Show this screen.
--data_path FILE Path to data file containing pairs of molecules
--dataset_name NAME Name of dataset (for use in output file naming)
--save_dir NAME Path to sav... |
from flask import render_template, url_for, flash, redirect, request
from app.forms import RegistrationForm, LoginForm, TransacoesForm, ClientForm, ProductForm, MenuForm
from app import app, psycopg2
from app import cursor
import xml.etree.ElementTree as ET
from lxml import etree
from io import StringIO, BytesIO
IsUse... |
import json
import frappe
from frappe.utils.logger import get_logger
from datetime import timedelta, datetime
from frappe.utils import cint, cstr
from frappe import _
from spine.spine_adapter.redis_client.redis_client import submit_for_execution
module_name = __name__
logger = None
def date_diff_in_Seconds(dt2, dt1... |
# Copyright 2019 Google 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
#
# Unless required by applicable law or agreed to in writing, ... |
import pygame
import game
class Snake:
def __init__(self, game_w, surface, length):
self.game = game_w
self.surface = surface
self.length = length
self.length_add = 0
self.direction = 'right'
# get resources
self.body_block = pygame.image.load("resources/t... |
#!/usr/bin/env python
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'www.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on yo... |
import pandas as pd
import numpy as np
def hazard_single(gm_prob: pd.Series, rec_prob: pd.Series):
"""
Calculates the exceedance probability given the specified
ground motion probabilities and rupture recurrence rates
Note: All ruptures specified in gm_prob have to exist
in rec_prob
Paramete... |
import torch
from torch import nn
def _mean_abs_cosine_similarity(A):
denom = (A * A).sum(1, keepdim=True).sqrt()
B = A.mm(A.T) / (denom * denom.T)
penalty = B.triu(diagonal=1).abs().sum() / ((len(A) * (len(A) - 1)) / 2)
return penalty
class CosinePenalty():
def __init__(self, weight=1e-4):
... |
from __future__ import print_function
import os, sys
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import math
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from absl import flags
FLAGS = flags.FLAGS
class ARCH_celeba():
def __init__(self):
print("Creatin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, argparse
parser = argparse.ArgumentParser(description='Used to match IP addresses to their subnet ¯\_(ツ)_/¯')
parser.add_argument('-i', '--input', nargs='?',
help="Specifies the input file")
parser.add_argument("-o", "--output",
type=argparse.FileT... |
import json
import threading
import requests as requests
import homeassistant.homeassistant
import homeassistant.light
import services.alarms
def check_if_lights_are_on_but_not_home(minutes, lights_id, person_id, mobile_app_id):
if not homeassistant.homeassistant.is_home(person_id):
if homeassistant.lig... |
from typing import Optional
from dexp.processing.filters.sobel_filter import sobel_filter
from dexp.processing.utils.blend_images import blend_images
from dexp.processing.utils.element_wise_affine import element_wise_affine
from dexp.processing.utils.fit_shape import fit_to_shape
from dexp.utils import xpArray
from de... |
import os
import pickle
from matplotlib import pyplot as plt
from matplotlib import rc
import settings
from compute import _compute_profile_data
from gtfspy.routing.node_profile_analyzer_time_and_veh_legs import NodeProfileAnalyzerTimeAndVehLegs
from util import get_data_or_compute
rc("text", usetex=True)
recompute... |
import numpy as np
import tensorflow as tf
class ImgPreprocess():
def __init__(self,is_training):
self.is_training=is_training
def img_resize(self, img_tensor, gtboxes_and_label, target_shortside_len, length_limitation):
'''
:param img_tensor:[h, w, c], gtboxes_and_label:[-1, 5]... |
from .models import *
from .module import *
from .tools import *
from .utils import * |
import windows.rpc
from windows.rpc import ndr
class PLSAPR_OBJECT_ATTRIBUTES(ndr.NdrStructure):
MEMBERS = [ndr.NdrLong,
ndr.NdrUniquePTR(ndr.NdrWString),
ndr.NdrUniquePTR(ndr.NdrLong), # We dont care of the subtype as we will pass None
ndr.NdrLong,
... |
from datetime import datetime
from src import db, ma
class Review(db.Model):
__tablename__ = 'reviews'
id = db.Column(db.Integer, primary_key=True)
star = db.Column(db.Float, nullable=True)
title = db.Column(db.String(120), nullable=True)
review = db.Column(db.String(), nullable=False)
created... |
import json
import logging
import re
from datetime import datetime, time
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.db import connection
from django.db.models import Count
from django.http import JsonResponse
from django.utils import timezone... |
# Copyright (c) 2013 Mirantis Inc.
#
# 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 writi... |
"""
Functions to parse the HTML roster
"""
import re
from bs4 import BeautifulSoup
from hockeydata.constants import HTMLREPORTS
import hockeydata.scrape.common as common
def get_roster(game_id: str) -> dict:
"""
:param game_id:
:return: dict of players and coaches
"""
roster_html = get_raw_html(... |
"""Module containing the logic for creating dynamicdict."""
import yaml
import json
from dynamicdict import DynamicDict
def create_from_json_file(filename, used_case_insensitive=False,
used_underscore_for_space=False,
used_underscore_for_hyphen=False,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.