content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from cto_ai import sdk, ux
cto_terminal = """
[94mββββββ[39m[33mβ[39m [94mββββββββ[39m[33mβ[39m [94mββββββ[39m[33mβ [39m [94mβββββ[39m[33mβ[39m [94mββ[39m[33mβ[39m
[94mββ[39m[33mββββββ[39m [33mβββ[39m[94mββ[39m[33mββββ[39m [94mββ[39m[33mββββ[39m[94mββ[39m[33mβ[39m... | python |
# http://book.pythontips.com/en/latest/for_-_else.html
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, "equals", x, "*", n // x)
break
else:
# loop fell through without finding a factor
print(n, "is a prime number")
# 2 is a prime number
# ... | python |
""" pygame module for loading and playing sounds """
import math
from pygame._sdl import sdl, ffi
from pygame._error import SDLError
from pygame.base import register_quit
import pygame.mixer_music as music
from pygame.mixer_music import check_mixer
from pygame.rwobject import (rwops_encode_file_path, rwops_f... | python |
# pylint: disable=missing-docstring
from openshift_checks import OpenShiftCheck, get_var
class DockerImageAvailability(OpenShiftCheck):
"""Check that required Docker images are available.
This check attempts to ensure that required docker images are
either present locally, or able to be pulled down from ... | python |
import torch
from torch.multiprocessing import Pool
class Simulator(torch.nn.Module):
r"""Base simulator class.
A simulator defines the forward model.
Example usage of a potential simulator implementation::
simulator = MySimulator()
inputs = prior.sample(torch.Size([10])) # Draw 10 sa... | python |
import re
from localstack.constants import TEST_AWS_ACCOUNT_ID
from localstack.utils.common import to_str
from localstack.services.generic_proxy import ProxyListener
class ProxyListenerIAM(ProxyListener):
def return_response(self, method, path, data, headers, response):
# fix hardcoded account ID in ARNs... | python |
from __future__ import absolute_import, print_function
from django.conf.urls import patterns, url
from .action_endpoint import SlackActionEndpoint
from .event_endpoint import SlackEventEndpoint
from .link_identity import SlackLinkIdentitiyView
urlpatterns = patterns(
"",
url(r"^action/$", SlackActionEndpoin... | python |
import cv2
import numpy as np
path = "./underexposed.jpg"
def _mask(img):
img = cv2.bitwise_not(img)
mask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blured_img = cv2.GaussianBlur(mask, (15, 15), cv2.BORDER_DEFAULT)
return blured_img
def _local_contrast_correction(img, mask):
exponent = np.repeat((... | python |
#!/usr/bin/env python
"""
Launch a distributed job
"""
import argparse
import os, sys
import signal
import logging
curr_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(curr_path, "./tracker"))
#print sys.path
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
... | python |
import logging
import copy
import numpy as np
from scipy.linalg import expm
from .population import Population
from spike_swarm_sim.utils import eigendecomposition, normalize
from spike_swarm_sim.algorithms.evolutionary.species import Species
from ..operators.crossover import *
from ..operators.mutation import ... | python |
# Generated by Django 2.2.7 on 2019-11-30 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('neighbourhood', '0005_neighbourhood_image'),
]
operations = [
migrations.AddField(
model_name='business',
name='imag... | python |
#!/usr/bin/env python
import exifread
import logging
class Exif2Dict:
def __init__(self, filename):
self.__logger = logging.getLogger("exif2dict.Exif2Dict")
self.__tags = {}
try:
with open(filename, 'rb') as fh:
self.__tags = exifread.process_file... | python |
#GUI Stuff
from tkinter import *
#GPIO setup for non-expander ports
import RPi.GPIO as GPIO
import time
#port Expander stuff
import board
import busio
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
#Port expander setup
i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP230... | python |
r""" This module implements Peak Signal-to-Noise Ratio (PSNR) in PyTorch.
"""
import torch
from typing import Union
from typing import Tuple, List, Optional, Union, Dict, Any
def _validate_input(
tensors: List[torch.Tensor],
dim_range: Tuple[int, int] = (0, -1),
data_range: Tuple[float, float] ... | python |
import numpy, random
import os
import uuid
import cloudpickle
import json
from flor.constants import *
from .. import stateful as flags
from torch import cuda
class Writer:
serializing = False
lsn = 0
pinned_state = []
seeds = []
store_load = []
partitioned_store_load = []
max_buffer = 500... | python |
from leapp.actors import Actor
from leapp.models import Report, OpenSshConfig
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
from leapp.libraries.common.reporting import report_generic
class OpenSshUsePrivilegeSeparationCheck(Actor):
"""
UsePrivilegeSeparation configuration option was removed.
Che... | python |
import tensorflow as tf
import tensorflow.keras as tk
import nthmc
conf = nthmc.Conf(nbatch=1, nepoch=1, nstepEpoch=1024, nstepMixing=64, stepPerTraj = 10,
initDt=0.4, refreshOpt=False, checkReverse=False, nthr=4)
nthmc.setup(conf)
beta=3.5
action = nthmc.OneD(beta=beta, transform=nthmc.Ident())
loss = nthmc.LossFu... | python |
from __future__ import annotations
from injector import Injector
from labster.domain2.model.structure import Structure, StructureRepository
from labster.domain2.model.type_structure import CO, DU, FA, LA, UN
def test_single():
universite = Structure(nom="Sorbonne UniversitΓ©", type_name=UN.name, sigle="SU")
... | python |
from django.contrib import admin
from .models import Confirguracoes
# Register your models here.
admin.site.register(Confirguracoes)
| python |
from __future__ import division
import matplotlib
#matplotlib.use('agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np
class RobotArm(object):
def __init__(self):
self.dh_a= [ 0,... | python |
""" Exceptions for the library. """
class CatnipException(Exception):
""" Base exception class. """
class NoFrame(CatnipException):
""" Failed to receive a new frame. """
| python |
# test of printing multiple fonts to the ILI9341 on a esp32-wrover dev kit using H/W SP
# MIT License; Copyright (c) 2017 Jeffrey N. Magee
from ili934xnew import ILI9341, color565
from machine import Pin, SPI
import tt14
import glcdfont
import tt14
import tt24
import tt32
fonts = [glcdfont,tt14,tt24,tt32]
text = 'No... | python |
"""
Simple time checker by David. Run with `python time_checker.py` in
the same folder as `bat_trips.json`
"""
import json
from datetime import datetime as dt
with open('bat_trips.json') as f:
start_times = []
end_times = []
for i in range(24):
start_times.append(0)
end_times.append(0)
... | python |
import cv2, numpy as np
import time
import math as mth
from PIL import Image, ImageDraw, ImageFont
import scipy.io
from keras.models import Sequential
from keras import initializations
from keras.initializations import normal, identity
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimiz... | python |
import pytest
from typing import Any, Callable, Tuple
from aio_odoorpc_base.sync.common import login
from aio_odoorpc_base.protocols import T_HttpClient
import httpx
@pytest.fixture(scope='session')
def runbot_url_db_user_pwd(runbot_url_db_user_pwd) -> Tuple[str, str, str, str]:
base_url, url_jsonrpc, db, usernam... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import math
import glob
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
from common import DataPreset, load_preset_from_file, save_plot
def plot_step(params):
name = params['name']
#preset = params['preset']
ste... | python |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Implements composite forecasters."""
__author__ = ["mloning"]
__all__ = [
"ColumnEnsembleForecaster",
"EnsembleForecaster",
"TransformedTargetForecaster",
"ForecastingPipeline",... | python |
# -*- coding: utf-8 -*-
import pandas
import numpy as np
from sklearn import preprocessing
from sklearn import neighbors
from sklearn.model_selection import StratifiedKFold, cross_val_score
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Tira limite de vizualiΓ§Γ£o do dataframe qu... | python |
from django.test import TestCase
from foia_hub.models import Agency, Office
from foia_hub.scripts.load_agency_contacts import (
load_data, update_reading_rooms, add_request_time_statistics,
extract_tty_phone, extract_non_tty_phone, build_abbreviation)
example_office1 = {
'address': {
'address_lin... | python |
import picobox
@picobox.pass_("conf")
def session(conf):
class Session:
connection = conf["connection"]
return Session()
@picobox.pass_("session")
def compute(session):
print(session.connection)
box = picobox.Box()
box.put("conf", {"connection": "sqlite://"})
box.put("session", factory=sessio... | python |
#pg.72 ex13 parameters, unpacking,variables
#sd3 combine input with aargv to make a script that gets more input from the user
from sys import argv
#read the WYSS section for how to run this
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your s... | python |
import unittest
import sys
from PyQt5.QtWidgets import QApplication, QDialog
from ui import DisclaimerDialog
app = QApplication(sys.argv)
disclaimer_dialog = QDialog()
disclaimer_dialog_ui = DisclaimerDialog.Ui_dialog()
disclaimer_dialog_ui.setupUi(disclaimer_dialog)
class DisclaimerDialogTests(unittest.TestCase):
... | python |
import json
with open('04_movies_save.json', 'r', encoding='UTF-8') as fr:
movies = json.load(fr)
with open('04_notfound_save.json', 'r', encoding='UTF-8') as fr:
not_found = json.load(fr)
with open('02_rating_save.json', 'r', encoding='UTF-8') as fr:
ratings = json.load(fr)
new_rating = []
new_movies =... | python |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
name=input("please enter your name: ")
age=input("please enter your age: ")
grade=input("please enter your grade: ")
school=input("please enter your school: ")
directory={}
directory.update({'name':name, 'age':age,'grade':grad... | python |
import logging
from os import access
import azure.functions as func
import mysql.connector
import ssl
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
from azure.identity import DefaultAzureCredential, AzureCliCredential, ChainedTokenCrede... | python |
import functools
from bargeparse.cli import cli
def command(*args, param_factories=None):
"""
Decorator to create a CLI from the function's signature.
"""
def decorator(func):
func._subcommands = []
func.subcommand = functools.partial(
subcommand, func, param_factories=pa... | python |
#pylint:skip-file
import sys
from argparse import ArgumentParser
import networkx as nx
def main(argv):
parser = ArgumentParser()
parser.add_argument('-i', '--input_file', help='Input .dot file',
required=True)
parser.add_argument('-s', '--start_id', help='Start ID (inclusive)',
... | python |
import os
import sys
from .toolkit import *
__version__ = '1.1.0'
class ToolkitCompileFileCommand(compiler.ES6_Toolkit_Compile_File):
def run(self):
self.execute()
class ToolkitDumpJsCommand(compiler.ES6_Toolkit_Dump_JS):
def run(self, edit, compiled_js):
self.execute(edit, compiled_js)
| python |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: lib.coginvasion.gui.CILoadingScreen
from direct.gui.DirectGui import OnscreenText
from direct.directnotify.DirectNotifyGlobal import dir... | python |
from unittest import TestCase
from musicscore.musicxml.groups.common import Voice
from musicscore.musicxml.elements.fullnote import Pitch
from musicscore.musicxml.elements.note import Note, Duration
class Test(TestCase):
def setUp(self) -> None:
self.note = Note()
self.note.add_child(Pitch())
... | python |
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
@author: Raven
@contact: aducode@126.com
@site: https://github.com/aducode
@file: __init__.py
@time: 2016/1/31 23:57
"""
import types
from type import Any
from type import Null
from type import Bool
from type import Byte
from type import Int16
from type import Int32
from ... | python |
import json
import matplotlib.pyplot as plt
import sys
import os
from matplotlib.backends.backend_pdf import PdfPages
from random import randrange
import re
import traceback
from datetime import datetime
import argparse
import operator
import matplotlib.dates as mdate
def buildChart(name, x,y, label1, x2,y2, label2):
... | python |
import argparse
import sys
import os
from subprocess import call, check_output
def main():
action = parse_commandline()
action()
def parse_commandline():
parser = argparse.ArgumentParser(
description='A simple program to compile and run OpenCV programs',
formatter_class=argparse.RawTextH... | python |
#!/usr/bin/env python3
#
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
#
# See ../../../LICENSE for clarification regarding multiple 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... | python |
def main():
print "plugin_b" | python |
# -*- coding: utf8 -*-
csv_columns = [
'DATE-OBS',
'TIME-OBS',
'FILENAME',
'OBSTYPE',
'OBJECT',
'NOTES',
'EXPTIME',
'RA',
'DEC',
'FILTERS',
'FILTER1',
'AIRMASS',
'DECPANGL',
'RAPANGL',
'NEXTEND'
]
| python |
import json
from tracardi_plugin_sdk.action_runner import ActionRunner
from tracardi_plugin_sdk.domain.register import Plugin, Spec, MetaData, Form, FormGroup, FormField, FormComponent
from tracardi_plugin_sdk.domain.result import Result
from tracardi_json_from_objects.model.models import Configuration
def validate(... | python |
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 ag... | python |
"""
Copyright (c) 2021 Heureka Group a.s. 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 law or agre... | python |
from django.test import TestCase, RequestFactory, Client
from chat.views import UnarchiveMessageHealthProfessionalView
from chat.models import Message
from user.models import HealthProfessional, Patient
class TestUnarchiveMessageHealthProfessionalView(TestCase):
def setUp(self):
self.health_professional... | python |
from py4jps.resources import JpsBaseLib
import os
from tqdm import tqdm
import time
import numpy as np
import pandas as pd
from SPARQLWrapper import SPARQLWrapper, CSV, JSON, POST
from shapely import geometry, wkt, ops
# read csv with regional code and WKT strings
df = pd.read_csv('scotland_lsoa_populations/scottish... | python |
"""
Customer Class including visualization.
"""
import random
import pandas as pd
import numpy as np
from a_star import find_path
from SupermarketMapClass import SupermarketMap
import constants
class Customer:
""" customer class including visualization."""
# possible states of a customer
STATES = ['che... | python |
from pathlib import Path
__version__ = '0.2.1'
TOOL_DIR = Path('~/.proteotools_software').expanduser()
COMET = TOOL_DIR / 'comet' / 'comet.linux.exe'
MSGF = TOOL_DIR / 'msgfplus' / 'MSGFPlus.jar'
TANDEM = TOOL_DIR / 'tandem' / 'bin' / 'static_link_ubuntu' / 'tandem.exe'
TPP = TOOL_DIR / 'tpp' / 'tpp_6-0-0.sif'
THERMO... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-04-17 22:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | python |
from azfs.cli.constants import WELCOME_PROMPT
from click.testing import CliRunner
from azfs.cli import cmd
def test_cmd():
result = CliRunner().invoke(cmd)
# result.stdout
assert result.stdout == f"{WELCOME_PROMPT}\n"
| python |
# -*- coding: utf-8 -*-
__author__ = 'S.I. Mimilakis'
__copyright__ = 'Fraunhofer IDMT'
# imports
import torch
from nn_modules import cls_fe_nnct, cls_basic_conv1ds, cls_fe_sinc, cls_embedder
def build_frontend_model(flag, device='cpu:0', exp_settings={}):
if exp_settings['use_sinc']:
print('--- Buildin... | python |
import collections
import heapq
import json
from typing import List, Optional
from binarytree import Node
def twoSum(nums, target):
compliment_set = collections.defaultdict(int)
for i, number in enumerate(nums):
compliment = target - number
if compliment in compliment_set:
return ... | python |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
import numpy as np
def test(model, imgL,imgR,disp_true):
model.eval()
imgL, imgR, disp_true = imgL.cuda(), imgR.cud... | python |
from datetime import datetime
from config import InputConfig
from .base import BaseDataLoader
from ..market import BaseMarket
from ..renderers import BaseRenderer
class BackTestDataLoader(BaseDataLoader):
def __init__(
self,
market: BaseMarket,
renderer: BaseRenderer,
... | python |
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E07000096"
addresses_name = "2020-02-03T10:27:29.701109/Democracy_Club__07May2020Dacorum.CSV"
stations_name = "2020-02-03T10:27:29.701109/Democracy_Club__07May... | python |
from django.db.models import Q
from .constants import (
STOP_WORDS,
)
from .models import (
WORD_DOCUMENT_JOIN_STRING,
DocumentRecord,
TokenFieldIndex,
)
from .tokens import tokenize_content
def _tokenize_query_string(query_string):
"""
Returns a list of WordDocumentField keys to fetch
... | python |
import torch
import suppixpool_CUDA as spx_gpu
import numpy as np
class SupPixPoolFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, img, spx):
spx = spx.to(torch.int)
K = spx.max()+1
assert(spx.size()[-2:]==img.size()[-2:])
# print(np.all(np.arange(K)==np.uni... | python |
"""Illustrates more advanced features like inheritance, mutability,
and user-supplied constructors.
"""
from simplestruct import Struct, Field
# Default values on fields work exactly like default values for
# constructor arguments. This includes the restriction that
# a non-default argument cannot follow a default a... | python |
def main():
print()
print("Result = ((c + ~d) * b) * ~(d + a * e)")
print()
print_table_header()
for i in reversed(range(0, 2**5)):
print_row(i)
def print_table_header():
print("| a | b | c | d | e | Result |")
print("|-----|-----|-----|-----|-----|---------|")
def pri... | python |
import tifffile
import h5py
import warnings
import os
TIFF_FORMATS = ['.tiff', '.tif']
H5_FORMATS = ['.h5', '.hdf']
LIF_FORMATS = ['.lif']
def read_tiff_voxel_size(file_path):
"""
Implemented based on information found in https://pypi.org/project/tifffile
"""
def _xy_voxel_size(tags, key):
a... | python |
import os,sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.abspath(os.path.join(THIS_DIR, os.pardir))
sys.path.append(ROOT_DIR)
from analysis.pymo.parsers import BVHParser
from analysis.pymo.data import Joint, MocapData
from analysis.pymo.preprocessing import *
from analysis.pymo.viz_tools ... | python |
import argparse
import numpy as np
import os
import matplotlib.pyplot as plt
import PIL.Image as Image
import torch
from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn import decomposition
from scipy.sparse import csr_matrix
import torchvision
import torch.nn as nn
from torchvision import transforms
import... | python |
# -*- coding: utf-8 -*-
#%% Packages
import numpy as np
import os, matplotlib
#matplotlib.use('Agg')
#from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import tensorfl... | python |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 |
import os
import sys
from yaku.scheduler \
import \
run_tasks
from yaku.context \
import \
get_bld, get_cfg
import yaku.tools
def configure(conf):
ctx.load_tool("python_2to3")
def build(ctx):
builder = ctx.builders["python_2to3"]
files = []
for r, ds, fs in os.walk("foo"):
... | python |
from sklearn.ensemble import IsolationForest
class IsolationModel:
"""
Simple Isolation Model based on contamination
"""
def __init__(self, data):
self.normalized_data = (data - data.mean()) / data.std()
self.iso = IsolationForest(contamination=.001, behaviour='new')
self.is... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module with several helper functions
"""
import os
import collections
import re
def file_extensions_get(fname_list):
"""Returns file extensions in list
Args:
fname_list (list): file names, eg ['a.csv','b.csv']
Returns:
list: file exten... | python |
from . import fcn8_resnet, fcn8_vgg16
def get_base(base_name, exp_dict, n_classes):
if base_name == "fcn8_resnet":
model = fcn8_resnet.FCN8()
elif base_name == "fcn8_vgg16":
model = fcn8_vgg16.FCN8_VGG16(n_classes=n_classes)
else:
raise ValueError('%s does not exist' % base_n... | python |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The datastore models for upload tokens and related data."""
from __future__ import absolute_import
import logging
import uuid
from google.appengine.ext i... | python |
import struct
from itertools import permutations
class bref3:
def __init__(self, filename):
self.stream = open(filename, 'rb')
self.snvPerms = list(permutations(['A','C','G','T']))
def readRecords(self):
# read the magic number
if self.read_int() != 2055763188:
rais... | python |
"""Utilities for make the code run both on Python2 and Python3.
"""
import sys
PY2 = sys.version_info[0] == 2
# urljoin
if PY2:
from urlparse import urljoin
else:
from urllib.parse import urljoin
# Dictionary iteration
if PY2:
iterkeys = lambda d: d.iterkeys()
itervalues = lambda d: d.itervalues()
... | python |
#!/usr/bin/env python
#
# Copyright (c) 2021, Djaodjin Inc.
# 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 notice,
# this ... | python |
#!/usr/bin/env python
import codecs
import logging
from pathlib import Path
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from regions import CircleSkyRegion
from gammapy.modeling import Fit
from gammapy.data import DataStore
from gammapy.datasets import (
MapDataset,
)
from... | python |
from __future__ import print_function
import argparse
import os
import random
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
import torchvision.utils as vutils
from torch.autograd import Variable
from model import _net... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=C0103,W0621
"""
Train a text generating LSTM on Slovenian poems and prose
- first train a few epochs on Slovenian poetry and prose (to learn basics of the language) (from <http://lit.ijs.si/>)
- afterwards train at least additional epochs on target texts ... | python |
#!/usr/bin/env python
# coding: utf-8
import os
import torch
import numpy as np
from sklearn.preprocessing import StandardScaler
class QSODataset(torch.utils.data.Dataset):
"""QSO spectra iterator."""
def __init__(self, filepath, partition, wavelength_threshold=1290.,
subsample=1, log_transfo... | python |
from xnemogcm import open_domain_cfg, open_nemo
from xnemogcm.nemo import nemo_preprocess
import os
from pathlib import Path
import xarray as xr
TEST_PATH = Path(os.path.dirname(os.path.abspath(__file__)))
def test_options_for_files():
"""Test options to provide files"""
domcfg = open_domain_cfg(
dat... | python |
"""Unit test package for ipgeo."""
| python |
"""Top-level package for SimpleBBox."""
__author__ = """Sergey Matyunin"""
__email__ = 'serge-m@users.noreply.github.com'
__version__ = '0.0.10'
| python |
import os
import json
import datetime
from performance.driver.core.classes import Reporter
from performance.driver.core.eventfilters import EventFilter
from performance.driver.core.events import StartEvent, ParameterUpdateEvent
class RawReporter(Reporter):
"""
The **Raw Reporter** is creating a raw dump of the r... | python |
# SecretPlots
# Copyright (c) 2019. SecretBiology
#
# Author: Rohit Suratekar
# Organisation: SecretBiology
# Website: https://github.com/secretBiology/SecretPlots
# Licence: MIT License
# Creation: 05/10/19, 7:52 PM
#
# Bar Locations
import numpy as np
from SecretPlots.constants import *
from SecretPlots.man... | python |
#Naive vowel removal.
removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem"
charToRemove = ['a', 'e', 'i', 'o', 'u']
... | python |
#Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
start=1
print("Please input your number")
end=input()
sum=0
while end.isdigit()==False:
print("Your input is not a valid number, please try again")
end=input()
for i in range(start,int(end)+1):
sum=sum+i
print("Sum f... | python |
import os.path
import pathlib
import subprocess
import sys
import urllib
from typing import Dict, List, Optional, Tuple
# Path component is a node in a tree.
# It's the equivalent of a short file/directory name in a file system.
# In our abstraction, it's represented as arbitrary bag of attributes
TestPathComponent = ... | python |
#!/usr/bin/env python2
# 4DML Transformation Utility
#
# (C) 2002-2006 Silas S. Brown (University of Cambridge Computer Laboratory,
# Cambridge, UK, http://ssb22.user.srcf.net )
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | python |
from click.testing import CliRunner
from flag_slurper.cli import cli
from flag_slurper.autolib.models import CredentialBag, Credential
from flag_slurper.conf.project import Project
def test_add_credentials(db):
runner = CliRunner()
result = runner.invoke(cli, ['creds', 'add', 'root', 'cdc'])
assert resul... | python |
import os
from dotenv import dotenv_values
from algofi_amm.v0.client import AlgofiAMMTestnetClient
from ..utils import compiledContract, Account
from algofi_amm.v0.client import AlgofiAMMClient
from algosdk.v2client.algod import AlgodClient
from algosdk.future import transaction
from random import randint
def startup... | python |
import unittest
import sys
from gluon.globals import Request
db = test_db
#execfile("applications/Problematica/controllers/default.py", globals())
class TestClass(unittest.TestCase):
# def setUp(self):
#request = Request() # Use a clean Request object
def test_search(self):
output_id = []
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Adjacency List
# Q4.1 - Route Between Nodes
class AdjacencyList:
def __init__(self, numOfNodes=None):
if numOfNodes is not None and numOfNodes > 0:
self.matrix = [[] for _ in range(numOfNodes)]
self.numOfNodes = numOfNodes
self.matrixVisited = []
self.s... | python |
#!python
"""Django's command-line utility for administrative tasks.
This file was auto generated by the Django toolchain. Type python manage.py
--help to see a list of available commands.
"""
import os
import sys
def main() -> None:
"""manage.py entry point."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',... | python |
#!/usr/bin/env python
import TUI.Base.TestDispatcher
testDispatcher = TUI.Base.TestDispatcher.TestDispatcher("sop", delay=1.5)
tuiModel = testDispatcher.tuiModel
dataList = (
"version=1.4",
'bypassNames=boss, ff_lamp, ffs, gcamera, hgcd_lamp, ne_lamp, uv_lamp, wht_lamp',
'bypassedNames=boss, ne_lamp, wht_... | python |
# Changes to this file by The Tavutil Authors are in the Public Domain.
# See the Tavutil UNLICENSE file for details.
#******************************************************************************\
#* Copyright (c) 2003-2004, Martin Blais
#* All rights reserved.
#*
#* Redistribution and use in source and binary forms... | python |
import io
import math
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Union
import discord
import matplotlib.pyplot as plt
import pandas as pd
import pytz
from blossom_wrapper import BlossomAPI
from dateutil import parser
from discord import Embed, File
from discord... | python |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 co... | python |
import types
from . import base_objs as baseInitObjs
import plato_fit_integrals.core.workflow_coordinator as wflowCoord
class SurfaceEnergiesWorkFlow(wflowCoord.WorkFlowBase):
def __init__(self, surfaceObj, bulkObj):
self.surfObj = surfaceObj
self.bulkObj = bulkObj
self._ensureWorkFoldersAreTheSame()
se... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.