content stringlengths 5 1.05M |
|---|
from django.urls import path
from onetimesecret.views import CreateSecret
from onetimesecret.views import ShowSharingInstructions
from onetimesecret.views import ViewSecret
urlpatterns = [
path("", CreateSecret.as_view(), name="home"),
path(
"private/<str:key>/<uuid:uuid>/",
ShowSharingInstruc... |
import serial
import re
import time
from msvcrt import getch
# user parameters - please adjust this block to your settings
############################################################################
serialPort = 'COM5' # the serial port name to the Printer
papertickness = 0.1 # the thickness of the messure ob... |
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from .signForm import UserForm, LoginForm
from .models import PubKeyWithServer
import hashlib
def index(request):
return render(request, 'secureChat/index.html', {})
def ro... |
# -*- coding: utf-8 -*-
from streck import app
from flask import render_template
import streck.controller.user
import streck.controller.product
import streck.controller.transaction
import streck.controller.admin
import streck.controller.stats
@app.route('/')
def index():
return render_template('index.html')
@app.rou... |
from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return 'Hello World!'
app.run(port=6010)
|
# from . import syntheticControl |
from plenum.common.messages.node_messages import Commit
from plenum.common.types import f
from plenum.common.util import compare_3PC_keys
from plenum.server.replica_validator_enums import DISCARD, INCORRECT_INSTANCE, PROCESS, ALREADY_ORDERED, FUTURE_VIEW, \
GREATER_PREP_CERT, OLD_VIEW, CATCHING_UP, OUTSIDE_WATERMAR... |
#!/usr/bin/env python
# coding=utf-8
# Copyright © 2016 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>
#
# 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.a... |
#!/usr/bin/python -tt
import sys
import numpy
import scipy
import random
import matplotlib
import matplotlib.pyplot as plt
def uniformDist(length_sec, fs):
print 'uniform distribution chosen (%d %d)' % ( length_sec, fs )
nsamp = fs*length_sec
return numpy.random.uniform(0,fs/2,nsamp)
def gaussDist(length_sec, fs... |
import numpy as np
import time
"""
list operation 4.133939743041992e-06
np2list operation 3.3020973205566406e-07
numpy operation 0.002478501796722412
"""
list1 = []
list2 = [i for i in range(1024)]
nlist1 = np.array([])
nlist2 = np.array([i for i in range(1024)])
counter = 1000
st = time.time()
for _ in range(co... |
# a project by nicole l'huillier + aarón montoya-moraga
# october 2020
# import Python modules
import os
import pathlib
import datetime
import time
# import Python modules
import vlc
mediaPlayer = vlc.MediaPlayer()
# folder to work with
myFolder = "myFolder/"
# time interval between repetitions,... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User
class UserAdmin(BaseUserAdmin):
fieldsets = BaseUserAdmin.fieldsets + (('Contact info', {'fields': ('phone_number', 'address')}),)
admin.site.register(User, UserAdmin)
|
import pytest
import pandas as pd
from GaiaCurves import gaia_lightcurve
def test_gaia_id():
"""
Unit test to evaluates the correctness of the gaia_id() function
"""
fetched_id = gaia_lightcurve.gaia_id('NQ Dra')
assert fetched_id == '2154100169676165120', 'Incorrect ID returned for \
NQ ... |
import os
import factsbeach
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = []
with open('requirements.txt') as f:
requires = f.read().splitlin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Christof Schöch, 2016-2019.
"""
Script to save settings and parameters to disk for documentation.
Each time coleto is run, a timestamped file is created with this information.
The purpose is to document, for any results, the parameters used.
Part of coleto, s... |
def detect_capital_use(word: str):
if word.islower() or word.isupper():
return True
if word[0].islower() or word[0].isupper():
return True if word[1:].islower() else False
def detect_capital_use_simplify(word: str):
return word.islower() or word.isupper() or (word[0].isupper() and word[1:]... |
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from django.contrib.auth import views
from apps.core.views import frontpage, gatos, products, dashboard, allergens, ordered_product... |
#!/usr/bin/env python
"""Various methods reused in main scripts"""
import sys, os, subprocess, struct, numpy, math, multiprocessing
PC_FILE_FORMATS = ['las','laz']
OCTTREE_NODE_NUM_CHILDREN = 8
DB_NAME = 'pc_extents'
DB_TABLE_RAW = 'extent_raw'
DB_TABLE_POTREE = 'extent_potree'
DB_TABLE_POTREE_DIST = 'potree_dist'
d... |
import tensorflow as tf
import tensorflow_model_analysis as tfma
from ltfx.common import get_raw_feature_spec
def _eval_input_receiver_fn(transform_output, schema, image_key, label_key):
feature_spec = get_raw_feature_spec(schema)
serialized_tf_example = tf.compat.v1.placeholder(dtype=tf.string, shape=[None... |
import math
def fibonacci_sphere(samples):
"""
:param samples: nr o fample points
:return: a list of points [[x,y,z]] of even spaced point on the surface of a sphere
"""
points = []
phi = math.pi * (3. - math.sqrt(5.)) # golden angle in radians
for i in range(samples):
y = 1 - ... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import LogLocator
import importlib
import scipy.io
import sys
if not '../aux/' in sys.path: sys.path.append('../aux/')
import paths; importlib.relo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 22.01.20
@author: felix
"""
NORMALIZE = False
class EasyDict(dict):
def __init__(self, *args, **kwargs):
global NORMALIZE
NORMALIZE = kwargs.pop('normalize', False)
super(EasyDict, self).__init__(*args, **kwargs)
def __get... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-13 02:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('characters', '0011_character_death'),
(... |
import lurkbotclass
import joinlist
import sys
bots = {}
thename = sys.argv[1]
def gobots(name):
global bots
bots[name] = lurkbotclass.LurkBot(name)
bots[name].ircJoin(name)
gobots(thename)
|
import torch
import torch.nn.functional as F
class SimilarityAttention(torch.nn.Module):
"""
A general attention module based on similarity w.r.t. another vector
"""
def __init__(self):
super(SimilarityAttention, self).__init__()
def forward(self, wrt_vector, candidate_vector):
"... |
# ----------------------------------------------------------------------------
# Copyright 2019-2021 Pelion
#
# SPDX-License-Identifier: Apache-2.0
#
# 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 Licens... |
from __future__ import absolute_import, unicode_literals
from unittest import TestCase
from django.test import Client
from mock import Mock
from eb_sqs import settings
from eb_sqs.worker.worker import Worker
from eb_sqs.worker.worker_exceptions import InvalidMessageFormatException, ExecutionFailedException
from eb_s... |
"""
The MIT License (MIT)
Copyright (c) 2015 Guillermo Romero Franco (AKA Gato)
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... |
def get_recognised_device(request):
device_override = request.session.get('device_override', None)
if device_override:
device = device_override
else:
device = request.META.get('HTTP_X_UA_BRAND_NAME', 'Other')
return {
'nokia': {
'name': device,
'template'... |
import subprocess
import json
import sys
DAO_ADDRESS = ''
NWK = 'main'
#se
#dev
if NWK in ['main', 'dev']:
SIGNER = 'prod_signer'
CLAIMERS_FILENAME = 'claimers01012022.json'
else:
SIGNER = 'norton'
CLAIMERS_FILENAME = 'claimers.test.json'
# Don't forget to clean existing claimers
# After running the ... |
from __future__ import absolute_import
from nose.tools import *
from payoneer_escrow_sdk.authenticator import Authenticator
def setup():
pass
def teardown():
pass
def test_secure_headers():
"""
Verify that secure_headers has the right keys and (certain) values.
We will test the value of the r... |
from tkinter import *
from robodk.robolink import *
import tkinter
import threading
# Create a new window
window = tkinter.Tk()
# Close the window
def onClose():
window.destroy()
quit(0)
# Trigger Select button
# IMPORTANT: We need to run the action on a separate thread because
# (otherwise, if we want to ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 27 17:39:36 2021
@author: seama
"""
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions import Categorical
from torch.distributions.mixture_same_family import Mixt... |
"""Convert CSV file into usable PostgreSQL database on Elephant SQL."""
import sqlite3
import psycopg2
import pandas as pd
from dotenv import load_dotenv
import os
# Load .env file
load_dotenv()
# Create postgres connection
pg_conn = psycopg2.connect(
dbname=os.getenv("DBNAME"), user=os.getenv("USER"),
passwo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytest import approx
from onion.area import calculate
__author__ = "Will Usher"
__copyright__ = "Will Usher"
__license__ = "mit"
def test_population_density():
population = 250000
dwellings = 100000
radius = 5 # km
actual = calculate(population, d... |
# -*- coding: utf-8 -*-
from django import forms
from cadastro.models import Usuario
from .models import *
class FormEquipamento(forms.ModelForm):
class Meta:
model = Equipamento
fields = ['codigo', 'nome', 'descricao']
class FormServico(forms.ModelForm):
def __init__(self,*args,**kwargs):
super (FormServic... |
from bot_main.text_to_speech import talk
from bot_main.GUI import gui
from bot_main.take_command import command
import nltk
from PyDictionary import PyDictionary
from pyNewsApi import PYNEWS
import requests
import webbrowser
import validators
import json
import wolframalpha
from mathparse import mathparse
def get_ste... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-28 03:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portal', '0002_auto_20170621_1519'),
]
operations = [
migrations.AddField(
... |
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
... |
from pypy.tool.tb_server.server import TBRequestHandler
import py
html = py.xml.html
import traceback
import cgi
import urllib
views = TBRequestHandler.views
class URL(object):
attrs='scm','netloc','path','params','query','fragment'
attrindex = dict(zip(attrs, range(len(attrs))))
# XXX authentication p... |
#!/usr/bin/python
# coding: utf8
import os, urllib, hmac, binascii, base64, hashlib, urllib2, json, pprint, simplejson, sys, time, csv
import MySQLdb
from optparse import OptionParser
import codecs
from warnings import filterwarnings
filterwarnings('ignore', category = MySQLdb.Warning)
host = ''
user = ''
password =... |
# coding=utf-8
import numpy as np
import random
import task_a
import utils
# Set seed
np.random.seed(8)
random.seed(8)
_SAVE_MODEL = False
def main():
best_mod, best_mod_feats = task_a.model_selection_and_evaluation()
if _SAVE_MODEL:
utils.save_model(best_mod, 'best_model.pkl')
if __name__ == '__... |
from pyparams import PyParam
import numpy as np
def matmul(matrix: np.ndarray, x: np.ndarray) -> np.ndarray:
"""matrix multiplication with magic"""
offset: float = PyParam(1.0, float, "matmul")
alpha: float = PyParam(1.0, float, "matmul")
return alpha * matrix @ x + offset
|
# -*- coding: utf-8 -*-
import json
import logging
import string
import jsonschema
from rest_framework import serializers
from .models import MapFunction, MapResult, ReduceFunction, Response, Survey, Attachment
logger = logging.getLogger(__name__)
# Note: a combinations of JSONB in postgres and json parsing gives... |
from __future__ import absolute_import, print_function, unicode_literals
from wolframclient.deserializers.wxf.wxfconsumer import WXFConsumerNumpy
from wolframclient.deserializers.wxf.wxfparser import WXFParser
from wolframclient.exception import WolframParserException
__all__ = ["binary_deserialize"]
def binary_des... |
from setuptools import setup
APP = ['Main.py']
setup(
app = APP,
setup_requires=['py2app'],
) |
import json
import logging
from enum import Enum
import re
import requests
import urllib3
from kube_hunter.conf import get_config
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event, K8sVersionDisclosure
from kube_hunter.core.types import (
Hunter,
Active... |
import fnmatch
import os
import re
import codecs
import sys
try:
import colorama
colorama.init()
def print_error(mess, **kwargs):
print(colorama.Fore.RED + colorama.Style.BRIGHT + mess + colorama.Style.RESET_ALL, **kwargs)
def print_warn(mess, **kwargs):
print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + m... |
import factory
from factory.django import DjangoModelFactory
from users.models import BasicUser, HostProfile, ClientProfile
class UserFactory(DjangoModelFactory):
class Meta:
model = BasicUser
username = factory.Sequence(lambda n: 'user%d' % n)
class HostFactory(DjangoModelFactory):
class Meta:... |
__doc__ = """This subpackage is designed for providing essential modules,
classes, functions that ``felapps`` needs to accomplish various different
tasks, basically all the modules are grouped by the type of the task.
"""
|
import xarray as xr
import numpy as np
import numpy.ma as ma
import matplotlib as plt
import matplotlib.pyplot as plt
import os
import cftime
import nc_time_axis
import numpy.matlib
from season_util import season_mean
from wgt_areaave import wgt_areaave as wa
def nino34(ds,var,seas):
"""
calculates Nino 3... |
import threading
import time
import logging
_LOGGER = logging.getLogger(__name__)
class StateManager(threading.Thread):
def __init__(self, fordpass, scan_interval, vehicles):
super().__init__()
self._fordpass = fordpass
self._interval = scan_interval
self._vehicles = v... |
#!/usr/bin/env python3
from threading import Timer
from datetime import datetime
import subprocess
import os
import sys
sys.path.append("../lib/")
import json
import json_parser
import pos
import pos_util
import cli
import pos_constant
import time
POS_ROOT = '../../../'
ARRAYNAME = "POSArray"
LOG_PATH = "rebuild_perf... |
from django.shortcuts import render,HttpResponseRedirect
from django.views.decorators import csrf
import time
def Logout(request):
response = render(request,'logout.html')
response.delete_cookie('token')
response.delete_cookie('editFormSelect')
response.set_cookie('time',str(time.time()))
return response |
# TODO: factor this out into separate class
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import create_pairwise_bilateral, create_pairwise_gaussian
from abc import ABC, abstractmethod
import numpy as np
from typing import *
from supermariopy import imageutils
# TODO: add unary from Guided Filtering (Colli... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
"""
- Application Factory
Documentação dos testes: https://fastapi.tiangolo.com/tutorial/testing/?h=testing
requests do client: https://docs.python-requests.org/en/master/
"""
from app import create_app
from app.database import Base, User
from fastapi.testclient import TestClient
from pytest import fixture
from sqlalc... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Osyris contributors (https://github.com/nvaytet/osyris)
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
import numpy as np
from .. import config
from ..core import Array
from pint.quantity import Quantity
def quiver(ax, x,... |
# Fern Zapata
# https://github.com/fernzi/dotfiles
# Qtile Window Manager - Key/mouse bindings
from libqtile.config import Click, Drag, Key, KeyChord
from libqtile.lazy import lazy
import settings
from util import audio
from util import mpc
from util import screenshot
from util import task
from util import window as ... |
import numpy as np
class MatMul:
def __init__(self, name, layers_dict):
self.params = layers_dict[name]
self.name = name
self.type = self.params["op"]
self.transpose_a = self.params["transpose_a"]
self.transpose_b = self.params["transpose_b"]
# shape为4维tensor,各参数含... |
"""
All data-processing code methods for images, including profile extraction and masking procedures.
"""
from tqdm import tqdm
from astropy.table import Table
from astropy.convolution import Gaussian2DKernel
from astropy.stats import gaussian_fwhm_to_sigma, sigma_clipped_stats
from numpy import copy, ndarray, floor, ... |
import neovim
import json
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
@neovim.plugin
class Main(object):
def __init__(self, vim):
self.vim = vim
def makeErrLine(self, buf, err):
name = buf.name
line = err['line']
col = err['column']
... |
import json
import torch
import torch.nn as nn
import tensorflow as tf
from .net import GPT_2
__all__ = ['load_trained_model_from_checkpoint']
def weight_loader(checkpoint_path):
def _loader(name, transpose=False):
weight = torch.from_numpy(tf.train.load_variable(checkpoint_path, name)).type(torch.get_d... |
import autobahn.wamp # noqa
|
# -*- coding: utf-8 -*-
# Copyright 2017 FUJITSU LIMITED
# 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... |
#! /usr/bin/env python3.6
# -*- coding: utf-8 -*-
import argparse
import os
from termcolor import colored
all_dir_count = 0
all_file_count = 0
end_hail = []
def list_me_dir_file(ls, path):
dirs = []
files = []
for x in ls:
if os.path.isdir(path + "/" + x):
dirs.append(x)
if ... |
import logging
from dbnd._core.constants import TaskRunState
from dbnd_luigi.luigi_postgres import (
handle_postgres_histogram_logging,
should_log_pg_histogram,
)
from dbnd_luigi.luigi_run_manager import LuigiRunManager
logger = logging.getLogger(__name__)
class LuigiEventsHandler:
def __init__(self):
... |
import discord
from discord.ext import commands
from cogs.core.defaults.defaults_embed import get_embed_footer, get_embed_thumbnail
from config import DEFAULT_EMBEDCOLOUR
class on_dm_message(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_dm_message(s... |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import render,redirect
from django.core.exceptions import ValidationError
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
... |
from django.db import models
class Events(models.Model):
"""docstring for events, collecting events data"""
name = models.CharField(max_length=60)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
location = models.CharField(max_length=60... |
from pydantic import BaseModel as PydanticBaseModel
def to_camel(string):
"""Convert a snake_case string to CamelCase"""
return "".join(word.capitalize() for word in string.split("_"))
class BaseModel(PydanticBaseModel):
"""BaseModel adds CamelCase aliases to a Pydantic model"""
class Config:
... |
import bpy
from bpy.props import *
from ...nodes.BASE.node_tree import RenderStackNode
from ...preferences import get_pref
import os
import time
import re
def update_node(self, context):
self.update_parms()
class RenderNodeSceneFrameRange(RenderStackNode):
bl_idname = "RenderNodeSceneFrameRange"
bl_la... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Tridz and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class CashbackLedger(Document):
# Transfer cashback amount to the customer's bank if cashback balanc... |
# Do not edit this file, pipeline versioning is governed by git tags
__version__ = '2.0.2'
__git_revision__ = 'fa00823'
|
'''
------------------------------
| WAKIS+WarpX simulations |
------------------------------
Contains auxiliary script to setup and run WarpX simulations
Usage:
------
Call it by wakis.execfile('warpx.py') from the input script
Requirements:
-------------
pip install pywarpx, wakis, numpy, h5py
'''
import time... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
import django.db.models.deletion
import mozillians.users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0011_remove_userprofile_is_spam'),
]
operations = [
migrations.AddField(
model... |
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.sessions.models import Session
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.shortcuts import redirect
from registration.models import Registration, Or... |
#!python3
# python col_std.py infile.txt >> stds.csv
import sys
import logging
import argparse
import numpy as np
from os.path import splitext, basename
from snom.io.pg import load_raw
logging.basicConfig(format="%(levelname)-7s - %(name)s - %(message)s")
logger = logging.getLogger()
def load_txt(fn):
with open(... |
import argparse
import base64
import json
import logging
# from http://flask.pocoo.org/ tutorial
from flask import Flask, render_template, request
import uuid
from mongo_handler import MongoHandler
from video_handler import VideoHandler
log = logging.getLogger("video_crowd_control")
parser = argparse.ArgumentParse... |
"""MSD module containing the MSD network class for use within JUNN."""
import tensorflow as tf
from . import Input, Model, warn_unused_arguments
from .functional.msd import msd_net
from .mixins.losses import DiceLoss
from .mixins.preprocessing import PerImageStandardizationPreprocessingMixin
from .mixins.tile_based_ne... |
import structlog
import structlog_extensions
# --- Structlog logging initialisation code
pre_chain = [
# Add the log level and a timestamp to the event_dict if the log entry
# is not from structlog.
structlog.stdlib.add_log_level,
structlog.stdlib.add_logger_name,
structlog_extensions.processors.C... |
# --------------------------------------------------------------------------
# Pelion Device Management SDK
# (C) COPYRIGHT 2017 Arm Limited
#
# 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
#
... |
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
# Press the green button in the gutter to run the script.
import cuboid_volume
if __name__ == '__main__':
print(cuboid_volume.gr... |
import tweepy
import csv
import webbrowser
import time
def get_all_tweets(tweepy_user):
alltweets = []
screen_name = input(
'Enter the screenname of the profile : @')
new_tweets = tweepy_user.user_timeline(screen_name=screen_name, count=200)
alltweets.extend(new_tweets)
oldest = alltweet... |
"""Dice rolling module
Adapted from source of https://github.com/Davarice/PyDice by original author.
"""
from re import compile
from secrets import randbelow
from typing import Optional, Tuple
dice_pattern = compile(r"(\d*d\d+([-+]\d+)*)")
die_modifier = compile(r"[-+]\d+")
def randint(low: int, high: int) -> int... |
import os
import pytest
import factory
import sqlalchemy as sa
import pemi
import pemi.testing as pt
import pemi.pipes.sa
from pemi.fields import *
sa_engine = sa.create_engine('postgresql://{user}:{password}@{host}/{dbname}'.format(
user=os.environ.get('POSTGRES_USER'),
password=os.environ.get('POSTGRES_PA... |
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import scipy.signal
import cv2,time,gym,os,sys
from matplotlib import rc, animation
from google.colab import files
# helper function to get name of logdir
# model logdir will be similar to 'run_01-lr_1e-5-nw_16-tmax_50'
def get_logdir(model_lo... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .mtv import MTVServicesInfoExtractor
from ..utils import update_url_query
class NickIE(MTVServicesInfoExtractor):
# None of videos on the website are still alive?
IE_NAME = 'nick.com'
_VALID_URL = r'https?://(?:(?:www|beta)\.)?nick(?... |
import pytest
from django.urls import resolve, reverse
pytestmark = pytest.mark.django_db
def test_weather():
assert (reverse("weather:location") == f"/weather/")
assert resolve(f"/weather/").view_name == "weather:location"
|
import _common
# Override the regular excepthook too -- it doesn't change anything either way
# because ipython doesn't use it, but we want to make sure Trio doesn't warn
# about it.
import sys
def custom_excepthook(*args):
print("custom running!")
return sys.__excepthook__(*args)
sys.excepthook = custom_e... |
import logging
from classmanager import class_loader
from modules.module import Module
from queue import Queue,Empty
import os
class Bot:
def __init__(self, tweet, host, port, log):
self.host = host
self.port = port
self.tweet = tweet
self.logging = log
self.queue = Queue()
self._load_all_missions("m... |
cfiles = {"train_features":'./legacy_tests/data/class_train.features',
"train_labels":'./legacy_tests/data/class_train.labels',
"test_features":'./legacy_tests/data/class_test.features',
"test_labels":'./legacy_tests/data/class_test.labels'}
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Lemmatizes the given input column, i.e. modifies inflected or variant forms
of a word into its lemma.
Created on Fri Oct 8 11:18:30 2021
@author: dhesenkamp
"""
from code.preprocessing.preprocessor import Preprocessor
from nltk.stem import WordNetLemmatizer
from n... |
import numpy as np
import torch
import soundfile as sf
import scipy.signal as signal
from torch.utils.data.dataset import Dataset
from torch.utils.data.dataloader import DataLoader
def ctc_collate_fn(tracks):
dim1 = tracks[0][0].shape[1]
dim2 = max([tensor.shape[2] for tensor, _ in tracks])
dim3 = min([te... |
'''ALUMNA: HUAMANI TACOMA ANDY
EJERCICIO 01: MaxNonoverlappingSegments'''
# DESCRIPCION: Encuentre un conjunto máximo de segmentos que no se superpongan.
def solution(A, B):
n = len(A)
# VERIFICA SI HAY UN ELEMENTO EN EL ARREGLO
if n <= 1:
return n
# INICIALIZACION DEL CONTADOR
count = 1
prev = ... |
from jaxrl.agents.awac.awac_learner import AWACLearner
from jaxrl.agents.bc.bc_learner import BCLearner
from jaxrl.agents.drq.drq_learner import DrQLearner
from jaxrl.agents.sac.sac_learner import SACLearner
from jaxrl.agents.sac_v1.sac_v1_learner import SACV1Learner
|
def check_permission(request):
return request.user.is_staff or request.user.is_superuser or (hasattr(request.user, 'profile') and request.user.profile.is_staff) |
def work(a, b):
a = int(a)
b = int(b)
return [a * b, True]
def run():
output = 1
nums = input("Write the numbers you want to multiply separated by spaces:\n")
nums = nums.split(" ")
for i in range(0, len(nums)):
current = int(nums[i])
output *= current
print(output)
|
from tentacular.tenctarium import DeviceCallback, device_callback, tenctarium |
#Priprava spletnega vmesnika
#S strani knjižnice Bottle si prenesite datoteko bottle.py.
#S spletne učilnice si prenesite osnovno HTML predlogo ter slike. Predlogo premaknite v mapo views, slike pa v mapo img.
#V glavni mapi repozitorija ustvarite datoteko vislice.py, kjer:
##Uvozite modula bottle in model.
#====
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.