content stringlengths 5 1.05M |
|---|
"""
tests.unit.test_exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~
Exceptions unit tests
"""
import textwrap
import traceback
import pytest
import saltfactories.exceptions
def test_process_failed_message():
message = "The message"
with pytest.raises(saltfactories.exceptions.FactoryFailure) as exc:
... |
from flask import Flask
from flask import jsonify,request
from flask_cors import CORS
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['JWT_SECRET_KEY'] = 'demofido'
jwt = JWTManager(app)
CORS(app)
from api import *
if __name__ == '__main__':
app.run(debug=Tru... |
"""
Airtime
send(phoneNumber: String, amount: String): Send airtime to a phone number.
send(recipients: Map<String,String>): Send airtime to a bunch of phone numbers. The keys in the recipients map are phone
numbers while the values are airtime amounts.
"""
import africastalking
import unittest
import random
from... |
import yaml
import main
def test_index():
main.app.testing = True
client = main.app.test_client()
r = client.get("/schema-builder", base_url="https://localhost")
assert r.status_code == 200
assert r.data.decode("utf-8") == open("index.html").read()
def test_post_non_json():
main.app.testin... |
# Refactored version of example1.py
# load survey data, perform factor analysis, and compare to mental health data
import os
from pathlib import Path
import pandas as pd
import numpy as np
from scipy.stats import pearsonr
from sklearn.decomposition import FactorAnalysis
from sklearn.preprocessing import scale
from co... |
import pymongo
import http.client
import hashlib
import urllib
import random
import json
import time
import os
with open('Spider/config_local.json', 'r', encoding='utf8') as f:
config_local = json.load(f)
appid = config_local['tr_appid']
secretKey = config_local['tr_secretKey']
mongo_port = config_loc... |
import os
from typing import Tuple
from unittest.mock import MagicMock
from bson import json_util
from flask import Flask
from mongomock import MongoClient
from application.data_validator import DataValidator
from application.service import make_app
class MockMongoClient(MongoClient):
"""
Фейковый класс под... |
import struct
from Cryptodome.Protocol.KDF import PBKDF2
from Cryptodome.Cipher import AES
from Cryptodome.Hash import HMAC
from Cryptodome.Hash.SHA1 import SHA1Hash
from Cryptodome.Util import Counter
from Cryptodome import Random
from .zipfile import (
ZIP_BZIP2, BadZipFile, BaseZipDecrypter, ZipFile, ZipInfo, ... |
from __future__ import print_function
import pytest
import click
from click.testing import CliRunner
from ..args import (
required_option,
default_option,
boolean_flag,
option,
boolean,
get_arg_default,
)
def test_boolean_flag():
runner = CliRunner()
def run_suite(default_value):
... |
from JumpScale import j
def cb():
from .StatManager import StatManager
return StatManager()
j.base.loader.makeAvailable(j, 'system')
j.system._register('statmanager', cb)
|
# Copyright 2018 Marco Galardini and John Lees
'''Predict phenotypes using a fitted elastic net model'''
import os
import sys
from .utils import set_env
from collections import deque
# avoid numpy taking up more than one thread
with set_env(MKL_NUM_THREADS='1',
NUMEXPR_NUM_THREADS='1',
OMP_N... |
#
# Copyright (c) 2021 Intel Corporation
#
# 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... |
"""LGSM: Latent Galaxy SED Model"""
__version__ = "0.1.0"
import lgsm.losses
from lgsm.lgsmodel import LGSModel
from lgsm.physics_layer import PhysicsLayer
|
from os.path import join
from svd_algebra.svd_algebra import *
a = SVDAlgebra('tests/models')
vocab = set(a.vocabulary)
with open('evaluate/data/questions-words.txt', 'r') as f:
analogies = {}
analogy_type = ''
for l in f:
l = l.strip().split()
if l[0].startswith(':'):
analogy... |
# -*- coding: utf-8 -*-
import datetime
def draw_squares(screen_width: int = 156,
square_size: int = 3,
outline_size: int = 1,
squares_count: int = 300):
print('*' * screen_width)
squares_in_row_count: int = screen_width // (outline_size + square... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 19:56:18 2019
@author: Craig Chisholm
"""
import matplotlib.pyplot as plt
import numpy as np
import RydbergFunctions as Rydberg
from fractions import Fraction
from matplotlib import cm
plt.close("all")
#Input information
atom = '87Rb'
nn = 50
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 20:28:39 2018
@author: Isaac
"""
# -*- coding: utf-8 -*-
# vispy: gallery 10
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
""" Demonstrates use of visual.Markers to create a poin... |
import musttyping
def f():
def f():
...
...
musttyping.must_typing()
|
import numpy as np
# Adapted from
# https://github.com/keon/algorithms/blob/master/algorithms/graph/minimum_spanning_tree.py
class Edge:
def __init__(self, u, v, weight):
self.u = u
self.v = v
self.weight = weight
class DisjointUnionSet:
# The disjoint union set is represented as a... |
lil = float(input("Digite um valor em litros: "))
print("Os litros digitados foram {} litros e em metros cubicos é {:.3f} ".format(lil,(lil/1000))) |
WELCOME = "Welcome to light out flip game!"
ENTER = "Select one lamp to light On/Off (Enter the index, start from 0): "
WIN = "Great!You light up all the lights"
INVALID = "Invalid input."
def get_lights(light_file):
with open(light_file, 'r') as f:
line = f.readline()
lights = [item for item in lin... |
# cost_functions.py
from keras import backend as K
def isd(y_true, y_pred):
"""
Itakura-Saito divergence
"""
y_true = K.clip(y_true, K.epsilon(), 1)
y_pred = K.clip(y_pred, K.epsilon(), 1)
# return K.sum(y_true * K.log(y_true / y_pred), axis=-1)
return (y_true/y_pred) - K.log(y_true/y_pred... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import os.path
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PYTHONFILES = os.path.join(ROOT, "pythonFiles", "lib", "python")
REQUIREMENTS = os.path.join(ROOT, "requirements.txt")
sys.path.in... |
#!/usr/bin/python
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
import threading
from itertools import product
from test_utils_pool import TestPool
from write_host_file import write_host_file
from daos_racer_utils import DaosRacerCommand
from osa_utils... |
from .base import PipBaseRecipe
class WerkzeugRecipe(PipBaseRecipe):
def __init__(self, *args, **kwargs):
super(WerkzeugRecipe, self).__init__(*args, **kwargs)
self.name = 'werkzeug'
self.version = '0.14.1'
self.pypi_name = 'Werkzeug'
|
"""
213. House Robber II
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it ... |
#!/ebio/ag-neher/share/programs/bin/python
#!/usr/bin/python
import sys,os,glob
# run the compiled C++ program to generate the data
executable = '/ebio/ag-neher/share/users/rneher/FluPrediction_code/toydata/src/flu'
cmd = executable+' '+' '.join(sys.argv[1:])
print cmd
os.system(cmd)
# reconstruct the destination di... |
from multi_harvest_zoo.environment.game.game import Game
from multi_harvest_zoo.environment import multi_harvest_zoo
n_agents = 2
num_humans = 1
max_steps = 100
render = False
level = 'deterministic_room'
reward_scheme = "scheme_1"
seed = 1
record = False
parallel_env = multi_harvest_zoo.parallel_env(level=level, n... |
from django.contrib.auth import get_user_model
from django.core import mail
from django.urls import reverse
from django.test import Client, TestCase
import re
from .models import UserProfile
UserModel = get_user_model()
class LoginTestCase(TestCase):
CLIENT = Client()
def test_returns_200_with_session_cook... |
import sys
import CleanCode
scan = CleanCode.scan()
scan.version(isShow = True)
input("按回车(Enter)继续")
clean = CleanCode.clean()
clean.version(isShow = True)
input("按回车(Enter)继续")
|
import pytest
from httpx import AsyncClient
from ecomerce.auth.jwt import create_access_token
from conf_test_db import app
@pytest.mark.asyncio
async def test_all_users():
async with AsyncClient(app=app, base_url="http://test") as ac:
user_access_token = create_access_token({"sub": "john@gmail.com"})
... |
from flask import Blueprint
import json
home_routes = Blueprint("home_routes", __name__)
@home_routes.route("/")
def home():
return "Server running.."
@home_routes.route("/about")
def about():
functions = {"/" : "server running",
"/about" : "route info",
"/database/get_... |
import binascii
import datetime
import os
import flask
from flask import flash, render_template, redirect, url_for
from flask_login import current_user, login_user, logout_user, login_required
from flask_mail import Message
from app import app, bcrypt, lm, mail, db
from forms.formuser import LoginForm, LostFormPasswor... |
from django.http import HttpRequest, HttpResponse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.urls.base import reverse
from visitors.decorators import user_is_visitor
def index(request: HttpRequest) -> HttpResponse:
"""Display the homepage."""
return ... |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from .models import Avaliacao, Disciplina, Matricula, Periodo, Professor
def index(request):
quantidade_disciplinas = Disciplina.objects.count()
quantidade_matriculas = Matricula.objects.count()
matriculas_cursando = Matricula.... |
import sys
from .logger import Logger
# for type hint
from typing import Any, Dict, Optional, Union
from argparse import Namespace
from torch.nn import Module
class PrintLogger(Logger):
def __init__(self,
log_dir: str,
config: Union[Namespace, Dict[str, Any]],
... |
from .dry import add_chunks
from .dry import make_records
from .dry import split_into_lines
|
from viaje import Viaje
from handler import Handler
v = Viaje()
hd = Handler()
hd.navigate(cine=,pelicula=,hora=)
hd.seleccion_sitios()
hd.login
hd.pagar
hd.exit()
|
'''
@auther: Samaneh
'''
import pandas as pd
import numpy as np
import math
import csv
import re
import math
import glob
import requests
#################################################################################
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
def falcon_call_db(text,... |
"""
Build tnseq_yeast.
"""
from setuptools import setup
# requirements = [line.strip() for line in open('requirements.txt')]
setup(
name = 'tnseq_yeast',
version = '0.3', #versioneer.get_version(),
author = 'Jim Chu',
author_email = 'biojxz@163.com',
url = 'https://tnseq_yeast.readthedocs.io/',
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implementation of Cellular network environment model
"""
import logging
import math
from functools import reduce
from collections import namedtuple, OrderedDict, defaultdict
import simplejson as json
from loadbalanceRL.lib.environment import environment_template
fro... |
#!/usr/bin/env python3
"""
Documentation
See also https://www.python-boilerplate.com/flask
"""
import os
import argparse
from flask import Flask, jsonify
from flask_cors import CORS
from logzero import logger
def create_app(config=None):
app = Flask(__name__)
# logzero.logfile("./campaign_service.log", maxBy... |
import os
import gettext
from .bottle import request, response, SimpleTemplate
class TranslationPlugin(object):
name = 'translation'
def __init__(self, configuration):
try:
self.translations = {
'de': gettext.translation('messages', os.path.join(os.path.dirname(os.path.re... |
# _*_ coding: utf-8 _*_
__author__ = 'Di Meng'
__date__ = '1/13/2018 5:31 PM'
import numpy as np
A = np.arange(2,14).reshape((3,4))
print(A)
# find index of min, max mean
print(np.argmin(A))
print(np.argmax(A))
print(np.mean(A))
# Same as abover
print(A.mean())
#find median
print(np.median(A))
#cumulate sum
np.cums... |
import os
import subprocess
class Memory:
def __init__(self):
self.noError = open(os.devnull, 'w')
def mem_scrape(self):
os.system('color 0A')
"""Acquires a raw memory dump from the target system"""
print("[+] Memory acquisition\n", flush=True)
# variable to point to t... |
import led_service
import config
# import requests_toolbelt.adapters.appengine
# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
# requests_toolbelt.adapters.appengine.monkeypatch()
app = notspotify.create_app()
if __name__ == "__main__":
app.run(host='127.0.0.1',... |
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Davide Gessa
'''
MIT License
Copyright (c) 2021 Davide Gessa
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 li... |
"""
Module containing class representing a transformation of the form:
$$x\\longrightarrow \\ln{\\big(f(x)\\big)}$$
**File**: $DISTPY/distpy/transform/LoggedTransform.py
**Author**: Keith Tauscher
**Date**: 17 May 2021
"""
import numpy as np
from .Transform import Transform
class LoggedTransform(Transform):
"... |
from epub_novel import epub
from instance import *
import API
class EpubFile:
def __init__(self, book_id, book_name, author_name):
self.book_id = book_id
self.book_name = book_name
self.author_name = author_name
self.epub = epub.EpubBook()
self.EpubList = list()
... |
from simple_NER.annotators import NERWrapper
from simple_NER import Entity
import requests
class SpotlightNER(NERWrapper):
def __init__(self, host='http://api.dbpedia-spotlight.org/en/annotate',
confidence=0.5, support=0, spotter="Default",
disambiguator="Default", policy="whitel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FELPY
__author__ = "Trey Guest"
__credits__ = ["Trey Guest"]
__license__ = "EuXFEL"
__version__ = "1.0.1"
__maintainer__ = "Trey Guest"
__email__ = "twguest@students.latrobe.edu.au"
__status__ = "Developement"
"""
import numpy as np
def lu_decomp3(a):
"""
... |
/home/runner/.cache/pip/pool/84/ed/b6/9d3fa2b55a188b2f305eb5d76331f0f3ab680a9fd4abe714451ef0e9c9 |
# Example Pipeline definition
# https://airflow.apache.org/docs/apache-airflow/1.10.1/tutorial.html#example-pipeline-definition
# Importa bibliotecas necessárias para criação desde Pipeline
from airflow import DAG
from datetime ... |
from test.defaults import defaultTests, simulator
import pytest
import inspect
class simulatorTests(defaultTests):
def __init__(self, simulator=simulator, **kwargs):
super().__init__(**kwargs)
self.simulator = simulator
self.kwargs["simulator"] = simulator
self.reduced_kwargs["simu... |
import CamCal
import Thresholding
import polynomial
import cv2
from moviepy.editor import VideoFileClip
max_fail_frames = 5
left_failure_counter = max_fail_frames
right_failure_counter = max_fail_frames
#======================Start of video Pipeline======================#
camcalibration_imgs = 'camera_cal\calibratio... |
#!/usr/bin/python3
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import json
import base64
import os
import mimetypes
import pprint
url_post = "https://YOUR-WP-URL-HERE/wp-json/wp/v2/posts"
url_media = "https://YOUR-WP-URL-HERE/wp-json/wp/v2/media"
user = "USERNAME"
password = "APPL... |
"""ThreatConnect API Logger"""
import time
from logging import Formatter, Handler
class TcExLogFormatter(Formatter):
"""Logger formatter for ThreatConnect Exchange API logging."""
def __init__(self, task_name=None):
"""Initialize Class properties."""
self.task_name = task_name
super(Tc... |
import setup_path
import airsim
import time
# connect to the AirSim simulator
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
print("fly")
client.moveToPositionAsync(0, 0, -10, 5).join()
print("reset")
client.reset()
client.enableAp... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import cohesity_management_sdk.models.smb_active_session
class SmbActiveFilePath(object):
"""Implementation of the 'SmbActiveFilePath' model.
Specifies a file path in an SMB view that has active sessions and opens.
Attributes:
active_sessio... |
class AlreadySubscribed(Exception):
"""Raised when the system tries to associate a new subscription to an already subscribed user
It could be raised by subscribeUserToAssociation mutation"""
class CustomerNotAvailable(Exception):
"""Raised when a user requests to access his customer portal, but the system... |
from mcstats import mcstats
mcstats.registry.append(
mcstats.MinecraftStat(
'eat_rawmeat',
{
'title': '生食者',
'desc': '吃過的生肉數量',
'unit': 'int',
},
mcstats.StatSumReader([
mcstats.StatReader(['minecraft:used','minecraft:porkchop']),
... |
n, m = map(int, input().split())
for i in range(n):
for j in range(m):
if (i+j)%2==0:
print('#', end='')
else:
print('*', end='')
print('\n')
|
#!/usr/bin/env python
"""
runner test
"""
# Import Modules
import pygame as pg
from frameRunner.FrameRunner import FrameRunner
from Animation import createBySheet
from PuyoAnima import puyoAnima
width = 1800
height = 1000
if not pg.font:
print("Warning, fonts disabled")
if not pg.mixer:
print("Warning, so... |
#
# PySNMP MIB module Wellfleet-PROTOPRI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-PROTOPRI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:34:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
"""Click commands for managing the app."""
import os
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
@click.command()
def clean():
"""Remove *.pyc and *.pyo files recursively starting at current directory.
Borrowed f... |
#!/usr/bin/env python
import sys
from dataclasses import dataclass, field
from textwrap import dedent
from ..argparser import ExtendedHelpArgumentParser, subcommand_exists
from .environment import Environment
@dataclass
class EnvCLI:
trace: bool
command: str
environment: Environment = field(init=False)
... |
import pandas as pd
def get_model_summary(model):
params_summary = pd.DataFrame(
[[n, p.numel()] for n, p in model.named_parameters()],
columns=['name', '# params']
)
num_params = params_summary['# params'].sum()
params_summary['# params'] = list(map('{:,}'.format,
params_summa... |
# Python3 program to print all conflicting
# appointments in a given set of appointments
# Structure to represent an interval
class Node:
def __init__(self):
self.i = None
self.max = None
self.left = None
self.right = None
def newNode(j):
temp = Node()
temp.i = j
temp.m... |
# Created by giuseppe
# Date: 26/11/19
import pybullet as p
import os
import pybullet_envs, pybullet_data
from pybullet_envs.bullet import kuka
import math
import numpy as np
class KukaNoTray(kuka.Kuka):
"""
This class loads the kuka arm for the pybullet simulation, without loading the tray on the table.
"""
... |
import tensorflow as tf
class subbranch:
def __init__(self, sign):
self.sign = sign
def __call__(self, inputs):
return self.sub_block(inputs)
def sub_block(self, x):
x = tf.keras.layers.Conv2D(
filters=1024,
kernel_size=3,
padding="SAME",
... |
import paho.mqtt.client as mqtt
from random import randrange, uniform
import time
import json
from datetime import datetime, timedelta
# Example market requests
# Should be managed as a queue by a brokerage thread
#
# MARKET_REQUESTS = {
# "8c36e86c-13b9-4102-a44f-646015dfd981": {
# 'type': 'INFO',
# ... |
import requests
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/manojadhikary.com.np",
auth=("api", "0ebf8ec5bd32560e3a02f3918b555926-602cc1bf-446bd4a0"),
data={"from": "Excited User <mailgun@manojadhikary.com.np>",
"to": ["adkmanoz38@gmail.c... |
# Copyright 2015 Google Inc. 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 ... |
import base64
import itertools
from math import ceil, log
def base32(hash_b16):
'''Returns lowercased RFC base32 encoding of a base16 hash'''
return base64.b32encode(bytes.fromhex(hash_b16)).decode().lower().rstrip('=') # Remove padding
def decode_base32(hash_base32):
'''Returns base16 encoding of case... |
# This file is part of GridCal.
#
# GridCal 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.
#
# GridCal is distributed in the hope that... |
"""
Stain normalization inspired by method of:
A. Vahadane et al., ‘Structure-Preserving Color Normalization and Sparse Stain Separation for Histological Images’, IEEE Transactions on Medical Imaging, vol. 35, no. 8, pp. 1962–1971, Aug. 2016.
Uses the spams package:
http://spams-devel.gforge.inria.fr/index.html
Use... |
from datetime import datetime
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
class UserProfile(AbstractUser):
nick_name = models.CharField(max_length=50,verbose_name="昵称",default='')
birthday = models.DateField(verbose_name="生日",null=True,blank=Tru... |
from pydantic import BaseModel
def a():
pass
a().<caret> |
import unittest
from selenium import webdriver
from tests.helper_methods import flatten, create_selenium_config
from test_data import enterprise, legal_unit, local_unit, company_house, value_added_tax, pay_as_you_earn, reporting_unit
from tests.constants import LEGAL_UNIT, LOCAL_UNIT, REPORTING_UNIT, COMPANY_HOUSE, VA... |
from io import BytesIO
from json import dumps
from time import sleep
from types import FunctionType
from urllib import request
from http.server import (
HTTPServer,
BaseHTTPRequestHandler,
)
from __init__ import (
Matchers,
Parser,
)
INDEX_HTML_PATH = 'theater/index.html'
def stringify_matcher(match... |
import numpy as np
import pytest
from nlp_profiler.constants import NaN, NOT_APPLICABLE
from nlp_profiler.high_level_features.ease_of_reading_check \
import ease_of_reading_score, ease_of_reading, ease_of_reading_summarised # noqa
# textstat.flesch_reading_ease() returned a score of -175.9
very_confusing_text1 =... |
# Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved.
# Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
import subprocess
class Shell:
"""A class to work with Shell commands."""
class RunError(BaseException):
"""Error/Exception when running... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
# For license information, please see license.txt
from __future__ import unicode_literals
import webnotes
import webnotes.utils
import os, datetime
from website.doctype.website_sitemap.website_sitemap import add_to... |
"""
Functions that help the run 'pps' command
"""
import functools
import subprocess
import inquirer
import toml
from .message import (
FILE_NOT_FOUND_MSG,
INQUIRER_MSG,
KEYBOARD_INTERRUPT_MSG,
KEYWORD_NOT_FOUND_MSG,
)
def exception(function):
"""
A decorator that wraps the passed in functio... |
"""
Copyright (c) 2020 Aiven Ltd
See LICENSE for details
File backup plugin.
This is mostly implemented as sanity check, to ensure that the
building blocks mostly work as they should.
Configuration:
- root_globs
( which is also stored in the backup manifest, and used when restoring )
"""
from .base import (
B... |
from config import conf
import os
from subprocess import Popen
from subprocess import PIPE
def wrapper_change_path(func):
cwd = os.getcwd()
def inner(*args, **kwargs):
return func(*args, **kwargs)
os.chdir(cwd)
return inner
class GitLog:
commands = {
'meta': 'meta_cmd',
'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" script for generate process template directories
This is xxx
"""
import sys
if __name__ == '__main__':
ls = raw_input().upper().split()
l = int(ls[0])
m = int(ls[1])
n = int(ls[2])
for i in xrange(l):
sys.stdout.write('A')
for i in ... |
from OpenGLCffi.EGL import params
@params(api='egl', prms=['dpy', 'attrib_list'])
def eglCreateDRMImageMESA(dpy, attrib_list):
pass
@params(api='egl', prms=['dpy', 'image', 'name', 'handle', 'stride'])
def eglExportDRMImageMESA(dpy, image, name, handle, stride):
pass
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-07 11:29
from __future__ import unicode_literals
import democracy.enums
from django.conf import settings
from django.db import migrations, models
import enumfields.fields
class Migration(migrations.Migration):
dependencies = [
('democracy', '0... |
import pytest
from scripts.AQP_byPath.cache_paths import convert_neo_result_to_dicts
def test_simplest():
#This isn't really a neo4j result, but it has the same interface.
result={'aid':'chebi:1','te0':'fakee0'}
_,outdicts= convert_neo_result_to_dicts(result)
assert len(outdicts) == 1
od = outdict... |
# 9/10
with open('whereami.in', 'r') as ifile:
s = ifile.readlines()[1].strip()
n = len(s)
x = 1
for i in range(1, n+1):
curr = s[i-x:i]
if curr in s[:i-1]:
x += 1
with open('whereami.out', 'w') as ofile:
ofile.write(str(x))
|
pjs_setting = {"hyperopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE":'"line"', "min_n_circle":1000, "max_n_circle":4000},
"gaopt" :{"AGENT_TYPE":'"ga"', "CIRCLE_TYPE":'"normal_sw"', "min_n_circle":500, "max_n_circle":3000},
"bayesopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE... |
import pandas as pd
def get_clean(source_file):
"""Generate a clean data frame from source file"""
print('Reading from source...')
df = pd.read_csv(source_file)
print('Cleaning up source csv...')
# Drop rows with too much NA data
df.drop(['Meter Id', 'Marked Time', 'VIN'], axis=1, inplace=True)... |
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
import torch
from torchtext.datasets import AG_NEWS
train_iter = AG_NEWS(split='train')
tokenizer = get_tokenizer('basic_english')
def yield_tokens(data_iter):
for _, text in data_iter:
yield tokenizer(tex... |
from __future__ import absolute_import, division, print_function, unicode_literals
# TODO: needs to be finished and integrated into the code.
import parsedatetime
from echomesh.element import Element
from echomesh.element import Load
CALENDAR = parsedatetime.Calendar()
BAD_DOCUMENTATION = """
type: schedule
entry... |
import gzip
import shutil
def gunzip_shutil(source_filepath, dest_filepath, block_size=65536):
with gzip.open(source_filepath, 'rb') as s_file, \
open(dest_filepath, 'wb') as d_file:
shutil.copyfileobj(s_file, d_file, block_size)
|
import vaping
import vaping.plugins
from builtins import str
from prometheus_client import start_http_server, Summary, Counter, Gauge
min_latency = Summary('minimum_latency_milliseconds', 'Minimum latency in milliseconds.', ['host']) # NOQA
max_latency = Summary('maximum_latency_milliseconds', 'Maximum latency in mill... |
def print_paper(_paper):
for i in range(max([*zip(*_paper)][0]) + 1):
for j in range(max([*zip(*_paper)][1]) + 1):
print( '█' if (i, j) in _paper else ' ', end="" )
print()
def fold_paper(paper, folds):
for step, fold in enumerate(folds):
fold_idx = int(fold.split('=')[-1])
... |
# encoding: utf-8
"""Integration-test suite for numeric-arrays."""
import numpy as np
import pytest
from cr.cube.cube import Cube
from ..fixtures import NA
class DescribeNumericArrays:
"""Test-suite for numeric-array behaviors."""
def it_provides_means_scale_measures(self):
slice_ = Cube(NA.NUM_A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.