content stringlengths 5 1.05M |
|---|
from django.shortcuts import get_object_or_404, render, redirect
from django.db.models import Prefetch
from django.contrib import messages
from django.conf import settings
from django.utils.translation import ugettext as _
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from sendfile import sendf... |
#Importing the required packages
from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
from sklearn.linear_model import LogisticRegression
app = Flask(__name__)
#Routing to initial home page
@app.route('/')
def home():
retu... |
# coding=utf-8
# Copyright 2022 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... |
#!/usr/bin/env python
#
# Jetduino Python library
# v1.0.0
#
# This file provides the basic mappings of the pins for the arduino and jetson for use with the Jetduino
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
... |
import sys
import re
import pymel.util as _util
import pymel.internal.pmcmds as cmds
import pymel.internal.factories as _factories
import pymel.internal.startup as _startup
import pymel.internal as _internal
import pymel.versions as _versions
import maya.mel as _mm
_logger = _internal.getLogger(__name__)
def _resolveU... |
# Copyright 2020 The HuggingFace Team. 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 applicab... |
from display import show
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
def get_images():
return sorted(list(Path('out').glob('*.jpg')))
w = 480
h = 320
delete_button_coords = [
int(w / 3),
int(h / 6 * 5),
int(w / 3 * 2),
int(h-2),
]
class Review:
... |
def IsPointInSquare(x, y):
return abs(x) <= 1 and abs(y) <= 1
x = float(input())
y = float(input())
if IsPointInSquare(x, y) is True:
print('YES')
else:
print('NO')
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
import datetime as dt
impo... |
from crypto.transactions.serializers.base import BaseSerializer
class DelegateResignationSerializer(BaseSerializer):
"""Serializer handling delegate resignation data
"""
def serialize(self):
return self.bytes_data
|
"""This keeps track of any context needed for auto-completions and expression evaluations
This therefore carries """
# Copyright (c) 2019 Seven Bridges. See LICENSE
from typing import List
from dataclasses import dataclass
from .intelligence import IntelligenceNode
from .workflow import Workflow, WFStepIntelligence... |
#!/usr/bin/env python3
import argparse
import numpy as np
import pandas as pd
#import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Palatino']})
rc('text', usetex=True)
rc('legend', **{'fontsize': 13})
#sns.set(styl... |
#!/usr/bin/env python
import json
import os
import sys
try:
from fwd_api.devices_response import DevicesResponse, DeviceResponse
except:
print('Error importing from fwd_api. Check that you ran ' +
'setup (see README).')
sys.exit(-1)
DEVICES_JSON = os.path.join(os.path.dirname(__file__),
... |
from typing import Dict, List, Optional, Union, Any, Tuple
from torch import nn
import numpy as np
from torch.nn.modules import module
from transformers import Trainer, AutoConfig
from transformers.trainer_utils import (
EvalLoopOutput,
PredictionOutput,
EvalPrediction,
speed_metrics,
denumpify_de... |
#!/usr/bin/env python3
import turtle as t
import random as r
title = 'Rainbow Circle'
t.title(title)
t.showturtle()
t.colormode(255)
t.speed(0)
t.width(3)
def circle():
x = 1
if x == 1:
while x == 1:
t.color(r.randrange(0,255),r.randrange(0,255),r.randrange(0,255))
t.begin_fill()
t.forward(2)
t.left(1)... |
#!/usr/bin/env python
import sys
import os
import sqlite3
import shutil
import argparse
import fcntl
from datetime import datetime
from pytz import timezone
import tempfile
from libpredweb import myfunc
from libpredweb import webserver_common as webcom
TZ = webcom.TZ
progname = os.path.basename(sys.argv[0])
rootnam... |
'''
Randomly show files under specific path
07.12.2019
@chenz
'''
import FileDirectory as fd
import Show as sh
import random
import sys
import argparse
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def main():
# Process Parameters
parser = argparse.ArgumentPar... |
import argparser
class Spotify():
# We want to get an URL from the command terminal (argparser)
# We need to make sure this is a playlist and contains music.
# For each of the songs, look it up in Spotify.
# Create a playlist in spotify
# Add the youtube playlist to the spotify playlist.
de... |
# Python Standard Library Imports
import re
class Re(object):
def __init__(self):
self.last_match = None
def match(self, pattern, text):
if type(pattern).__name__ == 'SRE_Pattern':
self.last_match = pattern.match(text)
else:
self.last_match = re.match(pattern, ... |
import pygatt
import logging
logging.basicConfig()
logging.getLogger('pygatt').setLevel(logging.DEBUG)
adapter = pygatt.BGAPIBackend()
try:
adapter.start()
finally:
adapter.stop()
|
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
# load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resx")
# core_resx(
# name = "core_resource",
# src = "src/TestFramework/MSTest.Core/Resources/FrameworkMessages.resx",
# identifier = "Microsoft.VisualStudio.TestTools.UnitTesting.Resources.FrameworkMessages.resources",
# )
# core_li... |
import ox3apiclient
import logging
import requests
import json
import report_config
ox = ox3apiclient.client_from_file().logon()
ox.logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ox.logger.addHandler(ch)
# YOUR SETTINGS LOADED FROM 'report_config.py' file
date_range = report_c... |
from typing import Optional
import xml.etree.ElementTree as ET
from ...xml.XmlReader import XmlReader as XR
from ..namespaces import API
from ..namespaces import DATA
from ...deserialization.create_enum import create_enum
from ..dto.AnnulmentData import AnnulmentData
from ..dto.AnnulmentVerificationStatus import Annulm... |
# -*- coding: utf-8 -*-
# --- part one ---
def parse_inputs(file):
with open(file, "r") as f:
inputs = f.readlines()
state = inputs[0].rstrip().split("initial state: ")[1]
rules = [line.rstrip() for line in inputs[2:]]
return state, rules
state, rules = parse_inputs("input.txt"... |
import pandas as pd
import numpy as np
from os import listdir
from os.path import isfile,join
import torch
import wfdb
from torch.utils import data
bit_per_sample = 11 # not used
freq = 360 # samples in sec - not used
SAMPLE_SIZE = 127
default_path_company = r'..\..\Data\MIT_BIH_CSV'
NUM_of_windows = {
4096: 158... |
import sys
import timeit
import unicodedata
import numpy as np
UNICODE_NSM = [
"\u0300",
"\u0301",
"\u0302",
"\u0303",
"\u0304",
"\u0305",
"\u0306",
"\u0307",
"\u0308",
"\u0309",
"\u030A",
"\u030B",
"\u030C",
"\u030D",
"\u030E",
"\u030F",
"\u0310",
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 09:27:11 2019
@author: Ronan Murphy 15397831
Assignment 3: Hand-coding solutions for the Abstraction and Reasoning Corpus
"""
import sys
import format_json as fj
"""
import sys and format json to give ability to read in json files
"""
"""
reads in the json files and ... |
import typing
from typing import List, Union, Tuple
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QSizePolicy
from brainframe_qt.api_utils import api
from brainframe.api import bf_codecs
from brainframe_qt.ui.resources import stylesheet_watcher, QTAsyncWorker
from brainframe_qt... |
"""
Django settings for django_AUS project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from path... |
import base64
import json
from blspy import PublicKeyMPL, SignatureMPL, AugSchemeMPL
from cryptography.fernet import Fernet
from src.util.byte_types import hexstr_to_bytes
from src.util.hash import std_hash
from src.wallet.derive_keys import master_sk_to_backup_sk
from src.wallet.util.wallet_types import WalletType
... |
###########################################################################
## ##
## GnomeBingLockScreen ##
## Copyright (C) 2018 张泽平 (Randy Hoffman) ##
## ... |
from __future__ import division
from __future__ import print_function
from nose.tools import assert_almost_equal, assert_equal, assert_raises, \
assert_true
from dit import Distribution, ScalarDistribution
from dit.distribution import BaseDistribution
from dit.exceptions import ditException, In... |
# coding=utf-8
# Copyright 2021 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... |
import os
import pkgutil
import sys
import importlib
import re
from wifipumpkin3.core.utility.printer import display_messages
# https://stackoverflow.com/questions/3365740/how-to-import-all-submodules
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subp... |
'''
Created on 28 de abr de 2020
@author: leonardo
Content: Classe do PoweUp de Velocidade
'''
from componentes.jogo.powerups import PowerUp
class Velocidade(PowerUp):
def poder(self, personagem):
pass
#personagem.velocidade += 1
#personagem.servidor.emitPoder("velocidade", personagem.ve... |
# Authors: Robin Schirrmeister <robintibor@gmail.com>
#
# License: BSD (3-clause)
import torch
from torch import nn
from torch.nn.functional import elu
from .modules import Expression, Ensure4d
from .functions import squeeze_final_output
class Conv2dWithConstraint(nn.Conv2d):
def __init__(self, *args, max_norm=... |
from vit.formatter.wait import Wait
class WaitAge(Wait):
def format(self, wait, task):
return self.age(wait)
|
# Generated by Django 2.2.8 on 2020-01-16 09:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0023_auto_20200108_1446'),
]
operations = [
migrations.AlterField(
model_name='apartmentsensorvalue',
name='... |
#!/usr/bin/env python
"""
_Step.Executor.CMSSW_
Implementation of an Executor for a CMSSW step.
"""
import logging
import os
import socket
import subprocess
import sys
from Utils.PythonVersion import PY3
from Utils.Utilities import encodeUnicodeToBytesConditional
from WMCore.FwkJobReport.Report import addAttributes... |
file = input("give an ascii file ") #Ζηταει απο τον χρηστη ενα file
for i in range(len(file)):
let = file[len(file)-i -1] #Διαβαζει απο το τελος τους χαρακτηρες
num = ord(let) # μετατροπη σε αριθμους
num2 = 128 - num # κατοπτρικο τους
ascii = chr(num2) # Τον μετατρεπω σε χαρακτηρα
print(asci... |
# Based on https://github.com/dfraze/binja_winmd/blob/main/main.py. Thank you, Dustin Fraze!
import json
import codecs
import sys
import logging
from collections import OrderedDict, defaultdict
from argparse import ArgumentParser
from pathlib import Path
import angr
from angr.sim_type import SimTypeFunction, SimTypeL... |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
raw = ifile.read()
lower, upper = map(int, raw.strip().split("-"))
passwords = tuple(map(str, range(lower, upper + 1)))
from itertools import groupby
from typing import Callable
def valid(group_size_rule: Callable[[int], bool], passw... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Class definition Dog
By: Steve Lammers, Steven.Lammers@UCDenver.edu
"""
# Imports
#import numpy as np
#import matplotlib
class Dog():
"""
Class Description
Args:
_color: string - dog color
_name: string - name of dog
"""
def __init__(self, color,... |
# Copyright 2019 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
from __future__ import unicode_literals
# Common Redis constants for discovery and transport classes
REDIS_BACKEND_TYPE_STANDARD = 'redis.standard'
REDIS_BACKEND_TYPE_SENTINEL = 'redis.sentinel'
REDIS_BACKEND_TYPES = (
REDIS_BACKEND_TYPE_STANDARD,
REDIS_BACKEND_TYPE_SENTINEL,
)
DEFAULT_MAXIMUM_MESSAGE_BYTES... |
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SubmitField
class AddForm(FlaskForm):
name = StringField('Name of Puppy:')
submit = SubmitField('Add Puppy')
class DelForm(FlaskForm):
id = IntegerField('Id Number of Puppy to Remove:')
submit = SubmitField('Remove Puppy'... |
from System.Windows import Application
from System.Windows.Controls import UserControl
root = Application.Current.LoadRootVisual(UserControl(), "app.xaml")
root.Message.Text = "Welcome to Python and Silverlight!"
|
from __future__ import print_function, division
from PyAstronomy import funcFit as fuf
from PyAstronomy import pyasl
from PyAstronomy.pyaC import pyaErrors as PE
import numpy as np
import scipy.interpolate as sci
from PyAstronomy.modelSuite import ic
import six.moves as smo
class LLGauss(fuf.OneDFit):
"""
A spec... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-06-11 16:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finncon2018', '0002_auto_20180429_2012'),
]
operations = [
migrations.AlterField(
model_name='signupextr... |
# SPDX-FileCopyrightText: 2020 Hlib Babii <hlibbabii@gmail.com>
#
# SPDX-License-Identifier: Apache-2.0
from codeprep.tokens.numeric import Number
from codeprep.parse.matchers import split_into_words
from codeprep.tokens.containers import SplitContainer
from codeprep.tokens.whitespace import NewLine, SpaceInString
fr... |
"""
파일 이름 : 14584.py
제작자 : 정지운
제작 날짜 : 2017년 5월 28일
"""
import sys
# 암호문을 입력 받는다.
password = input()
# 단어 개수와 각 단어를 입력받는다.
num = int(input())
# 단어는 리스트에 저장한다.
wordlst = []
for i in range(num):
word = input()
wordlst.append(word)
# 알파벳을 한 칸씩 평행이동하면서 암호문을 검사한다.
# 한 칸씩 평행이동하므로 총 26번을 반복한다.
temp_password = ''
for i i... |
"""Supplementary functions"""
import logging
import logging.config
import os
import yaml
LOGGING_CONFIG_FILEPATH = "logging.conf.yml"
logger = logging.getLogger("ext_summarizer")
def setup_logging():
"""Set up the logger from config file"""
with open(LOGGING_CONFIG_FILEPATH, 'r') as config_fin:
cfg... |
# -*- coding: utf-8 -*-
from TM1py.Objects import ElementAttribute, Element
from TM1py.Services.ObjectService import ObjectService
class ElementService(ObjectService):
""" Service to handle Object Updates for TM1 Dimension (resp. Hierarchy) Elements
"""
def __init__(self, rest):
super().__i... |
import pendulum
from app.api.business.agreement_business import get_old_agreements
from tests.app.helpers import BaseApplicationTest
class TestOldAgreement(BaseApplicationTest):
def setup(self):
super(TestOldAgreement, self).setup()
def test_old_agreement_end_dates_are_in_the_past(self, master_agree... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
#import matplotlib
#matplotlib.use('Agg')
from flask import Flask, render_template, Response
import sys
import time
import logging
import subprocess
import cv2
from collections import deque
from tracker import Tracker
import numpy as np
from scipy.optimize import linear_sum_assignment as linear_assignment
from pedest... |
# -*- coding: utf-8 -*-
"""
Drone_copySelectedPhotos.py
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU G... |
from typing import Literal, Sequence, SupportsFloat, SupportsInt, Union
from numpy import (float16, float32, float64, int0, int8, int16, int32, int64,
ndarray)
from pandas import DataFrame, Series
# Numerical
NumpyFloat = Union[float64, float32, float16] # Numpy Float types
NumpyInt = Union[int0, ... |
import json
import re
import os
from time import sleep
from requests_html import HTMLSession
from selenium import webdriver as wb
session = HTMLSession()
text_re = r"jsonData = (.*);"
regex = r"initData = (.*);"
options = wb.ChromeOptions()
def crawl_cmt(link, driver_path):
driver = wb.Chrome(executable_path=d... |
from django.test import TestCase
from core.models.base import OrderType, OutcomeType, PieceType
from core.game import create_new_pieces
from core.tests import DiplomacyTestCaseMixin
class TestCreateNewPieces(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = self.create_test_variant()
... |
from spiral.core.foundation import TestApp
from spiral.core.ml import MLHandler, MLInterface
from pytest import raises
# module tests
class TestMLInterface:
def test_interface(self):
assert MLInterface.Meta.interface == "ml"
class TestMLHandler:
def test_subclassing(self):
class MyMLHandle... |
import sys
import pandas as pd
from . import option, data, yahoo
def main():
opts = option.build_parser().parse_args()
# pandas config
pd.set_option("display.float_format", lambda x: f"{x:f}")
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
stocks = [yaho... |
import torch
from torch import Tensor
from radiomixer.io.signal import SignalFeature
from radiomixer.transforms.concatenator.concatenator import Concatenator
from radiomixer.transforms.transform import TransformType
class SummationConcatenator(Concatenator):
"""
Sequentially concatenate diffetent segments
... |
from pwn import *
p = process('./unlink')
p.recvuntil('stack address leak: ')
stack_addr = int(p.recvline()[2:], 16)
log.success('stack: {:#x}'.format(stack_addr))
p.recvuntil('heap address leak: ')
heap_addr = int(p.recvline()[2:], 16)
log.success('heap: {:#x}'.format(heap_addr))
p.recvline()
# gap between chunks... |
# -*- coding: utf-8 -*-
"""
reqs.py
=============================================
The request client for handling GETs to dagpi
"""
from typing import Optional
import requests
from .errors import DagpiException
class ReqClient():
"""
Main class for handling requests with dagpi
Parameters
--------... |
##############################################################################
#
# Copyright (c) 2007 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# 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.apach... |
import os
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from in_out import load_sample
import librosa
import numpy as np
from tqdm import tqdm
def check_directory(directory, good_path: str, bad_path:str, checks: list,
max_workers: int = 16):
'''
Runs check_sample on all... |
"""`bucky viz` CLI."""
import multiprocessing
from enum import Enum
from pathlib import Path
from typing import List, Optional
import typer
from ..viz.plot import main as plot_main
app = typer.Typer()
class AdmLevel(str, Enum):
adm0 = "adm0"
adm1 = "adm1"
adm2 = "adm2"
@app.command("plot")
def plot(
... |
#!/usr/bin/env python
import os, sqlite3
# -------------- constants -----------------------------------------
profilAppMain=os.path.join(os.environ["HOME"], ".mozilla/firefox")
profilUser= os.environ["USER"]
profilApp = ... |
import logging
import paho.mqtt.client as mqtt
logger = logging.getLogger(__name__)
class Mqtt:
def __init__(self, broker, port = 1883, subscription_topic=None, mqtt_callback=None):
self.broker = broker
self.port = port
self.mqtt_callback = mqtt_callback
self.connected_to_mqtt = Fa... |
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.conf import settings
import sys
from rest_framework import views... |
# Copyright 2019 Open Source Robotics Foundation, 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... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from MDRSREID.Networks.create_keypoints_predictor import create_keypoints_predictor
from MDRSREID.Networks.HOReID.HeatmapProcessor import HeatmapProcessor2
class HOReIDScoreMapComputer(nn.Module):
def __init__(self, cfg):
super(HOReIDScor... |
# -*- coding: utf-8 -*-
"""
/dms/elixier/utils.py
.. enthaelt Hilfefunktionen fuer den Elixier-Austausch
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 15.06.2007 Begi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# Custom
from src.normalisation import channel, instance
class ResidualBlock(nn.Module):
def __init__(self, input_dims, kernel_size=3, stride=1,
channel_norm=True, activation='relu'):
"""
input_... |
__all__ = ['Role']
from dataclasses import dataclass
from multibot import constants
from multibot.models.database import db
from multibot.models.enums import Platform
from multibot.models.event_component import EventComponent
@dataclass(eq=False)
class Role(EventComponent):
collection = db.role
_unique_keys... |
n = int(input())
h = list(map(int, input().split()))
e = 0
x = 0
dollars_spent = 0
for i in range(n):
y = h[i]
e += x - y
if e < 0:
dollars_spent += abs(e)
e = 0
x = h[i]
print(dollars_spent)
|
from argparse import ArgumentParser
from webmnist.export import export
from webmnist.train import train
parser = ArgumentParser()
parser.add_argument("-o", "--output", type=str, required=True)
parser.add_argument("-e", "--epochs", type=int, default=3)
parser.add_argument( "--train", action="store_true")
parser.... |
from copy import copy
from typing import cast, Optional, List, Union, Iterable
from pydfs_lineup_optimizer.solvers.base import Solver
from pydfs_lineup_optimizer.solvers.constants import SolverSign
from pydfs_lineup_optimizer.solvers.exceptions import SolverException, SolverInfeasibleSolutionException
try:
from mip... |
# -*- coding: utf-8 -*-
'''
{{module_name}} execution module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{{short_description}}
.. versionadded:: {{version}}
:configuration:
.. code-block:: yaml
<your example config>
'''
# Import Python libs
from __future__ import absolute_import
import logging
# Import salt li... |
'''
niceprints
==========
This module provides functions which add visual flair to your text, to make
your print statements more interesting.
These functions only do the minimum amount of transformation for their effect.
You should do your uppercase/lowercase, text wrap, etc. before calling
these functions.
'''
impor... |
from sepal_ui import model
from traitlets import Any
class OrderModel(model.Model):
order_index = Any(None).tag(sync=True)
orders = Any(None).tag(sync=True)
session = Any(None).tag(sync=True)
quads = Any(None).tag(sync=True)
|
from nonebot.rule import to_me
from nonebot import on_message
from nonebot.adapters.cqhttp import Bot, MessageEvent
from .data_source import get_message_reply, ChatMessageReply
chat = on_message(rule=to_me(), priority=10)
@chat.handle()
async def chat_handle(bot: Bot, event: MessageEvent):
if str(event.message):
... |
import struct
import typing
import zoneinfo
from datetime import datetime, timedelta, timezone
from uecp.commands import UECPCommand
from uecp.commands.base import (
UECPCommandDecodeElementCodeMismatchError,
UECPCommandDecodeNotEnoughData,
)
@UECPCommand.register_type
class RealTimeClockSetCommand(UECPComma... |
#############################################
## MODULE VARIABLES
#############################################
print('Load wsServer')
import sys, time, json, asyncio, traceback
import websockets, noteTool
_parent = sys.modules["__main__"]
_options = None
#######################################
async def d... |
# Module to test Icon
#-------------------------------------------------------------------------------
import pytest
import math
import numpy as np
import sympy
import probayes as pb
#-------------------------------------------------------------------------------
LOG_TESTS = [(math.exp(1.),1.)]
INC_TESTS = [(3,4)]
#... |
from turtle import *
bgcolor("green") # Define Background Color
pencolor("red") # Define the color of Pen, i.e our pattern's color
pensize(10) # Define the size of Pen, i.e. the width of our pattern's line
radius = 100 # Define the radius of each circle
turning_angle = 36 # Define how much the ... |
#!/usr/bin/env python
import glob
from pyraf import iraf
import json
from sys import argv
objlist = argv[1]
with open('myccds.json') as file:
settings = json.loads(file.read())
side = settings['mysettings']['side']
if side == "Blue":
print("Settings for blue side will be used.")
disp_axis = 1
elif side ==... |
# coding: utf-8
# flake8: noqa
from __future__ import absolute_import
# import models into model package
from swagger_server.models.model_flow_chart import ModelFlowChart
from swagger_server.models.model_flow_chart_edge import ModelFlowChartEdge
from swagger_server.models.model_flow_chart_edge_meta import ModelFlowCha... |
#!/usr/bin/python
"""
Setup tools script for Site-RM Utilities. This is mandatory for Frontend
and the agents to have this installed.
To Install:
python setup-agent.py build install
Copyright 2019 California Institute of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not u... |
#Non project imports
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#Project imports
from GuildPosts.models import PostModel
from UserProfiles.models import UserProfileModel
from GroupChat.models import Message
from GroupChat.forms import ChatModelForm
from Notifications.... |
from tapis_cli.display import Verbosity
from .create import MetadataCreate
from .formatters import MetadataFormatOne
from .helpers import create_update, generate_name
from .models import Metadata
from .mixins import MetadataUUID
from .mixins import UploadMetadataFile
from . import API_NAME, SERVICE_VERSION
class Met... |
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode
from bitstring import BitArray
class Usad8(AbstractOpcode):
def __init__(self, m, d, n):
super(Usad8, self).__init__()
self.m = m
self.d = d
self.n = n
def execute(self, processor):
if processor.conditi... |
'''
Plot predictions of a selected sequence from Caltech Pedestrian Dataset (Dollar et al. 2009, http://www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/) outputted by trained PreCNet.
Based on code related to PredNet - Lotter et al. 2016 (https://arxiv.org/abs/1605.08104 https://github.com/coxlab/prednet).
'''... |
import asynctest
import pytest
from jsondaora import dataclasses
@pytest.mark.asyncio
async def test_should_set_already_not_found_error_when_get_many_with_fields(
repository, mocker
):
fake_entity = 'fake'
repository.memory_data_source.hmget = asynctest.CoroutineMock(
return_value=[None, None, Non... |
from pathlib import Path
import logging
import yaml
def load_config(config_path, section):
"""Tests for a valid config file and loads a section of the yaml file,
or if not specified, the entire configuration
"""
config_path = Path(config_path)
# config path needs to be a valid yaml file that exist... |
# Copyright 2018 University of Groningen
#
# 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 i... |
from typing import Any, Union
from boa3.builtin import CreateNewEvent, NeoMetadata, metadata, public
from boa3.builtin.contract import Nep17TransferEvent, abort
from boa3.builtin.interop.blockchain import get_contract
from boa3.builtin.interop.contract import GAS, call_contract
from boa3.builtin.interop.runtime import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.