content stringlengths 5 1.05M |
|---|
"""
ExactTarget OAuth support.
Support Authentication from IMH using JWT token and pre-shared key.
Requires package pyjwt
"""
from datetime import timedelta, datetime
import jwt
from social.exceptions import AuthFailed, AuthCanceled
from social.backends.oauth import BaseOAuth2
class ExactTargetOAuth2(BaseOAuth2):
... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 59,
"id": "fatty-container",
"metadata": {},
"outputs": [],
"source": [
"def cuad_pmedio(a, b, f):\n",
" \"\"\"Implementación de la regla del punto medio\n",
" \n",
" Parameters\n",
" ----------\n",
" f: L... |
#!/usr/bin/env python
import cv2
import rospy
import roslib
import numpy as np
roslib.load_manifest('object_detection')
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
'''
This script uses hsv (hue, saturation and value) thresholds to attempt
and identify colors. It the proceeds to fin... |
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... |
import re
from typing import List
LINK_PATTERN = re.compile(r"\[(.+?)\]\((.+?)\)")
MKAPI_PATTERN = re.compile(r"^(#*) *?!\[mkapi\]\((.+?)\)$", re.MULTILINE)
NODE_PATTERN = re.compile(
r"<!-- mkapi:begin:(\d+):\[(.*?)\] -->(.*?)<!-- mkapi:end -->",
re.MULTILINE | re.DOTALL,
)
def node_markdown(index: int, m... |
from typing import List, Union
from src.buildchain import checker
from src.valtypes import Value, string, boolean, number
from src.errors import RTError
class Array(Value):
def __init__(self, value:List[Value]):
super().__init__()
self.value = value
self.length = len(value)
def add(self,... |
class SECRET:
GITHUB_CLIENT_ID = "GITHUB_CLIENT_ID"
GITHUB_CLIENT_SECRET = "GITHUB_CLIENT_SECRET"
SUPER_SECRET = 'FLASK_SUPER_SECRET'
class DB:
HOST = 'DATABASE_HOST'
DB = 'DATABASE_NAME'
USER = 'DATABASE_USER'
PW = 'DATABASE_SECRET'
PORT = 'DATABASE_PORT'
|
from __future__ import division, unicode_literals
import functools
import re
import threading
import typing
import http.server
if typing.TYPE_CHECKING:
from .common import FileDownloader
from ..postprocessor.metadataparser import MetadataParserPP
from ..utils import (
sanitized_Request,
)
class Augment():
... |
'''
Utility that performs the dependency searches.
'''
import re
import subprocess
def find_deps(query_package, current_package=None, package_list=[]):
'''
Recursively finds all dependencies of a package.
Paramaters
----------
query_package: string
Name of the query package.
current_p... |
# python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... |
import unittest
from os.path import abspath, basename, join, splitext as split_ext
from tempfile import mkstemp, mkdtemp
from os import remove, close, environ
from time import sleep
from itertools import combinations
try:
from urllib.request import Request, urlopen
except ImportError:
from urllib2 import Requ... |
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
import logging
from math import ceil
import numpy as np
import torch
import torch.nn.functional as F
from quantization.adaround.quantizer import ADAROUND_QUANTIZER_MAP
from quantization.adaround.utils import (
MODE_TO_LOSS_TYPE,
AdaRound... |
# Copyright (C) 2019 Cancer Care Associates
# 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 ... |
from flask import Flask, abort
from flask_restx import Resource, Api, reqparse
from flask_restx import inputs, fields
app = Flask(__name__)
api = Api(app)
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
return ['hello', 'world']
@api.route('/lects/<int:lect_id>', endpoint='goober')
class... |
################################################################################
# Project : AuShadha
# Description : Immunisation Models.
# Author : Dr.Easwar T.R , All Rights reserved with Dr.Easwar T.R.
# Date : 16-09-2013
##########################################################################... |
"""
@Time : 2021/10/9 10:59
@File : moco.py
@Software: PyCharm
@Desc :
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from physiossl.dist.utils import is_distributed_enabled
class Moco(nn.Module):
def __init__(self, base_encoder: nn.Module, feature_dim: int, m: float = 0.999, K:... |
# -*- coding: utf-8 -*-
# Copyright 2015 www.suishouguan.com
#
# Licensed under the Private License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE
#
# Unless ... |
from django.apps import AppConfig
class GraphConfig(AppConfig):
name = 'Graph'
|
#!/usr/bin/env/python3
# This Python file uses the following encoding:utf-8
# Author: Jolanda de Koff Bulls Eye
# GitHub: https://github.com/BullsEye0
# Website: https://hackingpassion.com
# linkedin: https://www.linkedin.com/in/jolandadekoff
# Facebook: facebook.com/jolandadekoff
# Facebook Page: https://www.facebook... |
import os
import numpy as np
import numpy.random as npr
import PIL
import PIL.ImageOps
import PIL.ImageEnhance
import PIL.Image
import matplotlib
class TransfOps(object):
'''
Class to handle the decoding of the strings used with the genetic
algorithm and all the data transformations.
'''
def __init__(self):
... |
from flask import g, request
from flask_jsonschema import validate
from app.core import ApiResponse
from app import db
from app.models import Country
from app.api.decorators import json_response
from . import cp
@cp.route('/countries', methods=['GET'])
def get_cp_countries():
"""Return countries
**Example re... |
import csv
import json
import abc
class BaseFormatter(abc.ABC):
def __init__(self, headers, data, export_to):
self.headers = headers
self.data = data
self.export_to = export_to
def export(self):
""""""
def print(self):
""""""
class CSVFormatter(BaseFormatter):
... |
# Servirtium: Service Virtualized HTTP
#
# Copyright (c) 2019, Paul Hammant and committers
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistri... |
from gama import GamaCluster
if __name__ == "__main__":
file_path = "../tests/data/breast_cancer_{}.arff"
automl = GamaCluster(max_total_time=180, store="nothing", n_jobs=1)
print("Starting `fit` which will take roughly 3 minutes.")
automl.fit_from_file(file_path.format("train"))
label_prediction... |
#!/usr/bin/python
import argparse
import arguments
import logconfig
import session
from scaffold.iam.cf_builder import IAMBuilder
def create_stack(args):
boto3_session = session.new(args.profile, args.region, args.role)
builder = IAMBuilder(args, boto3_session, False)
return builder.build(args.dry_run)... |
import os
import shutil
import sys
from typing import (
Any,
cast,
ClassVar,
Generic,
List,
Optional,
Type,
TYPE_CHECKING,
TypeVar,
Union,
)
import wandb
from wandb import util
from wandb.sdk.interface.artifacts import b64_string_to_hex, md5_files_b64
from ._private import MED... |
# Copyright (C) 2019 Matthew James Harrison
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distrib... |
from __future__ import division #Make integer 3/2 give 1.5 in python 2.x
from CoolProp.CoolProp import PropsSI
from Correlations import Tsat
class PumpClass():
"""
Pump Model based on correlations obtained from experimental results
"""
def __init__(self,**kwargs):
#Load up the parameters p... |
from cloud_inquisitor.app import initialize
from cloud_inquisitor.plugins.commands import BaseCommand
class Setup(BaseCommand):
"""Sets up the initial state of the configuration stored in the database"""
name = 'Setup'
option_list = ()
def run(self, **kwargs):
initialize()
|
import argparse
import json
import logging
import sys
import requests
parser = argparse.ArgumentParser()
parser.add_argument('-payload', '--queuePayload', help='Payload from queue', required=True)
parser.add_argument('-apiKey', '--apiKey', help='The apiKey of the integration', required=True)
parser.add_argument('-ops... |
from distutils import log
from distutils.command.check import check
from distutils.command.clean import clean
from setuptools.command.install import install
from setuptools.command.build_ext import build_ext
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError:
bdist_wheel = None
def add_rust_ex... |
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Fail functions because called from wrong mode test for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase
class FailingModeTest(VimivTestCase):
"""Failing Mode Tests."""
@classmethod
def setUpClass(cls):
... |
import os
import numpy as np
import rouge
def score_sentence(sent_rouge, highlights, scorer):
scores = scorer.get_scores(sent_rouge, highlights)
avg_rouge = (scores['rouge-1']['f'] + scores['rouge-2']['f'] +
scores['rouge-l']['f']) / 3.0
return avg_rouge
def save_rouge(filename, content_r... |
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 functools import wraps
import weakref
from asyncio import coroutine, gather
class Named:
def __init__(self, *args, name, **kws):
super().__init__(*args, **kws)
self.name = name
class Annotate(Named):
""" annotation that is transformed to a class """
def __new__(cls, definition):
... |
from django.apps import AppConfig
class VerificationsConfig(AppConfig):
name = 'verifications'
verbose_name = 'Verifications'
|
try:
from .version import __version__
except:
pass
from .get_data import get_data
from .get_data import map_segmentation_to_dataframe
from .get_data import random_basis_projection
from .get_data import hierarchical
from .get_data import deep_brain_parcellation
from .get_data import deep_tissue_segmentation
fr... |
# Author: Fei Gao
# Date: 7/6/14
# Definition for a binary tree node
class TreeNode(object):
def __init__(self, x=None):
self.left = None
self.right = None
self.dic = dict()
if isinstance(x, (list, tuple)):
self = self.build_from_list(list(x))
else:
... |
#urllib module in python.
"""Urllib module is the url handling module for python. It is used fetch URL's(uniform resource locators). It uses the urlopen() and is able to fetch url's using a
variety of different protocols"""
#Urllib is a package that collects several modules for working with URL's.
"""urllib.r... |
# This file is part of faro.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (https://www.lsst.org).
# See the COPYRIGHT file at the top-level directory of this distribution
# for details of code ownership.
#
# This program is free software: you can re... |
if "snakemake" in locals():
debug = False
else:
debug = True
if not debug:
import sys
sys.stderr = open(snakemake.log[0], "w")
import pandas as pd
def merge_deep_arg_calls(mapping, meta_data, deep_arg_calls, output):
mapping = pd.read_excel(mapping)
meta_data = pd.read_csv(meta_data, sep="|... |
from math import *
import pandas
#Molecular Weights
MW_SiO2 = 60.0855
MW_TiO2 = 79.88
MW_Al2O3 = 101.96
MW_Fe2O3 = 159.69
MW_FeO = 71.85
MW_MgO = 40.3
MW_CaO = 56.08
MW_Na2O = 61.98
MW_K2O = 94.2
MW_H2O = 18.02
#Partial Molar Volumes
#Volumes for SiO2, Al2O3, MgO, CaO, Na2O, K2O at Tref=1773 K (Lange,... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimensi... |
if None is None:
print "OK"
|
class AStanfordDataProcessor(object):
def __init__(self, path_images, transforms, path_human_readable_labels):
self.path_images = path_images
self.transforms = transforms
self.path_human_readable_labels = path_human_readable_labels
def preprocess_data(self, path_to_matdata, validation... |
import sys
import re
import pprint
import itertools
my_name = sys.argv[0]
print("my_name:", my_name)
day_nr = re.search(r"\d+", my_name).group()
print("day_nr:", day_nr)
processed_colors_a = dict()
processed_colors_b = dict()
def read_input():
_all = list()
for line in sys.stdin:
_all.append(int(l... |
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import sip
from app.tabs import *
class App(QMainWindow):
def __init__(self):
super().__init__()
# main window
self.setWindowTitle('Iata analyses')
self.setGeometry(50, 50, 1000, 1000)
... |
"""Tools for handling noisy output from classification."""
import numpy as np
from scipy import ndimage as nd
from skimage.filters import rank
def fill_nearest_neighbor(a):
"""Fills masked cells with value from nearest non-masked cell.
Args:
a (MaskedArray): A 2D array.
Raises:
TypeError... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
import logging
import docopt
import pprint
import psd_tools.reader
import psd_tools.decoder
from psd_tools import PSDImage
from psd_tools.user_api.layers import group_layers
logger = logging.getLogger('psd_tools')
logger.... |
□spam□
#
@admin_cmd()
async def spam(event):
id = event.chat_id
raw = event.raw_text.split(" ")
try:
spamCount = raw[1]
except:
await event.edit("**ERROR OCCURRED \n Do :** ```.spam <number> | <spam Message>``` ")
try:
spamCount = int(spamCount)
except:
await event.edit("**ERROR OCCURRED \n... |
#
# @lc app=leetcode id=225 lang=python3
#
# [225] Implement Stack using Queues
#
# @lc code=start
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
... |
from datetime import datetime
import unittest
from dateutil import parser
from jinja2 import FunctionLoader
from csv_model import CSVModel, cast_to_date
from csv_view import CSVJinjaView
class TestViewFilters(unittest.TestCase):
def setUp(self):
self.view = CSVJinjaView(env_options={'loader': FunctionLo... |
from typing import NoReturn
from cryspy.A_functions_base.function_1_objects import \
form_items_by_dictionary
from cryspy.B_parent_classes.cl_1_item import ItemN
from cryspy.B_parent_classes.cl_2_loop import LoopN
class Range(ItemN):
"""Contains range information.
Attributes
----------
... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "leftORleftANDnonassocLELEGEGTEQNEADD ALERT ALL ALTER AND AS ASC CHAR CONNECT CREATE DELETE DESC DROP EQ EXIT FROM GE GRANT GT HELP ID INDEX INSERT INT INTO IS JDBC KEY L... |
import StellarMass
import numpy as n
from scipy.stats import norm
from scipy.integrate import quad
from scipy.interpolate import interp1d
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
import glob
import astropy.io.fits as fits
import os
import time
import numpy as n
import sys
import XrayLumi... |
#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 1997-2016 California Institute of Technology.
# Copyright (c) 2016-2021 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/pa... |
import os
import unittest
from rdflib import URIRef, Graph
from rdflib.namespace import OWL, RDFS, RDF
from linkml import METAMODEL_CONTEXT_URI
from linkml.generators.jsonldcontextgen import ContextGenerator
from linkml.generators.jsonschemagen import JsonSchemaGenerator
from linkml.generators.owlgen import OwlSchema... |
from __future__ import absolute_import
import datetime
from datetime import timedelta
from django.utils import timezone
from freezegun import freeze_time
from parsimonious.exceptions import IncompleteParseError
from sentry.api.event_search import (
convert_endpoint_params, event_search_grammar, get_snuba_query_a... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Dct2d(nn.Module):
"""
Blockwhise 2D DCT
"""
def __init__(self, blocksize=8, interleaving=False):
"""
Parameters:
blocksize: int, size of the Blocks for discrete cosine transform
... |
# Generated by Django 3.1.1 on 2021-01-27 15:19
from django.db import migrations, models
from invoice.models import Invoice, Payment
def update_existing_payments_status(app, schema_editor):
for inv in Invoice.objects.all():
if inv.status == Invoice.Status.CLOSED:
for pmt in inv.payment_set.all... |
# _*_ coding: utf-8 _*_
from wtforms import StringField, IntegerField, FileField, MultipleFileField
from wtforms.validators import DataRequired, AnyOf, length, Email, Regexp, ValidationError
from app.validators.base import BaseValidator
from app.libs.enums import ScopeEnum
class CDKeyValidator(BaseValidator):
cd... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from .channel import Channel
from .enums import FileMode, NoarchType, PathType
from .index_record import IndexRecord, IndexJsonRecord
from .._vendor.auxlib.entity import (BooleanFie... |
"""
Given a binary tree root, find the largest subtree (the one with the most nodes) that is a binary search tree.
Constraints
n ≤ 100,000 where n is the number of nodes in root
https://binarysearch.com/problems/Largest-Binary-Search-Subtree-in-Nodes
"""
# class Tree:
# def __init__(self, val, left=None, ri... |
from pathlib import Path
import typing
import logging as log
import shutil
import pickle
from .matcher import Matcher
from .. import cluster
class TypeCosMatcher(Matcher):
def __init__(
self,
fdir: Path = None,
name=None,
create=False,
exclude_types=["https://www.w3.org/20... |
"""
This module is responsible for preparing the waiting room for a load test.
1. Reset the waiting room via API
2. Update the inlet handler Lambda function environment variables
with desired rate and duration
AWS credentials from the environment are required.
"""
import json
import os
import time
from urllib.par... |
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
n = len(s)
if n>12 or n<4:
return []
def check(s):
if int(s[0])==0 and int(s)!=0:
return False
if int(s)==0 and len(s)!=1:
return False
if int(s)... |
# -*- coding: utf-8 -*-
#
# wat-bridge
# https://github.com/rmed/wat-bridge
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Rafael Medina García <rafamedgar@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... |
'''
Author: In Ming Loh
Email: inming.loh@countercept.com
Requirements:
1. Python 3
2. pip install pywintrace
3. pip install psutil
4. Windows machine
'''
import time
import etw
import psutil
def getService(name):
service = None
try:
service = psutil.win_service_get(name... |
from ...common import Object
from . import ls
from ...exception import RemoteDirectoryNotFound
class SrcDstParam(Object):
__instance = None
@staticmethod
def instance(src, dest=None):
SrcDstParam(src, dest)
return SrcDstParam.__instance
def __init__(self, src, dest=None):
se... |
"""
Quickstart introduction
"""
import pandas as pd
import random
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, average_precision_score
from donatello.components.data import Dataset
from donatello.components.estimator imp... |
from .tasks import Tasks
def setup(fff):
fff.add_cog(Tasks(fff))
|
# -*- coding: utf-8 -*-
# Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved.
# Please refer to our terms for more information:
#
# https://www.sqreen.io/terms.html
#
""" Binding for the WAF Input Data Structure
"""
from ctypes import (POINTER, Structure, byref, c_bool, c_char_p, c_int,
... |
"""
Copyright (c)
Author: James Bennion-Pedley
Date: 2021 - present
Licence: MIT
"""
# from dashboard import app
from flask import Blueprint, render_template
from flask_login import login_required, current_user
main = Blueprint('main', __name__)
# Home page
@main.route('/')
@login_required
def index():
return rend... |
import datetime
import os
from test import DATA_DIR, TEST_DIR, pushd
import numpy as np
import pytest
from RAiDER.constants import Zenith
from RAiDER.delay import tropo_delay
from RAiDER.utilFcns import gdal_open, makeDelayFileNames, modelName2Module
SCENARIO_DIR = os.path.join(TEST_DIR, "scenario_1")
_RTOL = 1e-4
... |
"""fine-tune training
https://github.com/dredwardhyde/gpt-neo-fine-tuning-example/blob/main/gpt_neo.py
"""
import click
import joblib
import torch
from torch.utils.data import random_split
from transformers import AutoModelForCausalLM
from transformers import AutoTokenizer
from transformers import IntervalStrategy
from... |
from rest_framework.permissions import BasePermission
class OnlyWxUserCreate(BasePermission):
def has_permission(self, request, view):
if request.method == 'POST':
if not request.user or not getattr(request.user, 'is_wechat', False):
return False
return True
... |
"""
Parts of this code from:
http://arcade.academy/examples/procedural_caves_cellular.html#procedural-caves-cellular
"""
import random
import arcade
from level import create_grid
from level import Level
from constants import *
from randomly_place_sprite import randomly_place_sprite
from wander_sprite import DragonSpr... |
# coding: utf-8
import logging
import pathlib
import os
import datetime
import ast
import random
import numpy as np
import pandas
import plotly.express as px
import plotly.offline.offline as poff
from io import BytesIO
from matplotlib import pyplot
from matplotlib import dates as mdates
from operator import or_
from fl... |
file_to_skip = [] |
import random
lista = ['Paulo', 'Ana', 'Pedro', 'Maria']
escolhido = random.choice(lista)
print('O aluno escolhido foi {}'.format(escolhido))
|
"""
==============================================================
Deep Belief Network features for digit classification
==============================================================
Adapted from http://scikit-learn.org/stable/auto_examples/neural_networks/plot_rbm_logistic_classification.html#sphx-glr-auto-examples-... |
#!/usr/bin/env python
import os, json, argparse, ConfigParser
from twisted.internet import reactor, defer
from twisted.internet.task import deferLater
from twisted.web.resource import Resource
from twisted.web.server import Site, NOT_DONE_YET
from twisted.web import static
THIS_DIR=os.path.dirname(os.path.realpath(__... |
#!/usr/bin/env python3
from os import urandom
from hashlib import sha1
from Crypto.Util.number import GCD, getPrime, inverse, long_to_bytes, bytes_to_long
class RSA(object):
def __init__(self, key):
self._n, self._e, self._d = key
self._digest = sha1(b'').digest()
@staticmethod
def gener... |
from .grasp_cifar10_dber import GraspCifar10
class GripCifar10(GraspCifar10):
def __init__(self, root=None, train=True,
transform=None, target_transform=None,
download=False, im_shape=(32, 32, 3), data=None, indexing=False, base_folder='cifar10'):
super(GripCifar10, self)... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import ensemble
import random
df_all = pd.read_csv("data/CTrainTestNAsRemoved.csv", sep=";")
cat_keys = [key for key in df_all.keys() if not np.issubdtype(df_all[key].dtype, np.numb... |
#! coding: utf-8
from django.core.urlresolvers import reverse_lazy
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from django.contrib.auth.decorators impo... |
"""
Generate Truth Tables from boolean expressions.
Example usage:
>>> tt = TruthTable('p and (~q or (p and r))', 'p or q and r', 'p -> q')
>>> tt.display()
┌───┬───┬───┬─────────────────────────┬──────────────┬────────┐
│ p │ q │ r │ p and (~q or (p and r)) │ p or q and r │ p -> q │
├───┼───┼───┼────────────────────... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function, division
from astropy.table import Table
from ...catalog import FluxDistribution
def test_FluxDistribution():
table = Table([dict(S=42)])
flux_distribution = FluxDistribution(table, label='dummy')
|
# -*- coding: utf-8 -*-
"""Tests for the maxentropy package:
Machine translation example -- English to French -- from the paper 'A
maximum entropy approach to natural language processing' by Berger et
al., 1996.
Consider the translation of the English word 'in' into French. We
notice in a corpus ... |
from __future__ import annotations
import itertools
import typing
import aiohttp
import asyncio
import logging
import zlib
from .dispatch import GatewayDispatch
from ..exceptions import GatewayError
logger: logging.Logger = logging.getLogger("tinycord")
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
inflator = zlib.decompressobj... |
"""
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in bina... |
data = (
'byum', # 0x00
'byub', # 0x01
'byubs', # 0x02
'byus', # 0x03
'byuss', # 0x04
'byung', # 0x05
'byuj', # 0x06
'byuc', # 0x07
'byuk', # 0x08
'byut', # 0x09
'byup', # 0x0a
'byuh', # 0x0b
'beu', # 0x0c
'beug', # 0x0d
'beugg', # 0x0e
'beugs', # 0x0f
'beun', # 0x10
'... |
#coding : utf-8
import os
import json
import random
import logging
import requests
import responder
import copy
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import (MessageEvent, FollowEvent, PostbackEvent, UnfollowEvent, TextMessage, TextSend... |
import pytest
import time
from rever import rever, ReachedMaxRetries
class TestRever:
"""
Generally the types of exceptions being raised do not really matter for the tests
# because of the default max pause time of about 1 second, more or less takes a second per test
"""
def test_no_kwargs_raise... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required()
def web_ssh(request):
return render(request, 'admin/shell.html', {
'host': request.GET.get('host', ''),
'type': request.GET.get('type', ''),
'port': request.GET.get('port', '22')... |
import re
tam_re = re.compile(r'(.*)\((.*)\.(.*)\.(.*)\)')
def split_TAM(TAM_tag):
"""Split TAM tag and return parts as dict
! DEPRECATED !
Starting with yiqtol, we have deprecated
this function since tense tags have now
changed. The function process_TAM now
fulfills the old role.
""... |
import requests_mock
from pycryptoclients.request import DEFAULT_USER_AGENT
from pycryptoclients.markets.stocks_exchange.api import StocksExchangeAPI
from pycryptoclients.markets.stocks_exchange.request import STOCKS_EXCHANGE_BASE_URL
from tests import CCAPITestCase
from tests.test_markets import *
class TestStocksE... |
"""
Copyright BOOSTRY Co., 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 law or agreed to in writing,
software distr... |
import dash_html_components as html
carreta1="When there is a problem over whichever piece of the energy infrastructure in certain place, and it makes a costumer or a group of them do not receive power supply, EPM generates a work order, in which they specify some tasks that a technical crew have to execute over energ... |
from setuptools import setup
setup( name = 'Custom-env',
version = '0.0.1',
install_requires = ['gym']
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.