content stringlengths 5 1.05M |
|---|
# importing the Python-provided time library to access delays (time.sleep)
import time
# importing the Subinitial library to access the Stacks commands
import subinitial.stacks as stacks
# Connecting to the Stacks Core and Analog Deck
core = stacks.Core(host="192.168.1.49")
analogdeck = stacks.AnalogDeck(core_deck=co... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# This software is released under the MIT License.
#
# Copyright (c) 2014 Cloudwatt
#
# 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... |
# 2. Бонус точки
# Дадено е цяло число – начален брой точки. Върху него се начисляват бонус точки по правилата, описани по-долу.
# Да се напише програма, която пресмята бонус точките, които получава числото и общия брой точки (числото + бонуса).
# • Ако числото е до 100 включително, бонус точките са 5;
# • Ако числото ... |
import paddle
import torchvision
import torch
import paddle.nn as nn
import numpy as np
import os
def trans():
path='./resnet_pytorch.pth'
model=torchvision.models.resnet101(num_classes=1000)
torch_dict=torch.load(path)
model.load_state_dict(torch_dict['net'])
paddle_dict = {}
# paddleModel=padd... |
from gpueater.gpueater import *
|
from .cutmix import *
|
from django.contrib.contenttypes.models import ContentType
from django.http import Http404
from django.shortcuts import get_object_or_404
from cms.contacts.forms import ContactLocalizationForm
from cms.contacts.models import *
from cms.contacts.serializers import *
from rest_framework.permissions import IsAdminUser
f... |
import time
from selenium import webdriver
class InternetSpeedHandler:
def __init__(self, driver: webdriver.Firefox, wait):
self.driver = driver
self.wait_time = wait
def get_speed(self):
url = 'https://www.speedtest.net/'
self.driver.get(url)
time.sleep(5)
go... |
#!/usr/bin/env python
#<examples/lmfit_brute.py>
from __future__ import print_function
import copy
import numpy as np
from lmfit import minimize, Minimizer, Parameters
# EXAMPLE 1 #
# taken from: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.brute.html
# create a set of Parameters
params = Pa... |
from fisher_py.mass_precision_estimator.estimator_results import EstimatorResults
from fisher_py.mass_precision_estimator.precision_estimate import PrecisionEstimate
|
from django.contrib import admin
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from arkestra_utilities.output_libraries.plugin_widths import (
get_placeholder_width, get_plugin_ancestry, calculate_container_width)
from links.admin import ObjectLinkInlineForm
from links.models ... |
from nevow import loaders, tags
from nevow.livetrial import testcase
class SetNodeContent(testcase.TestCase):
jsClass = u'Divmod.Runtime.Tests.SetNodeContent'
class AppendNodeContent(testcase.TestCase):
jsClass = u'Divmod.Runtime.Tests.AppendNodeContent'
class AppendNodeContentScripts(testcase.TestCase)... |
# coding:utf-8
from multiprocessing import Pool
import time
i =100
def Foo():
global i
i = i+1
print i
def Bar(arg):
print arg
if __name__ == '__main__':
t_start=time.time()
pool = Pool(5)
for i in range(10):
pool.apply_async(func=Foo, args=(), callback=Bar)#维持执行的进程总数为processes,... |
import pytest
from tempest.lib.exceptions import CommandFailed
import esileapclient.tests.functional.utils.esi_interfaces as esi
from esileapclient.tests.functional.base import ESIBaseTestClass
from esileapclient.tests.functional.utils.dummy_node import DummyNode
class PolicyTests(ESIBaseTestClass):
@classmethod... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Miscellaneos functions relating the projects app
import os
from datetime import datetime
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from django.conf import settings
def project_required(func):
"""
Decorator function for other actions that
require a project to be ... |
#!/usr/bin/env python
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
from std_msgs.msg import String
from sensor_msgs.msg import JointState
from moveit_commander.conversions import pose_to_list
from trajectory_msgs.msg import (JointTrajec... |
# The optimal flows for AC/DC/Hybrid AC DC power systems
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 12:32:13 2018
@author: Javier Alejandro Acevedo Barroso
Script de Python para la visualización de la simulación en 3D.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import rcParams
rcPar... |
#! /usr/bin/python3
# Simple script to parse specs and produce CSV files.
# Released by Rusty Russell under CC0:
# https://creativecommons.org/publicdomain/zero/1.0/
from optparse import OptionParser
import sys
import re
import fileinput
def main(options, args=None, output=sys.stdout, lines=None):
# Example inpu... |
from collections import OrderedDict
from p4z3.base import z3, log, copy
from p4z3.base import P4Extern, StaticType
from p4z3.state import LocalContext, P4State
from p4z3.callables import P4Control, merge_parameters
def create_state_args(state_ctx, type_ctx, p4_params):
state_args = []
instances = {}
for p... |
import random
class Note:
def __init__(self):
self._notes = ["C", "C#", "Db", "D", "D#", "Eb", "E", "F", "F#", "Gb", "G", "G#", "Ab", "A", "A#", "Bb", "B"]
def get_random_note(self) -> str:
i = random.randint(0, len(self._notes) - 1)
return self._notes[i]
def get_random_notes(sel... |
lyrics_dict = {('Without Me', 'Halsey'): {'found': 1, 'heart': 1, 'broke': 1, 'filled': 1, 'cup': 1, 'overflowed': 1, 'close': 2, 'afraid': 1, 'leave': 1, 'ooh': 1, 'catch': 2, 'fall': 4, 'laugh': 2, 'fuck': 2, 'em': 3, 'knees': 2, 'put': 10, 'back': 2, 'feet': 2, 'advantage': 2, 'hows': 4, 'feel': 4, 'sittin': 3, 'fee... |
import codecs
with codecs.open('data/news.en.heldout-00001-of-00050','r','utf-8') as f:
total = 0
k = 0
ll = []
for line in f:
ll += ["aa"]
total += len(line.strip().split())
k += 1
print ll
print total
print k
|
out=open("abc.txt","w")
for i in range(1,10,1):
out.write("Hello")
out.close()
|
import random
import numpy as np
import pandas as pd
import spacy
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from learntools.core import *
review_data = pd.read_csv('../input/nlp-course/yelp_ratings.csv')
nlp = spacy.load('en_core_web_lg')
all_vectors = np.load('../input/n... |
"""
A helper file to aid with discord.py scripting. Using this requires you to have discord.py installed.
These Classes will not allow users to preform any major actions on your guilds, the most major being banning members.
Use these instead of passing raw discord.py models to your users, as these could be used to obta... |
import falcon
import json
from sqlalchemy.exc import SQLAlchemyError
from db import session
import model
import util
class Email(object):
def on_post(self, req, resp):
"""
Specifikace POST pozadavku:
{
"Subject": String,
"Body": String,
"Reply-To": Str... |
# Step 0: Add NRPy's directory to the path
# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory
import os,sys
nrpy_dir_path = os.path.join("..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
giraffefood_dir_path = os.path.join("in_progress","GiRaFFEfood_NRPy")
if giraf... |
# this is an implementation of the sparse gamma deep exponential family experiment presented in
# Ranganath, Rajesh, Tang, Linpeng, Charlin, Laurent, and Blei, David. Deep exponential families.
#
# the Olivetti faces dataset is originally from http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
#
# compar... |
from __future__ import division, print_function, absolute_import
from torchreid import metrics
from torchreid.losses import AngularPenaltySMLoss
from torchreid.losses import TripletLoss, CrossEntropyLoss
from ..engine import Engine
class ImageArcFaceEngine(Engine):
r"""Softmax-loss engine for image-reid.
A... |
# Copyright The OpenTelemetry 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 agreed to in ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from random import getrandbits
import hashlib
import base64
standardgroup = 17
class DiffieHellman():
global standargroup
def __init__(self, group=standardgroup):
validgroups = [5, 14, 16, 17, 18]
if group not in validgroups:
print(... |
# -*- coding: utf-8 -*-
# Copyright 2020-2021 James Knight
from docutils import nodes
from os import path
from sphinx.transforms.post_transforms import SphinxPostTransform
__version__ = '0.3.0-dev0'
class AliceThemeTransform(SphinxPostTransform):
default_priority = 400
def run(self, **kwargs):
# f... |
#! /usr/bin/env python
import os
import sys
import json
import shutil
import random
import argparse
import datetime
import fileinput
def datetime_to_utc_epoch(dt):
"""
Converts python datetime.datetime into epoch_time in milliseconds. This is copied from the csep package and done to
keep this script runn... |
from threading import Thread
from random import choice
from string import ascii_lowercase
import numpy as np
import cv2
import onnxruntime as rt
import os
import errno
from os import path
from ndu_gate_camera.api.ndu_camera_runner import NDUCameraRunner
from ndu_gate_camera.utility import constants, geometry_helper
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OpenPromoBudget import OpenPromoBudget
from alipay.aop.api.domain.OpenPromoCamp import OpenPromoCamp
from alipay.aop.api.domain.OpenPromoPrize import OpenPromoPrize
... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from typing import Dict, Any
class Loader:
cache = dict(resource={}, client={}) # type: Dict[str, Any]
client_kwargs = dict(default={}) # type: Dict[str, Dict]
def __init__(self, factory):
self.factory = factory
def __getattr__(self, attr):
if attr == "__name__":
return ... |
# Load and process a corpus into trigram frequencies, subject to certain settings
# Members:
# shift_key: str
# space_key: str
# key_counts: dict[str, int]
# bigram_counts: dict[Bigram, int]
# trigram_counts: dict[Trigram, int]
# trigrams_by_freq: list[Trigram] - possibly just use trigram_counts... |
import asyncio
import logging
from typing import List, Union, Tuple
from aiohttp.client_exceptions import ClientConnectionError, ServerTimeoutError
from utils.api import ApiWrapper, ClanWrapper, WoWsNumbersWrapper
from utils.api_errors import InvalidApplicationIdError
from utils.stat_colors import color_avg_dmg, color_... |
# what is the largest prime factor of 600851475143 ?
from __future__ import print_function
import math
import timeit
try:
range = xrange
except NameError:
pass
start = timeit.default_timer()
def is_prime(x):
if x == 2:
return True
if x == 1 or x % 2 == 0:
return False
for i i... |
from flask import current_app
from redis import Redis
from rq_scheduler import Scheduler
from recruit_app.user.tasks import run_alliance_corp_update, run_api_key_update
import datetime as dt
scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue
def schedule_tasks():
scheduler.sc... |
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.template.context import Context
from django.template.loader import get_template
from pynliner import Pynliner
from celery.contrib.methods import task_method
from celery import current_app as app
from urlparse import... |
class LoginPageLocators:
"""Страница логина"""
LOGIN_INPUT_EMAIL_CSS = '#user_email'
LOGIN_INPUT_PASS_CSS = '#user_password'
LOGIN_SUBMIT_BUTTON_CSS = 'button.yellow-btn'
LOGIN_REGISTER_LINK_CSS = 'a[href*="sign_up"]'
LOGIN_WRONG_EMAIL_OR_PASS_CSS = 'div.login-block div#flash_alert'
|
# Copyright [2021] [Daniel Garcia <contacto {at} danigarcia.org>]
#
# 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 require... |
class Token(object):
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return f'Token({self.type}, {self.value})'
def __repr__(self):
return self.__str__()
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2017 Juan Cabral
# 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 withou... |
# Add your Python code here. E.g.
from microbit import *
while True:
display.scroll('Hello from main.py!')
|
'''
The main module which spawns a gui and a effect thread and opens a socket connection to the specified
host. The effect algorithm is in the effect module. Change this file to develop your effect.
Change the host and port to your needs in this main file and also the values representing your led configuration.
Create... |
from typing import Any
from typing import Dict
from typing import Union
import numpy as np
from imblearn.utils import check_sampling_strategy
from sklearn.utils import check_random_state
from .base import BaseSampler
from .base import ONE_DIM_ARRAYLIKE_TYPE
from .base import TWO_DIM_ARRAYLIKE_TYPE
class ModifiedRa... |
# Copyright 2016 Pinterest, Inc.
#
# 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 writi... |
# Python Object Oriented Programming by Joe Marini course example
# Using the __str__ and __repr__ magic methods
class Book:
def __init__(self, title, author, price):
super().__init__()
self.title = title
self.author = author
self.price = price
# the __eq__ method checks for e... |
from email.mime.text import MIMEText
import smtplib
def send_email(email, height, average_height, count):
from_email = "Height Collector <kalzkidandaba@gmail.com>"
to_email = email
subject = "Height data"
message = "Hey there, your height is <strong>%s</strong>. Average height of all is <strong>%s</st... |
import os
# DJANGO ######################################################################
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS = (
'django.contrib.admin',
'django.co... |
import sys
rl = input
# rl = lambda: sys.stdin.readline()
N = int(rl())
A = list(map(int, rl().split()))
B, C = map(int, rl().split())
answer = 0
# 총 감독관
for i in range(N):
A[i] -= B
answer += 1
if A[i] > 0:
if A[i] % C == 0:
answer += A[i] // C
else:
answer += (A... |
#!/usr/bin/env python3
"""
Looks up addresses to discover future garbage and/or recycle pickup dates
within the city of Milwaukee, WI
Usage:
mkerefuse --help
mkerefuse [options]
Options:
-a, --address STRING House number
-d, --direction STRING Address direction (N, S, E, W)
-s, --stre... |
import sqlite3
import numpy as np
import time
from ...utils.mass_calc import PeptideIonCalculator as ion_calc
from ..library_base import LibraryBase, mod_mass_dict
from ...config.unimod import unimod_dict
_mod_dict = {
"Acetyl[ProteinN-term]": ".(UniMod:1)",
"Carbamidomethyl[C]": "C(UniMod:4)",
"Oxid... |
"""
A sample script running MPDS Aiida workflow
"""
import os
import yaml
import pandas as pd
from mpds_client import MPDSDataRetrieval
from aiida.plugins import DataFactory
from aiida.orm import Code
from aiida.engine import submit
from mpds_aiida.workflows.crystal import MPDSCrystalWorkchain
def get_formulae():
... |
# -*- coding: utf-8 -*-
# MIT License (see LICENSE.txt or https://opensource.org/licenses/MIT)
"""This is the actual InputStream Helper API script"""
from __future__ import absolute_import, division, unicode_literals
from . import Helper
from .kodiutils import ADDON, log
def run(params):
"""Route to API method""... |
from django.conf.urls import url
from . import views
app_name="map"
urlpatterns = [
url("", views.default_map, name="map"),
url("<int:my_id>/isEmpty", views.isEmpty, name="isEmpty"),
] |
from __future__ import print_function
import argparse
import glob
import os
import shutil
import time
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transf... |
# -*- coding: utf-8 -*-
"""
Unit tests for signal_processing/outliers/gesd.py.
"""
import random
import numpy as np
import pytest
from signal_processing_algorithms.determinism import deterministic_random
from signal_processing_algorithms.gesd import gesd
class TestGesdInputs(object):
""" Test error handling. ""... |
import os
import peachy
import peachy.fs
basedir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'res')
def test_setup():
print(basedir)
peachy.Engine()
def test_load_image():
image_tests = ['test_bmp.bmp', 'test_jpg.jpg', 'test_png.png',
'test_gif.gif']
for test in ... |
#!/usr/bin/env python
"""Writer for FASTA sequence format
"""
__author__ = "Jeremy Widmann"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jeremy Widmann", "Rob Knight", "Gavin Huttley"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jeremy Widmann"
__email__ = "jeremy.widmann@c... |
"""This module currently provides alternative implementations for two
functions in Python's itertools and functools modules, respectively.
The alternative implementations can be used as drop-in replacements, however,
potentially enhancing the performance when used in secure computations. More
specifically, these imple... |
from django.contrib import admin
# Register your models here.
from monitor import models
from monitor import otherModels
class AdminSysMenu(admin.ModelAdmin):
list_display = ('id', 'code', 'code_name', 'code_class', 'up_code', 'url', 'file_path', 'table', 'type', 'icon')
ordering = ('id',)
class AdminSysMa... |
from gen3utils import *
def test_import():
pass
|
import matplotlib.pyplot as plt
import numpy as np
import pickle as pickle
# a utility function for the plotting
def batch_mean(it,val,window):
assert len(it) == len(val) #the iteration list should have the same length as the values
x = []
y = []
current_index = 0
while current_index+window<len(v... |
from ipw import db
class Interested(db.Model):
__tablename__ = 'interested'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, index=False, unique=False, nullable=False)
def __repr__(self):
return '<Interested {}>'.form... |
from django import template, forms
from django.contrib.admin.views.decorators import staff_member_required
from django.template import loader
from django.shortcuts import render_to_response
from django.contrib.sites.models import Site
from django.conf import settings
from django.utils.importlib import import_module
fro... |
""" done
import lcd_auth
import lcd_authz
import lcd_bank
import lcd_distribution
import lcd_gov
import lcd_mint
import lcd_slashing
import lcd_wasm
import lcd_tendermint
import lcd_ibc
import lcd_ibc_transfer
"""
from terra_sdk.client.lcd import LCDClient
from terra_sdk.client.lcd.api.tx import CreateTxOptions, Sig... |
import numpy as np
import pytest
import artssat
from artssat import ArtsSimulation
from artssat.atmosphere import Atmosphere1D
from artssat.atmosphere.absorption import O2, N2, H2O
from artssat.scattering import ScatteringSpecies, D14
from artssat.atmosphere.surface import Tessem, Telsem, CombinedSurface
from artssat.... |
import numpy as np # linear algebra, vector operations, numpy arrays
import matplotlib.pyplot as plt # allows for plotting
from scipy.io import wavfile # data IO
import os
import config as CFG
class DataGen:
def __init__(self):
self.working_dir = CFG.AUDIO_SOURCE
... |
""" Module to centralize detection of python language version. """
import sys
# A pair (M,m) that can be easily compared.
PYVER = (sys.version_info[0], sys.version_info[1])
if PYVER < (3,0):
PY3 = False
RSTR_CHARSET = "utf-8"
irange = xrange
ustr = unicode
def rstr(s):
""" Convert unico... |
import common.ibc.api_lcd
import common.ibc.constants as co
import common.ibc.util_ibc
COIN_RECEIVED = "coin_received"
COIN_SPENT = "coin_spent"
class MsgInfoIBC:
""" Single message info for index <i> """
lcd_node = None
ibc_addresses = None
def __init__(self, wallet_address, msg_index, message, lo... |
from unittest.mock import MagicMock, patch
import pytest
from datastore.migrations.core.migration_logger import (
MigrationLogger,
MigrationLoggerImplementation,
)
from datastore.shared.di import injector
from tests import reset_di # noqa
@pytest.fixture()
def migration_logger(reset_di): # noqa
inject... |
import os
from flask import Flask, json, jsonify, request
from flask_cors import CORS
from flask_caching import Cache
from decouple import config
import logging
# setting up for local testing, wnat to be able to log the database
"""
We want to be able to test locally and log information for debugging
"""
# Local sql... |
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple
import netaddr
from netaddr import EUI, IPNetwork
from core.api.grpc.wrappers import Interface, Link, LinkType, Node
from core.gui import nodeutils as nutils
from core.gui.graph.edges import CanvasEdge
from core.gui.graph.node impo... |
#!usr/bin/env/python3
# -*- coding: utf-8 -*-
import docker
import minipresto.test.helpers as helpers
from inspect import currentframe
from types import FrameType
from typing import cast
from minipresto.settings import RESOURCE_LABEL
def main():
helpers.log_status(__file__)
helpers.start_docker_daemon()
... |
#Crie um programa que leia o nome de uma pessoa
#e diga se ela tem 'SILVA' no nome.
n = str(input('Digite o nome completo: ')).upper()
nome = n.strip().split()
print(f'O nome tem Silva?: {"SILVA" in nome}')
|
# flake8: noqa
import logging
from hammurabi.config import config
from hammurabi.law import Law
from hammurabi.notifications.base import Notification
from hammurabi.pillar import Pillar
from hammurabi.preconditions.attributes import (
HasMode,
HasNoMode,
IsNotOwnedBy,
IsOwnedBy,
)
from hammurabi.precon... |
# Copyright 2015, Pinterest, Inc.
#
# 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 writ... |
import numpy as np
import SimpleITK as sitk
import os
simg = sitk.ReadImage('/mnt/FileSystem-DeepLearning/tom/Atlas-GAN/EATT_data/average/average.nii.gz')
npy_img = np.zeros([48,80,80])
npy_img[0:47,0:61,0:66] = sitk.GetArrayFromImage(simg)
np.savez_compressed(
'/mnt/FileSystem-DeepLearning/tom/Atlas-GAN/EATT_dat... |
#!/usr/bin/python
# coding: utf-8
# Copyright 2013 The Font Bakery 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... |
import sys
import re
import os
def upcase_first_letter(s):
return s[0].upper() + s[1:]
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for root, dirs, files in os.walk(self.dirname):
for filename in files:
file_path = root + '/' + filename
for line... |
"""
Very sick and extremely sick people go to the hospital. So do doctors and nurses..
"""
import math
from covid19sim.locations.location import Location
class Hospital(Location):
"""
Hospital location class, inheriting from covid19sim.base.Location
"""
ICU_AREA = 0.10
def __init__(self, env, rng,... |
from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset
from .cityscapes import CityscapesDataset
from .custom import CustomDataset
from .dataset_wrappers import ConcatDataset, RepeatDataset
__all__ = [
'CustomDataset',
'build_dataloader',
'ConcatDataset',
'RepeatDataset',
'DATASE... |
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, list_output, _arg_split
@click.command('get_datatypes')
@click.option(
"--extension_only",
help=""
)
@click.option(
"--upload_only",
help=""
)
@pass_context
@custom_exception
@list_output
def ... |
# import os
# import binascii
# import itertools as it
from django.conf import settings
import digitalocean as api
from core import logging
from . import models
logger = logging.getLogger(__name__)
class Lifecycle:
""" Manage mark and sweep to servers using digitalocean """
name = 'object'
def _... |
#!/usr/bin/env python
# encoding: utf-8
"""
Tests the Table formatting with different parameters such as width and
alignment
"""
from inscriptis.annotation import Annotation, horizontal_shift
from inscriptis.html_properties import HorizontalAlignment
def test_horizontal_shift():
a = [Annotation(0, 4, 'test')]
... |
# chardet's setup.py
from distutils.core import setup
setup(
name = "bitpay",
packages = ["bitpay"],
version = "2.3.3",
description = "Accept bitcoin with BitPay",
author = "BitPay Integrations Team",
author_email = "integrations@bitpay.com",
url = "https://github.com/bitpay/bitpay-python",
... |
from owlready2 import *
from rdflib import *
from rdflib.namespace import RDFS
from SPARQLWrapper import SPARQLWrapper, JSON, POST, BASIC, DIGEST
import xlrd ### pip install xlrd==1.2.0
import csv
Compression = 'usecases/Concrete/Data/Druckfestigkeit'
Dynamic = 'usecases/Concrete/Data/E-modul'
Mixture = 'usecases/C... |
# Generated by Django 2.2.7 on 2019-11-19 23:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wavefunction', '0002_auto_20191107_0016'),
]
operations = [
migrations.AlterField(
model_name='hadron',
name='descri... |
import unittest
from datetime import datetime
from models import *
class Test_BaseModel(unittest.TestCase):
"""
Test the base model class
"""
def setUp(self):
self.model1 = BaseModel()
test_args = {'created_at': datetime(2017, 2, 10, 2, 6, 55, 258849),
'updated_a... |
from typing import List, Union
import h5py
import numpy as np
import pandas as pd
class TrackCollection(object):
@staticmethod
def from_hdf5_track_file(track_file, person_id_handler: "PersonIDHandler", crop_idx=4,
tracks_header="Tracks", features_header="features_vgg",
... |
""" Crie um programa que leia um número real qualquer pelo teclado e mostre na
tela a sua porção inteira.
Ex: Digite um número: 6.127
O número 6.127 tem a parte inteira 6.
"""
# importando flor da biblioteca math
from math import floor
# floor arredonda o número para baixo
num = float(input('Digite um número real: '... |
# Copyright Iris-ugrid contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Unit tests for all of :mod:`iris-ugrid`."""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.