content
stringlengths
5
1.05M
# %% # Imports import pickle import pandas as pd # %% # Define functions def clean_strings(row): """ Accepts a string of comma seprated topic names and converts that into a list. Also removes the extraneous space """ topic_names = row['Topic name'] topic_names = topic_names.replace(', ', ','...
import torch import torch.nn as nn from torchvision.models.alexnet import AlexNet as VisionAlexNet from torchvision.models.alexnet import model_urls import torch.utils.model_zoo as model_zoo __all__ = ['AlexNet', 'alexnet'] class AlexNet(VisionAlexNet): def __init__(self, in_feat=3, num_classes=1000): s...
from stackformation import (Infra, BotoSession, Context) from stackformation.aws.stacks import (vpc, ec2, s3) import mock import pytest @mock.patch("stackformation.boto3.session.Session") def test_boto_session(mock_sess): mock_sess.return_value=True session = BotoSession() assert session.get_conf("regio...
from django.http import HttpResponse import json from pokemon import utilities # Create your views here. def searchPokemonInfoByName(request): try: name = request.GET['name'] if len(name) < 4: response = "The minimum character allowed is 4" else: utilities_pokemon...
import argparse import os from common.parse import parse_problem def get_problem_name(problem): sp = problem.url.split('/') if 'problemset' in problem.url: contest = sp[-2] else: contest = sp[-3] index = sp[-1] problemname = problem.name.split(' ', 1)[1] return "CF_{}{}_{}".fo...
import tensorflow.keras.backend as K def nll_gaussian(y_true, y_pred): """ Negative - log -likelihood for the prediction of a gaussian probability """ mean = y_pred[:,0] sigma = y_pred[:,1] + 1e-6 # adding 1-e6 for numerical stability reasons first = 0.5 * K.log(K.square(sigma)) second =...
import platform import psutil import writer #constant for multi platforming uname = platform.uname() def main(): configure_arr = writer.configure() write_content = checks(configure_arr) writer.write_info(write_content) #checks the ticked boxes def checks(check_arr): content = [] if check_arr[0...
import numpy as np from math import sqrt def manhattan(x,y): x = np.array(x) y = np.array(y) diff = abs(x-y) return diff.sum() def get_intersect(A, B, C, D): cx=0 cy=0 solved=False if( ((C[1] < A[1] and D[1] > B[1]) or (C[1] > A[1] and D[1] < B[1]) ) and ((C[0] > A[0] and D[0] < B[0]) ...
import os import shutil import json from datetime import datetime src = r"C:\Users\jagan\Desktop\BackupSchedler\SRC" dst = r"C:\Users\jagan\Desktop\BackupSchedler\DES" def BackUp(src, dst, file): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) ...
from sketchresponse import sketchresponse from sketchresponse.grader_lib import GradeableFunction from sketchresponse.grader_lib import Asymptote problemconfig = sketchresponse.config({ 'width': 750, 'height': 420, 'xrange': [-3.5, 3.5], 'yrange': [-4.5, 4.5], 'xscale': 'linear', 'yscale': 'lin...
# Custom rate is calculated for unique events in the simulation # Author = Thomas Davis, email = [email protected] / University of Birmingham # This rate calculator has a full implementation of the pair interaction method # for up to second nearest neighbours # Cu and Vacancies clustering works # Only first neighbour h...
import h5py import os.path as osp import numpy as np from tempfile import TemporaryDirectory from testpath import assert_isfile from karabo_data import RunDirectory, H5File def test_write_selected(mock_fxe_raw_run): with TemporaryDirectory() as td: new_file = osp.join(td, 'test.h5') with RunDire...
from math import log import numpy as np import dolfin as df import operator def estimate_from_convergence(y, x): '''Half step estimate''' assert len(x) == len(y) if len(y) >= 2: return -log(y[-1]/float(y[-2]))/log(x[-1]/x[-2]) else: return np.nan def least_square_estimate(y,...
import os import scrapy.settings from ..items import Media from ..services.storage_util import StorageUtil class DirectDownloadSpider(scrapy.Spider): name = "datacollector_direct_download" start_urls = ['https://www.youtube.com'] custom_settings = { "CONCURRENT_ITEMS": "1", "MEDIA_ALLOW...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.testutil.mock_logger import MockLogger as MockLogger # noqa from pants_test.deprecated_testinfra import deprecated_testinfra_module deprecated_testinfra_module('pants.testuti...
# -*- coding: utf-8 -*- # @Time : 2019/1/9 12:46 PM # @Author : Zhixin Piao # @Email : [email protected] import sys sys.path.append('./') import smtplib import time from email.mime.text import MIMEText from email.header import Header from config import mail_host, mail_user, mail_pass def send_emai...
import copy import pytest from tempocli.cli import cli from tempocli.cli import ENVVAR_PREFIX from tests.helpers import write_yaml def test_tempocli(cli_runner): result = cli_runner.invoke(cli) assert result.exit_code == 0 assert 'Usage:' in result.output @pytest.mark.freeze_time('2018-08-05') class T...
# Copyright (c) 2020-2021 NVIDIA CORPORATION & AFFILIATES. 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 r...
import turtle # TODO: Explain superclass and subclass. class DoubleTimeTurtle(turtle.Turtle): def forward(self, distance): turtle.Turtle.forward(self, 2 * distance) def backward(self, distance): turtle.Turtle.backward(self, 2 * distance) class OppositeTurtle(turtle.Turtle): def forward(self, distance):...
#! python3 # pdfParanoia.py - Add password in command line # to every PDF in folder and subfolders. import PyPDF2, os, sys password = sys.argv[1] for foldername, subfolders, filenames in os.walk(os.getcwd()): # Find each PDF after walking through given directory. for filename in filenames: if (filename.endswith...
from __future__ import absolute_import, division, print_function from odo.append import append def test_append_list(): L = [1, 2, 3] append(L, [4, 5, 6]) assert L == [1, 2, 3, 4, 5, 6] def test_append_list_to_set(): s = set([1, 2, 3]) append(s, [4, 5, 6]) assert s == set([1, 2, 3, 4, 5, 6]) ...
# -*- coding: utf-8 -*- from functools import wraps def remove_empty_params_from_request(exclude=None): """ ENG: Remove empty query params from request RUS: Удаляет пустые параметры из запроса """ if exclude is None: exclude = [] def remove_empty_params_from_request_decorator(func): ...
import ast import requests from bs4 import BeautifulSoup from .objMusic import Music class Album: """This object represents a RadioJvan album. Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their :attr:`url` is equal. .. versionadded:: ...
# # file: final_program_distance.py # # RTK, 28-Jan-2021 # Last update: 28-Jan-2021 # ################################################################ import numpy as np import editdistance prg = [i[:-1] for i in open("runs_10.txt")] dist = [] for i in range(len(prg)): for j in range(len(prg)): if (i...
from kivymd.uix.dialog import MDDialog from kivymd.uix.button import MDFlatButton from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivymd.uix.list import ThreeLineListItem from kivy_garden.graph import Graph, MeshLinePlot from kivymd.uix.label import MDLabel class InfoDialog(MDDialog): "...
import tweepy import random from config import create_api, logger RESPONSES = ["Iewl", "Huuuuu", "Brrrrr", "Vies hè", "Gedverderrie", "Blèh"] RANDOM_INTERVAL = 5 class HutsbotStreamListener(tweepy.StreamListener): """ Listens to incoming tweets containing the word 'hutspot' and quotes them """ ...
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
# coding: utf-8 import ctypes from objc_util import c, ObjCInstance import matrix4 import matrix3 import matrix2 import vector3 import vector4 def CFAllocatorGetDefault(): func = c.CFAllocatorGetDefault func.argtypes = None func.restype = ctypes.c_void_p return ObjCInstance(func()) def GLKMatrixStackCreate...
import csv import os import rpy2.robjects as robjects # R integration from rpy2.robjects.packages import importr # import the importr package from R #from orm.glmcoefficients import * # to store the glm coefficients #from db import * # postgresql db information import math from commit_guru.caslogging import logging cl...
import pytest pytest.importorskip('olm') # noqa from matrix_client.crypto.encrypt_attachments import (encrypt_attachment, decrypt_attachment) def test_encrypt_decrypt(): message = b'test' ciphertext, info = encrypt_attachment(message) assert decrypt_a...
# -*- coding: utf-8 -*- """ hss_app.milenage ~~~~~~~~~~~~~~~~ This module implements the Milenage algo set as per 3GPP TS 35.206 V9.0.0 (2009-12). """ import hmac import random from collections import namedtuple from Crypto.Cipher import AES AMF_DEFAULT_VALUE = bytes.fromhex("8000") INITIALIZATION_...
"""Implementation of the workflow for demultiplexing sequencing directories.""" import collections import csv import glob import gzip import itertools import json import logging import os import shutil import subprocess import sys from threading import Thread, Lock import tempfile import xml.etree.ElementTree as ET f...
# -*- coding: utf-8 -*- """ :Author: Jaekyoung Kim :Date: 2017. 11. 21. """ import matplotlib.pyplot as plt from statistics.statistic_calculator import get_stats_results from clustering.k_means import get_highest_volatility_group from data.data_reader import get_market_capitalization_sum def show_window_k_scatter(wi...
# -*- coding: utf-8 -*- from filebrowser.sites import site as filebrowser_site urlpatterns = patterns('', url(r'^admin/filebrowser/', include(filebrowser_site.urls)), ) + urlpatterns
# Generated by Django 2.0.1 on 2018-03-15 08:19 from django.db import migrations, models import posts.models class Migration(migrations.Migration): dependencies = [ ('posts', '0004_auto_20180315_1343'), ] operations = [ migrations.AlterField( model_name='post', n...
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 20:12:07 2020 @author: DS """ """ Example of WebScrapping using python """ from pytube import YouTube import bs4 import requests playlist=[] url=input("Enter the Youtube Playlist URL : ") #Takes the Playlist Link try: data = requests.get(url) except: print("...
import time import os from multiprocessing import Process from gtmcore.configuration import Configuration from gtmcore.files.lock import FileWriteLock from gtmcore.fixtures import mock_config_file def write_function(filename: str, delay: int, value: str, lock: FileWriteLock) -> None: """ A test function that...
import requests class Mailgun: MAILGUN_DOMAIN = '' MAILGUN_API_KEY = '' FROM_NAME = '' FROM_EMAIL = '' @classmethod def send(cls, to_emails, subject, content): requests.post("https://api.mailgun.net/v3/{}/messages".format(cls.MAILGUN_DOMAIN), auth=("api", cls.MAIL...
from source.db_models.bets_models import * from source.db_models.nhl_models import * from datetime import date, datetime, timedelta from sqlalchemy import func, and_, or_, not_, asc, desc import pandas as pd import sqlalchemy from sqlalchemy import select from sqlalchemy.orm import aliased from tqdm import tqdm from so...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "[email protected]" import copy import struct import sys from io import BytesIO """兼容性处理""" try: from itertools import izip compat_izip = izip except ImportError: compat_izip = zip if sys.version_info < (3,): def iteritems(...
# coding=utf-8 # Name: eva vanatta # Date: july 11th 2018 #index - starts with 0 in an index # slice of list # print var[0:3] # all but first # print var [1:] # all but the last # print var [:-1] # replace #var[0] = "tree" # loop # for var in list: # print item # to change # counter = 0 ...
# Copyright 2016-2018 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # # or in the "license" f...
#!/usr/bin/python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # 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...
## strobpy\strobopy '''Function to load dm3s and get their meta_data ''' def load_dm3(filename,get_meta=False, stack=False): import numpy as np from pycroscopy.io.translators.df_utils.dm_utils import read_dm3 '''Loads a single dm3 into a numpy array. If get_meta=True gets all corresponding metadata aswell ...
from typing import Dict, List import torch from torch.autograd import Variable from torch.nn.functional import nll_loss from torch.nn.functional import softmax import numpy as np from allennlp.common import Params from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules impo...
from PySide import QtCore, QtGui # https://qt.gitorious.org/pyside/pyside-examples/source/060dca8e4b82f301dfb33a7182767eaf8ad3d024:examples/richtext/syntaxhighlighter.py class Highlighter(QtGui.QSyntaxHighlighter): '''Perform simple syntax highlighting by subclassing the QSyntaxHighlighter class and descri...
from django.forms import * from django.forms.models import BaseModelFormSet from django.forms.models import BaseInlineFormSet from django.forms.models import ModelChoiceIterator from django.forms.models import InlineForeignKeyField from django.utils.text import capfirst from .formsets import BaseFormSet from django....
from __future__ import absolute_import from django.utils import timezone from celery.schedules import crontab from celery.task import periodic_task from .models import Grantee @periodic_task(run_every=crontab()) def publish_grantees(): Grantee.objects.filter(status=Grantee.STATUS_READY_FOR_PUBLISH, published_a...
#!/usr/bin/python3 ''' Abstract: This is a program to exercise what I learned in CH2. Usage: 20180329_CH2_3_cheating_among_students.py Editor: Jacob975 concept: Privacy algorithm assume interviewer didn't know how many fliping you do. Head or tails for each flip. flip coin -> heads ->...
from framework.utils.common_utils import by_css from pages.page import Page from tests.testsettings import UI_TEST_TIMEOUT CANCEL_LINK = by_css('div.ui-dialog[style*="block"] > div.ui-dialog-content > div > a.no_button') CONFIRM_LINK = by_css('div.ui-dialog[style*="block"] > div.ui-dialog-content > div > a.yes_button'...
from cnddh import app from cnddh.utils import template_checa_permissao from sqlalchemy import func import locale from config import TIMEZONE, LOCALE, EMAIL_LOGIN @app.context_processor def inject_functions(): return dict( checa_permissao = template_checa_permissao ) @app.template...
from datasets.avmnist.get_data import get_dataloader import torch.autograd as A import torch.nn.functional as F import torch.nn as nn import torch from unimodals.common_models import GlobalPooling2D import sys import os sys.path.append(os.getcwd()) # %% class GP_LeNet(nn.Module): def __init__(self, args, in_chan...
import numpy as np from wssnet.Network.TrainerController import TrainerController from wssnet.Network.CsvInputHandler import CsvInputHandler import config def load_indexes(index_file): """ Load patch index file (csv). This is the file that is used to load the patches based on x,y,z index """ indexe...
weight=4 _instances=2 p=[100,300] def run(): # not necessary but useful for visualising on gui r.conf_set('send_status_interval', 10) r.conf_set('accel', 500) # robot accelerates to given speed 100 for 500ms r.conf_set('alpha', 500) # robot accelerates (rotation) to given speed 100 for 500ms r.speed(100) # nat...
salar = float(input('Qual o seu salario? ')) if salar >= 1250: aumen = 10 salar = salar + (salar * 0.10) else: aumen = 15 salar = salar + (salar * 0.15) print('Seu salario com o aumento de {}% agora fica {} reais'.format(aumen, salar))
class TestLine: def test_size(self, line): assert line.size == 5 def test_end_offset(self, line): assert line.end_offset == 5 def test_text(self, line): assert line.text == "aaaaa" def test_offset_in_file(self, line): assert line.offset_in_file == 0
import os import cv2 import json import numpy as np import torch import matplotlib.pyplot as plt from tqdm import tqdm from config import system_configs from utils import crop_image, normalize_ from external.nms import soft_nms, soft_nms_merge import sys sys.path.append("../../") ...
# -*- coding: utf-8 -*- # Copyright (c) 2019 Pavel 'Blane' Tuchin from __future__ import unicode_literals import json import six from . import generation from . import utils RES_DEFS = generation.DEFAULT_RESOURCE_DEFS_FILE_NAME TYPE_DEFS = generation.DEFAULT_TYPE_DEFS_FILE_NAME def defs_from_generated(resources_fil...
from sklearn.naive_bayes import MultinomialNB from sklearn.svm import SVC def SVC_model(c_index, dataset_target): svc_model = SVC(kernel='linear',C=1.0).fit(c_index, dataset_target) return svc_model """ subistituir SVC""" def prediction(model, tranf_dtest, dataset_test): predicted = model.predict(tranf_dte...
import enum import numpy as np from scipy import interpolate from matplotlib import pyplot as plt class ContrastLandscape(enum.Flag): FIXED = 0 RANDOM_PATH = enum.auto() RANDOM_BACKGROUND = enum.auto() SHARED_RANDOM = enum.auto() def gabor_kernel(size, scale, wavelength, phase, orientation): ...
#!/usr/bin/env python3 # || ---------- test_entry.py ---------- || # Tests for entry.py # # Ben Carpenter and Nancy Onyimah # April 24, 2022 # ------------- test_entry.py ------------- from datetime import datetime from entry import Entry import crypto def test_construction(): """ Test that: 1. Clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- # (C) 2010 Alan Franzoni. # # Commandline integration for property mapping. class CommandLinePropertyParser(object): def parse(self, arglist): return [ arg[3:] for arg in arglist if arg.startswith("-PD") ]
from urllib.request import urlopen from bs4 import BeautifulSoup def extract_top40_songs(url): with urlopen(url) as f: html = f.read() soup = BeautifulSoup(html, "lxml") song_divs = soup.findAll(attrs={'class': 'song-details'}) songs = [] for song_div in song_divs: title_elem = ...
#!/usr/bin/env python import sys from app import create_app from app.models import Role def main(app=create_app()): with app.app_context(): Role.insert_roles() print 'Added roles' if __name__ == '__main__': sys.exit(main())
import numpy as np import tensorflow as tf import os from tqdm import tqdm from tensorflow.keras import datasets from tensorflow.keras.losses import Loss from tensorflow.keras.layers import Layer from tensorflow.keras import backend as K from tensorflow.python.keras.utils.vis_utils import plot_model """ Center loss: ...
from prob_13 import prob_13 n = int(input("Ingrese un numero: ")) print (prob_13(n))
#!/usr/bin/env python """ Centrality measures of Krackhardt social network. """ # Author: Aric Hagberg ([email protected]) # Date: 2005-05-12 14:33:11 -0600 (Thu, 12 May 2005) # Revision: 998 # Copyright (C) 2004-2016 by # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <sw...
"""List package presets.""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers import ordering COLUMNS = ['name', 'keyName', 'description', ] @click.command() @click.argument('package_k...
import numpy.random as random from scipy.stats import truncnorm SAMPLES = 200 def truncated_normal(mean=0, sd=1, low=0, upp=10, samples=SAMPLES): a, b = (low - mean) / sd, (upp - mean) / sd return truncnorm(a, b, loc=mean, scale=sd).rvs(samples) # fn_map = {"uniform": random.uniform, "normal": truncated_no...
import requests, base64, json, hashlib from Crypto.Cipher import AES def push_server_chan(logs): if sckey is None or sckey == "": print("跳过推送") return params = { 'text': "网易云音乐自动脚本", 'desp': logs } serverURL = "https://sc.ftqq.com/" + sckey + ".send" response = requ...
# coding: utf8 """ ################################ assertion schema ################################ schema = int schema = lambda v: v in [0, 1] schema = (int, float, str) # OR schema = (int, float, str, type(None)) # can be `null` (i.e. `None` in python) schema = (int, floa...
import cPickle import sys from moduleUsefulFunctions_20180215 import * from random import randint import subprocess def returnNumberMutations(alignInfoList): numberMutations=0 for eachEl in alignInfoList: if eachEl.typeOfEvent=='Start': startPosition=eachEl.position elif eachEl.type...
# coding=utf-8 from matplotlib import pyplot as plt from matplotlib import font_manager a=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- PIXEL_ON = '#' PIXEL_OFF = '.' GROWTH_PER_ITERATION = 3 ITERATIONS_PART_ONE = 2 ITERATIONS_PART_TWO = 50 def filter_to_integer(image, x, y, default_value): # The image enhancement algorithm describes how to enhance an image by simultaneously # converting all pixels i...
from selenium import webdriver from selenium.webdriver.chrome.options import Options def create_driver(): chrome_options = Options() chrome_options.add_argument("--headless") # create a new chrome session driver = webdriver.Chrome(options=chrome_options) driver.implicitly_wait(19) return driver...
# this code will help importing strategies from external files # which isn't very easy in Python for some reason import imp # import strategy module from the given path def import_strategy(module_name, full_path): return imp.load_source(module_name, full_path)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r""" This module provides an implementation of the *Extremal Perturbations* (EP) method of [EP]_ for saliency visualization. The interface is given by the :func:`extremal_perturbation` function: .. literalinclude:: ../examples/extremal_perturbati...
from node.base import AttributedNode from node.behaviors import Events from node.events import EventAttribute from node.events import EventDispatcher from node.events import suppress_events from node.events import UnknownEvent from node.interfaces import IEvents from node.utils import UNSET from plumber import Behavior...
""" Basic data structure used for general trading function in VN Trader. """ from dataclasses import dataclass from datetime import datetime from logging import INFO from .constant import Direction, Exchange, Interval, Offset, Status, Product, OptionType, OrderType ACTIVE_STATUSES = set([Status.SUBMITTING, Status.NO...
####################################################### # # https://firebase.google.com/docs/firestore/quickstart # ####################################################### ################################################### import firebase_admin from firebase_admin import credentials from firebase_admin import firest...
# Perfect maze (tree) in a 70x70 grid # Nodes: 806 # Edges: 805 adjList = [ [19, 1], [23, 2, 0], [29, 1], [30, 4], [24, 3], [18, 6], [27, 5], [8], [26, 9, 7], [34, 10, 8], [53, 9], [54, 12], [11], [36, 14], [37, 13], [38, 16], [39, 15], [18], [4...
import pafy url = "https://www.youtube.com/watch?v=OE7wUUpJw6I&list=PL2_aWCzGMAwLPEZrZIcNEq9ukGWPfLT4A" video = pafy.new(url) print(video.title) stream=pafy.new(url).streams best=video.getbest() for i in stream: print(i) print(best.resolution,best.extension) print(best.url) best.download(quiet=False)
import socket UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) listen_addr = ("", 3386) UDPSock.bind(listen_addr) server_ip = None client_ip = None server_ports = {} client_ports = {} while True: data, addr = UDPSock.recvfrom(1024) data = str(data, encoding = "utf-8") ip_type, attr = data.split(...
# # Copyright 2018 Joachim Lusiardi # # 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...
from rest_framework import response from .utils import checkotp, createjwt, createotp, emailbody from rest_framework.response import Response from django.http import HttpResponse from rest_framework.views import APIView from .mongo import database_entry from .backends import CustomPerms from rest_framework import statu...
from codes.a_config._rl_parameters.on_policy.parameter_ppo import PARAMETERS_PPO from codes.e_utils.names import * from codes.a_config.parameters_general import PARAMETERS_GENERAL class PARAMETERS_LUNAR_LANDER_PPO(PARAMETERS_GENERAL, PARAMETERS_PPO): ENVIRONMENT_ID = EnvironmentName.LUNAR_LANDER_V2 DEEP_LEARN...
#!/usr/bin/env python from distutils.core import setup setup(name='celestial-client', version='0.1', description='Python client for www.celestial-automl.com', author='Lars Hertel', author_email='[email protected]', url='https://github.com/LarsHH/celestial-client', project_url...
import discord import asyncio import random import steam from steam.steamid import SteamId from steam.steamprofile import SteamProfile from steam.steamaccountuniverse import SteamAccountUniverse from steam.steamaccounttype import SteamAccountType from discord.ext import commands from utils import checks from mods.cog i...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud 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, merge, p...
#!/usr/bin/env python """ RS 2018/02/23: Digesting Obsidian Output Plots we want to see: Trace plots of key parameters like layer depths, rock properties Histograms of residuals between forward model values and data Contour maps of residuals between forward models and data """ import numpy as np import ...
# Copyright (c) 2013 MetaMetrics, Inc. # # 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, merge, publish, d...
import json from sequana import sequana_data from sequana.modules_report.summary import SummaryModule from sequana.utils import config def test_summary_module(tmpdir): directory = tmpdir.mkdir('test_variant_calling_module') config.output_dir = str(directory) config.sample_name = 'JB409847' summary_di...
""" Determine if the given number is a power of two. Example For n = 64, the output should be isPowerOfTwo(n) = true; For n = 5, the output should be isPowerOfTwo(n) = false. """ def isPowerOfTwo(n): while n % 2 == 0: n >>= 1 if n == 1: return True return False
# webhook test file to test webhook for live stats project
import unittest from tools37.tkfw.evaluable import EvaluableDictItem, EvaluableListItem, EvaluablePath class TestEvaluableDictItem(unittest.TestCase): def test_method_evaluate(self): # on missing key self.assertRaises(KeyError, EvaluableDictItem("key").evaluate, {}) # on wrong data type ...
import sys import textwrap import pytask import pytest from _pytask.mark import MarkGenerator from pytask import cli from pytask import main @pytest.mark.unit @pytest.mark.parametrize("attribute", ["hookimpl", "mark"]) def test_mark_exists_in_pytask_namespace(attribute): assert attribute in sys.modules["pytask"]...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Parse Maven POM file. """ import logging import os from xml.etree.ElementTree import parse from pyschool.cmdline import parse_args class InvalidArtifact(Exception): pass class Artifact(object): NAMESPACE = "http://maven.apache.org/POM/4.0.0" DEFAULT_G...
import ac import acsys import os import sys import platform import math # Import Assetto Corsa shared memory library. # It has a dependency on ctypes, which is not included in AC python version. # Point to correct ctypes module based on platform architecture. # First, get directory of the app, then add correct folder...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: __init__.py # # Copyright 2018 Costas Tyfoxylos # # 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...
""" This module provides errors/exceptions and warnings of general use for SunPy. Exceptions that are specific to a given package should **not** be here, but rather in the particular package. """ import warnings __all__ = ["NoMapsInFileError", "SunpyWarning", "SunpyUserWarning", "SunpyDeprecationWarning", ...