content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
import json
import yaml
import time
import flask
import distro
import psutil
import random
import string
import threading
import jinja2.exceptions
from flask import request
from turbo_flask import Turbo
from datetime import datetime
try:
from mcipc.query import Client
except: # server offline
pass
... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'scanwindow.ui'
#
# Created: Sun Jun 5 22:23:54 2016
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Att... | python |
import argparse
import datetime
import json
import logging
import os
import subprocess
import tempfile
import arcpy
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)
def get_args():
parser = argparse.ArgumentParser()
parser.add_argu... | python |
import requests
from src.models import Company
from bs4 import BeautifulSoup as bs
import time
import asyncio
class Scrap:
def __init__(self):
self.headers={
"Host":"www.nepalstock.com",
"User-Agent":"Mozilla/5.0 (X11; Linux aarch64; rv:78.0) Gecko/20100101 Firefox/78.0",
... | python |
from common_fixtures import * # NOQA
import jinja2
import os
if_upgrade_testing = pytest.mark.skipif(
os.environ.get("UPGRADE_TESTING") != "true",
reason='UPGRADE_TESTING is not true')
pre_upgrade_namespace = ""
post_upgrade_namespace = ""
pre_port_ext = ""
post_port_ext = ""
@pytest.fixture(scope='session... | python |
from backdoors.backdoor import *
class Perl(Backdoor):
prompt = Fore.RED + "(perl) " + Fore.BLUE + ">> " + Fore.RESET
def __init__(self, core):
cmd.Cmd.__init__(self)
self.intro = GOOD + "Using Perl module"
self.core = core
self.options = {
"port" : Optio... | python |
pow2 = []
for x in range(1, 10):
pow2.append(2 ** x)
print(pow2)
new_pow2 = [2 ** x for x in range(1,10)] # Comprehensions
print(new_pow2)
new_pow3 = [2 ** x for x in range(1,10) if x % 2 == 0] # Comprehensions with IF
print(new_pow3)
power = lambda x: 2 ** x
conditional_values = [1,2,3,4,5]
new_pow4 = [power(... | python |
#!/usr/bin/env python3
"""
A module which implements the MergeSort algorithm.
"""
import sys
def parseInput(input):
"""
Converts an input string of integers into an array of integers.
"""
return [int(num) for num in input.split(',')]
def mergeSort(a):
"""
Sorts and array of numbers into asc... | python |
"""
У каждой статьи указаны авторы (их несколько) и темы (их тоже
несколько). Определите самую частую пару автор-тема. Если несколько
пар встретились одинаковое число раз, то выведите обе (каждую на
новой строчке).
Формат ввода
На каждой строчке сначала указаны фамилии авторов через пробел, потом
запятая, потом темы (... | python |
# Listing_20-1.py
# Copyright Warren & Csrter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Minimum code for a PyQt program
import sys
from PyQt4 import QtCore, QtGui, uic # Import the Qt libraries we need
form_cla... | python |
#!/usr/bin/env python
import rospy
# from sensor_msgs.msg import Temperature
from django_interface.msg import SilviaStatus
from django_interface.srv import SilviaStatusRequest, SilviaStatusRequestResponse
class StatusServer:
"""
Store machine status through subscription to status topic
Respond to service r... | python |
# Importing the Kratos Library
import KratosMultiphysics as KM
# CoSimulation imports
import KratosMultiphysics.CoSimulationApplication.factories.solver_wrapper_factory as solver_wrapper_factory
def Create(settings, models, solver_name):
input_file_name = settings["input_file"].GetString()
settings.RemoveValu... | python |
from flask import render_template, redirect
from flask_login import login_required
from . import home
from .. import db
@home.route('/')
@home.route('/index')
def homepage():
"""
Handles requests to `/` and `/index` routes
It's the landing page, index page, homepage or whatever you like to call it
"""... | python |
'''
Blind Curated 75 - Problem 40
=============================
Reverse Bits
------------
Reverse the bits of a given 32-bit unsigned integer.
[→ LeetCode][1]
[1]: https://leetcode.com/problems/reverse-bits/
'''
def solution(n):
'''
Working inwards from both ends, use bitwise logic to swap each pair of bits.
'... | python |
from collections import namedtuple
from collections import defaultdict
import spacy
import warnings
import numpy as np
connection = namedtuple('connection', 'node weight')
Index = namedtuple('Index', 'pid, sid, wid')
nlp = spacy.load('en')
# nlp = spacy.load('en_core_web_lg')
# nlp = spacy.load('en_vectors_web_lg', ... | python |
import praw
import pdb
import re
import os
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
#GET request url
coin_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
reddit = praw.Reddit('BTC9KBABY') #selects reddit... | python |
"""
3D IoU Calculation and Rotated NMS
Written by Shaoshuai Shi
All Rights Reserved 2019-2020.
"""
import torch
import numpy as np
from opencood.utils.common_utils import check_numpy_to_torch
from opencood.pcdet_utils.iou3d_nms import iou3d_nms_cuda
def boxes_bev_iou_cpu(boxes_a, boxes_b):
"""
Args:
... | python |
#! /usr/bin/env python
import rospy
from time import time, sleep
from datetime import datetime
from ar_track_alvar_msgs.msg import AlvarMarkers
from controlmulti import *
from callback_alvar import *
if __name__ == '__main__':
# try:
rospy.init_node('control_node', anonymous= False)
rate = rospy... | python |
from enum import auto
import graphene
from serflag import SerFlag
from handlers.graphql.types.access import create_access_type
class VMActions(SerFlag):
attach_vdi = auto()
attach_network = auto()
rename = auto()
change_domain_type = auto()
VNC = auto()
launch_playbook = auto()
changing... | python |
import numpy as np
from typing import Tuple, Union
from .values_generator import ValuesGenerator
class UniformGenerator(ValuesGenerator):
def __init__(
self,
bounds: Tuple[Union[int, float], Union[int, float]],
resolution: int = 1_000,
seed: int = None,
):
super(UniformGenerator, self).__init__(bounds... | python |
from mimesis import Person
from tests.base import BaseTestCase
from tests.utils import add_user, add_group, add_user_group_association
class TestGroupModel(BaseTestCase):
"""
Test Group model
"""
# Generate fake data with mimesis
data_generator = Person('en')
def test_model_group_add_group(s... | python |
'''
Usage:
python remove_from_env.py $PATH $TO_BE_REMOVED
returns $PATH without paths starting with $TO_BE_REMOVED
'''
import sys
ENV = sys.argv[1]
REMOVE = sys.argv[2]
new_path = []
for path in ENV.split(':'):
if path.startswith(REMOVE):
continue
new_path.append(path)
print ':'.join(n... | python |
"""
{This script calculates spread in velocity dispersion (sigma) from mocks for
red and blue galaxies as well as smf for red and blue galaxies. It then
calculates a full correlation matrix using sigma and smf of both galaxy
populations as well as a correlation matrix of just sigma
measurements of both galaxy po... | python |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | python |
A, B, X = map(int, input().split())
print("YES" if 0 <= X-A <= B else "NO") | python |
from content.models import PopularQuestion
from ..loader import dp
from aiogram import types
from ..utils.filters import starts_with
from ..keyboards.inline import generic
from ..utils.helpers import get_message_one_button
@dp.callback_query_handler(starts_with('FAQ_element'))
async def send_faq_carousel(callback_que... | python |
# Import required library
import os # To access environment variables
from dotenv import load_dotenv # To load environment variables from .env file
import serial # To connect via the serial port
import time # To sleep for a few seconds
# The thing ID and acc... | python |
from py2neo import Graph,Node,Relationship,Subgraph
graph = Graph('http://localhost:7474',username='neo4j',password='123456')
tx = graph.begin()
# ### 增加
# # 可以一个一个创建
# a = Node('Person',name='bubu')
# graph.create(a)
# b = Node('Person',name='kaka')
# graph.create(b)
# r = Relationship(a,'KNOWS',b)
# graph.create(r... | python |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
import SocketServer
from tools.tools import is_unsigned_integer
import re
import simplejson
import cgi
# urls:
# - https://docs.python.org/3/glossary.html#term-global-interpreter-lock
# - http://stac... | python |
def formatString(input):
input = re.sub("\s+", " ", input)
if " " == input[0]:
input = input[1:]
if " " == input[-1]:
input = input[:-1]
return input
| python |
# Copyright 2015 The Oppia 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 applicable ... | python |
import scrapy.http.response
class CacheResponse(scrapy.http.response.Response):
is_cache = False
def mark_cache(self):
self.is_cache = True
return self
def judge_cache(self):
if not hasattr(self, 'is_cache'):
return False
return self.is_cache
| python |
from django.core.management.base import BaseCommand, CommandError
from coinhub import pullData as myModel
# Run via cron job similar to the form shown below
# * * * * * python manage.py data_grabber --url https://api.coinmarketcap.com/v1/ticker/
class Command(BaseCommand):
help = 'Collects data from an exchange'
... | python |
import settings
import shutil
def make_cbz():
shutil.make_archive('comic','zip',root_dir=settings.IMAGES_PATH)
shutil.move('comic.zip','comic.cbz')
if __name__ == "__main__":
make_cbz() | python |
from __future__ import absolute_import
import string
from struct import unpack
from vertica_python.vertica.messages.message import BackendMessage
class ParameterStatus(BackendMessage):
def __init__(self, data):
null_byte = string.find(data, '\x00')
unpacked = unpack('{0}sx{1}sx'.format(null_by... | python |
import torch as to
from torch.distributions.uniform import Uniform
from pyrado.policies.base import Policy
from pyrado.policies.base_recurrent import RecurrentPolicy
from pyrado.utils.data_types import EnvSpec
class IdlePolicy(Policy):
""" The most simple policy which simply does nothing """
name: str = 'id... | python |
#!/usr/bin/env python
# Title : XGB_BostonHousing.py
# Description : After using LinearRegression and GradientBoostingRegressor, we
# can further improve the predicitions with state-of-the-art
# algorithms, like XGBReegressor. It can use regularization and
# bet... | python |
import pytest
from pandas import Timedelta
@pytest.mark.parametrize('td, expected_repr', [
(Timedelta(10, unit='d'), "Timedelta('10 days 00:00:00')"),
(Timedelta(10, unit='s'), "Timedelta('0 days 00:00:10')"),
(Timedelta(10, unit='ms'), "Timedelta('0 days 00:00:00.010000')"),
(Timedelta(-10, unit='ms... | python |
from flask import Blueprint, jsonify, request
from threading import Thread, Lock, Event
from copy import deepcopy
from node import Node
import pickle
import config
import random
import time
node = Node()
rest_api = Blueprint('rest_api', __name__)
# ------------------------------------------
# ------------- Node endpo... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-06-24 10:45
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("timeline_logger", "0001_initial"),
]
operations = [
migrations.AlterModelOptions(
... | python |
#!/usr/bin/python3
import fitz, shutil
from fitz.utils import getColor
from os import listdir
from os.path import isdir, isfile, join
import PySimpleGUI as sg
print = sg.EasyPrint
help_lisc_input = "Ce logiciel est soumis à la licence GPL v2, (c) Jodobear 2019.\n\nMentionner uniquement le dossier compr... | python |
from torch.optim.lr_scheduler import LambdaLR
class Scheduler(object):
"""Simple container for warmup and normal scheduler."""
def __init__(self, normal_schededuler, warmup_scheduler=None):
self.warmup = warmup_scheduler
self.sched = normal_schededuler
def get_last_lr(self):
""" R... | python |
"""
Pyncette ships with an optional Prometheus instrumentation based on the official prometheus_client
Python package. It includes the following metrics:
- Tick duration [Histogram]
- Tick volume [Counter]
- Tick failures [Counter]
- Number of currently executing ticks [Gauge]
- Task duration [Histogram]
- Task volum... | python |
from alc import dyn
# example of metadata to be added in VSD WAN Service:
# "rd=3:3,vprnAS=65000,vprnRD=65000:1,vprnRT=target:65000:1,vprnLo=1.1.1.1"
# example of tools cli to test this script: tools perform service vsd evaluate-script domain-name "l3dom1" type vrf-vxlan action setup policy "py-vrf-vxlan" vni 12... | python |
from abaqusConstants import *
from .GeometricRestriction import GeometricRestriction
from ..Region.Region import Region
class SlideRegionControl(GeometricRestriction):
"""The SlideRegionControl object defines a slide region control geometric restriction.
The SlideRegionControl object is derived from the Geome... | python |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@File : test_RPSprepare.py
Description :
@Author : pchaos
tradedate: 18-5-16
-------------------------------------------------
Change Activity:
18-5-16:
@Contact : p19992003#gmail.com
--... | python |
from amigocloud import AmigoCloud
# Use amigocloud version 1.0.5 or higher to login with tokens
# This will raise an AmigoCloudError if the token is invalid or has expired
ac = AmigoCloud(token='<token>')
query = ({
"author": "",
"extra": "",
"layer_name": "0",
"name": "My first basela... | python |
#!/usr/bin/env python3
from bank.user import User
from bank.account import Account
carter = User("Carter", 123, 1)
account = Account(123, 1000, "checking")
print("{} has account number {} with a pin number {}".format(carter.name, carter.account, carter.pin_number))
print("{} account with account number {} has balanc... | python |
from setuptools import setup, find_packages
setup(
name='s3filesmanager',
version='0.5.3',
description='AWS S3 files manager',
#long_description=open('docs/index.rst').read(),
author='Jeffrey Hu',
author_email='zhiwehu@gmail.com',
url='https://github.com/zhiwehu/s3filesmanager',
instal... | python |
import sys
sys.path.insert(0, "/work/ml_pipeline/regression_models/")
import regression_models
import numpy as np
from sklearn.model_selection import train_test_split
import pipeline
from processing.data_management import load_dataset, save_pipeline
from config import config
from regression_models import __version__ as... | python |
# Generated by Django 2.1.7 on 2019-03-06 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0005_auto_20190220_1112'),
]
operations = [
migrations.AlterField(
model_name='activeproject',
name='proj... | python |
import numpy as np
from .vice import VICE
from .sac_classifier import SACClassifier
from softlearning.misc.utils import mixup
class VICEGoalConditioned(VICE):
def _timestep_before_hook(self, *args, **kwargs):
# TODO(hartikainen): implement goal setting, something like
# goal = self.pool.get_goal.... | python |
# (C) Copyright 2015 Hewlett Packard Enterprise Development LP
# 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/LICEN... | python |
from pybithumb.core import *
from pandas import DataFrame
import pandas as pd
import datetime
import math
class Bithumb:
@staticmethod
def _convert_unit(unit):
try:
unit = math.floor(unit * 10000) / 10000
return unit
except:
return 0
... | python |
from django import forms
from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
from django.forms import TypedChoiceField
from django.forms.models import inlineformset_factory
from django.utils.translation import ugettext_lazy as _
from keyform.models import Request, KeyData, Contact, KeyType
cl... | python |
#!/usr/bin/python
# module_check: supported
# Avi Version: 17.1.1
# Copyright 2021 VMware, Inc. All rights reserved. VMware Confidential
# SPDX-License-Identifier: Apache License 2.0
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'commun... | python |
from .api import NasapiError, Nasapi #noqa | python |
import sys
from people_flow import YOLO
from people_flow import detect_video
if __name__ == '__main__':
video_path = 'test1.MP4'
output_path='human_counter-master'
detect_video(YOLO(), video_path, output_path)
print('sun')
| python |
from .routes import Tesseract_OCR_BLUEPRINT
from .routes import Tesseract_OCR_BLUEPRINT_WF
#from .documentstructure import DOCUMENTSTRUCTURE_BLUEPRINT | python |
# Copyright 2009-2013 Eucalyptus Systems, Inc.
#
# 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; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# b... | python |
import json5
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from home.models import SiparisKayitlari, Masa
from kullanici.models import Profil
from menu.models import Menu
import datetime
@login_required(login_url="/l... | python |
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Product,Denomination, Order, OrderItem
from end_users import serializers
# Create your views here.
""" All Product related APIs here"""
class ProductApiView(APIView):
seriali... | python |
"""
Contains some helper functions and classes.
"""
import os
import shutil
import typing as t
class attrdict(dict):
"""
Sub-class like python dict with support for I/O like attr.
>>> profile = attrdict({
'languages': ['python', 'cpp', 'javascript', 'c'],
'nickname': 'doge gui',
... | python |
"""
In this module are stored the main Neural Networks Architectures.
"""
from .base_architectures import (BaseDecoder, BaseDiscriminator, BaseEncoder,
BaseMetric)
__all__ = ["BaseDecoder", "BaseEncoder", "BaseMetric", "BaseDiscriminator"]
| python |
"""kernels tests."""
| python |
nome = str(input('Digite seu nome completo: ')).strip()
n = nome.split()
print(f"Seu primeiro nome é: {n[0]}")
print(f"Seu último nome é {n[len(n)-1]}")
| python |
#!/usr/bin/env python3
from matplotlib import pyplot as plt
from nltk.tokenize import word_tokenize
from classify import load_data
from features import FeatureExtractor
import pandas as pd
import numpy as np
def visualize_class_balance(data_path, classes):
class_counts = {c: 0 for c in classes}
for c in clas... | python |
from lib.userInterface import userInterface
if __name__ == '__main__':
ui = userInterface()
if ui.yesNoQuery("Input from file? [y/n]"):
path = input("Please input path of your file: ")
ui.fileInput(path)
else:
ui.userInput()
ui.quantize().predict()
print ("The predicted pr... | python |
from django.core.urlresolvers import reverse
from nose.tools import eq_
from mozillians.common.tests import TestCase
from mozillians.groups.tests import GroupFactory
from mozillians.users.tests import UserFactory
class OldGroupRedirectionMiddlewareTests(TestCase):
def setUp(self):
self.user = UserFactor... | python |
import os
hosturl = os.environ.get('HOSTURL')
from lightserv import create_app
from lightserv.config import DevConfig,ProdConfig
import socket
flask_mode = os.environ['FLASK_MODE']
if flask_mode == 'PROD':
app = create_app(ProdConfig)
elif flask_mode == 'DEV':
app = create_app(DevConfig)
if __name__ == '__main__':
... | python |
from dataclasses import dataclass
from expungeservice.models.charge import ChargeType
from expungeservice.models.charge import ChargeUtil
from expungeservice.models.expungement_result import TypeEligibility, EligibilityStatus
@dataclass(frozen=True)
class SevereCharge(ChargeType):
type_name: str = "Severe Charge... | python |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... | python |
# coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | python |
"""
Rewrite spec/functional_specs/email_accounts_spec.rb
Creates account and checks, if the emails informing about the
new service subscription, new application sign-up to service and application
subscription to an app plan have been sent.
"""
import os
import re
import pytest
import yaml
import backoff
from testsuit... | python |
a, b, x, y = (int(input()) for _ in range(4))
p, q = (x - 1) * a + x, (x + 1) * a + x
e, r = (y - 1) * b + y, (y + 1) * b + y
print(-1 if q < e or r < p else str(max(p, e)) + ' ' + str(min(q, r)))
| python |
#!/usr/bin/python
"""
This is the most simple example to showcase Containernet.
"""
from containernet.net import Containernet
from containernet.node import DockerSta
from containernet.cli import CLI
from containernet.term import makeTerm
from mininet.log import info, setLogLevel
from mn_wifi.link import wmediumd
from m... | python |
from ErnosCube.mutation_node import MutationNode
from ErnosCube.cube_mutation import CubeMutation
from pytest import mark
class TestMutationNode:
"""Collection of all tests run on instances of the MutationNode."""
@mark.dependency(name="construction_1")
def test_construction_1(self):
MutationNode... | python |
import numpy
from SLIX import toolbox, io, visualization
import matplotlib
from matplotlib import pyplot as plt
import pytest
import shutil
import os
matplotlib.use('agg')
class TestVisualization:
def test_visualize_unit_vectors(self):
example = io.imread('tests/files/demo.nii')
peaks = toolbox.s... | python |
# Copyright 2012 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.
from __future__ import absolute_import
import argparse
import logging
import shutil
import sys
import tempfile
import six
from telemetry import benchmark
fr... | python |
"""Kata url: https://www.codewars.com/kata/61123a6f2446320021db987d."""
from typing import Optional
def prev_mult_of_three(n: int) -> Optional[int]:
while n % 3:
n //= 10
return n or None
| python |
import numpy as np, json
import pickle, sys, argparse
from keras.models import Model
from keras import backend as K
from keras import initializers
from keras.optimizers import RMSprop
from keras.utils import to_categorical
from keras.callbacks import EarlyStopping, Callback, ModelCheckpoint
from keras.layers import *
f... | python |
import mne
import mne_bids
import numpy as np
from config import fname, n_jobs
report = mne.open_report(fname.report)
# Load raw data (tSSS already applied)
raw = mne_bids.read_raw_bids(fname.raw, fname.bids_root)
raw.load_data()
report.add_figs_to_section(raw.plot_psd(), 'PSD of unfiltered raw', 'Raw', replace=True... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import itertools
import time
import datetime
import threading
import traceback
import shutil
import re
import math
import wx
import pygame
from pygame.locals import MOUSEBUTTONDOWN, MOUSEBUTTONUP, KEYDOWN, KEYUP, USEREVENT
import cw
... | python |
from lib.config.config import cfg, pth
import torch
import torchvision
from torchvision import transforms, datasets
import os
import sys
sys.path.append('..')
sys.path.append('../..')
dataset_save_pth = pth.DATA_DIR
# 画像ファイルを読み込むための準備(channels x H x W)
transform = transforms.Compose([
transforms.ToTensor()
])
... | python |
from decimal import Decimal
while True:
a = input('Number: ').replace('0.', '')
b = Decimal('0')
for i, c in zip(a, range(-1, -1 - len(a), -1)):
b += Decimal(str(i)) * Decimal('2') ** Decimal(str(c))
print(b) | python |
class Color:
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
LIGHT_GRAY = (200, 200, 200)
GRAY = (127, 127, 127)
DARK_GRAY = (50, 50, 50)
RED = (0,0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
YELLOW = (0, 255, 255)
CYAN = (255, 255, 0)
MAGENTA = (255, 0, 255)
| python |
#%%
import os
import pickle
import time
from pathlib import Path
import colorcet as cc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.feature_selection import VarianceThreshold
from sklearn.model_selection import train_tes... | python |
class Final(type):
def _new_(meta,name,bases,attrs):
if issubclass():
raise TypeError
return super()._new_(meta,name,bases,attrs)
class Sealed(metaclass=Final):pass
class ShouldFail(Sealed):pass
| python |
"""COUNTER 5 test suite"""
| python |
# -*- coding: utf-8 -*-
#
# tborg/tborg.py
#
"""
The TunderBorg API
by Carl J. Nobile
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS ... | python |
# Generated by Django 3.2.3 on 2021-05-24 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.BigAutoField... | python |
#-------------------------------------------------------------------------------
# Author: Lukasz Janyst <lukasz@jany.st>
# Date: 26.11.2017
#
# Licensed under the 3-Clause BSD License, see the LICENSE file for details.
#-------------------------------------------------------------------------------
import logging
i... | python |
from setuptools import setup, find_packages
setup(
name='sixfab-tool',
version='0.0.3',
author='Ensar Karabudak',
author_email='ensarkarabudak@gmail.com',
description='Sixfab Diagnostic Tool',
license='MIT',
url='https://github.com/sixfab/setup-and-diagnostic-tool.git',
dependency_links... | python |
import json
import numpy
import torch
#intrinsics_dict = None
def load_intrinsics_repository(filename, stream='Depth'):
#global intrinsics_dict
with open(filename, 'r') as json_file:
intrinsics_repository = json.load(json_file)
if (stream == 'Depth'):
intrinsics_dict = dict((i... | python |
from adjudicator.base import Season, Phase
from adjudicator.decisions import Outcomes
from adjudicator.paradoxes import find_circular_movements
def process(state):
"""
Processes all orders in a turn.
"""
orders = state.orders
pieces = state.pieces
for order in orders:
order.check_legal... | python |
import petl
import simpleeval
from ..step import Step
from ..field import Field
class field_add(Step):
code = "field-add"
def __init__(
self,
descriptor=None,
*,
name=None,
value=None,
position=None,
incremental=False,
**options,
):
... | python |
import math
import random
from simulator.constants import BYTES_PER_PACKET
from simulator.trace import Trace
class Link():
def __init__(self, trace: Trace):
self.trace = trace
self.queue_delay = 0.0
self.queue_delay_update_time = 0.0
self.queue_size = self.trace.get_queue_size()
... | python |
import numpy as np
import torch
def covariance(m, rowvar=False):
'''Estimate a covariance matrix given data.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element `C_{ij}` is the covar... | python |
import tweepy
import networkx as nx
class Utils():
"""
Utility functions for rundown.
"""
def __init__(self):
"""Constructor. Nothing to see here."""
self.rundown = self.init_rundown()
def init_rundown(self):
"""
Authenticates API, etc.
Parameters
-... | python |
'''Crie as classes necessárias para um sistema de gerenciamento de uma biblioteca. Os
bibliotecários deverão preencher o sistema com o título do livro, os autores, o ano, a editora, a
edição e o volume. A biblioteca também terá um sistema de pesquisa (outro software), portanto
será necessário conseguir acessar os atrib... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.