content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 30 11:54:11 2019
@author: Wentao
"""
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from core import *
from algos import *
from backtest import *
import ffn
ffn.extend_pandas()
#generate fake data
data = pd.DataFrame(np.r... |
import boto3
import os
import requests
import json
from random import (randrange, randint)
from datetime import datetime
from datetime import timedelta
APPTWEAK_API_KEY = os.getenv('APPTWEAK_API_KEY')
FIREHOSE_STREAM_NAME = 'firehose-blinkist-ratings'
COUNTRY = 'de'
BLINKIST_APPS = {
'ios': '568839295',
'andro... |
from cidc_schemas.prism import SUPPORTED_ASSAYS, PROTOCOL_ID_FIELD_NAME
from .utils import (
copy_dict_with_branch,
get_prismify_args,
get_test_trial,
LocalFileUploadEntry,
PrismTestData,
)
assay_data_generators = []
def assay_data_generator(f):
assay_data_generators.append(f)
return f
... |
#!/usr/bin/env python
""" generated source for module EWrapperMsgGenerator """
#
# Original file copyright original author(s).
# This file copyright Troy Melhase, troy@gci.net.
#
# WARNING: all changes to this file will be lost.
from ib.ext.AnyWrapperMsgGenerator import AnyWrapperMsgGenerator
from ib.ext.EClientSocket... |
class EvaluationResult:
def __init__(self, individual_id: str, accuracy_test: float = -1.0, f1_test: float = -1.0):
self.individual_id = individual_id
self.accuracy_test = accuracy_test
self.f1_test = f1_test
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deps(repo_mapping = {}):
if "com_github_kazuho_picojson" not in native.existing_rules():
http_archive(
name = "com_github_kazuho_picojson",
url = "https://github.com/kazuho/picojson/archive/v1.3.0.tar.gz",
... |
#MIT License
#
#Copyright (c) 2017 TheChyz
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, d... |
# Copyright 2022 The etils Authors.
#
# 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 wr... |
"""Django views for core CAP collector functionality."""
__author__ = "Arkadii Yakovets (arcadiy@google.com)"
import json
from bs4 import BeautifulSoup
from core import models
from core import utils
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.decorators impo... |
#!/usr/bin/env python
"""
Generic PUT/update script
usage: create.py key url [key=value ...]
"""
import os, sys
sys.path.insert( 0, os.path.dirname( __file__ ) )
from common import update
data = {}
for k, v in [ kwarg.split('=', 1) for kwarg in sys.argv[3:]]:
data[k] = v
update( sys.argv[1], sys.argv[2], data )... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, IntegerField
from wtforms.validators import DataRequired
from flask_login import current_user
from app.models import Address
class Delivery(FlaskForm):
phone_number = IntegerField('Phone Number', validators=[DataRequired()])
street_addr... |
import argparse
import sys
import os
from . import LModule, bash, yn, optionSelect
class Stop (LModule):
"""
Stop node
"""
NAME = "stop"
DESCRIPTION = 'stop node'
def parseArgs(self):
self.args = self.parser.parse_args (sys.argv[2::])
self.lnode.setPath(self.args.basepath)... |
# Copyright (c) 2018 FlashX, LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distrib... |
"""
Copyright (c) 2015 SONATA-NFV
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 applicable law or agreed to... |
from robot.api.deco import keyword # imported from here by keyword modules
from .action import ActionKeywords
from .context import (
ActionNotPossible,
ElementNotFound,
LibraryContext,
ControlNotFound,
MultipleControlsFound,
TimeoutException,
WindowControlError,
with_timeout,
)
from .e... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=C0301
# pylint: disable=C0111
import os
import re
import sys
import time
from urllib import parse
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdr... |
# Keep this file separate
def oauth() :
return { "consumer_key" : "8nGiBTEaZQ9wYlcXonD80GyaK",
"consumer_secret" : "tPSTUnHqFLLLtpXVIv7ZMH0x4RoXgHhT6FtV7YqCgvk9GWy4ej",
"token_key" : "215665928-IEJ3KCbG4NX1xfb0dE2M2qvgbWSTmLj15ZRfO5TI",
"token_secret" : "kqunLoUGTTvcpdzKriIwMbSsK3M52dA0rdsa... |
# This data processing script for a customly segmented dataset is heavily based
# on the preparation scripts of fairseq speech-to-text
# https://github.com/pytorch/fairseq/blob/main/examples/speech_to_text/
import argparse
import shutil
from itertools import groupby
from pathlib import Path
from typing import Tuple
... |
"""Converter that converts HTML files from the Ghbook library
to OpenITI mARkdown.
The converter has two main functions:
* convert_file: convert a single html file.
* convert_files_in_folder: convert all html files in a given folder
Usage examples:
>>> from html_converter_Ghbook import convert_file
>>> folder... |
import logging
from typing import Awaitable, Callable, Dict, Optional, Set, Tuple, Type, Union
from immutables import Map
from tickit.core.management.event_router import InverseWiring, Wiring
from tickit.core.management.schedulers.base import BaseScheduler
from tickit.core.state_interfaces.state_interface import Stat... |
"""
Topology-Attributes Coupling Simmilarity (TACSim) measure.
"""
#!/usr/bin/env python
# Copyright (C) 2015 by
# Xiaming Chen <chen_xm@sjtu.edu.cn>
# All rights reserved.
# BSD license.
import itertools, copy
import numpy as np
import networkx as nx
from typedecorator import params
__author__ = "Xiaming Chen"
__ema... |
from __future__ import print_function
import sys
from msp import MSP, MSP_SET_WP, MSP_GET_WP
from serial import Serial
COMMENT_START_CHAR = '#'
MSP_WAYPOINT_ACTIONS = {
"MISSION_WAYPOINT" : 1, # Set waypoint
"MISSION_HOLD_UNLIM" : 2, # Poshold unlimited
"MISSION_HOLD_TIME" : 3, # Hold for ... |
from django.shortcuts import resolve_url as r
from django.test import TestCase
from orcamentos.proposal.models import Work
from .test_base import BaseWorkTest
class WorkTest(BaseWorkTest, TestCase):
def test_create(self):
self.assertTrue(Work.objects.exists())
def test_str(self):
self.assert... |
class Solution:
def minWindow(self, S: str, T: str) -> str:
|
# This code is sourced (inspired) from and found at Github under the MIT License.
# All credits to the original authors. If you are the author, Thank You!
import math
import struct
import pyaudio as pa
def play_frequency(frequency, fs, stream, amplitude = 5, duration = 0.31102):
N = int(fs / frequency)
T = int(freq... |
"""
The draw_bus() function
"""
from easygraphics import *
def draw_bus():
"""
Draw a simple bus.
"""
set_color("lightgray")
rect(0, 0, 210, 130)
set_color("red")
set_fill_color("blue")
draw_circle(60, 100, 10) # draw tyre
draw_circle(140, 100, 10) # draw tyre
rect(20, 20, ... |
"""
Test suite for the entire program. Run this to execute all test cases.
Do not import this from other modules.
"""
import unittest
from util import time_function, time_class
import tanks
import tank_components
import shells
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.asse... |
"""Tests to check the full era5cli workflow."""
import logging
import pytest
from textwrap import dedent
from era5cli.cli import main
# combine calls with result and possible warning message
call_result = [
{
# orography is translated to geopotential in the query
"call": dedent("""\
... |
import pytest
from numpy import expand_dims, ndarray
from nujo import Tensor
from nujo.autodiff._functions._elementary import _Addition
# ====================================================================================================
# Test Tensor value and creator properties
def test_tensor_value(tensors):
... |
import pytest
from plenum.common.messages.fields import HexField
valid_hex_hash = "0123456789abcdefABCDEF"
validator = HexField(length=len(valid_hex_hash))
def test_valid_hex():
assert not validator.validate(valid_hex_hash)
def test_empty_string():
assert validator.validate('')
def test_invalid_length():... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Admin panel for ldap synchronizations."""
import flask
from flask import Blueprint, current_app, flash, redirect, requ... |
from keras.models import Model
from keras.layers.convolutional import ZeroPadding2D
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose
from keras.utils.vis_utils import plot_model
def keras_model(x_train, save_model=True):
inputs = Input(x_train.shape[1:]) # Input(shape), return a... |
class Leverage:
def __init__(self):
self.leverage = 0.0
self.maxQty = 0.0
self.symbol = ""
@staticmethod
def json_parse(json_data):
result = Leverage()
result.leverage = json_data.get_float("leverage")
result.maxQty = json_data.get_float("maxQty")... |
from mongoengine import Document, StringField
from mongoengine_plus.models import BaseModel
class TestModel(BaseModel, Document):
id = StringField()
secret_field = StringField()
__test__ = False
_hidden = ['secret_field']
def test_hide_field():
model = TestModel(id='12345', secret_field='secret... |
from django.apps import AppConfig
from suit.apps import DjangoSuitConfig
from suit.menu import ParentItem, ChildItem
class AuctionConfig(AppConfig):
name = 'auction.auction'
verbose_name = "Auction"
def ready(self):
"""Override this to put in:
Users system checks
Users sign... |
#!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import argparse
import bson
import numpy as np
import matplotlib.pyplot as pyplot
import matplotlib.animation as animation
import functools
from arvet.config.global_configuration import load_global_config
import arvet.database.connection as dbconn
import arvet.... |
import traceback
import sys
import os
from functools import partial
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' #hiding pygame greeting console output
import pygame
import json
from engine import *
import tkinter
import tkinter.filedialog
import tkinter.messagebox as mb
from tkinter import scrolledtex... |
# Copyright 2018 Michael DeHaan LLC, <michael@michaeldehaan.net>
#
# 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 app... |
# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de>
import os
import numpy as np
import torch
from utils.matlab import load, save
from . import types
def default_collate(inputs):
if np.isscalar(inputs):
return inputs
else:
return {key: default_collate([d[key] for d in inputs]) for ke... |
"""BB2 api agent modul"""
import requests
from .adapter import adapter
class BB2APINotAvailable(Exception):
"""Exception to raise for BB2API timeout issues"""
class Agent:
DEFAULT_VERSION = 2
DEFAULT_PLATFORM = 'pc'
"""BB2 api agent"""
BASE_URL = "http://web.cyanide-studio.com/ws/bb2/"
def __ini... |
#
# This file is part of AceQL Python Client SDK.
# AceQL Python Client SDK: Remote SQL access over HTTP with AceQL HTTP.
# Copyright (C) 2021, KawanSoft SAS
# (http://www.kawansoft.com). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in comp... |
import argparse
import json
import pickle
#
import ray
from ray import tune
import gym
#
from utils.config import read_tune_params
def train(env: str,
run: str,
stop: dict = None,
config: dict = None,
results_dir: str = None,
verbose: int = 2,
checkpoint_fre... |
from unittest.mock import MagicMock
from snowflake.connector.cursor import SnowflakeCursor, DictCursor
import pytest
import snowflake.connector as sf
from prefect.tasks.snowflake import SnowflakeQuery
class TestSnowflakeQuery:
def test_construction(self):
task = SnowflakeQuery(
account="test... |
from matplotlib import ticker
thousands_ticker_formatter = ticker.FuncFormatter(lambda x, p: "%dk" % int(x / 1000))
def fmt_thousands(val: int) -> str:
return format(val, ",")
def fmt_percentage(total: int):
return lambda val: "%.1f%%" % (100 * val / total)
def fmt_barplot(ax, values, total):
ax.bar_... |
import numpy as np
import itertools as it
import scipy
import statsmodels.api as sm
import os
from sys import argv
def read_chrom(chrom_file):
"""
Read a list of chromosomes.
Args:
chrom_file (str): name of the file (ex: 'dm3.chrom.sizes')
Returns:
chrom_list (list): list of chromosome na... |
"""An Implementation of Binary Tree."""
from typing import Any
class Node:
"""Binary Tree node."""
__slots__ = "_data", "_left", "_right"
def __init__(self, data: Any, left: "Node"=None, right: "Node"=None):
self._data = data
self._left = left
self._right = right
def display(... |
import requests
from itertools import product
class ForceAttackModule(object):
"""
Module finds links on the website. It uses brute-force method.
"""
def __init__(self, proxies=None, start=1, stop=2, capital=False):
"""
Constructor of the class.
:param proxies: Proxy informati... |
""" This module stores the default config settings for the server.
It is optionally overriden by a local_config module in the same directory.
The local configs are for dev debugging/testing.
"""
import importlib
# Flask app settings
APP_HOST = "0.0.0.0"
APP_PORT = 5000
FLASK_DEBUG = False
VERBOSE = False
CLEANUP_SNS =... |
import pytest
from intcode import solve
@pytest.mark.parametrize('opcodes,solution', [
([1,0,0,0,99],[2,0,0,0,99]),
([2,3,0,3,99], [2,3,0,6,99]),
([2,4,4,5,99,0], [2,4,4,5,99,9801]),
([1,1,1,4,99,5,6,0,99], [30,1,1,4,2,5,6,0,99])
])
def test_solve(opcodes, solution):
assert solve(opcodes) == solu... |
"""Autocomplete urls."""
from django.urls import path
from . import views
urlpatterns = [
path('get_names', views.get_names, name='get_names'),
]
|
# Copyright 2020 Tabacaru Eric
#
# 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 writ... |
from nose.tools import *
from .generator import generate_resource
import math
import udaru_anomaly_detection.check_gramma as check_gramma
fr3 = 1/3
def test_loss_calculation():
# Test loss on:
# ^ -> A -> $
model = check_gramma.CheckGrammaModel()
node_a = model.add_node()
node_a.increment_emis... |
# -*- coding: utf-8 -*-
from . import data_processor as dp
from . import data_simulator as ds
from . import train, evaluate, optimize, fcnet, hpmodel, nodeframe, utils
import torch
from torch.autograd import Variable
import torch.multiprocessing as mp
import numpy as np
#%% multilayer perceptron (MLP)
class MLP(trai... |
import unittest
from amonlite.web.template import *
from nose.tools import eq_
class TestTemplateFilters(unittest.TestCase):
def test_dateformat(self):
date = dateformat(1319737106)
eq_('27-10-2011-17:38', date)
def test_timeformat(self):
time = timeformat(1319737106)
eq_('17... |
from django.shortcuts import render
from stock.models import Stock, StockPrice, StockNews, StockTweet
from datetime import datetime, date
from stock.utils.ticker import Ticker
import json
from stock.utils.signals import Signals
import math
from collections import Counter
import pandas as pd
from stock.utils.load_data i... |
#!/usr/bin/env python
import boto3
import json
TABLE_NAME='vehicle'
client = boto3.client('dynamodb')
response = client.delete_item(
TableName = TABLE_NAME,
Key = {'device': {'S': 'DR003'}},
ReturnValues = 'ALL_OLD'
)
print(json.dumps(response, indent=4)) |
from pathlib import Path
from secret_santa.util.path import PathUtils
def test_get_project_root(project_root_directory: Path):
# This more of a double validation, making sure that both point to the same directory
code_project_root = PathUtils.get_project_root()
assert code_project_root == project_root_di... |
"""
References:
https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py
"""
import cv2
import numpy as np
def vec_gaussian(img, sigma):
cons = 1 / (sigma * np.sqrt(2 * np.pi))
return cons * np.exp(-((img / sigma) ** 2) * 0.5)
def get_window(img, center, k_siz... |
""" func.py - Additional tools for working with functions and callable objects
"""
__all__ = ['persistent_cache']
import functools
from .collections import PersistentDict
def _map_wrapper(user_func, m):
@functools.wraps(user_func)
def wrapper(*args, **kwargs):
key = args + tuple(kwargs.items())
... |
"""
The model is adapted from the tensorflow tutorial:
https://www.tensorflow.org/get_started/mnist/pros
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class Model(object):
def __init__(self, fea_dim=1024):
self.x_input = ... |
import requests
def _f(path):
return 'http://localhost:8080/' + path
def create_user(params):
assert 'sid' in params
assert 'name' in params
assert 'pass' in params
res = requests.post(_f('users'), json=params)
return res.status_code == 200
def search_user(sid):
res = requests.get(_f('s... |
from ..emailer import sendemail
import subprocess
notifytext = """
Děkujeme za registraci na LinuxDays. Ještě je potřeba registraci potvrdit.
Jméno: {name[0]}
Odebírat oznámení: {announces[0]}
Účast: {days[0]}
Oběd sobota: {mealsat[0]}
Oběd neděle: {mealsun[0]}
Svou registraci prosím potvrďte kliknutím na následujíc... |
#!/usr/bin/env python2
# -*- encoding:utf-8 -*-
"""
使用 Python 计算 Fibonacci 数:0, 1, 1, 2, 3, 5, ...
1. fibonacci_simple, 最简单的写法,直接利用递归调用
2. fibonacci_list,使用列表缓存中间结果
3. fibonacci_formula,使用公式推导
"""
from __future__ import print_function
import signal
import time
def signle_handler(signal_n, frame):
"""
利用信号处理... |
import numpy as np
from . import _pynqs_gpu
def argchecker(kwargs, ArgCheckList):
for arg in ArgCheckList:
if not arg in kwargs:
raise Exception ('You omit an essential argument registered in :', ArgCheckList)
class RBM:
def __init__(self, **kwargs):
"""
floatType : 'fl... |
from datetime import timedelta
from fastapi import APIRouter, Body, HTTPException, status
from app.core.auth import authenticate_user, create_access_token
from app.core.config import config
from app.models.v1.auth import Token, UserAuthenticate
router = APIRouter()
ACCESS_TOKEN_EXPIRE_MINUTES = config.JWT_EXPIRY
... |
# Generated by Django 3.2.12 on 2022-03-22 18:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0003_auto_20220322_1759'),
]
operations = [
migrations.AlterField(
model_name='order',
name='total_price'... |
from dust_mie import calc_mie
import numpy as np
import matplotlib.pyplot as plt
wave = np.linspace(0.5,2.5,50)
qext, qsca, qback, g = calc_mie.get_mie_coeff_distribution(wave,r=1.0,material='SiO2',s=0.5)
plt.plot(wave,qext)
plt.xlabel('Wavelength ($\mu$m)')
plt.ylabel('Q$_{ext}$')
plt.savefig('extinct_func_distribut... |
# -*- coding:utf-8 -*-
import os
import logging
import math as m
import numpy as np
import scipy.io as sio
import scipy.signal as signal
from typing import AnyStr
# DON'T DELETE THIS! This is used by other modules.
from sklearn.model_selection._split import check_random_state
def cart2sph(x, y, z):
'''
Tran... |
# -*- coding: utf-8 -*-
"""
Created on Saturday March 24 at 9:04 am 2018
@author: milesws
"""
import pandas as pd
import numpy as np
from os import listdir
import re
#Establish directory to files of false name matches comparing 1900 to 1910 censuses
files = listdir(r"R:\JoePriceResearch\record_linking\pro... |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... |
import os
from qtpy import QtGui, QtWidgets, QtCore
import typhos.utils
class Splash(QtWidgets.QDialog):
def __init__(self, *args, **kwargs):
super(Splash, self).__init__(*args, **kwargs)
self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
self._base_path = os.path.dirn... |
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start):
queue = []
queue.append([start])
while queue:
path = queue.pop(0)
node = path[-1... |
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
# The first node is called the head
self.head = None
# insert at beginning
def insert_at_beginning(self, data):
node = Node(data, self.... |
import scrapy
from tutorial.items import FileDemoItem
class FiledemoSpider(scrapy.Spider):
name = 'FileDemo'
allowed_domains = ['quotes.toscrape.com']
start_urls = [
'http://quotes.toscrape.com/',
]
def parse(self, response):
for quote in response.xpath('//div[@class="quote"]'... |
from .homspace import HeckeModuleHomspace, is_HeckeModuleHomspace
from .module import HeckeModule_free_module, HeckeModule_generic, is_HeckeModule
from .hecke_operator import HeckeOperator, is_HeckeOperator
from .degenmap import DegeneracyMap
from .algebra import HeckeAlgebra, is_HeckeAlgebra
from .morphism import... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.test import TestCase
from system.models import Configuration
from physical.errors import NoDiskOfferingError, NoDiskOfferingLesserError, \
NoDiskOfferingGreaterError, DiskOfferingMaxAutoResize
class PhysicalErrorsTestCase(TestCase):
d... |
import sys
import os
from time import sleep
from core.system import *
from modules.logo import *
class lt(object):
def notinl(self):
Mylogo()
print("\n\n\033[1;31m Error \033[01;33m\'localtunnel\' \033[01;31mis not installed in "+system+".\033[00m")
sleep(2)
def locals(self):
while True:
os... |
import os
import traceback
import platform
import time
#import sys
#sys.path.append("../..") # tell python to add top level directories so we can import from here as well.
from .build_tools import *
'''
Run cmake script is in charge of calling the cmake command for
every versions of maya. Basically it calls t... |
from railroad import NonTerminal, Terminal, Choice, OneOrMore, ZeroOrMore, Diagram, Optional, Sequence, Group, MultipleChoice, Comment, Start, DEFAULT_STYLE
tfm_diagram = Group(Choice(0, "Normalizer", "MinMaxScaler", "RobustScaler", "StandardScaler", "PCA"), "tfm")
est_diagram = Group(Choice(0, "LogisticRegression", "... |
#!usr/bin/python3
import subprocess
from fabric import Connection, ThreadingGroup, SerialGroup
import getpass
import json
import time
def get_node_list(node_config):
return node_config["workers"] + [node_config["master"]]
def get_node_group(nodes):
return ThreadingGroup(*nodes, user="root", forward_agent=Tru... |
#!/usr/bin/env python
print("Generating leds");
fd = open("leds.inc", "w")
for ix in range(0,35):
for iy in range(0, 47):
fd.write('''
(module tom-opto:B1010RGBT-HG (layer F.Cu) (tedit 5FCE6CDB) (tstamp 5FD3D3A9)
(at {} {})
(descr "RGB 1.0mm x 1.0mm")
(path /5FD9C85A/5FF7642E)
(attr smd)
... |
from thinksocket import ThinkSocket
import base64
import glob
with ThinkSocket() as sock:
sock.bind()
sock.listen(1)
connection, client_address = sock.accept()
print "Got connection from client:", client_address
with ThinkSocket(connection) as conn:
registration = conn.receive_json()
... |
from _sha256 import sha256
from common.serializers.serialization import domain_state_serializer
from plenum.common.constants import STEWARD, ROLE
LAST_SEQ_NO = "lsn"
VALUE = "val"
LAST_UPDATE_TIME = "lut"
def is_steward(state, nym, is_committed: bool = False):
role = get_role(state, nym, is_committed)
retur... |
class DeviceConfiguration():
def __init__(self, session):
self.session = session
def get_device_list_by_template_id(self, template_id):
url = f'{self.session.api_url}/template/device/config/attached/{template_id}'
r = self.session.get(url)
return r.json()
def get_device_t... |
# coding: utf8
from __future__ import unicode_literals
STOP_WORDS = set(
"""
à às área acerca ademais adeus agora ainda algo algumas alguns ali além ambas ambos antes
ao aos apenas apoia apoio apontar após aquela aquelas aquele aqueles aqui aquilo
as assim através atrás até aí
baixo bastante bem boa bom breve
c... |
def diff_map_info(W, verbose=False):
'''
Construct the information necessary to easily construct diffusion map for any t
Inputs:
W a numpy array of size n x n containing the affinities between points
Outputs:
diff_vec a numpy array of size n x n-1 containing the n-1 nontr... |
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import slack
# Create webapp
app = Flask(__name__)
api = Api(app)
# Limitations per host per day / hour
limiter = Limiter(
app,
key_func=get_rem... |
import json
from easydata.data import DataBag
from easydata.managers import ModelManager
from tests.factory import data_dict
from tests.factory.models import ProductJsonModel
def load_data_bag_with_model():
model_manager = ModelManager(ProductJsonModel())
data_bag = DataBag(main=json.dumps(data_dict.item_wi... |
import random
from .base import PublicTestCase
class SimulatorTestCase(PublicTestCase):
def test_get_simulator(self):
response = self.client.simulator(amount=random.randint(1000, 10000))
self.assertEqual(response.status_code, 200)
|
# Criar Variáveis para nome (str), idade (int), altura(float) e peso(float) de uma pessoa.
# Criar a variável com ano atual (int)
# Obter o ano de nascimento da pessoa (baseado na idade e no ano atual)
# Obter o IMC da pessoa com 2 casas decimais (peso e na altura da pessoa)
# Exibir um texto com todos os valores na te... |
from enum import Enum
# 型の定義
class ColumnType(Enum):
INT = 1
DOUBLE = 2
STRING = 3
DATE = 4
DATETIME = 5
BOOL = 6
from .read_definition import read_definition
from .write_for_mysql import write_for_mysql
|
from django.utils.translation import ugettext_lazy as _
class GrapheneDjangoJWTBaseException(Exception):
default_message = _('You do not have permission to perform this action')
code = 401
class JSONWebTokenError(GrapheneDjangoJWTBaseException):
pass
class PermissionDenied(GrapheneDjangoJWTBaseExcepti... |
# https://www.codingame.com/training/easy/morellets-random-lines
def gcd(a, b):
while b:
a, b = b, a % b
return a
def is_point_on_line(x, y, line):
return line[0] * x + line[1] * y + line[2] == 0
def reduce_equation(a, b, c):
g = gcd(gcd(a, b), c)
return a // g, b // g, c // g
def ge... |
import logging
from typing import NamedTuple, Union, Dict, Optional, Type
from pydantic.main import BaseModel
from hikaru.model.rel_1_16 import *
from .models import PrometheusKubernetesAlert, PrometheusAlert
from ..helper import exact_match, prefix_match
from ..kubernetes.custom_models import RobustaPod, RobustaDeplo... |
#__all__ = ["scraper", "logging_aux", "res_obj_manipulator","jdownloader"]
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# Variablendefinition
a = 15
b = 5
# Funktionsdefinitionen
def trenner(anzahl):
for zaehler in range(anzahl):
print("-", end="")
print()
def restalkohol(promille, stundenschlaf):
abgebaut = (promille / 10) * stundenschlaf
restalkohol = round(promille - abgebaut, 2)
return restalkohol
def ... |
import logging
import numpy as np
from scipy.stats import beta
from scipy.ndimage import gaussian_filter
logger = logging.getLogger(__name__)
def make(n=101, r=25, ishift=0, jshift=0,
sigma_noise=0.1, sigma_smooth=2,
cut_b=0, cut_theta=0, cut_thickness=5, rs=None):
"""
Make a bright circ... |
from setuptools import setup, find_packages
import os
import sys
assert sys.version_info >= (3, 4), (
"Please use Python version 3.4 or higher, "
"lower versions are not supported"
)
here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with open(os.path.join(here... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import curses
from math import floor
from datetime import datetime as date
import sys
import time
import signal
from exchanges.bitfinex import Bitfinex
last_price = 0
screen = curses.initscr()
width = 0
height = 0
origin_x = 0
origin_y = 0
glyph = {
'0': [" ##### ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.