content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import sys
import glob
import json
import scipy.signal as signal
import numpy.ma as ma
import numpy as np
import matplotlib
import matplotlib.pylab as plt
import matplotlib.dates as mdates
import datetime
import statsmodels.api as sm
lowess = sm.nonparametric.lowess
def savitzky_golay(y, window_size, order,... | python |
#!/usr/bin/env python
#
# Copyright 2019 YugaByte, Inc. and Contributors
#
# Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# https://github.com/YugaByte/yugabyte-db/blob/master/licenses... | python |
from __future__ import print_function
import json
import logging
import sys
import os
this_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append("{0}/../lib".format(this_dir))
sys.path.append("{0}/../src".format(this_dir))
from jsonschema import validate
from generator.generator import convert_to_imacro
l... | python |
import argparse
import traceback
import warnings
import torch
import wandb
from gym_carla.envs.carla_env import CarlaEnv
from gym_carla.envs.carla_pid_env import CarlaPidEnv
from termcolor import colored
from torch.utils.data import DataLoader
from bc.train_bc import get_collate_fn
from models.carlaAffordancesDataset... | python |
from odio_urdf import *
def assign_inertia(im):
return Inertia(ixx=im[0], ixy=im[1], ixz=im[2], iyy=im[3], iyz=im[4], izz=im[5])
my_robot = Robot("walker_a")
contact = Contact(Lateral_Friction("100"))
s = 1
inertia_matrix_body = [0.6363636364, 4.908571429, 4.51012987, 4.51012987, 0.6363636364, 4.908571429]
inert... | python |
import argparse
import constants
from data_support.tfrecord_wrapper import TFRecordWriter
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("data_dir", type=str, default='../resources/tf_data',
help="Directory where tfrecord files are stored")
parser.add_argumen... | python |
import copy
import json
import time
from io import open
from .exceptions import (
WebpackBundleLookupError,
WebpackError,
WebpackLoaderBadStatsError,
WebpackLoaderTimeoutError,
)
class WebpackLoader(object):
_assets = {}
def __init__(self, name, config):
self.name = name
self... | python |
import os
import shutil
from ptest.assertion import assert_true
from ptest.decorator import TestClass, BeforeMethod, Test, AfterMethod
from watchdog.events import FileCreatedEvent
from shirp.event import EventConf
from shirp.handler import HDFSHandler
HDFS_GROUP = "grp-hdfs"
@TestClass(run_mode="singleline")
class... | python |
"""Project-level configuration and state."""
import os.path
class Project(object):
"""A Project tracks the overall build configuration, filesystem paths,
registered plugins/keys, etc. and provides services that relate to that."""
def __init__(self, root, build_dir):
"""Creates a Project.
... | python |
# -*- coding: utf-8 -*-
import json
from bs4 import BeautifulSoup
from django.contrib.auth import get_user_model
from django.test import TestCase
class BaseTestCase(TestCase):
fixtures = [
'users.json',
]
USER_PWD = 'password'
# Superuser - admin/adminpassword
# User - neo/password
... | python |
from django.contrib import sitemaps
from django.urls import reverse
from booru.models import Post
class PostSitemap(sitemaps.Sitemap):
priority = 0.8
changefreq = 'daily'
def items(self):
return Post.objects.approved()
def location(self, item):
return item.get_absolute_url()
def ... | python |
from .utils import check_token
from .models import Entry
from .checks_models import EntryCheck
open_entry_checks = EntryCheck()
open_entry = Entry()
| python |
import requests
import pytest
from helpers import (create_user,
get_random_email,
login_user,
refresh_token, get_user)
from requests import HTTPError
HOST = 'localhost:5000'
def test_register():
email = get_random_email()
new_user = create_user(em... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. currentmodule:: test_Point
.. moduleauthor:: Pat Daburu <pat@daburu.net>
This is a unit test module.
"""
import unittest
from djio.geometry import GeometryException
class TestGeometryExceptionSuite(unittest.TestCase):
def test_initWithoutInner_verify(self):... | python |
#!/usr/bin/env python
import os
import uuid
import time
import zlib
import random
import numpy as np
from string import ascii_lowercase
list_chars = list(c.encode('utf8') for c in ascii_lowercase)
# Number of objects
#num_files_list = [1]
num_files_list = [1, 100, 1000, 10000, 100000, 1000000]
# Hash functions
#comp... | python |
_base_ = ['./rotated_retinanet_obb_r50_fpn_1x_dota_le90.py']
fp16 = dict(loss_scale='dynamic')
| python |
from tksheet import Sheet
import tkinter as tk
class Sheet_Listbox(Sheet):
def __init__(self,
parent,
values = []):
Sheet.__init__(self,
parent = parent,
show_horizontal_grid = False,
show_verti... | python |
# 1.
# C = float(input('输入摄氏温度'))
# F = (9/5)*C + 32
# print('%.2F 华氏度' %F)
# 2.
# import math
# r = float(input('输入圆柱半径:'))
# l = float(input('输入圆柱高:'))
# area = r*r*math.pi
# volume = area*l
# print('面积:%.2f' %area)
# print('体积:%.2f' %volume)
# 3.
# feet = float(input('请输入英尺数:'))
# meters = feet... | python |
# You are provided with a code that raises many exceptions. Fix it, so it works correctly.
# numbers_list = input().split(", ")
# result = 0
#
# for i in range(numbers_list):
# number = numbers_list[i + 1]
# if number < 5:
# result *= number
# elif number > 5 and number > 10:
# result /= ... | python |
#! /usr/bin/env python3
"""This is a prototype work manager which reads work requests from a file and
submits them as messages to a RabbitMQ queue.
This is development only. For a real system, you would get work from a
database or other entity.
"""
import os
import sys
import json
import logging
from argpa... | python |
# coding: utf-8
import numpy as np
from numpy import matrix as mat
import cv2
import os
import math
def undistort(img, # image data
fx, fy, cx, cy, # camera intrinsics
k1, k2, # radial distortion parameters
p1=None, p2=None, # ta... | python |
from http import HTTPStatus
import json
from src.common.encoder import PynamoDbEncoder
class HTTPResponse(object):
@classmethod
def to_json_response(cls, http_status, message=None):
"""
Access-Control-Allow-Origin is needed for CORS to work
Access-Control-Allow-Credentials is needed f... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-11-26 09:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('libretto', '0044_auto_20190917_1200'),
]
operations = [
migrations.AlterFi... | python |
from setuptools import setup, find_packages
classifiers = ['Development Status :: 4 - Beta',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
... | python |
"""============================================================================
The input is a file containing lines of the following form:
equation_name arg1 ...
For example:
energy 5.4 3.7 99
something 7 280.01
energy 88.94 73 21.2
whizbang 83.34 14.34 356.43 139593.7801
something .001 25
You ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import init_printing,Integral,latex,pretty,pprint,sqrt,symbols,srepr
init_printing(use_unicode=True)
x,y,z = symbols('x y z')
print(Integral(sqrt(1/x),x))
print(srepr(Integral(sqrt(1/x), x)))
pprint(Integral(sqrt(1/x), x), use_unicode=False)
print(pretty(Integ... | python |
from django.contrib import admin
from django.contrib.admin import register
from bbbs.main.models import Main
from bbbs.users.utils import AdminOnlyPermissionsMixin
from .forms import MainAdminForm
@register(Main)
class MainAdmin(AdminOnlyPermissionsMixin, admin.ModelAdmin):
empty_value_display = "-пу... | python |
""" uTorrent migration to qBittorrent module """
from tkinter import Tk, StringVar, N, W, E, S, filedialog, messagebox, HORIZONTAL
from tkinter.ttk import Frame, Entry, Button, Label, Progressbar
from shutil import copy
from os import path
from hashlib import sha1
from time import time
from re import compile as ... | python |
#!/usr/bin/env python3
import argparse
import logging
import logging.config
import os
import sys
import time
import yaml
from cluster_manager import setup_exporter_thread, \
manager_iteration_histogram, \
register_stack_trace_dump, \
update_file_modification_time
sys.path.append(
os.p... | python |
import itertools
from numbers import Number
from graphgallery.utils.type_check import is_iterable
def repeat(src, length):
if src is None:
return [None for _ in range(length)]
if src == [] or src == ():
return []
if isinstance(src, (Number, str)):
return list(itertools.repeat(src, l... | python |
from __future__ import absolute_import
from __future__ import unicode_literals
import inspect
import logging
LOG = logging.getLogger(__name__)
def is_generator(func):
"""Return True if `func` is a generator function."""
return inspect.isgeneratorfunction(func)
| python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (C) 2012 by Xose Pérez
#
# 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, ei... | python |
def countPattern(genome, pattern):
"""
Find the number of specific pattern in a genome sequence
"""
count = 0
for index in range(0, len(genome)-len(pattern)+1):
if genome[index:index+len(pattern)] == pattern:
count += 1
return count
def findPattern(genome, pattern):
"... | python |
import logging
import asyncio
from ..Errors import *
from ..utils import Url
logger = logging.getLogger(__name__)
class Commander:
"""
Manages looping through the group wall and checking for commands or messages
Attributes
-----------
prefix: :class:`str`
The command prefix
"""
... | python |
"""Class implementation for the scale_x_from_center interface.
"""
from typing import Dict
from apysc._animation.animation_scale_x_from_center_interface import \
AnimationScaleXFromCenterInterface
from apysc._type.attr_linking_interface import AttrLinkingInterface
from apysc._type.number import Number
fr... | python |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.shell.lint.shfmt.rules import ShfmtFieldSet, ShfmtRequest
from pants.backend.shell.lint.s... | python |
#!/usr/bin/env python
__author__ = "Yaroslav Litvinov"
__copyright__ = "Copyright 2016, Rackspace Inc."
__email__ = "yaroslav.litvinov@rackspace.com"
from os import system
import psycopg2
import argparse
import configparser
from pymongo import DESCENDING
from collections import namedtuple
from datetime import datetim... | python |
# -*- coding: utf-8 -*-
from django.urls import path,re_path
from . import views
app_name = 'ajunivel'
urlpatterns = [
path('', views.index, name='index'),
path('index.html', views.index, name='index'),
path('index', views.index, name='index'),
path('menu', views.menu, name='menu'),
] | python |
import os
import socket
from pathlib import Path
class Config(object):
"""
Basic configuration, like socket default timeout, headers
"""
def __init__(self):
super(Config, self).__init__()
self.socket_timeout = 20
# set socket layer timeout as 20s
socket.setdefaulttimeout(self.socket_timeout)
# self.hea... | python |
from dataclasses import dataclass
@dataclass
class ModelException:
pass
| python |
import numpy as np
from torchmeta.utils.data import Task, MetaDataset
class Relu(MetaDataset):
"""
Parameters
----------
num_samples_per_task : int
Number of examples per task.
num_tasks : int (default: 2)
Overall number of tasks to sample.
noise_std : float, optional
... | python |
# flake8: noqa
CLOUDWATCH_EMF_SCHEMA = {
"properties": {
"_aws": {
"$id": "#/properties/_aws",
"properties": {
"CloudWatchMetrics": {
"$id": "#/properties/_aws/properties/CloudWatchMetrics",
"items": {
"$... | python |
import torch
from torchvision import transforms, datasets
import numpy as np
from PIL import Image
from skimage.color import rgb2lab, rgb2gray, lab2rgb
def count_params(model):
'''
returns the number of trainable parameters in some model
'''
return sum(p.numel() for p in model.parameters() if p.requir... | python |
from datetime import date
ano = int (input ('Digite o ano de nascimento: '))
idade = date.today().year - ano
if idade <= 9:
print ('Sua idade {}, Até 9 anos: Mirim'.format(idade))
elif idade > 9 and idade <= 14:
print ('Sua idade {}, Até 14 anos: Infantil'.format(idade))
elif idade > 14 and idade <= 19:
pri... | python |
# -*- coding: utf-8 -*-
"""
"""
from flask import flash, redirect, url_for, render_template, request
from sayhello import app, db
from sayhello.forms import HelloForm
from sayhello.models import Message
@app.route('/', methods=['GET', 'POST'])
def index():
"""
# TODO 分页BUG未解决
"""
form = HelloForm()
... | python |
from aws_google_auth import exit_if_unsupported_python
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import unittest
import sys
import mock
class TestPythonFailOnVersion(unittest.TestCase):
@mock.patch('sys.stdout', new_callable=StringIO)
def test_python26(self, moc... | python |
import json
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.http import JsonResponse
from django.shortcuts import render, redirect
import re
import loggi... | python |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: variable
Author: ken
CreateDate: 5/21/2018 AD
Description:
-------------------------------------------------
"""
__author__ = 'ken' | python |
import chess
from .external_chess_player import ExternalChessPlayer
MAX_RETRIES = 3
class ChessPlayer(object):
def __init__(self, external_player):
"""
:param external_player:
:type external_player: ExternalChessPlayer
"""
self.ext_player = external_player
def end_ga... | python |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from meanfield import MeanField
def d_tanh(x):
"""Derivative of tanh."""
return 1. / np.cosh(x)**2
def simple_plot(x, y):
plt.plot(x, y)
plt.xlim(0.5, 3)
plt.ylim(0, 0.25)
plt.xlabel('$\sigma_\omega^2$', fontsize=1... | python |
from tests.conftest import JiraTestCase
class PrioritiesTests(JiraTestCase):
def test_priorities(self):
priorities = self.jira.priorities()
self.assertEqual(len(priorities), 5)
def test_priority(self):
priority = self.jira.priority("2")
self.assertEqual(priority.id, "2")
... | python |
"""
Please implement a `test` (e.g. pytest - this is up to you) for the method `compute_phenotype_similarity()`
- The details are up to you - use whatever testing framework you prefer.
"""
| python |
# Aula 10 - Desafio 31: Custo da viagem
# Pedir a distancia de uma viagem em seguida:
# se a viagem for até 200Km de distancia, o valor da passagem será de R$0,50 por Km rodado
# se for maior que 200 Km, o valor sera de R$0,45 por Km rodado
d = int(input('Informe a distancia em Km da sua viagem: '))
if d <= 200:
... | python |
import os,shutil
from .ExtensibleFileObject import ExtensibleFileObject
def file_list_dedup(file_list):
new_list=list(set(file_list))
new_list.sort(key=file_list.index)
return new_list
def relpath(a,b):
pass
def check_vfile(func):
pass
def refresh_directory(path):
if os.path.exists... | python |
import nuke
t=nuke.menu("Nodes")
u=t.addMenu("Pixelfudger", icon="PxF_Menu.png")
t.addCommand( "Pixelfudger/PxF_Bandpass", "nuke.createNode('PxF_Bandpass')", icon="PxF_Bandpass.png" )
t.addCommand( "Pixelfudger/PxF_ChromaBlur", "nuke.createNode('PxF_ChromaBlur')", icon="PxF_ChromaBlur.png")
t.addCommand( "Pixelfud... | python |
BOT_NAME = 'naver_movie'
SPIDER_MODULES = ['naver_movie.spiders']
NEWSPIDER_MODULE = 'naver_movie.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2
COOKIES_ENABLED = True
DEFAULT_REQUEST_HEADERS = {
"Referer": "https://movie.naver.com/"
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.U... | python |
import asyncio
import uvloop
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from scrapper import scrap
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
if __name__ == "__main__":
scheduler = AsyncIOScheduler()
scheduler.add_job(scrap, 'interval', seconds=5)
scheduler.start()
... | python |
from ..classes import WorkflowAction
class TestWorkflowAction(WorkflowAction):
label = 'test workflow state action'
def execute(self, context):
context['workflow_instance']._workflow_state_action_executed = True
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC biomass Project.
Unit D1 Bioeconomy.
"""
# Built-in modules #
import os
# Third party modules #
# First party modules #
from autopaths import Path
from autopaths.auto_paths import AutoPaths
from autopaths... | python |
import numpy as np
import interconnect
import copy
# # VARIABLES
N = 3001 # max clock cycles +1
FW = 16 # flit width
FPP = 32 # flits per packet
def get_header(FW=16):
'''
generates a random header for a flit-width of FW)
'''
return np.random.random_integers(0, (1 << FW)-1)
# data, day = np.loa... | python |
from py_db import db
import NSBL_helpers as helper
# Re-computes the team hitting tables
db = db('NSBL')
def process():
print "processed_team_hitting"
db.query("TRUNCATE TABLE `processed_team_hitting_basic`")
db.query("TRUNCATE TABLE `processed_team_hitting_advanced`")
yr_min, yr_max = db.query("... | python |
"""
The MIT License (MIT)
Copyright (c) 2020-Current Skelmis
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, mer... | python |
# -*- coding: utf-8 -*-
try:
import mdp
use_mdp = True
except ImportError:
print 'mdp (modular data processing) module not installed. Cannot do PCA'
use_mdp = False
import numpy as np
from neuropype import node
from itertools import imap, repeat
from copy import deepcopy, copy
from neuropype import par... | python |
import json
import codecs
import tldextract
urls = dict()
duplicates = list()
with codecs.open('/home/rkapoor/Documents/ISI/data/Network/intersecting-urls.jsonl', 'r', 'utf-8') as f:
for line in f:
doc = json.loads(line)
url = doc['url']
if url in urls:
urls[url] += 1
el... | python |
import subprocess
from uuid import uuid1
import yaml
from jinja2 import Environment, PackageLoader
from sanetrain.workflow_builder import generate_training
def test_generate_training():
env = Environment(loader=PackageLoader('sanetrain', 'templates'))
template = env.get_template('test_template.py')
wit... | python |
#!/usr/bin/python
import time
fact_arr = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
class memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args[0]]
except KeyError:
... | python |
#! /usr/bin/env python
def condense(w):
return w[0] + str(len(w)-2) + w[-1:]
def expand(w):
length = int(w[1:-1]) + 2
for word in get_words(length):
if word.startswith(w[0]) and word.endswith(w[-1:]):
print word
def get_words(length, filename = '/usr/share/dict/words'):
return (wor... | python |
#
#
# Use: genKey(5)
# => "xmckl"
#
#
import math, random
def genKey(n):
alphabet = list("abcdefghijklmnopqrstuvwxyz")
out = ""
for i in range(n):
out += alphabet[math.floor(random.randint(0, 25))]
return out
| python |
linha1 = input().split(" ")
linha2 = input().split(" ")
cod1, qtde1, valor1 = linha1
cod2, qtde2, valor2 = linha2
total = (int(qtde1) * float(valor1)) + (int(qtde2) * float(valor2))
print("VALOR A PAGAR: R$ %0.2f" %total) | python |
# https://github.com/dannysteenman/aws-toolbox
#
# License: MIT
#
# This script will set a CloudWatch Logs Retention Policy to x number of days for all log groups in the region that you exported in your cli.
import argparse
import boto3
cloudwatch = boto3.client("logs")
def get_cloudwatch_log_groups():
kwargs... | python |
from backend.util.crypto_hash import crypto_hash
HEX_TO_BINARY_CONVERSION_TABLE ={
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
... | python |
import numpy as np
from numpy.linalg import inv, cholesky
from scipy.stats import norm, rankdata
from synthpop.method import NormMethod, smooth
class NormRankMethod(NormMethod):
# Adapted from norm by carrying out regression on Z scores from ranks
# predicting new Z scores and then transforming back
def ... | python |
from caty.core.spectypes import UNDEFINED
from caty.core.facility import Facility, AccessManager
class MongoHandlerBase(Facility):
am = AccessManager() | python |
nome=input('digite seu nome completo =')
nomeup=nome.upper()
nomelo=nome.lower()
nomese=nome.strip()
dividido=nome.split()
print('em maiusculas = {}'.format(nomeup.strip()))
print('em minusculas = {}'.format(nomelo.strip()))
print('o seu nome tem {} letras'.format(len(nomese)-nomese.count(' ')))
print('o seu primeiro n... | python |
from flask import render_template, request
from sqlalchemy import desc
from app.proto import bp
from app.models import Share
@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
def index():
user_id = request.args.get('user_id')
shares = Share.query.filter_by(user_id=user_id).o... | python |
import ProblemFileHandler as handler
import OJTemplate
# 生成一个题目文件
# 第一种方法:problem_text_file + test_cases_file
text_file1 = '../resources/OJ/demo_problem1_text.txt'
test_cases_file1 = '../resources/OJ/demo_problem1_test_cases.txt'
output_file1 = '../resources/OJ/Problems/Problem1.plm'
handler.generate_problem(p... | python |
import random
import os
import time
import server
import discord
import ctypes
import server
from discord.ext import commands
from cogs.musiccog import Music
from cogs.funcog import Fun
find_opus = ctypes.util.find_library('opus')
discord.opus.load_opus(find_opus)
TOKEN = os.getenv("DISCORD_TOKEN")
# Silence useless... | python |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch.nn as nn
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.layers.non_local import init_nl_module
from .generalized_rcnn import GeneralizedRCNN
import torch
from maskrcnn_benchmark.layers i... | python |
# Copyright 2017 ForgeFlow S.L.
# Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountPaymentMode(models.Model):
_inherit = "ac... | python |
''' FUNCTIONS
Functions are pieces(block) of code that does something.
''' | python |
from classifiers.base_stance_classifier import BaseStanceClassifier
from classifiers.random_stance_classifier import RandomStanceClassifier
from classifiers.greedy_stance_classifier import MSTStanceClassifier
from classifiers.maxcut_stance_classifier import MaxcutStanceClassifier
| python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
import threading
import time
from opentelemetry.context import attach, detach, set_value
from opentelemetry.sdk.metrics import Meter
from opentelemetry.sdk.metrics.export import MetricsExportResult
from azure_monitor.sdk.a... | python |
from art import logo
import os
clear = lambda: os. system('cls')
def new_bidder():
global greater_bid
bidder = input("What's your name?: ")
bid = int(input("What's your bid?: "))
new_bidder_dict = {"Bidder": bidder, "Bid": bid}
if bid > greater_bid["Bid"]:
greater_bid = new_bidder_dict
... | python |
from geocoder import main
from geocoder import STARTTIME, NUM_DOCS
import re
import os
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from datetime import datetime #for testing time of script execution
RE_URLS = 'http[s]?:\/\/(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+'
RE_AT_M... | python |
#Making List l
l = [11, 12, 13, 14]
#Using append function on list
l.append(50)
l.append(60)
print("list after adding 50 & 60:- ", l)
#Using remove function on list
l.remove(11)
l.remove(13)
print("list after removing 11 & 13:- ", l)
#Using the sort function with their parameters changed
#Implementing sorting in a... | python |
budget_wanted = float(input())
total = 0
money_full = False
command = input()
while command != "Party!":
drink_name = command
number_of_drinks = int(input())
price = int(len(drink_name))
drinks_price = price * number_of_drinks
if drinks_price % 2 == 1:
drinks_price -= drinks_price * 25 / ... | python |
#!/usr/bin/env python
# coding:utf-8
#DESCRICAO
#Esse script foi desenvolvido para facilitar a forma como cadastramos,
#alteramos ou excluímos os principais ativos em dois ou mais servidores zabbix.
#A ideia é utilizar esse script para ambientes onde os eventos não estão sincronizados,
#permitindo uma ótima facilida... | python |
# ToggleButton examples.
import os
from ocempgui.widgets import *
from ocempgui.widgets.Constants import *
def _create_vframe (text):
frame = VFrame (Label (text))
frame.spacing = 5
frame.align = ALIGN_LEFT
return frame
def create_button_view ():
states = ("STATE_NORMAL", "STATE_ENTERED", "STATE_A... | python |
from sys import stdin
def print_karte(karte):
for i in range(len(karte)):
liste = [str(x) for x in karte[i]]
print(''.join(liste))
zeilen = []
max_x = 0
max_y = 0
for line in stdin:
eingabe = line.strip()
eingabe = eingabe.split(" ")
eins = [int(x) for x in eingabe[0].split(",")]
zw... | python |
from django.apps import apps
from .models import State, Workflow
def create_builtin_workflows(sender, **kwargs):
"""
Receiver function to create a simple and a complex workflow. It is
connected to the signal django.db.models.signals.post_migrate during
app loading.
"""
if Workflow.objects.exi... | python |
import os
from codecs import open
from setuptools import setup
import suit_rq
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
set... | python |
import os
import wget
## Verify if directory exists. Create if it doesnt exist.
def check_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
## Download source Files from urls
def download_files(urls, out_path='downloads/', silent=False):
for url ... | python |
"""Morse code handling"""
from configparser import ConfigParser
import os
from pathlib import Path
import sys
import warnings
import numpy as np
import sklearn.cluster
import sklearn.exceptions
from .io import read_wave
from .processing import smoothed_power, squared_signal
class MorseCode:
"""Morse code
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn.preprocessing import StandardScaler
X = [[0, 15],
[1, -10]]
# scale data according to computed scaling values
print(StandardScaler().fit(X).transform(X))
| python |
#!/usr/bin/env python3
#Author: Stefan Toman
if __name__ == '__main__':
print("Hello, World!")
| python |
from l_00_inventory import inventory
import json
with open("m02_files/l_00_inventory.json", "w") as json_out:
json_out.write(json.dumps(inventory))
with open("m02_files/l_00_inventory.json", "r") as json_in:
json_inventory = json_in.read()
print("l_00_inventory.json file:", json_inventory)
print("\njson pre... | python |
import datetime
import time as samay
try:
from pac import voice_io
except ModuleNotFoundError:
import voice_io
def date():
x = datetime.datetime.now().strftime("%d/%m/%Y")
voice_io.show(f"Today's date is {x} (DD/MM/YYYY)")
def time():
#x=datetime.datetime.now().strftime("%H:%M:%S")
loca... | python |
from settings import settings
from office365.graph.graph_client import GraphClient
def get_token_for_user(auth_ctx):
"""
Acquire token via user credentials
:type auth_ctx: adal.AuthenticationContext
"""
token = auth_ctx.acquire_token_with_username_password(
'https://graph.microsoft.com',... | python |
import os
import pytest
import responses
from ewhs.client import EwhsClient
@pytest.fixture(scope="function")
def client():
client = EwhsClient("test", "testpassword", "9fc05c82-0552-4ca5-b588-c64d77f117a9", "ewhs")
return client
@pytest.fixture(scope="session")
def authenticated_client():
client = Ewhs... | python |
# -*- coding: utf-8 -*-
"""
chanjo.cli
~~~~~~~~~~~
Command line interface (console entry points). Based on Click_.
.. _Click: http://click.pocoo.org/
"""
from __future__ import absolute_import, unicode_literals
from pkg_resources import iter_entry_points
import click
from . import __version__
from ._compat import t... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.