content
stringlengths
0
894k
type
stringclasses
2 values
import torch from torch import nn class RunningStats(nn.Module): def __init__(self, shape, eps = 1e-5): super().__init__() shape = shape if isinstance(shape, tuple) else (shape,) self.shape = shape self.eps = eps self.n = 0 self.register_buffer('old_mean', torch.ze...
python
# zapp.py - Reactive data viz app template for Coda.to __version__ = '0.1' __all__ = ['layout', 'callback'] #import collections #import json import os #import pickle #from datetime import datetime #from pathlib import Path #import requests as req import pandas as pd import dash_core_components as dcc import dash_html...
python
"""Module that contains exceptions handled in config parsing and loading.""" import traceback from typing import Any class ParseError(Exception): """Parsing exception caused by a syntax error in INI file.""" def __init__(self, message: str, line: int = None) -> None: super().__init__() self....
python
""" Unit tests for testing inheritance mixins """ import unittest from unittest.mock import Mock import ddt from django.utils.timezone import now, timedelta from xblock.core import XBlock from xblock.fields import ScopeIds from xblock.test.tools import TestRuntime from xmodule.modulestore.inheritance import Inherit...
python
'''The user module.''' import views import models
python
import re import os import time import json import math import asyncio import traceback from io import BytesIO from pySmartDL import SmartDL from datetime import datetime from pyrogram import filters, errors from pyrogram.types import Message from tronx import app from tronx.helpers import ( gen, ) app.CMD_HE...
python
from setuptools import setup setup(name="cryx4ck", version="1.0", description="This package is a multi text cryptograpy package.", author="Rakib Hossain", author_email="teamx4ck@gmail.com", license="License", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers',...
python
#!/usr/bin/env python # # Tests for bind configuration parsing from leapp.libraries.common import isccfg # # Sample configuration stubs # named_conf_default = isccfg.MockConfig(""" // // named.conf // // Provided by Red Hat bind package to configure the ISC BIND named(8) DNS // server as a caching only nameserver (as...
python
# Copyright (c) 2021 PaddlePaddle 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 app...
python
# # Py-Alpha-AMD Registration Framework # Author: Johan Ofverstedt # Reference: Fast and Robust Symmetric Image Registration Based on Distances Combining Intensity and Spatial Information # # Copyright 2019 Johan Ofverstedt # # Permission is hereby granted, free of charge, to any person obtaining a copy of this softwa...
python
import aiohttp from logging import getLogger logger = getLogger(__name__) async def asyncGet(*args, **kwargs): async with aiohttp.ClientSession() as client: async with client.get(*args, **kwargs) as response: if response.status == 200: response.body = await response.read() ...
python
from rest_framework import permissions from rest_framework_simplejwt.authentication import JWTAuthentication class IsNotAuthenticated(permissions.BasePermission): message = 'Not accessible if authenticated.' def has_permission(self, request, view): return not request.user or not request.user.is_authe...
python
""" OpenVINO DL Workbench Class for local profiling job Copyright (c) 2020 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 ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='fn_utilities', version='1.0.5', license='MIT', author='IBM Resilient', author_email='support@resilientsystems.com', description="Resilient Circuits Utility Functions", long_description="R...
python
from setuptools import setup setup( name="saffio_core", version="0.2.5", description="core", url="", author="Ivoria Nairov", author_email="", license="MIT", packages=["saffio_core"], install_requires=[ "numpy", "pandas", "nltk", "pythainlp" ], ...
python
# -*- coding: utf-8 -*- from django.test import TestCase import io import wave from 臺灣言語平臺.項目模型 import 平臺項目表 from django.core.exceptions import ObjectDoesNotExist class 項目模型試驗(TestCase): def setUp(self): self.外語內容 = { '外語資料': '水母', } 檔案 = io.BytesIO() with wave.open(檔...
python
''' @Description: @Author: HCQ @Company(School): UCAS @Date: 2020-07-16 00:38:08 @LastEditors: HCQ @LastEditTime: 2020-07-16 13:22:49 ''' # https://blog.csdn.net/t8116189520/article/details/81874309 # post 需要传参 from flask import Flask, g from flask_restful import reqparse, Api, Resource from flask_httpauth import HT...
python
import unittest import os from ibis.model.join import Join from ibis.utilities.config_manager import ConfigManager from ibis.settings import UNIT_TEST_ENV BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class JoinActionFunctionsTest(unittest.TestCase): """Tests the functionality of the Join Action class"""...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-08 19:33 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('portal', '0007_auto_20171007_0031'), ...
python
from sforce.api.client import JsonResource resources_tree = { 'simple': {}, 'custom_path': {'path': 'custom/'}, 'custom_class': {'class': JsonResource}, 'custom_class_module': {'class': 'sforce.api.client.JsonResource'}, 'cascading': {'resources': {'foo':{}}}, }
python
# -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ful...
python
from django.db import models class Todo(models.Model): title = models.CharField(max_length=128, null=False) status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, editable=False) class Meta: app_label = 'todo' ordering = ('-status', '-created',)
python
# Local Imports import re import nltk from nltk import PorterStemmer from crawler.crawler_instance.constants.strings import STRINGS, ERROR_MESSAGES from crawler.crawler_services.constants.constant import spell_check_constants from crawler.crawler_services.helper_services.helper_method import helper_method class spell...
python
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QMessageBox, QFileDialog from PyQt5.QtCore import QSettings, QTextCodec from demo_main_window import * from demo_company_list import * from demo_check_item_list import * class mainWindow(QMainWindow, Ui_MainWindow): def __init__(s...
python
#!/usr/bin/env python from distutils.core import setup import pathlib here = pathlib.Path(__file__).parent.resolve() # Get the long description from the README file long_description = (here / 'README.md').read_text(encoding='utf-8') try: # Python 3.x from distutils.command.build_py import build_py_2to3 as buil...
python
from autonmt.vocabularies.bytes_vocab import BytesVocabulary from autonmt.vocabularies.whitespace_vocab import Vocabulary
python
from x64dbgpy.utils import is_64bit from .. import x64dbg def Size(): return x64dbg.Size() # x86 Registers def GetEAX(): return x64dbg.GetEAX() def SetEAX(value): return x64dbg.SetEAX(value) def GetAX(): return x64dbg.GetAX() def SetAX(value): return x64dbg.SetAX(value) def GetAH(): retu...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-04-03 13:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( m...
python
from peewee import * from Model.BaseModel import BaseModel class Person(BaseModel): id = AutoField() nomeperson = CharField(max_length=80, unique=True) emailperson = CharField() dtanascimentoperson = DateField() telefoneperson = CharField(max_length=14)
python
# Copyright 2017 FiberHome Telecommunication Technologies CO.,LTD # 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/LI...
python
from rest_framework import serializers class TestSimpleBoundField: def test_empty_bound_field(self): class ExampleSerializer(serializers.Serializer): text = serializers.CharField(max_length=100) amount = serializers.IntegerField() serializer = ExampleSerializer() ...
python
# leetcode class Solution: def hammingDistance(self, x: int, y: int) -> int: ans = 0 xor = bin(x^y)[2:] for l in xor: if l == '1': ans += 1 return ans
python
#!/usr/bin/env python import logging logger = logging.getLogger() import argparse import sys import os import string import re if __name__ == "__main__": parser = argparse.ArgumentParser(description="Filters uncertainty symbols ?,* and + from MLST call files.") parser.add_argument("-o", "--output", type=str,...
python
# -*- coding: utf-8 -*- system_proxies = None; disable_proxies = {'http': None, 'https': None}; proxies_protocol = "http"; proxies_protocol = "socks5"; defined_proxies = { 'http': proxies_protocol+'://127.0.0.1:8888', 'https': proxies_protocol+'://127.0.0.1:8888', }; proxies = system_proxies; if __name_...
python
#!/usr/bin/python # sl_control.py # display structured light patterns via OSC # capture images via mjpeg-streamer # requires osc_display_client # requires mjpeg-streamer (patched for valid timestamps) import signal, os import cv2 import sys import urllib import optparse import numpy as np import time from Queue impor...
python
from __future__ import print_function from logging import root from gevent import monkey monkey.patch_all() import gevent from pysoda import ( submit_dataset_progress, bf_add_account_api_key, bf_add_account_username, bf_account_list, bf_dataset_account, bf_account_details, bf_submit_dataset...
python
#!/usr/bin/python3 """Define User """ from models.base_model import BaseModel class User(BaseModel): """User Attr: email: string - empty string password: string - empty string first_name: string - empty string last_name: string - empty string """ em...
python
"""Computing statistics from a polynomial expansions.""" from equadratures.basis import Basis import numpy as np from itertools import * class Statistics(object): """ Compute statistics (mean, variance, skewness, kurtosis and sensitivity indices) of an orthogonal polynomial defined via parameters, a basis and ...
python
import numpy as np def sigmoid(z): """ z: vector / Numpy array --> Ham se ap dung tren toan cac phan tu --> Vectorized form """ return 1.0 / (1.0 + np.exp(-z))
python
# BS mark.1-55 # /* coding: utf-8 */ # BlackSmith plugin # macrokill_plugin.py # Coded by: WitcherGeralt (WitcherGeralt@jabber.ru) # http://witcher-team.ucoz.ru/ def handler_set_botnick(type, source, body): if source[1] in GROUPCHATS: if body: nick = replace_all(body, {' ': '_', '"': '', "'": ''}) if len(...
python
def test_double_index_event(deployed_logs_events, blockchain_client): """ This is a really week test but I'm not sure what to test yet. """ txn_a_hash = deployed_logs_events.logDoubleIndex('test-key-a', 'test-key-b', 'test-val_a', 12345) txn_b_hash = deployed_logs_events.logSingleIndex('test-key-a...
python
from .models import * from .deprecated.wikidump_io import * from .deprecated.table_parser import * from .deprecated.rdd_datasets import * from .misc import *
python
'''Trains a simple convnet on the permuted MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU. ''' from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequen...
python
# regression testing of core logic: # - always (?) compare to basic negamax implementation # - build random game trees and test that both come up with the same outcome # - need to build random game trees # - run standard AIs on these # - test same output # - also some unit tests for specific changes # - build s...
python
# Copyright 2020 Huy Le Nguyen (@usimarit) # # 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 t...
python
from flask import Flask app = Flask(__name__) from app import views """ This script should be in your 'app' folder, where you application package is located. We create the object 'Flask' as app. Then we invoke the views.py file. """
python
from random import choice mMD = ['tsenitelya', 'pisatelya', 'obyvatelya', 'pokoritelya', 'sozidatelya', 'slushatelya', 'vykljuchatelya', 'osvezhitelya', 'pravitelya', 'dejatelya', 'dushitelya', 'obvinitelya', 'razrushitelya', 'potrebitelya', 'blagodetelya', 'rastochitelya', 'tselitelyem', 'grabitelyem', 'tsenitelyem', ...
python
#!/usr/bin/env python #################################################################### ### This is the PYTHON version of program 3.2 from page 64 of # ### "Modeling Infectious Disease in humans and animals" # ### by Keeling & Rohani. # ### # ### It is the SIS model wit...
python
# Copyright 2018 The Tensor2Tensor 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 agr...
python
import json import logging from abc import abstractmethod from datetime import datetime from typing import Any, Dict, Tuple from django.conf import settings from django.utils import timezone from rest_framework import serializers from rest_framework.exceptions import ValidationError from gnosis.eth.django.serializer...
python
import os import json from files import Files from pyramide import Pyramide from write import Write_Files class Edit(): def PyrorLos(self, fichier): self.a = input("Saisissez une hauteur inférieur ou égale à 1000 pour votre {}: ".format("losange" if self.x == 'l' else "pyramide")) if self.a...
python
class MarkdownFormatException(Exception): """Raised if the passed in file is formatted incorrectly """ class ReformatInconsistentException(RuntimeError): """Raised if a reformated Markdown file would be reformatted differently If you get this error, you should open a bug report. """
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json import schnipsllogger logger = schnipsllogger.getLogger(__name__) class JsonStorage: '''loads and saves persistent data as json to disk ''' def __init__(self, filename, default): ''' creates a persistent data link to a config file on disk ...
python
# python3 # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in wr...
python
# ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD """ @package ros_test_generator @file setup.py @author Anthony Remazeilles @brief Standard ROS python package setup file Copyright (C) 2020 Tecnalia Research and Innovation Distributed under the Apache 2.0 license. """ from distutils.core import setup from ...
python
import tensorflow as tf import numpy as np #full_model = tf.keras.models.load_model("./trained_models/model_ToyCar.hdf5") full_model = tf.keras.models.load_model("./trained_models/ad01.h5") #print(full_model(np.random.randn(1, 640))) models = [("full_model", full_model)] import torch import torch.nn as nn from torch....
python
"""Adds config flow for Readme.""" from collections import OrderedDict import voluptuous as vol from homeassistant import config_entries from .const import DOMAIN @config_entries.HANDLERS.register(DOMAIN) class ReadmeFlowHandler(config_entries.ConfigFlow): """Config flow for Readme.""" VERSION = 1 CONN...
python
from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'customers', views.CustomerView) router.register(r'products', views.ProductView) router.register(r'orders', views.OrderView) router.register(r'order_items', views.OrderItemView...
python
from rest_framework import generics, authentication, permissions from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer, AuthTokenSerializer class CreateUserView(generics.CreateAPIView): """Create a new user in the s...
python
import configparser from file_common import dir_utils ini_path = dir_utils.get_app_root_path() + "properties/conf/" print("=============== 配置文件根目录" + ini_path) def get_config_by_name(config_name, cf: configparser.ConfigParser = None): if not cf: cf = configparser.ConfigParser() # 读取配置文件 ...
python
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. """ A convenience script used to drive each individual source generation script. Replace by batch script GenerateNativeFormatSources.bat. """ import sys import os if __...
python
# Lint as: python3 # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
python
# coding: utf-8 import pprint import six from enum import Enum class SubscriptionCreateRequest: swagger_types = { 'component_configurations': 'list[SubscriptionComponentReferenceConfiguration]', 'currency': 'str', 'product': 'int', 'selected_components': 'list[SubscriptionPr...
python
# 005 - Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. userName = input('First name: ') print(f'\n{input("Last name: ")} {userName}')
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from lib.stoneException import StoneException class TestStoneException(unittest.TestCase): """Test case docstring.""" def setUp(self): pass def tearDown(self): pass def test_StoneException(self): with self.assert...
python
from django.contrib import admin from .models import WebHook, GroupSignal, TimerSignal, FleetSignal, HRAppSignal, CharacterSignal, StateSignal, SRPSignal from .app_settings import fleets_active, timers_active, hr_active, srp_active class WebHookAdmin(admin.ModelAdmin): list_display=('name', 'enabled') admin.site...
python
import argparse import sys from typing import List from .main import WebEncoder PROGRAM = "WebEncoder" USAGE = "python -m web_encoder [ e | d ] data [ --no-compress ]" DESCRIPTION = """ ------------------------------------------------------------------------------ Description: This module was created to encode and ...
python
import os import unittest import numpy as np #from scipy.integrate import quadrature as quadrature from scipy.integrate import quad as quadrature from statsmodels.nonparametric import kernels as sm_kernels from hpbandster.optimizers.kde import kernels as hp_kernels import ConfigSpace as CS from pdb import set_t...
python
"""Test DSS functions.""" import matplotlib.pyplot as plt import numpy as np import pytest from numpy.testing import assert_allclose from scipy import signal from meegkit import dss from meegkit.utils import demean, fold, rms, tscov, unfold @pytest.mark.parametrize('n_bad_chans', [0, -1]) def test_dss0(n_bad_chans):...
python
from sklearn.model_selection import cross_val_score #Methods from sklearn import naive_bayes from sklearn.neighbors import KNeighborsClassifier from sklearn import tree from sklearn import svm def classification(X, y): decision_tree_method = tree.DecisionTreeClassifier(random_state=42) svm_method = svm....
python
import argparse import copy import os import torch from copy import deepcopy from torch import nn from torchvision import datasets, transforms import numpy as np from models.LeNet5 import LeNet5 from eval.metrics import get_accuracy from bitarray import bitarray from models.YourNet import TeacherNet, YourNet from matpl...
python
import requests from paymentcorner.auth import Auth class Config(object): _token = None ENV_PROD = 'prod' ENV_SANDBOX = 'sandbox' ENV_URLS = { ENV_PROD: 'http://sandboxapi.paymentcorner.com/', ENV_SANDBOX: 'http://sandboxapi.paymentcorner.com/', } ENDPOINT_URLS = { '...
python
import threading import time import metaparticle_sync def master_fn(): print('I am the master') def lost_master_fn(): print('I lost the master') el = metaparticle_sync.Election('test', master_fn, lost_master_fn) def run(): time.sleep(30) el.shutdown() def main(): t = threading.Thread(None,...
python
# -*- coding: utf-8 -*- import os from contextlib import contextmanager import pytest from beer_garden.local_plugins.env_help import ( expand_string, has_env_var, is_valid_name, var_name, ) @contextmanager def mangle_env(updates): env_orig = os.environ.copy() os.environ.update(updates) ...
python
import argparse from logger import logging def parse(): global args parser = argparse.ArgumentParser() parser.add_argument( "-d", "--debug", help="Print lots of debugging statements", action="store_const", dest="loglevel", const=logging.DEBUG, defau...
python
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import argparse import numpy as np import itertools import torch.utils.data import torch.nn.functional as F from torch.optim.lr_sch...
python
from context import PyEDGAR import unittest class TestCIKTools(unittest.TestCase): """Test the `cik_tools` in the `util` module. """ def test_CIKMatch(self): """Test a unique match of the CIK. This test uses the ticker 'AAPL', with the expected match returning a CIK '0000320193'...
python
# -*- coding: utf-8 -*- from Controller.Utils import DBFRead, pyqt_pdb from Controller.config import ENCODING_SUPPORT from Controller.dbfread.exceptions import MissingMemoFile import csv def Tocsv(self, header=[], data=[]): """ """ delimiter = ',' quotechar = '"' quoting = csv.QUOTE_ALL if heade...
python
from face_recons import test from face_recons import train import argparse parser = argparse.ArgumentParser(description = "Face Application - Command Line Interface") parser.add_argument("--mode", default = False, help="Enable Command Line Interface", action='store') parser.add_argument("--input", type=str, required=...
python
# basic method to load to MiHIN # should make nicer and add to loaders in django management import os import json import questionnaire.utils # used for one-off loads from IDE tools_dir = 'tools' this_dir = '.' def handle(dir_name, files, resource_type): client = questionnaire.utils.getFhirClient(questionnaire.ut...
python
import sys import pickle import random def Count_Alignment(file_path): char_confusion = {} # simulate insertion errors * -> c (use the previous char as key) char_insert_confusion = {} with open(file_path, "rb") as F: X = pickle.load(F) op_cnt = [0] * 3 for x in X: #print(x) so...
python
""" RiscEmu (c) 2021 Anton Lydike SPDX-License-Identifier: MIT This file holds Executable and LoadedExecutable classes as well as loading and some linking code. FIXME: refactor this code into muliple files """ from dataclasses import dataclass, field from typing import Dict, List, Tuple, Union, Optional from .Excep...
python
"""Super-classes of common datasets to extract id information per image.""" import torch import torchvision import random from ..consts import * # import all mean/std constants import torchvision.transforms as transforms from PIL import Image, ImageFilter import os import glob from torchvision.datasets.imagenet im...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-17 10:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('family', '0002_kid_avatar'), ] ...
python
from typing import List, Dict, Tuple, Union, Any from collections import defaultdict import logging from allennlp.semparse import util as semparse_util from allennlp.semparse.domain_languages.domain_language import ExecutionError from allennlp.semparse.contexts.table_question_knowledge_graph import MONTH_NUMBERS from ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wagtail.wagtailcore.fields import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailimages', '0006_add_verbose_names'), ('wagtaildocs', '0003_a...
python
""" :mod:`zsl.utils.redis_helper` ----------------------------- Helper module for working with redis. .. moduleauthor:: Peter Morihladko """ from __future__ import unicode_literals from builtins import object from functools import partial from future.utils import viewitems from zsl import Config, inject def red...
python
from flask import request, jsonify import flask app = flask.Flask(__name__) from confluent_kafka import Producer p = Producer({'bootstrap.servers': 'localhost:9092'}) @app.route('/topic', methods=['POST']) def topic(): d = request.get_json() url = d.get('url') if url is None: return 'failure', 4...
python
import json import os import sagemaker from transformers import pipeline, AutoTokenizer, AutoModelForQuestionAnswering def model_fn(model_dir): session = sagemaker.Session() bucket = os.getenv("MODEL_ASSETS_S3_BUCKET") prefix = os.getenv("MODEL_ASSETS_S3_PREFIX") session.download_data(path=model_dir, ...
python
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
python
def genFib(): f1 = 0 f2 = 1 yield 0 yield 1 while True: next = f1 + f2 yield next f1 = f2 f2 = next fib = genFib() n = int(input('How many fibonacci numbers would you like? - ')) for i in range(n): print(fib.__next__())
python
from typing import Union, Dict, Iterable, Tuple, cast, List, Optional, Generator, Mapping from collections import defaultdict from enum import Enum import warnings import bisect import numpy as np import sympy.ntheory from qupulse._program.waveforms import Waveform, ConstantWaveform from qupulse._program.volatile imp...
python
""" Provides a simple check based on lsof output to see if a path is in use by another process """ from time import time from msort.log import getLogger from msort.check import BaseCheck, CheckSkip from msort.system import call_output class InUseCheck(BaseCheck): """ Check if the file being scanned is in use """ ...
python
#!/usr/bin/env python3 import threading import multiprocessing from abc import ABC, abstractmethod class Daemon(ABC): def __init__(self, event): self.stop_event = event self.daemon = True def stop(self): self.stop_event.set() def stopped(self): return self.stop_event.is_se...
python
from django.utils.translation import ugettext_lazy as _ from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .models import BlogIndexPluginModel, BlogRecentPluginModel, BlogPost @plugin_pool.register_plugin class BlogIndexPluginPublisher(CMSPluginBase): model = BlogIndexPluginM...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import numpy as np from scipy import integrate import argparse import numpy as np import matplotlib as mpl mpl.use('Agg') #silent mode from matplotlib import pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter def thermo_i...
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="simplepythonwer", version="1.0.3", author="Rob Smith", author_email="robmsmt@gmail.com", description="A small basic python implementation of WER (word error rate) and levenshtein", lon...
python
# -*- coding: utf-8 -*- # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
python
import cv2, os, dlib, sys import numpy as np from py_utils.face_utils import lib from concurrent.futures import ProcessPoolExecutor seed = 100 # Employ dlib to extract face area and landmark points pwd = os.path.dirname(os.path.abspath(__file__)) front_face_detector = dlib.get_frontal_face_detector() lmark_predictor =...
python
from ex_109 import moeda p = float(input('Digite o preço: R$')) print(f' A metade de {moeda.moeda(p)} é {moeda.metade(p, True)}') print(f' O dobro de {moeda.moeda(p)} é {moeda.dobro(p, True)}') print(f' Aumentado 10%, temos {moeda.aumentar(p, 10, True)}') print(f' Reduzindo 13%, temos {moeda.diminuir(p, 10, True)} ') ...
python