content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import logging
from clx.analytics import detector_utils as du
log = logging.getLogger(__name__)
class DetectorDataset(object):
"""
Wrapper class is used to hold the partitioned datframes and number of the records in all partitions.
"""
def __init__(self, df, batch_size):
"""This function ins... | python |
# 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 argparse
from dataclasses import dataclass
import os
from datasets import registry as datasets_registry
from foundations import desc
fr... | python |
import logging
import numpy as np
import paddle
from ..common import get_logger
from .var_group import *
from .pruning_plan import *
from .filter_pruner import FilterPruner
__all__ = ['L1NormFilterPruner']
_logger = get_logger(__name__, logging.INFO)
class L1NormFilterPruner(FilterPruner):
def __init__(self, mo... | python |
# Component to translate alias values into strings
import os, re, logging, json
from pathlib import Path, PosixPath, WindowsPath
_ValAliases = {} # Keeps track of classes which have been registered
def addAliasClass(aliasClass, tag=None):
'''Add a class to the supported alias list so that the ValAlias.makeAlias
m... | python |
import json
import multiprocessing
import os
import shutil
from typing import Dict, List, Tuple
import cv2
import numpy as np
from flask import request
from tensorpack.utils import logger
from tqdm import tqdm
from werkzeug import FileStorage
from werkzeug.utils import secure_filename
from zipfile import ZipFile
from... | python |
import numpy
def print_table(table, path):
f = open(path, 'w')
for row in range(len(table)):
for col in range(len(table[row])):
f.write(str(table[row][col]))
f.write(' ')
print(table[row][col], end=' ')
if col == len(table[row])-1:
print("... | python |
# -*- coding: utf-8 -*-
# created: 2021-06-30
# creator: liguopeng@liguopeng.net
import asyncio
import logging
import threading
from abc import abstractmethod
from datetime import datetime
import paho.mqtt.client as mqtt
from gcommon.server.server_config import ServerConfig
from gcommon.utils import gtime
logger =... | python |
from scipy.optimize import minimize
from numpy.random import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm, ticker
from matplotlib.colors import LogNorm
import numpy as np
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import py... | python |
# Generated by Django 3.0.11 on 2020-11-11 20:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_auto_20201111_1505'),
]
operations = [
migrations.AlterField(
model_name='language',
name='listing',
... | python |
## Written by Daniel Buscombe,
## MARDA Science
## daniel@mardascience.com
##> Release v1.3 (July 2020)
###===================================================
# import libraries
import sys, getopt, json, os
# set to False if you wish to use cpu (not recommended)
##True or False
USE_GPU = True
# PREDICT = False
#
#... | python |
"""Expected errors."""
import inspect
import sys
UNREPRODUCIBLE_SUGGESTION_TEXT = (
'Here are things you can try:\n'
'- Run outside XVFB (e.g. you will be able to see the launched program '
'on screen.) with `--disable-xvfb`, which is especially useful for '
'Chrome.\n'
'- Run with the downloaded... | python |
import tensorflow as tf
import fire
import json
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.training.input import batch
import model, sample, encoder
import model
import numpy as np
import tensorflow as tf
from tensorflow.contrib.training import HParams
def interact_model(
model_nam... | python |
# -*- coding: utf-8 -*-
# Copyright 2020 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... | python |
from datetime import date, datetime
from typing import Any, Dict
from dateutil import relativedelta
from django.db.models import Sum, Count
from em.models import Account, Transaction
class AccountHelper(object):
date_fmt = '%m-%Y'
day_fmt = '%Y-%m-%d'
@staticmethod
def get_spendings(overall_expns, ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .type_convert import anything_to_string
from .type_convert import anything_to_bytes
from .spamc_header import SpamcHeader
from .spamc_body import SpamcBody
class SpamcProtocol(SpamcHeader, SpamcBody):
def __init__(self):
super().__init__()
def cre... | python |
#!/usr/bin/python
#
# coveragePlot.py
#
# This program generates genomic coverage plots
# Chiu Laboratory
# University of California, San Francisco
# January, 2014
#
# Copyright (C) 2014 Charles Y Chiu - All Rights Reserved
# SURPI has been released under a modified BSD license.
# Please see license file for details.
... | python |
# *******************************************************************************
# Copyright (C) 2020-2021 INAF
#
# This software is distributed under the terms of the BSD-3-Clause license
#
# Authors:
# Ambra Di Piano <ambra.dipiano@inaf.it>
# **************************************************************************... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
class Calculator:
def __init__(self, number1, number2):
self.number1 = int(number1)
self.number2 = int(number2)
def add(self):
print(self.number1 + self.number2)
return self.number1 + self.number2
def subtract(self):
print(self.number1 - self.number2)... | python |
from flask import Blueprint
bp = Blueprint('auth', __name__)
from diploma.auth import auth, emails, forms, routes
| python |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
""" This is the example of input record for the test_tranform_data. """
input_test_data = [
{
"targetingCriteria": {
"include": {
"and": [
{
"or": {
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from mm.utils.opengl import Render
from mm.utils.mesh import generateFace
from mm.models import MeshModel
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, img_as_float
if __name__ == '__main__':
# Load the first image from the video
... | python |
import copy
from cantoolz.module import CANModule
class ecu_switch(CANModule):
name = "CAN Switch"
help = """
This module emulating CAN Switch.
Init params (example):
{
'Cabin': { # From Cabin interface
'OBD2':[ # To OBD2 allowed next ID
0x... | python |
from collections import defaultdict
start, end = 357253, 892942
num_digits = 6
def solve(start, end, strict=False):
length = end - start
count = 0
for i in range(length):
number = start + i
previous = number % 10
consecutives = defaultdict(int)
for j in range(1, num_digit... | python |
# -----------------------------------------------------------------------------
# NDN Repo getfile client.
#
# @Author jonnykong@cs.ucla.edu
# @Date 2019-10-24
# -----------------------------------------------------------------------------
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
imp... | python |
import attr
import logging
from typing import Callable
from mmds.exceptions import PackageNotFoundError
try:
from PIL import Image
except:
raise PackageNotFoundError("pillow", by="rgbs modality.")
from .ts import TimeSeriesModality
logger = logging.getLogger(__name__)
dumb_image = Image.new("RGB", (32, 32))... | python |
all_teams = ["ANC", "APO", "CSU", "GUC", "LTI", "MIN", "MRL", "NAI", "POS", "RI1", "RAK", "SOS", "ZJU"]
semi_teams = ["APO", "CSU", "GUC", "MIN", "MRL", "POS", "SOS", "ZJU"]
team_names = {
# "BAS" : "Baseline (no agents)",
"ANC" : "anct_rescue2013",
"APO" : "Apollo-Rescue",
"CSU" : "CSU-YUNLU",
"GU... | python |
import warnings
class AppPlatformError(Exception):
"""
Raised by :meth:`Client.request()` for requests that:
- Return a non-200 HTTP response, or
- Connection refused/timeout or
- Response timeout or
- Malformed request
- Have a malformed/missing header in the response.
"""
... | python |
import setuptools
from glob import glob
setuptools.setup(
name="noteboard-extension",
version='0.1.0',
url="https://github.com/yuvipanda/noteboard",
author="Yuvi Panda",
description="Simple Jupyter extension to emit events about current notebooks to a noteboard server",
data_files=[
('s... | python |
import os.path as osp
import numpy as np
class Dataset(object):
def __init__(self, ids, labels, is_train=True, name='default'):
self._ids = list(ids)
self._labels = labels
self.name = name
self.is_train = is_train
def get_data(self, id):
activity = np.load(id)
... | python |
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#color spaces --> rgb spaces,grayscal
img = cv.imread('photos/dog.jpg')
cv.imshow('Dog',img)
# plt.imshow(img)
# plt.show()
# point to note --> there is conversion of colour spaces in matplotlib
# BGR to grayscale -->
gray = cv.cvtColor(img,cv.COLO... | python |
from rest_framework import serializers
from users.models.organizations import Organization
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'domain')
| python |
import sys
from data_wrapper.settings import MESSAGES
class DataWrapper:
def __init__(self, db=None, params=None, environment=None):
if db:
if db.lower() == 'mongodb':
from data_wrapper.mongodb_wrapper import MongodbDbWrapper
self.db = True
self... | python |
# Copyright 2019 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 logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
from telemetry.internal.util import binary_manager
class Min... | python |
# ------------------------------------------------------------------------------
# Portions of this code are from
# OpenPCDet (https://github.com/open-mmlab/OpenPCDet)
# Licensed under the Apache License.
# ------------------------------------------------------------------------------
import numpy as np
import torch
i... | python |
import typing
def printBinary(n: int) -> None:
if n > 1:
printBinary(n // 2)
print(n % 2, end = "")
def main() -> None:
N = int(input("Input an integer:\n"))
printBinary(N)
return None
main() | python |
# Authors: David Alexander, Lance Hepler
from __future__ import absolute_import, division, print_function
from GenomicConsensus.arrow.utils import allSingleBaseMutations
from GenomicConsensus.variants import Variant
from GenomicConsensus.quiver.diploid import variantsFromAlignment
import numpy as np
import ConsensusC... | python |
"""Tests for the /sessions/.../commands routes."""
import pytest
from datetime import datetime
from decoy import Decoy, matchers
from fastapi import FastAPI
from fastapi.testclient import TestClient
from httpx import AsyncClient
from typing import Callable, Awaitable
from tests.helpers import verify_response
from op... | python |
import discord
from discord.ext import commands
import steam
from steam import WebAPI, SteamID
import keys
##TODO: convert to psql or something
import pickle
import asyncio
import os
import re
## Used to track the worst players in MM
class PlayerTracker(commands.Cog):
## Init
def __init__(self, bot):
... | python |
__all__ = ['ioc_api', 'ioc_common', 'ioc_et', 'xmlutils'] | python |
import modin.pandas as pd
import swifter # Do not remove - this modified bindings for modin
import sys, os
import datetime
import csv
import random
import h5py
import numpy as np
import ipaddress
import datetime as datetime
def write_single_graph(f, graph_id, x, edge_index, y, attrs=None, **kwargs):
'''
store... | python |
# Class to generate batches of image data to be fed to model
# inclusive of both original data and augmented data
# https://gist.github.com/devxpy/a73744bab1b77a79bcad553cbe589493
# example
# train_gen = PersonDataGenerator(
# train_df,
# batch_size=32,
# aug_list=[
... | python |
from ._abstract import AbstractSearcher
from ._result import RecipeLink, SearchResult
import urllib.parse
from typing import List
class NyTimes(AbstractSearcher):
def __init__(self):
AbstractSearcher.__init__(self)
@classmethod
def host(cls):
return "https://cooking.nytimes.com"
d... | python |
import json
import requests
import time
import hmac
import hashlib
from requests.exceptions import HTTPError
SDK_VERSION = '1.0.0'
CLOCK_DRIFT = 300
class HTTPClient(object):
def request(self, method, url, headers, data=None, auth=None):
raise NotImplementedError('subclass must implement request')
cl... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
if subprocess.Popen(['./problem']).wait() != 0:
print("Wow, you\'ve crushed this")
flagfile = open('flag')
if not flagfile:
print("Flag is missing, tell admin")
else:
print(flagfile.read())
| python |
"""
Sudo2 is for Loomgild.py
"""
import time
from time import sleep
# Command Functions
def help():
print("Hello!")
print("Welcome to Loomgild, a script that imitates a command line.")
print("This is one of the few commands that you can use.")
print("We will now load the commands you can use..")
p... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to hold temporary routines created during the beamtime.
Everything added here is star (*) imported into the IPython shell after the
``SplitAndDelay`` object has succesfully instantiated. Therefore, it is
recommended to run the specific unit-test to quickly ensur... | python |
from random import randint
while True:
print("----------\n[j] para jogar o dado\n[e] para fechar")
res = str(input().replace(" ", "").lower())
if res == "j":
print(f"\nvalor do dado: {randint(1, 6)}")
if res == "e":
break
print("----------\n")
| python |
import contextlib
import logging
import os
from pathlib import Path
import shutil
from subprocess import CalledProcessError, check_output
import sys
from tempfile import NamedTemporaryFile
from typing import cast
from spython.main import Client
from lm_zoo import errors
from lm_zoo.backends import ContainerBackend
fr... | python |
#importamos la libreria forms:
from django import forms
#creamos una lista de las posibles opciones del select:
from .pqrsf import PQRSF_CHOICES
#creamos la estructura dl formulario
class ContactFrom(forms.Form):
"""creamos los campos"""
email = forms.EmailField(label="correo electrรณnico", widget=forms.EmailInput(a... | python |
def test_load(session, inline):
inline("PASS")
| python |
TAG_MAP = {
('landuse', 'forest'): {"TYPE": "forest", "DRAW_TYPE": "plane"},
('natural', 'wood'): {"TYPE": "forest", "SUBTYPE": "natural", "DRAW_TYPE": "plane"}
}
def find_type(tags):
keys = list(tags.items())
return [TAG_MAP[key] for key in keys if key in TAG_MAP]
| python |
from twilio.twiml.voice_response import VoiceResponse, Dial
def generate_wait():
twiml_response = VoiceResponse()
wait_message = (
'Thank you for calling. Please wait in line for a few seconds.'
' An agent will be with you shortly.'
)
wait_music = 'http://com.twilio.music.classical.s3.... | python |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from helper import find_csv
grid = plt.GridSpec(2, 2, wspace=0.4, hspace=0.3)
ax1 = plt.subplot(grid[0,0])
ax2= plt.subplot(grid[0,1])
ax3= plt.subplot(grid[1,:])
for i in find_csv():
df = pd.read_csv(i,header=None)
df_forward = df[:int(le... | python |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class SetMaterialRgbParamNode(Node, ArmLogicTreeNode):
'''Set material rgb param node'''
bl_idname = 'LNSetMaterialRgbParamNode'
bl_label = 'Set Material RGB Param'
bl_icon = 'GAME'
def ... | python |
#!/usr/bin/env python
# encoding: utf-8
from smisk.mvc import *
from smisk.serialization import data
import datetime, time
# Importing the serializers causes them to be registered
import my_xml_serializer
import my_text_serializer
# Some demo data
DEMO_STRUCT = dict(
string = "Doodah",
items = ["A", "B", 12, 32.1... | python |
#!/usr/bin/env python
"""Stp - Stock Patterns
Usage: stp_mgr
stp_mgr insider
"""
from docopt import docopt
import stp
print(stp.__file__)
from stp import feed
from stp.feed.insidertrading import data
import sys
def insider():
records = data.get_records()
for record in records:
print(record)
... | python |
# --------------------------------------------------------
# CRPN
# Written by Linjie Deng
# --------------------------------------------------------
import yaml
import caffe
import numpy as np
from fast_rcnn.config import cfg
from fast_rcnn.nms_wrapper import nms
from quad.quad_convert import whctrs, mkanchors, quad_2... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from yandex.cloud.access import access_pb2 as yandex_dot_cloud_dot_access_dot_access__pb2
from yandex.cloud.containerregistry.v1 import registry_pb2 as yandex_dot_cloud_dot_containerregistry_dot_v1_dot_registry__pb2
from yandex.cloud.con... | python |
#-----------------------------------------------------------------------
#Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam
#
#Author: Daniel M. Pelt
#Contact: D.M.Pelt@cwi.nl
#Website: http://dmpelt.github.io/msdnet/
#License: MIT
#
#This file is part of MSDNet, a Python implementation of the
#Mixed-Scale Dense... | python |
import numpy as np
from utils.misc import arr2grid
from planner.astar import AStar
from planner.dijkstra import Dijkstra
from planner.bestfirst import BestFirst
from planner.breadthfirst import BreadthFirst
from planner.bi_astar import BiAStar
from planner.bi_dijkstra import BiDijkstra
from planner.bi_bestfirst import ... | python |
#!/usr/bin/env python3
# coding: utf8
# Author: Lenz Furrer, 2017
'''
Formatter base classes.
'''
import os
import io
from lxml import etree
class Formatter:
'''
Base class for all formatters.
'''
ext = None
binary = False # text or binary format?
def __init__(self, config, fmt_name):
... | python |
# ์ฒซ ๋์ฐฉ์ง
# ์ง์: 1 -> 2
# ํ์: 1 -> 3
# ๋๋ฒ์งธ ๋์ฐฉ์ง
# ์ง์: 1 -> 3
# ํ์: 1 -> 2
# 3๋ฒ์งธ ๋์ฐฉ์ง
# ์์ ์์ด๊ฐ ๋๋ฒ์งธ ์์ด์๊ฒ ์นํ๋ค. (๋ง์ง๋ง์ ์ ์ธํ๊ณ ๋ค์ ๋ญ์น๋ค.)
# 4๋ฒ์งธ
# 3๋ฒ์งธ๋ก ํฐ ์์ด๊ฐ ๋น ๊ณณ์ผ๋ก ๊ฐ๋ค.
# 5๋ฒ์งธ
# ์์ ์์ด๊ฐ ๋๋ฒ์งธ + 3๋ฒ์งธ ์์ด์๊ฒ ์นํ๋ค. (๋ง์ง๋ง์ ์ ์ธํ๊ณ ๋ค์ ๋ญ์น๋ค.)
import sys
n = int(sys.stdin.readline())
count = 0
# ๋งค๊ฐ๋ณ์ : ์ด ๊ฐ์, ์์, ๋ชฉํ, other,...?
def hanoi(total, sta... | python |
from __future__ import unicode_literals
from .common import InfoExtractor
class YouJizzIE(InfoExtractor):
_VALID_URL = r'https?://(?:\w+\.)?youjizz\.com/videos/(?:[^/#?]+)?-(?P<id>[0-9]+)\.html(?:$|[?#])'
_TESTS = [{
'url': 'http://www.youjizz.com/videos/zeichentrick-1-2189178.html',
'md5': '... | python |
# see https://docs.python.org/3/reference/expressions.html#operator-precedence
# '|' is the least binding numeric operator
# '^'
# OK: 1 | (2 ^ 3) = 1 | 1 = 1
# BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0
print(1 | 2 ^ 3)
# '&'
# OK: 3 ^ (2 & 1) = 3 ^ 0 = 3
# BAD: (3 ^ 2) & 1 = 1 & 1 = 1
print(3 ^ 2 & 1)
# '<<', '>>'
# OK: 2 &... | python |
import sys
import os
def jeff():
print('quick attack the enemy press a to attack b to block c for super ')
bob=10
alice=60
turn1=0
turn2=2
spr=5
mod1=0
mod2=0
speed=0
c1=print('bob health is ',bob)
c2=print('alice health is ',alice)
print(c1,c2)
... | python |
wild = "https://image.ibb.co/dPStdz/wild.png"
wild_plus_four = "https://image.ibb.co/jKctdz/wild_4.png"
red = {
'0': 'https://image.ibb.co/gnmtB8/red_0.png',
'1': 'https://image.ibb.co/hvRFPT/red_1.png',
'2': 'https://image.ibb.co/f9xN4T/red_2.png',
'3': 'https://image.ibb.co/hDB4Jo/red_3.png',
'4'... | python |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Copyright 2020 Tecnativa - Pedro M. Baeza
from odoo import api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Type",
compute="_... | python |
import importlib
from functools import partial
from multiprocessing import Process, Queue
from flask import Flask, request
app = Flask("serverfull")
bees = ["a", "b"] # TODO: get this from somewhere
workers = {}
def bee_loop(handler, inq, outq):
request = inq.get()
print("Got request")
outq.put(handl... | python |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
facedetection = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while True:
ret, frame = cap.read()
gry = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face = facedetection.detectMultiScale(gry,1.3,5)
fo... | python |
# Copyright 2017 VMware Inc. All rights reserved.
# 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
#
# ... | python |
# -*- coding: UTF-8 -*-
"""
Automatized configuration and execution of Inspect peptide identification for
a list of spectrum files and a list of reference proteomes. Specifications of
posttranslational modifications can either be directly passed by the user or
assigned to the dataset by its filename (if dataset group i... | python |
from django.db import models
# Create your models here.
class TipoElectrodomestico(models.Model):
nombre = models.CharField(max_length=200)
foto = models.ImageField(null =True, blank=True)
def __str__(self):
#Identificar un objeto
return self.nombre
def numProductos(self):
... | python |
# Copyright 2021 Lucas Fidon and Suprosanna Shit
"""
Data loader for a single case.
This is typically used for inference.
"""
import torch
from monai.data import Dataset, DataLoader
def single_case_dataloader(inference_transform, input_path_dict):
"""
:param inference_transform
:param input_path_dict: di... | python |
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import threading
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
class WriteToCallback(beam.PTransform):
def __init__(self, callback, lock):
self._callback = callback
self._lock... | python |
from sys import path
path.append('/home/joerojas/Desarrollo/Curso-Basico-Python/101_misModulos/modules')
import modulo2
zeroes = [0 for i in range(5)]
ones = [1 for i in range(5)]
print(modulo2.suma(zeroes))
print(modulo2.producto(ones)) | python |
'''
Classes from the 'LinkPresentation' framework.
'''
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
LPMultipleMetadataPresentationTransformer = _Cla... | python |
### Worker threads and payloads for sending web requests
from enum import Enum
from threading import Thread
import requests
from requests.adapters import HTTPAdapter
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
# The Worker class is reused for both stages of execution, so it needs to be able to... | python |
import os
from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, \
render_template, abort, send_from_directory
from doctor_api.app import doctor_api_bp
from patient_api.app import patient_api_bp
app = Flask(__name__)
app.config.from_pyfile('flaskapp.cfg')
app.register_blueprint... | python |
# -*- coding: utf-8 -*-
# trump-net (c) Ian Dennis Miller
from flask_security import ConfirmRegisterForm
from flask_wtf.recaptcha import RecaptchaField
class ExtendedRegisterForm(ConfirmRegisterForm):
recaptcha = RecaptchaField()
def validate(self):
rv = ConfirmRegisterForm.validate(self)
if... | python |
from crestdsl.model import * # bad practice, but used for the evaluation of commands
from .simulator import Simulator
import logging
logger = logging.getLogger(__name__)
import io
try:
import colored
from colored import stylize
color_enabled = True
except ImportError:
color_enabled = False
except io.... | python |
#
# Constant Price Market Making Simulator
#
# simulate different liquidity provision and trading strategies
#
from typing import Tuple
import csv
import numpy as np
import pandas as pd
from numpy.random import binomial, default_rng
# TODO: switch to decimal type and control quantization. numeric errors will kill us... | python |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def load_external_go_repositories():
########## Server request handling ###############
go_repository(
name = "com_github_andybalholm_brotli",
importpath = "github.com/andybalholm/brotli",
commit = "1d750214c25205863625bb3eb8190a51b2cef... | python |
from datapackage_pipelines.wrapper import ingest, spew
from datapackage_pipelines.utilities.resources import PROP_STREAMING
from nli_z3950.load_marc_data import get_marc_records_schema, parse_record
from pymarc.marcxml import parse_xml_to_array
import datetime, json
def get_resource(parameters, stats):
stats['sea... | python |
import os
import sqlite3
class DatabaseRepository:
def __init__(self, database_file, schema_file):
db_is_new = not os.path.exists(database_file)
self.connection = sqlite3.connect(database_file, check_same_thread=False)
if db_is_new:
with open(schema_file, 'rt') as f:
... | python |
"""Utility methods for interacting with Kubernetes API server.
This module is merged into the `metalk8s_kubernetes` execution module,
by virtue of its `__virtualname__`.
"""
from __future__ import absolute_import
from salt.exceptions import CommandExecutionError
import salt.utils.files
import salt.utils.templates
imp... | python |
import logging.config
import configparser
import metrics
from datetime import datetime
import urllib.request
from unittest import mock
from requests import request
from aiohttp.web import Response
from jiracollector import JiraCollector
import pytest
config = configparser.ConfigParser()
config.read('metrics.ini')
lo... | python |
"""
MIT License
mift - Copyright (c) 2021 Control-F
Author: Mike Bangham (Control-F)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software, 'mift', and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limita... | python |
from constant_sum import *
if __name__ == "__main__":
t = 56
n = 510
s = 510
for i in range(500):
l = (T_len(t,n-i,s))
if l>0:
print(log(l,2),t, n-i, s, t*n - s+i, t*n )
#for b in range(t, 1, -1):
# p = 0
# k = min(n*(t - b + 1), s)
# #k = s
#... | python |
from .statement_base import Statement
import sasoptpy
class DropStatement(Statement):
@sasoptpy.class_containable
def __init__(self, *elements):
super().__init__()
for i in elements:
self.elements.append(i)
self.keyword = 'drop'
def append(self, element):
pas... | python |
R = int(input())
print(2*3.141592653589793*R)
| python |
import numpy as np
import pandas as pd
import sys
from typing import Literal
from arch import arch_model
import warnings
from sklearn.exceptions import ConvergenceWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=ConvergenceWarning)
def get_rolling_vol_forecasts(return_series,
... | python |
from django.templatetags.static import static as get_static_url
from django.shortcuts import redirect
from .exceptions import UnknownMessageTypeError
from .models import Dispatch
from .signals import sig_unsubscribe_failed, sig_mark_read_failed
def _generic_view(message_method, fail_signal, request, message_id, disp... | python |
"""
Modules for prediciting topological properties
"""
| python |
"""
Class of water block
"""
import os
from .block import Block
import math
class CurrentWaterRight(Block):
"""
Represents the block of water
"""
def __init__(
self,
settings: any,
path: str = 'advancing_hero/images/blocks/water3.png',
):
super().__init__(os.path.ab... | python |
# Importar las dependencias de flask
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for
# Importar clave/ayudantes de encriptacion
from werkzeug import check_password_hash, generate_password_hash
# Importar FireBase
from firebase import firebase
# Importar el objeto de base d... | python |
def ErrorHandler(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e: # pragma: no cover
pass
return wrapper
| python |
import pandas as pd
import numpy as np
import tensorflow as tf
from math import floor
from dataset.date_format import START_CODE, INPUT_FNS, OUTPUT_VOCAB, encodeInputDateStrings, encodeOutputDateStrings, dateTupleToYYYYDashMMDashDD
def generateOrderedDates(minYear: str, maxYear: str) -> list:
daterange = pd.date... | python |
from __future__ import division, print_function, absolute_import
# LIBTBX_SET_DISPATCHER_NAME iota.single_image
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1
'''
Author : Lyubimov, A.Y.
Created : 05/31/2018
Last Change... | python |
๏ปฟimport requests
from bs4 import BeautifulSoup
import urllib.request
import pytesseract
from PIL import Image
from PIL import ImageEnhance
def shibie(filepath):
# ๆๅผๅพ็
img = Image.open(filepath)
img = img.convert('RGB')
enhancer = ImageEnhance.Color(img)
enhancer = enhancer.enhance(0)
enhancer =... | python |
import random
import uuid
from datetime import timedelta
import re
from discord import AllowedMentions, ButtonStyle, Embed
from squid.bot import CommandContext, SquidPlugin, command
from squid.bot.errors import CommandFailed
from squid.utils import now, parse_time, s
from .views import GiveawayView
class Giveaways(S... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.