content
stringlengths
0
894k
type
stringclasses
2 values
import torch import getopt import math import numpy import os import PIL import PIL.Image import sys import torch.nn.functional as F import torchvision.transforms as transforms import skimage.io as io import numpy as np from skimage import morphology from scipy import ndimage import math transform = transforms.Compos...
python
import ssl import sys import json import os import requests import toml import atexit import re import traceback from pyVim import connect from pyVmomi import vim from pyVmomi import vmodl # GLOBAL_VARS DEBUG = False # CONFIG VC_CONFIG = '/var/openfaas/secrets/vcconfig' service_instance = None class bgc: HEADER...
python
from datetime import datetime from product import Product class Slides(Product): def __init__(self, raw_product): Product.__init__(self, raw_product) bib_info = raw_product.get('slides', {}) self._parse_bib_info(bib_info) def _parse_bib_info(self, bib_info): self._repository =...
python
from django.shortcuts import render from django.http import HttpResponse from django.template import loader from data_crystal.settings import URL_PREFIX from data_manager.models import Data ############################################################################### def app_home(request): template = loader.get_temp...
python
import argparse import torch import torch.nn.functional as F from gat_conv import GATConv from torch.nn import Linear from datasets import get_planetoid_dataset from snap_dataset import SNAPDataset from suite_sparse import SuiteSparseMatrixCollection from train_eval_cs import run import pdb from torch_geometric.nn impo...
python
import os from config.defaults import * if os.environ.get("ENV") == 'dev': print("==== Loading DEV environment ====") from config.local import * elif os.environ.get("ENV") == 'docker': print("==== Loading Docker environment ====") from config.docker import * else: print("==== Loading HERKOU enviro...
python
from typing import Any, Dict, List, Optional, Tuple, Type, Union import gym import numpy as np from stable_baselines3.common.distributions import SquashedDiagGaussianDistribution import torch as th from torch.distributions.multivariate_normal import MultivariateNormal import torch.nn as nn from torch.nn.utils ...
python
import os import urllib2 import uuid import falcon import mimetypes import requests import logging from datetime import datetime __author__ = 'Maged' logging.basicConfig(filename='dropbox_upload_manager.log', level=logging.DEBUG) WGET_CMD = '/usr/bin/wget' ALLOWED_TYPES = ( 'text/plain', 'image/gif', 'i...
python
from unittest import TestCase, main from os import remove from os.path import exists, join from datetime import datetime from shutil import move from biom import load_table import pandas as pd from qiita_core.util import qiita_test_checker from qiita_db.analysis import Analysis, Collection from qiita_db.job import Jo...
python
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='pdt-r']/div[@class='t']/div[@class='l']/h1", 'price' : "//div[@class='l']/div/p/span", 'category' : "//body/form[@id...
python
"""pydantic models for GeoJSON Feature objects.""" from typing import Dict, Generic, List, Optional, TypeVar from pydantic import Field, validator from pydantic.generics import GenericModel from geojson_pydantic.geometries import Geometry from geojson_pydantic.types import BBox Props = TypeVar("Props", bound=Dict) ...
python
"""Async version of stream-unzip (https://github.com/uktrade/stream-unzip). MIT License.""" import zlib from struct import Struct async def stream_unzip(zipfile_chunks, chunk_size=65536): local_file_header_signature = b'\x50\x4b\x03\x04' local_file_header_struct = Struct('<H2sHHHIIIHH') zip64_compressed_...
python
""" Given two sequences ‘s1’ and ‘s2’, write a method to find the length of the shortest sequence which has ‘s1’ and ‘s2’ as subsequences. Example 2: Input: s1: "abcf" s2:"bdcf" Output: 5 Explanation: The shortest common super-sequence (SCS) is "abdcf". Example 2: Input: s1: "dynamic" s2:"programming" Output: 1...
python
"""The yale_smart_alarm component."""
python
import numpy as np #import numpy library #intergers i=10 print(type(i)) #print out the data type 1 a_i = np.zeros(i,dtype=int) #declare an array of ints print(type(a_i)) #will return ndarray print(type(a_i[0])) #will return int64 #floats x = 119.0 #floating point number print(type(x)) #print out the...
python
"""Utilties for distributed processing""" import horovod.tensorflow.keras as hvd def rank(): try: return hvd.rank() except ValueError: return 0 def barrier(): try: hvd.allreduce([], name='Barrier') except ValueError: pass
python
import os import time import pytest from rhcephcompose.compose import Compose from kobo.conf import PyConfigParser import py.path @pytest.fixture def conf(fixtures_dir): conf_file = os.path.join(fixtures_dir, 'basic.conf') conf = PyConfigParser() conf.load_from_file(conf_file) return conf class Test...
python
# Copyright 2020 The TensorFlow Probability 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 o...
python
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
python
''' Created on Jul 13, 2018 @author: friedl ''' import subprocess import sys def run_bwa_aln(genome_index, fastq_in_file, sai_out_file, bwa_path='bwa', threads=1, R_param=None): ''' calls bwa aln ''' # build bwa command command = [bwa_path, 'aln', '-t', str(threads), '-f', sai_out_file] if(R_par...
python
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Given the taxonomy output from AlchemyAPI, for each level of taxonomies, extract the graph so that the taxons in this level are connected based on ***Jaccardi score*** for the users sharing these taxons in their tweets """ import codecs from collections import defau...
python
# Copyright 2017 Neosapience, 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 wri...
python
# problems init file from tigerforecast.problems.core import Problem from tigerforecast.problems.sp500 import SP500 from tigerforecast.problems.uci_indoor import UCI_Indoor from tigerforecast.problems.enso import ENSO from tigerforecast.problems.crypto import Crypto from tigerforecast.problems.random import Random fro...
python
import sys sys.path.append('..') import torch.nn as nn import torch class ConvBlock(nn.Module): """Layer to perform a convolution followed by LeakyReLU """ def __init__(self, in_channels, out_channels): super(ConvBlock, self).__init__() self.conv = Conv3x3(in_channels, out_channels) ...
python
import os import pickle import socket import threading import time from cryptography.fernet import Fernet from scripts import encryption from scripts.consts import MessageTypes # IP = socket.gethostbyname(socket.gethostname()) IP = 'localhost' PORT = 8004 class Server: def __init__(self): self.active_co...
python
#!/usr/bin/env python import pytest import os import sys import logging logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) from pathlib import Path from dselib.thread import initTLS initTLS() from dselib.context import DSEContext from dselib.defaults import Defaults from dselib...
python
# -*- coding: utf-8 -*- """ Created on Wed May 27 20:06:01 2015 @author: Thomas """ # Python standard library imports import csv import os def main(): costs = [] for file in os.listdir("reformatted/"): print 'getting data from.. ' + file cost_total = [] cost_2000 = [] ...
python
class SveaException(Exception): pass class MissingFiles(SveaException): pass class DtypeError(SveaException): pass class PathError(SveaException): pass class PermissionError(SveaException): pass class MissingSharkModules(SveaException): pass
python
from __future__ import print_function import yaml from cloudmesh.common.util import path_expand from cloudmesh.shell.command import PluginCommand from cloudmesh.shell.command import command, map_parameters from cloudmesh.openapi3.function.server import Server from cloudmesh.common.console import Console from cloudmes...
python
#! /usr/bin/env python """ Author: Scott H. Hawley Based on paper, A SOFTWARE FRAMEWORK FOR MUSICAL DATA AUGMENTATION Brian McFee, Eric J. Humphrey, and Juan P. Bello https://bmcfee.github.io/papers/ismir2015_augmentation.pdf """ from __future__ import print_function import numpy as np import librosa from random impo...
python
text = input() for index, letter in enumerate(text): if letter == ":": print(letter + text[index + 1])
python
class Node: def __init__(self, val): self.val = val self.left = left self.right = right root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4)
python
import argparse import datetime import fnmatch import os import pickle import re from time import time from typing import List import tensorflow.keras import numpy import numpy as np from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard from tensorflow.keras.preprocessin...
python
lst = ["A","guru","sabarish","kumar"] last=lst[-1] length=0 for i in lst: length=length+1 if i == last: break print("The length of list :",length)
python
def dp(n, k): if
python
# Copyright (c) nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/vulnerablecode/ # The VulnerableCode software is licensed under the Apache License version 2.0. # Data generated with VulnerableCode require an acknowledgment. # # You may not use this software except in compliance ...
python
#!/usr/bin/env python3 # encoding: utf-8 import re import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from collections import OrderedDict import torch import torch.nn as nn import math import numpy as np import time import os import sys import torchvision #__all__ = ['DenseNet121','DenseNet169...
python
from django.apps import AppConfig class BizcontactsConfig(AppConfig): name = 'bizcontacts'
python
''' --- Day 9: Encoding Error --- With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you. Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon conn...
python
import os import subprocess import unittest from fs import open_fs from celery import Celery, group import magic from fs.copy import copy_file from parameterized import parameterized app = Celery('test_generators') app.config_from_object('unoconv.celeryconfig') app.conf.update({'broker_url': 'amqp://guest:guest@local...
python
from .base import BaseDocument import markdown import html_parser class MarkdownDocument(BaseDocument): def __init__(self, path): self.path = path def read(self): self.document = open(self.path, "r") text = self.document.read() html = markdown.markdown(text) return html_parser.html_to_text(html) def c...
python
while True: try: string = input() print(string) except EOFError: break
python
# Eerst met PCA. Deze resulteert nu in 3 coponenten, waarvoor je dus twee plot nodig hebt pca = PCA() pcas = pca.fit_transform(X) fig = plt.figure(figsize=(15, 8)) ax = fig.add_subplot(121) plt.scatter(pcas[:, 0], pcas[:, 1], c=color, cmap=plt.cm.Spectral) ax = fig.add_subplot(122) plt.scatter(pcas[:, 2], pcas[:, 1], c...
python
# Copyright (c) 2019 Dan Ryan # MIT License <https://opensource.org/licenses/mit> from __future__ import absolute_import, unicode_literals import collections import csv import io import pathlib import sqlite3 import tempfile import uuid from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union impor...
python
import abc import flask from flask import jsonify, make_response from ..app.swagger_schema import Resource, Schema from ..extensions.audit import AuditLog from ..logger.app_loggers import logger from ..swagger import AfterResponseEventType, BeforeRequestEventType, BeforeResponseEventType class ResourceResponse: ...
python
# -*- coding: utf-8 -*- """ Module for common converters settings and functions """ import os from config import log, root_directory, DEFAULT_LANGUAGE def db_get_statistic(models_list): """ :return: """ log.info("Start to get statistic of imported items:") [log.info("%s: %s", model.__name__, mode...
python
from django.conf.urls import url from django.contrib.auth.views import logout from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^change_city/$', views.change_city, name='change_city'), url(r'^parse/$', views.parse, name='parse'), url(r'^logout/$', logout, {'next_page': ...
python
max_n1 = int(input()) max_n2 = int(input()) max_n3 = int(input()) for num1 in range(2, max_n1 + 1, 2): for num2 in range(2, max_n2 + 1): for num3 in range(2, max_n3 + 1, 2): if num2 == 2 or num2 == 3 or num2 == 5 or num2 == 7: print(f"{num1} {num2} {num3}")
python
from typing import Callable, Dict, Tuple, Any __all__ = ['HandlerResponse', 'Handler'] HandlerResponse = Tuple[int, Dict[str, str], str] Handler = Callable[[Dict[str, Any], Dict[str, str]], HandlerResponse]
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
python
import sys # cyheifloader allows specifying the path to heif.dll on Windows # using the environment variable LIBHEIF_PATH. from cyheifloader import cyheif from PIL import Image from PIL.ExifTags import TAGS # Print libheif version print(f'LibHeif Version: {cyheif.get_heif_version()}') file_name = sys.ar...
python
from bibliopixel.animation.matrix import Matrix try: from websocket import create_connection except ImportError: create_connection = None import threading import numpy as np WS_FRAME_WIDTH = 640 WS_FRAME_HEIGHT = 480 WS_FRAME_SIZE = WS_FRAME_WIDTH * WS_FRAME_HEIGHT def clamp(v, _min, _max): ...
python
import os import json from pathlib import Path import yaml import unittest import click from click.testing import CliRunner os.environ['QA_TESTING'] = 'true' # Missing: # - tests with --share # - tests with CI=ON CI_COMMIT=XXXXXX class TestQaCli(unittest.TestCase): @classmethod def setUpClass(self): self.p...
python
ASCII_MAZE = """ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ S | | | | | | +-+ + +-+-+ + + + + +-+ + + +-+-+-+ + + + | | | | | | | | | | | | | | | + + +-+ + +-+ + +-+-+ +-+-+ +-+-+ + + + + | | | | | | | | +-+-+-+-+-+ +-+-+ +-+ +-+-+ +-+-+-+-+-+ + | | ...
python
from Instruments.devGlobalFunctions import devGlobal class CounterClass(devGlobal): # Human readable name for the gui, note: Needs to be unique name = "Counter" def __init__(self, *args): devGlobal.__init__(self, *args) self.func_list = self.func_list + [ self.C...
python
from . import config from .genome import Genome class Population(): def __init__(self, default=True): self.genomes = [] self.speciesRepresentatives = [] self.species = 0 if default: self.initialize() def initialize(self): for i in range(config.populationSiz...
python
from __future__ import print_function import setuptools import sys # Convert README.md to reStructuredText. if {'bdist_wheel', 'sdist'}.intersection(sys.argv): try: import pypandoc except ImportError: print('WARNING: You should install `pypandoc` to convert `README.md` ' 'to reSt...
python
# Module to describe all the potential commands that the Renogy Commander # supports. # # Author: Darin Velarde # # from collections import namedtuple # I typically don't like import * but I actually need every symbol from # conversions. from conversions import * # Register # ** immutable data type ** # Represents ...
python
# 视觉问答模型 from keras.layers import Conv2D, MaxPooling2D, Flatten from keras.layers import Input, LSTM, Embedding, Dense from keras.models import Model, Sequential import keras # First, let's define a vision model using a Sequential model. # This model will encode an image into a vector. vision_model = Sequential() visi...
python
# Generated by Django 3.1.3 on 2020-12-07 23:51 from django.db import migrations, models import django.db.models.deletion import django_update_from_dict class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0003_auto_20201206_1634'), ] operations = [ mig...
python
from django.contrib.auth import logout, authenticate, login from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, get_object_or_40...
python
from typing import Any # NOQA import optuna from optuna._experimental import experimental from optuna._imports import try_import with try_import() as _imports: from catalyst.dl import Callback if not _imports.is_successful(): Callback = object # NOQA @experimental("2.0.0") class CatalystPruningCallback(...
python
#!/usr/bin/python """Copyright 2016 Google Inc. 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 l...
python
import pygame from Clock import Clock from Timer import Timer class TileManager(object): # Call constructor def __init__(self, screenWidth, screenHeight, tileWidth, tileHeight, tileImage, tileType): self.tiles = [] self.tileWidth = tileWidth self.tileHeight = tileHeight self.scr...
python
"""In this module are all SuperCollider Object related classes"""
python
# Crie um programa que peça um número ao usuário e retorne se antecessor e o seu sucessor. print('=-'*7 'DESAFIO 7' ''=-'*7) n = int(input('Digite um número: ')) print('Analisando o número {}, seu antecessor é {} e seu sucessor é {} '.format(n, n - 1, n + 2))
python
import pygame from pygame.locals import QUIT, K_ESCAPE, K_a, K_d, K_s, K_SPACE from time import time from os.path import dirname, realpath def main(): running, settings = load() while running: settings = update(settings) draw(settings) running = check_exit(settings) pygame.quit() de...
python
# # 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 writing, software # distributed under...
python
from vplot import GetOutput import subprocess as sub import numpy as np import os cwd = os.path.dirname(os.path.realpath(__file__)) import warnings import h5py import multiprocessing as mp import sys import bigplanet as bp def test_bpstats(): #gets the number of cores on the machine cores = mp.cpu_count() ...
python
import cv2 import pickle import face_recognition class recognize: def __init__(self): self.data = pickle.loads(open("./encodings.pickle", "rb").read()) self.detector = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml") def recognize_face(self, frame): gray = cv2.cv...
python
token = 'BOT-TOKEN' initial_extensions = ['cogs.general', 'cogs.groups', 'cogs.lights', 'cogs.scenes'] prefix = '>' owner_only = True owner_id = DISCORD-USER-ID bridge_ip = 'BRIDGE-IP'
python
# -------------- import numpy as np import pandas as pd import matplotlib.pyplot as plt # code starts here df = pd.read_csv(path) total_length = len(df) print(total_length) fico = 0 for i in df['fico'] > 700: fico += i print(fico) p_a = fico/total_length print(round(p_a, 2)) debt = 0 for i in df['purpose'] ==...
python
import requests, zipfile import os import pandas as pd def gdpimporter(url, filename=None, filetype='csv'): """Download the zipped file, unzip, rename the unzipped files, and outputs a dataframe along with the title from meta data. This function downloads the zipped data from URL to the local path, un...
python
from functools import partial from typing import Callable, Union import jax import jax.numpy as np from rbig_jax.transforms.histogram import get_hist_params from rbig_jax.transforms.inversecdf import ( invgausscdf_forward_transform, invgausscdf_inverse_transform, ) from rbig_jax.transforms.kde import get_kde_...
python
# -*- coding: utf-8 -*- import csv from collections import defaultdict, namedtuple from datetime import datetime, timedelta import pkg_resources import re from zipfile import ZipFile from enum import Enum, unique from io import TextIOWrapper Train = namedtuple("Train", ["name", "kind", "direction", "stops", "service_...
python
from __future__ import (absolute_import, division, print_function) __metaclass__ = type raise Exception('this code should never execute')
python
skills = [ { "id" : "0001", "name" : "Liver of Steel", "type" : "Passive", "isPermable" : False, "effects" : { "maximumInebriety" : "+5", }, }, { "id" : "0002", "name" : "Chronic Indigestion", "type" : "Combat", ...
python
from netmiko import ConnectHandler, file_transfer from getpass import getpass ios_devices = { "host": "cisco3.lasthop.io", "username": "pyclass", "password": "88newclass", "device_type": "cisco_ios", } source_file = "testTofu.txt" dest_file = "testTofuBack.txt" direction = "get" file_...
python
#!/usr/bin/env python3 # coding: utf-8 from threading import Thread from queue import Queue class TaskQueue(Queue): def __init__(self, num_workers=1): super().__init__() self.num_workers = num_workers self.start_workers() def add_task(self, task, *args, **kwargs): args = args ...
python
#!/usr/bin/env python import logging import os import shutil import sys import tempfile from io import BytesIO from itertools import groupby from subprocess import Popen,PIPE, check_output import requests from KafNafParserPy import * from lxml import etree from lxml.etree import XMLSyntaxError from .alpino_dependenc...
python
import os import pytest from packaging import version from unittest import TestCase from unittest.mock import patch from osbot_utils.utils.Dev import pprint from osbot_utils.utils.Files import temp_folder, folder_files, folder_delete_all, folder_create, file_create_bytes, \ file_contents_as_bytes, file_contents, ...
python
# Generated by Django 3.1.4 on 2021-11-13 12:20 import datetime from django.db import migrations, models from django.utils.timezone import utc import uuid class Migration(migrations.Migration): dependencies = [ ('library_app', '0007_auto_20211113_1319'), ] operations = [ migrations.Alte...
python
# Original script acquired from https://github.com/adafruit/Adafruit_Python_MCP3008 # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import time # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev...
python
""" This component provides basic support for the Philips Hue system. For more details about this component, please refer to the documentation at https://home-assistant.io/components/hue/ """ import asyncio import json import ipaddress import logging import os import async_timeout import voluptuous as vol from homea...
python
import re import sys import boa3 from boa3 import neo from boa3.constants import SIZE_OF_INT32, SIZE_OF_INT160, DEFAULT_UINT32 from boa3.neo import cryptography from boa3.neo.utils.serializer import Serializer from boa3.neo.vm.type.Integer import Integer class NefFile: """ The object encapsulates the informa...
python
""" @author: Skye Cui @file: layers.py @time: 2021/2/22 13:43 @description: """ import tensorflow as tf class ConvAttention(tf.keras.layers.Layer): def __init__(self, l, h, w, c, k): super(ConvAttention, self).__init__() self.reshape = tf.keras.layers.Reshape((l, w * h * c)) self.layer1 =...
python
start_case_mutation = """\ mutation startCase($case: StartCaseInput!) { startCase(input: $case) { case { id } } }\ """ intervalled_forms_query = """\ query allInterForms { allForms (metaHasKey: "interval") { pageInfo { startCursor endCursor } edges { node { met...
python
# -*- coding: utf-8 -*- # pylint: disable=no-self-use, too-many-locals, too-many-arguments, too-many-statements, too-many-instance-attributes """Invite""" import string import time import json from configparser import ConfigParser import requests from flask import request from library.couch_database import Co...
python
from __future__ import annotations from dataclasses import dataclass from dataclasses import field import boto3 from ..ec2api.vpcs import VPCs from ..ec2common.ec2exceptions import * # See vpc notes at the end of this file. @dataclass class VPCAttributes: CidrBlock: str = None DhcpOptionsId: str = None ...
python
# coding=utf-8 from particles import Particle class RectParticle(Particle): def __init__(self, l): Particle.__init__(self, l) # super(RectParticle, self).__init__(l) rectMode(CENTER) self.rota = PI/3 def display(self): stroke(0, self.lifespan) fill(204...
python
import pytest from detect_secrets.core.potential_secret import PotentialSecret from testing.factories import potential_secret_factory @pytest.mark.parametrize( 'a, b, is_equal', [ ( potential_secret_factory(line_number=1), potential_secret_factory(line_number=2), T...
python
""" Basic shared function to read input data for each problem; the data file must be in the subdirectory 'input' and with the name '<prog_name>.txt', where '<prog_name>.py' is the name of the program being run """ import inspect import pathlib def get_input(): """ Get input data for currently running program...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Holds fixtures for the smif package tests """ from __future__ import absolute_import, division, print_function import json import logging import os from copy import deepcopy import numpy as np import pandas as pd from pytest import fixture from smif.data_layer import S...
python
import os import sys from setuptools import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wheel') os.system('python -m twine upload dist/*') sys.exit() setup()
python
#!/usr/bin/env python3 # Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice...
python
# Based on https://www.geeksforgeeks.org/get-post-requests-using-python/ # importing import requests import time # defining the api-endpoint API_ENDPOINT = "https://api.gfycat.com/v1/gfycats" # your API key here # API_KEY = "XXXXXXXXXXXXXXXXX" # your source code here external_url = input("Please input the externa...
python
import unittest from datetime import datetime from models import * class Test_UserModel(unittest.TestCase): """ Test the user model class """ def setUp(self): self.model = User() self.model.save() def test_var_initialization(self): self.assertTrue(hasattr(self.model, "ema...
python
""" Configuration file """ __author__ = 'V. Sudilovsky' __maintainer__ = 'V. Sudilovsky' __copyright__ = 'ADS Copyright 2014, 2015' __version__ = '1.0' __email__ = 'ads@cfa.harvard.edu' __status__ = 'Production' __license__ = 'MIT' SAMPLE_APPLICATION_PARAM = { 'message': 'config params should be prefixed with the...
python
import asyncio class ClientServerProtocol(asyncio.Protocol): metrics = {} def __init__(self): # self.metrics = {} self.spliter = '_#_' self.ok_message = 'ok\n' self.error_message = 'error\nwrong command\n\n' def connection_made(self, transport): self.transport = t...
python
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de' from scipy import random, asarray, zeros, dot from pybrain.structure.modules.neuronlayer import NeuronLayer from pybrain.tools.functions import expln, explnPrime from pybrain.structure.parametercontainer import ParameterContainer class StateDependentLayer(Neuron...
python