content stringlengths 5 1.05M |
|---|
import pytest
from zeep import Client
def test_factory_namespace():
client = Client('tests/wsdl_files/soap.wsdl')
factory = client.type_factory('http://example.com/stockquote.xsd')
obj = factory.Address(NameFirst='Michael', NameLast='van Tellingen')
assert obj.NameFirst == 'Michael'
assert obj.Na... |
import os
def get_nmap(options,ip):
command = "nmap " + options + " " + ip
process = os.popen(command)
results = str(process.read())
return results
|
#!/usr/bin/env python
import optparse
import pathlib
from kubepy import appliers
from kubepy import appliers_options
from kubepy import base_commands
class InstallAllCommand(base_commands.BaseCommand):
def handle(self, args, options):
directory_strings = options.directories or ['.']
directories =... |
#coding: utf-8
def loadDataSet():
#return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [1, 2, 3, 4, 5], [1, 3, 4, 5], [1, 2, 3, 5, 6], [1, 2, 3, 5, 7], [1, 2, 3, 5, 8], \
[1, 2, 3, 5, 9], [2, 3, 5, 6], [2, 4, 5], [2, 5]]
def createC1(dataSet):
C1 = [] #C1是大小为1的所有候选项集的集合... |
# Link --> https://www.hackerrank.com/challenges/30-scope/problem
# Code:
def computeDifference(self):
maxDiff = 0
elements = self.__elements
for i in range(len(elements)):
for j in range(i+1 , len(elements)):
current_diff = abs(elements[j] - elements[i])
... |
"""
sample script for categorical encoding
"""
import re
import unidecode
import pandas as pd
import clintk.text2vec.tools
def normalize_cat(X, strat='tokens'):
""" normalize categories in a
Parameters
----------
X : iterable
strat : str, ('tokens', 'strings'), default='tokens"
if 'tok... |
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class ActionBar(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.set_title("ActionBar")
self.set_default_size(200, 200)
self.connect("destroy", Gtk.main_quit)
gri... |
import factory
from children.models import Child, Relationship
from projects.models import Project
from users.factories import GuardianFactory
class ChildFactory(factory.django.DjangoModelFactory):
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")
birthdate = factory.Faker("... |
__author__ = "David Melamend, Reeder Ward, Majbrit Schoettner"
__email__ = "dmelamed@stud.hs-bremen.de, rward@stud.hs-bremen.de, mshoettner@stud.hs-bremen.de"
__title__ = "Implement Toolchain for .OBJ Objects in PyQt5 GUI to Create a 3D Modelling Software"
__course__ = "Computer Graphics"
class vertex:
def __i... |
# This creates a table in a PostGIS enabled PostgreSQL database called usda_districts_ia.
# It requires an existing table with Iowa counties called counties_ia.
# counties_ia must have a column geom_wgs that uses SRID 4326.
districts = {
'Northwest': ('Lyon', 'Osceola', 'Dickinson', 'Emmet',
'Sio... |
# Generic modules
import logging
# Modules
from singupy.verification import dataframe_columns as verify_df_columns
import pandas as pd
# Initialize log
log = logging.getLogger(__name__)
def parse_aclineseg_scada_csvdata_to_dataframe(
file_path: str,
aclinesegment_mrid_col_nm: str = "ACLINESEGMENT_MRID",
... |
from rdkit import Chem
from rdkit import rdBase
from rdkit.Chem import RDConfig
from rdkit.DataStructs import TanimotoSimilarity
from rdkit.Chem import QED, AllChem
from rdkit.Chem import MolFromSmiles as smi2mol
from rdkit.Chem import MolToSmiles as mol2smi
import selfies
_get_fp = lambda x: Chem.RDKFingerprint(x)
d... |
import numpy as np
my_empty = np.empty
import logging
from npstructures import npdataclass
logger = logging.getLogger(__name__)
wrapper = lambda x: x
def repr_bytes(n):
if n < 10 ** 4:
return str(n) + "b"
elif n < 10 ** 7:
return str(n // 1000) + "kb"
elif n < 10 ** 11:
return s... |
from stacker.lookups import Lookup
def generate_definition(base_name, stack_id, **overrides):
definition = {
"name": "%s.%d" % (base_name, stack_id),
"class_path": "stacker.tests.fixtures.mock_blueprints.%s" % (
base_name.upper()),
"namespace": "example-com",
"parameter... |
#!/usr/bin/env python
__author__ = 'meatz'
import csv
import gzip
import sys
import time
import os
import re
import json
import time
import calendar
import datetime
from collections import defaultdict
from collections import Counter
import fnmatch
def to_terabyte(val):
return (float(val) / 1024 / 1024 / 1024 / 1... |
import plotly.offline as py
py.init_notebook_mode()
from pre_process import pre_process
def pollution_change(pollution, source, year, option='Mean'):
df1 = pre_process(pollution, source, year, option)
df2 = pre_process(pollution, source, '2016', option)
df1[source+' '+option] = df1[source+' '+option].astype(fl... |
# 导入类库
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
# 实例化对象
bootstrap = Bootstrap()
mail = Mail()
db = SQLAlchemy()
# 封装函数 完成初始化
def config_extensions(app):
bootstrap.init_app(app=app)
mail.init_app(app=app)
db.init_app(app=app) |
# Sebastian Raschka 2014-2020
# mlxtend Machine Learning Library Extensions
#
# Principal Component Analysis for dimensionality reduction.
# Author: Sebastian Raschka <sebastianraschka.com>
#
# License: BSD 3 clause
import numpy as np
from .._base import _BaseModel
class PrincipalComponentAnalysis(_BaseModel):
"... |
###############################################################################
# Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
# Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
# other details. No copyright assignment is required to contribute to Ascent.
#########... |
import rivalcfg
class TestListSupportedMice(object):
def test_returns_the_supported_mice(self):
assert len(list(rivalcfg.list_supported_mice())) > 0
def test_returns_name_vendorid_productid_of_each_mouse(self):
for mouse in rivalcfg.list_supported_mice():
assert len(mouse) == 3
... |
input_num = input()
for digit in reversed(input_num):
num = int(digit)
for i in range(num):
if num != 0:
symbol = chr(num + 33)
print(symbol, end='')
if num == 0:
print('ZERO')
else:
print() |
# models.py - example2
from django.db import models
class AbstractRecipe(models.Model):
name = models.CharField(max_length=255)
ingredients = models.TextField()
directions = models.TextField()
class Meta:
abstract = True
class Recipe(AbstractRecipe):
pass
class Batch(AbstractRecipe):... |
'Generated protocol buffer code.'
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
from ....tensorflow.core.fra... |
import json
from flag_engine.django_transform.document_builders import (
build_environment_document,
build_identity_document,
)
from flag_engine.utils.json.encoders import DecimalEncoder
def test_build_identity_document(django_identity):
# When
identity_document = build_identity_document(django_ident... |
#!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
@client.command()
async def privacy(ctx):
await ctx.send('We do not require a privacy policy because we store none of your info. If you have any questions, DM the bot owner: Owner#1234.')
|
import os
from flask import Flask
def create_app(template_folder):
# Create app
app = Flask(__name__, template_folder=template_folder)
app.config["DEBUG"] = os.environ.get("DEBUG", False)
app.config["SECURITY_PASSWORD_SALT"] = os.environ.get("PASSWORD_SALT", "default_salt")
app.config["SECRET_KEY... |
# docker run --rm -it --user="$(id -u):$(id -g)" -v "$(pwd)":/manim manimcommunity/manim manim --config_file manim.cfg scene_dfs.py -q k -r 3200,1800
# [CLI]
# frame_width=12
# frame_height=38
from collections import defaultdict, deque
from mdeque import Mdeque
from mval import Mval
from mnode import Mnode, Mhiddenno... |
"""This is an example of a local_settings.py module needed by Emocracy Change as
needed and rename it to local_settings.py """
SECRET_KEY = 'SERVER SPECIFIC DO NOT SHARE!'
DEBUG = True
CONSUMER_KEY = "abc"
CONSUMER_SECRET = "abc"
REALM = 'emo.preeker.net'
EMOCRACY_API_SERVER = "http://emo.preeker.net/"
DATABASE_ENG... |
#!/usr/bin/env python
# see http://bugs.python.org/issue8876
# this is just a quick hack so we can test build in vagrant
import os
if os.environ.get('USER','') == 'vagrant':
del os.link
from setuptools import setup, find_packages
setup(name='lraudit',
version='0.1.1',
description='Adds auditing to LR F... |
import logging
import os
from morghulis.downloader import BaseDownloader
from morghulis.os_utils import ensure_dir
log = logging.getLogger(__name__)
IMAGES_URL = 'http://tamaraberg.com/faceDataset/originalPics.tar.gz'
ANNOTATIONS_URL = 'http://vis-www.cs.umass.edu/fddb/FDDB-folds.tgz'
class FddbDownloader(BaseDown... |
import sys
import keras
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Add, Activation, Concatenate, Input
from keras.models import Model
from keras.applications.mobilenet import MobileNet
from src.keras_utils import save_model
def res_block(x,sz,filter_sz=3,in_conv_size=1):
xi = x
for i in ... |
#
# Copyright Bertil Kronlund, 2017
#
# 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 writin... |
from unittest import TestCase
from tests import TestPrediction
from sklearn.ensemble import RandomForestClassifier
class RandomForestClassifierTest(TestPrediction, TestCase):
predict_method = "predict_proba"
def _fit(self):
self.models = [
RandomForestClassifier(n_estimators=10, random_s... |
import time
class T:
def __init__(self, h, m):
self.tm_hour = h
self.tm_min = m
t = T(10, 36)
def is_earlier(h, m):
# 10 10 40 20
return (t.tm_hour == h and t.tm_min > m) or t.tm_hour > h
def is_later(h, m):
# 23 23 00 01
r... |
import json
import logging
import requests
from elastalert.alerter import Alerter
from elastalert.exceptions import EAException
from elastalert.utils.time import DateTimeEncoder
from elastalert.utils.util import lookup_es_key
from requests import RequestException
log = logging.getLogger(__name__)
class HTTPPostAler... |
from textwrap import dedent
import pytest
from twindb_backup.configuration import TwinDBBackupConfig, ConfigurationError
def test_backup_dirs(config_file):
tbc = TwinDBBackupConfig(config_file=str(config_file))
assert tbc.backup_dirs == [
'/', '/root/', '/etc', '/dir with space/', '/dir foo'
]
... |
import logging
from typing import Any, Dict, List
from pydantic import BaseModel
from givenergy_modbus.model.battery import Battery
from givenergy_modbus.model.inverter import Inverter
from givenergy_modbus.model.register import HoldingRegister, InputRegister
from givenergy_modbus.model.register_cache import Register... |
n = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049... |
def only_with_cdms_skip(func):
def wrapper(self, *args, **kwargs):
if not self.cdms_skip:
raise NotImplementedError(
'{method} not implemented yet'.format(method=func.__name__)
)
return func(self, *args, **kwargs)
return wrapper
|
import discord
from discord import utils
from discord.ext import commands, tasks
from datetime import timedelta
from extra import utils
from extra.analytics import SlothAnalyticsTable, DataBumpsTable
from PIL import Image, ImageFont, ImageDraw
from typing import List
import os
import io
bots_and_commands_channel_id ... |
from django.dispatch import Signal
action = Signal(providing_args=['verb', 'action_object', 'related_action_object',
'target', 'description', 'timestamp'])
|
# -*- coding: utf-8 -*-
total, n = 0, 0
while(True):
age = int(input())
if (age < 0):
break
total += age
n += 1
average = total / n
print("%.2f" % average) |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... |
numeros = []
entrada = input().split()
for i in entrada:
numeros.append(int(i))
for n in sorted(numeros):
print(n)
print()
for it in numeros:
print(it) |
# Authors:
# Trevor Perrin
#
# See the LICENSE file for legal information regarding use of this file.
import os
from tack.crypto.Digest import Digest
from .cryptomath import numberToBytes, bytesToNumber
from .ecdsa import generator_256, Public_key, Private_key, Point
from .Python_ECPublicKey import Python_ECPublicK... |
# -*- coding: utf-8 -*-
"""
helper function: convert Midi pitch (floating point) from frequency
Args:
fInHz: The frequency to be converted, can be scalar or vector
fA4InHz: The reference tuning frequency (default: 440Hz)
Returns:
Midi values of the input dimension (floating point)
"""
import numpy as... |
import FWCore.ParameterSet.Config as cms
from RecoJets.Configuration.CaloTowersRec_cff import *
from RecoJets.JetProducers.CaloJetParameters_cfi import *
from RecoJets.JetProducers.AnomalousCellParameters_cfi import *
CaloTowerConstituentsMapBuilder = cms.ESProducer("CaloTowerConstituentsMapBuilder",
MapFile = c... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import (
StringField,
DateTimeField,
SubmitField,
TextAreaField,
)
from wtforms import HiddenField
from wtforms import validators
from wtforms.validators import DataRequired, Length
from config import Config
... |
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.PostListView.as_view(), name="index"),
path("user/<str:username>", views.UserPostListView.as_view(), name="user-posts"),
path("post/<int:pk>/", views.PostDetailView.as_view(), name="detail"),
path("post/n... |
import os, glob, librosa, scipy
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow.keras.optimizers import Adam
from models.ssrn import SSRN
from models.modules import griffin_lim
from util.hparams import *
checkpoint_dir = './checkpoint/2'
save_dir = './output'
os.makedirs(sav... |
# -*- coding: utf-8 -*-
"""
Created on May 4 - 2019
---Based on the 2-stage stochastic program structure
---Assumption: RHS is random
---decompose the 2slp problem into a master and subproblems
---save the distributoin of the random variables and return the
---random variables
@author: Siavash Tabrizian - stabrizian... |
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from keras import metrics
from sklearn.decomposition import PCA
from sklearn.cluster import AffinityPropagation
from itertools import cycle
from adjustText import adjust_text
from SMILESX import model, utils, token, augm... |
class TrainConfig():
_SEED = 240797
_LEARNING_RATE = 1e-3
_WEIGHT_DECAY = 0#1e-3
_PAD_TOKEN = '[PAD]'
_UNK_TOKEN = '[UNK]'
_CHECKPOINT_FOLDER = 'mm_action_prediction/checkpoints' |
from numpy.testing import assert_almost_equal
import numpy
import torch
from torch.autograd import Variable
from torch.nn import Parameter
from allennlp.common import Params
from allennlp.common.testing.test_case import AllenNlpTestCase
from allennlp.modules.attention import LinearAttention
from allennlp.modules.atten... |
"""
VVVVID Downloader - VVVVID Utility Functions
Author: CoffeeStraw
GitHub: https://github.com/CoffeeStraw/VVVVID-Downloader
"""
import re
import sys
import requests
from copy import deepcopy
from colorama import Fore, Back, Style
def get_requests_obj():
"""Create a dictionary to manage a persistent session with... |
from . import two
|
# Copyright (c) 2019, Riverbank Computing Limited
# All rights reserved.
#
# This copy of SIP is licensed for use under the terms of the SIP License
# Agreement. See the file LICENSE for more details.
#
# This copy of SIP may also used under the terms of the GNU General Public
# License v2 or v3 as published by the Fr... |
from model.group import Group
import random
# def test_modify_group(app):
# if app.group.count() == 0:
# app.group.create(Group(name="test group"))
# old_groups = app.group.get_group_list()
# app.group.modify_first_group(Group(name="group1", header="group1_header", footer="group1_footer"))
# ne... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Factory module to return the default interace to the batch farm
"""
from __future__ import absolute_import, division, print_function
# This sets the default job type.
# We are going to want a better way to control this down the road
DEFAULT_JOB_TYPE ... |
"""
The MIT License (MIT)
Copyright (c) 2015 <Satyajit Sarangi>
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, ... |
import tensorflow as tf
import numpy as np
from keras.engine import data_adapter
from matplotlib import cm
from subclassed_losses_and_metrics import SSIMLoss, ReconstructionLoss, calculate_metrics
def colorize_img(value, vmin=None, vmax=None, cmap='jet'):
"""
A utility function for TensorFlow that maps a gray... |
store.set_global_value('hotkey', '<meta>+1')
engine.set_return_value('<ctrl>+1')
engine.run_script('combo') |
"""updated Meeting.id
Revision ID: 8005dddb1ef3
Revises: a6ddb8e136f8
Create Date: 2021-07-09 17:32:24.239365
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '8005dddb1ef3'
down_revision = 'a6ddb8e136f8'
branch_labels = None
depends_on = None
def upgrade():
... |
#coding=utf-8
"""
收集看到好玩的Python代码
"""
__author__ = "Yihang Yang"
__version__ = "0.1"
|
from typing import Any, Dict, Optional, Sequence
from ..helpers.typing_annotations import LpModelDatatypes
import numpy as np
from .. import shop_runner
from .row import RowBuilder, RowTypeBuilder
from .var import VarBuilder, VarTypeBuilder
from .index import IndexTypeBuilder
class LpModelBuilder(object):
shop:'... |
"""https://adventofcode.com/2020/day/10"""
##
## advent of code Day10
##
# Import libraries
from typing import List
from collections import Counter
class Adapter:
def __init__(self, output: str) -> None:
self.output = output
def parse(self) -> list[int]:
return [
int(out)
... |
import logging
import pika
from queue import Queue
class Rabbit:
def __init__(self):
self.host = "localhost"
self._queues = []
self._connected = False
self._configure_pika_logging()
def make_queue(self):
self.connect()
queue = Queue(self)
self._queues... |
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd
import expense_chart_generator
class ExpenseSheetGenerator:
def __init__(self, df, title, cate... |
project = 'Telephone Bot'
author = 'Telephone Bot team & contributors'
copyright = '2018-2021 the Telephone Bot team & contributors'
exclude_patterns = []
templates_path = ['_templates']
primary_domain = ''
extensions = [
'sphinx.ext.extlinks',
'sphinx_rtd_theme',
'sphinxcontrib.httpdomain',
'sphinx... |
from distutils.core import setup
setup(
name='brpm',
version='0.4.1',
description='A tool for building RPM packages',
long_description='brpm is a simple tool for building RPMs.',
author='Silas Sewell',
author_email='silas@sewell.org',
license='MIT License',
url='https://github.com/silas... |
import os
def call_shell_wrapper(args):
"""
Intended to make it easy to add additional metrics from shell calls,
such as capturing return values, etc.
Currently no additional value.
Subprocess module is recommended but didn't work for some uname calls.
"""
return os.popen(" ".join(args)).re... |
#!/usr/bin/python3
try: # need for development
from irciot import PyLayerIRCIoT
except:
from PyIRCIoT.irciot import PyLayerIRCIoT
def main():
irciot = PyLayerIRCIoT()
datumset_text = '[{"bigval":"long-long-value-xxxxxxxxxxxxxxxxxxxxxxxxxxx'
datumset_text += 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class NewNew(models.Model):
npw = models.CharField(max_length=25)
def __str__(self):
return self.site
class Post(models.Model):
site = models.CharField(max_l... |
# File created by Utkarsh Gupta
# Dated 20/02/2020
# Touched on 20/02/2020 by Utkarsh Gupta
# Execution of boosted tree
import TreeClassifier
class TreeRunner:
def __init__(self):
self.tree = TreeClassifier.treeClassifier()
self.tree.getParameterList(noOfTree=5, maxTreeDepth=7, learningRate=0.1... |
#Escreva um programa que pergunte a distância de uma viagem em KM:
#Calcule o preço da passagem, cobrando 0,50 centavos por KM para viagens até 200km e 0,45 para viagens mais longas.
d = int(input('Qual foi distância percorrida em Km? '))
if d <= 200:
print('A distância percorrida foi {}, e você irá pagar R${:.2f} ... |
import functools
import json
import logging
import os
import warnings
from toolz import groupby
from typing import List
import sdk_cmd
import sdk_diag
from bundle import Bundle
import agent
import config
log = logging.getLogger(__name__)
class ServiceBundle(Bundle):
DOWNLOAD_FILES_WITH_PATTERNS = ["^stdout(\\.... |
"""norm.py
Normalization & Preprocessing Tools
> Tyler Ganter, tganter@sandia.gov
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
def standardize(x, axis=None):
"""Transforms data to have mean 0 and std dev 1.
Args:
x (array-like): the data to standardize
axis :... |
import os
import sys
import imp
import getpass
#------------------------------------------------------------
def mainIsFrozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "im... |
#!/usr/bin/env python
"""
dbd.py - a collection of routines for reading the .dbd file loaded into an ioc,
extracting some of the information into a python object, and using that
information to do a couple of tricks. I've not been very careful about
handling legal variations in the .dbd syntax. Probably the most usef... |
# Copyright 2017 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... |
import datetime
import json
from pathlib import Path
from create_rtf_and_pdf import add_to_bible_readings
from create_rtf_and_pdf import create_rtf_and_pdf
from get_bible_book_metadata import get_bible_book_metadata
from create_library_of_readings import create_library_of_readings
from create_bible_audio_playlist impo... |
import warnings
from typing import List, Optional, Dict, Tuple, TYPE_CHECKING
import pandas as pd
import numpy as np
from sklearn.decomposition import TruncatedSVD, NMF
import matplotlib.pyplot as plt
import seaborn as sns
from data_describe.config._config import get_option
from data_describe.text.text_preprocessing ... |
def temperatura2(grados, escala, convertir):
resultado = 0
if escala == "Farenheit":
if convertir == "Kelvin":
resultado = ((5*(grados-32))/(9)) + 273.15
elif convertir == "Celsius":
resultado = ((9/5)*grados)+32
elif escala == "Kelvin":
if... |
#!/usr/bin/env python
# coding: utf-8
# ```
# Copyright 2019. IBM 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/L... |
"""docstring."""
import asyncio
import aiounittest
from aiotaskmgr import TaskManager, Task
class TaskManagerTests(aiounittest.AsyncTestCase):
"""TaskManagerTests."""
def get_event_loop(self):
self.my_loop = TaskManager().get_event_loop()
return self.my_loop
def change_event_loop(self):... |
from unittest import TestCase
from archiver.instrument_model import illumina
class InstrumentModelTest(TestCase):
def test_illumina_instrument_model(self):
# given:
genome_analyzer = illumina('Illumina Genome Analyzer II')
# expect:
self.assertEqual('illumina genome analyzer ii'... |
import pandas as pd
from pandas.api import types as pdt
from visions.backends.pandas.series_utils import (
series_handle_nulls,
series_not_empty,
series_not_sparse,
)
from visions.types.string import String
pandas_has_string_dtype_flag = hasattr(pdt, "is_string_dtype")
@series_handle_nulls
def _is_strin... |
from unittest import TestCase
from unittest.mock import patch
from pogui.lib.async_ops import AsyncListManifests
@patch('pog.fs.pogfs.localfs', autoSpec=True)
@patch('pog.fs.pogfs.b2fs', autoSpec=True)
@patch('pog.fs.pogfs.s3fs', autoSpec=True)
class AsyncListManifestsTest(TestCase):
def setUp(self):
pas... |
#!/usr/bin/python
from database_tables import DrawingHistory
from webserver_utils import verify_id
import cgi
import cgitb
import datetime
def createNew(title, creator, history, layers):
kwargs = {"date": datetime.datetime.now(),
"title": title,
"history_json": history,
... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Interpreter config dialog(modal)
"""
from pyqode.qt import QtWidgets, QtCore
from interpreterForm import Ui_InterpreterDlg
import utils
from settings import Settings
class InterpreterConfigDialog(QtWidgets.QDialog, Ui_InterpreterDlg):
def __init__(self, parent=None... |
""" Module extracts numerical topics of each document with LDA """
import gensim.corpora as corpora
import numpy as np
import pandas as pd
from gensim.models import LdaMulticore
from preprocessing.corpus import build_corpus
class LDATopic:
""" Class to extract the LDA topics """
def __init__(self, num_topi... |
import wx
from .file_cache import FileCache
textchars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ')
text_view_transtable = bytes([c if chr(c) in textchars else ord('.') for c in range(256)])
class HexViewLayout(object):
''' Encapsulates information ab... |
"""
==============================================
A demo of A2C algorithm in PBall2D environment
==============================================
Illustration of how to set up an A2C algorithm in rlberry.
The environment chosen here is PBALL2D environment.
.. video:: ../../video_plot_a2c.mp4
:width: 600
"""
# sph... |
# coding=utf-8
"""
Python语言基础,公众号:只差一个程序员了
Version: 0.0.1
Author : yichu.cheng
"""
import math
class SingleNumberShape(object):
""" 某一类图形,可以用一个数字计算其面积 """
name = 'I"m a SingleNumberShape.'
def __init__(self, length=0):
"""初始化实例"""
self.length = length
def area(self):
"""返回面积"... |
#!/usr/bin/env python
try:
from setuptools import setup
args = {}
except ImportError:
from distutils.core import setup
print(
"""\
*** WARNING: setuptools is not found. Using distutils...
"""
)
from setuptools import setup
try:
from pypandoc import convert
read_md = lambda f: c... |
# Copyright 2020 EMBL - European Bioinformatics Institute
#
# 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... |
#!/usr/bin/python
def primes_sieve(limit):
limitn = limit+1
not_prime = [False] * limitn
primes = []
for i in range(2, limitn):
if not_prime[i]:
continue
for f in xrange(i*2, limitn, i):
not_prime[f] = True
primes.append(i)
return primes
x = primes_sieve(2000000)
sum = 0
for i in range(len(x)):
su... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import time
import tensorflow as tf
from tensorflow.contrib import layers
from six.moves import range
import numpy as np
import zhusuan as zs
from examp... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
class Attn(nn.Module):
def __init__(self, hidden):
super().__init__()
self.hidden = hidden
self.attn = nn.Linear(self.hidden * 2, hidden)
self.v = nn.Parameter(torch.rand(hidden))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.