content
stringlengths
5
1.05M
# coding=utf-8 from flask import Blueprint,jsonify,current_app,request,session house_blueprint=Blueprint('house',__name__) from models import Area,Facility,House,HouseImage,User,Order import json from status_code import * from qiniu_sdk import put_qiniu #获取地区信息,并进行缓存 def get_areas(): area_dict_list=current_app.re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import asyncio import os from pyppeteer.launcher import launch from syncer import sync from wdom.document import get_document from wdom import server from ..base import TestCase server_config = server.server_config class PyppeteerTestCase(TestCase): if os.getenv...
# Copyright 2016 - 2018 CERN for the benefit of the ATLAS collaboration. # # 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 ...
""" #' The linearized matrix L #' #' Function computes the derivative of the model with respect to the between subject variability #' terms in the model (b's and bocc's) evaluated at #' a defined point #' (b_ind and bocc_ind). #' #' @inheritParams mf3 #' @param bpop The fixed effects parameter values. Sup...
POWER = 0xFF02FD RED = 0xFF1AE5 GREEN = 0xFF9A65 BLUE = 0xFFA25D BRIGHTEN = 0xFF3AC5 DIM = 0xFFBA45 WHITE = 0xFF22DD # TODO Add more supported IR codes
from __future__ import division, unicode_literals from past.utils import old_div import math import time from util import hook, urlnorm, timesince, http title_length = 80 expiration_period = 60 * 60 * 24 # 1 day ignored_urls = [urlnorm.normalize("http://google.com")] # We have a bunch of much better plugins to ha...
# Generated by Django 2.0.5 on 2018-05-10 08:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inscript', '0002_auto_20180506_1716'), ] operations = [ migrations.AlterField( model_name='course', name='lab_slot',...
#!/usr/bin/env python3 import tvm import math from tvm import relay from tvm.relay.testing.lstm import lstm_cell, get_workload import numpy as np import sys def generate_random_tensor(ty): return tvm.nd.array(np.random.uniform(-1.0, 1.0, tuple([int(i) for i in ty.shape])).astype(ty.dtype)) def main(argv): dt...
from .queued_run_coordinator_daemon import QueuedRunCoordinatorDaemon
from app import app import os from flask import render_template, flash, redirect, url_for from app.forms import LoginForm from config import Config @app.route('/', methods=['GET']) @app.route('/index', methods=['GET']) def index(): """ service = get_service() spreadsheet_id = os.environ["GOOGLE_SPREADSHEET...
# lesson3/exercises.py # Variables # # This file contains exercises about Python variables. # Variables print("What's a variable?") # 1) What's a variable? # Creating web apps, games, and search engines all involve storing and working # with different types of data. # They do so using variables. A variable stores ...
__source__ = 'https://leetcode.com/problems/score-of-parentheses/' # Time: O(N) # Space: O(1) # # Description: Leetcode # 856. Score of Parentheses # # Given a balanced parentheses string S, # compute the score of the string based on the following rule: # # () has score 1 # AB has score A + B, where A and B are balanc...
from django.shortcuts import render from vianeyRest.models import Usuario,Materia,Persona from vianeyRest.serializers import UsuarioSerializer,MateriaSerializer,PersonaSerializer from rest_framework import generics # Create your views here. class UsuarioList(generics.ListCreateAPIView): queryset = Usuario.objects....
import datetime import os from typing import Dict, List, Optional, Tuple, Union from prompt_toolkit.clipboard import pyperclip from pydantic import BaseModel # config_file = os.path.join(os.path.expanduser("~"), r".v_bank.config") store_file = os.path.join(os.path.expanduser("~"), ".v_bank_store.json") class V(Base...
# TODO: Properly compile this before running on OTHR computers import pyximport; pyximport.install() from reversialphazero.command_line_interface import CommandLineInterface def main(): weights_file = './final-long-running-test/checkpoint-00062.zip' nn_name = 'reversialphazero.distributed_8_by_8.neural_networ...
class TestReport2Splunk(object): def test_pass(self): assert True def test_fail(self): assert False
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # SKS.SKS.get_interfaces # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ---------------------------------------------------------...
from flask import Flask, request, jsonify from keras.preprocessing import image from itertools import compress from io import BytesIO from keras_applications import inception_v3 import base64, json, requests, numpy as np from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/hello/', methods=['GET'...
import pyaudio import numpy as np from math import pi, sin from pygame import midi from itertools import count midi.init() mi=midi.Input(device_id=midi.get_default_input_id()) st=pyaudio.PyAudio().open(44100,1,pyaudio.paInt16,output=True,frames_per_buffer=256) try: nd={} while True: if nd:st.write(np.int16([sum...
lower_bound = '236491' upper_bound = '713787' # first formulate password rules def test_increase(password: str) -> bool: return password == ''.join(sorted(password)) def test_length(password: str) -> bool: return len(password) == 6 def test_range(password: str) -> bool: return int(password) in range(int...
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['snsql', 'snsql._ast', 'snsql._ast.expressions', 'snsql.reader', 'snsql.sql', 'snsql.sql._mechanisms', 'snsql.sql.parser', 'snsql.sql.reader', 'snsql.xpath', 'snsql.xpath.parser'] package_data = \ {'': ['*']} install_requires = \ ['PyYAML>=5...
import numpy as np import sys import os # Handle import of module fluxions differently if module # is being loaded as __main__ or a module in a package. if __name__ == '__main__': cwd = os.getcwd() os.chdir('../..') import fluxions as fl os.chdir(cwd) else: import fluxions as fl # *****************...
""" MPP Solar Inverter Command Library library of utility and helpers for MPP Solar PIP-4048MS inverters mpputils.py """ import logging from .mppcommands import mppCommands from .mppcommands import NoDeviceError logger = logging.getLogger() def getVal(_dict, key, ind=None): if key not in _dict: return "...
with open("input.txt") as f: pub_1, pub_2 = map(int, f.read().splitlines()) mod = 20201227 loop_size, value, pub = 0, 1, None while not pub: value = (value * 7) % mod loop_size += 1 if value == pub_1: pub = pub_2 elif value == pub_2: pub = pub_1 value = 1 for _ in range(loop_size)...
#!/usr/local/bin/python3 # coding: utf-8 # YYeTsBot - share_excel.py # 12/18/21 19:21 # __author__ = "Benny <[email protected]>" import openpyxl import pathlib import sys web_path = pathlib.Path(__file__).parent.parent.resolve().as_posix() sys.path.append(web_path) from Mongo import Mongo from tqdm import tqdm ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # 装饰器的应用 __author__ = 'sphenginx' def funA(fn): print("C语言中文网") fn() # 执行传入的fn参数 print("http://c.biancheng.net") return "装饰器函数的返回值" @funA def funB(): print("学习 Python") if __name__ == '__main__': print(funB)
# Generated by Django 3.1.12 on 2021-07-01 20:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("polio", "0015_auto_20210630_2051"), ] operations = [ migrations.CreateModel( name="Config", fields=[ ...
import subprocess import json import yaml from ckan_cloud_operator import logs class DeisCkanInstanceSolr(object): def __init__(self, instance): self.instance = instance self.solr_spec = self.instance.spec.solrCloudCollection def update(self): self.instance.annotations.update_status...
import sys import os import time import pylidc as pl import numpy as np from sklearn.utils import shuffle import better_exceptions import pickle from numba import jit from sklearn.feature_extraction import image import keras import time import random from tqdm import tqdm import pickle import cProfile import unet_3d f...
# -*- coding: utf-8 -*- ''' dburi的对象 created by HanFei on 19/2/28 ''' import re import os import urllib.parse default_port = { 'mongodb': 27017, 'mysql': 3306, 'postgres': 5432, 'redis': 6379, 'hbase': 9090, 'elasticsearch':9200 } def parse_extra(str): qs = dict( (k, v if len(v)>1 else v...
import numpy as np from pyhack.py_runko_aux import * from pyhack.boris import boris_rp, boris_iter def vv_pos(tile,dtf=1): c = tile.cfl cont = tile.get_container(0) pos = py_pos(cont) vel = py_vel(cont)*c E,B = py_em(cont) nq = pos.shape[0] dims = pos.shape[1] g = gui(c,vel)[:,np.new...
""" file: donkey_sim.py author: Tawn Kramer date: 2018-08-31 """ import base64 import logging import math import os import time import types from io import BytesIO from typing import Any, Callable, Dict, List, Tuple, Union import numpy as np from PIL import Image from gym_donkeycar.core.fps import FPSTimer from gym_d...
from django.test import TestCase from django.contrib.auth.models import User class ProfileMethodTests(TestCase): def setUp(self): user = User.objects.create_user( username='lichun', email='[email protected]', password='lichun_password', ) user.profile.url = 'h...
""" Module `chatette_qiu.cli.interactive_command.save_command`. Contains the strategy class that represents the interactive mode command `save` which writes a template file that, when parsed, would make a parser that is in the state of the current parser. """ from __future__ import print_function import io from chate...
from django.urls import path from django.views.generic import TemplateView app_name = 'frontend' urlpatterns = [ path('', TemplateView.as_view(template_name='frontend/index.html'), name='index'), ]
"""Classical Checkpoints classes implementations """ # main imports import os import logging import numpy as np # module imports from macop.callbacks.base import Callback from macop.utils.progress import macop_text, macop_line class BasicCheckpoint(Callback): """ BasicCheckpoint is used for loading previous...
import torch import torch.nn as nn from torch.nn.modules import activation import lightconvpoint.nn as lcp_nn from lightconvpoint.nn.conv_fkaconv import FKAConv as conv from lightconvpoint.nn.pool import max_pool from lightconvpoint.nn.sampling_knn import sampling_knn_quantized as sampling_knn from lightconvpoint.nn.sa...
""" This paver file is intented to help with the release process as much as possible. It relies on virtualenv to generate 'bootstrap' environments as independent from the user system as possible (e.g. to make sure the sphinx doc is built against the built numpy, not an installed one). Building a fancy dmg from scratch...
import cv2 import matplotlib.pyplot as plt img = cv2.imread('/home/pi/book/dataset/4.2.07.tiff', 1) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 75, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, ...
'''256 color terminal handling ALL_COLORS is a dict mapping color indexes to the ANSI escape code. ALL_COLORS is essentially a "palette". Note that ALL_COLORS is a dict that (mostly) uses integers as the keys. Yeah, that is weird. In theory, the keys could also be other identifiers, although that isn't used much at t...
import torch import pdb import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence from .beam_search import CaptionGenerator __DEBUG__ = False def process_lengths(input): # the input sequence s...
w = 12 x = 3 y = 2 z = 4 y < z # no chaining, with True answer z < y # no chaining, with False answer x < z > y # should be same as (3 < 4 and 4 > 2), True answer x < z > w # should be same as (3 < 4 and 4 > 12), False answer (x < z) > y # should be same as (3 < 4 and True > 2) y < x < z < w # 5-chain True answer y...
from sys import argv def print_even_odd_zero(d): if d == 0: print("I'm Zero.") elif d % 2: print("I'm Odd.") else: print("I'm Even.") try: if len(argv) == 1: pass elif len(argv) > 2: raise Exception else: d = int(argv[1]) print_even_odd...
import time from enum import Enum from typing import Dict, Optional, Union class StateChange(Enum): BECAME_OPEN = 'became_open' BECAME_THROTTLED = 'became_throttled' STILL_THROTTLED = 'still_throttled' STILL_OPEN = 'still_open' STATE_CHANGE_MAP = { # Key: (did change, current state) (True, T...
#!/usr/bin/env python import os import pprint # ------------------------------------------------------------------------------ # # This example demonstrates various utilities to inspect, print, trigger stack # traces and exceptions with RU. # # -------------------------------------------------------------------------...
"""Fitting Models to Fit data with.""" import numpy as np from scipy.integrate import odeint from scipy.special import erf, erfc from scipy.stats import norm, skewnorm from iminuit import Minuit, describe import sys import yaml import logging from .utils.static import sfgn thismodule = sys.modules[__name__] logger = ...
#--*-- coding:utf-8 --*-- import requests, requests.utils, pickle import httplib import sys import pprint from bs4 import BeautifulSoup import re, shutil, xml.dom.minidom, json import netrc import os.path, time import random from optparse import OptionParser from SimpleHTTPServer import SimpleHTTPRequestHandler from B...
# -*- coding: utf-8 -*- from datetime import date from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.views.generic import ListView, DetailView from djang...
import os.path as osp import os from six.moves import shlex_quote from rlf.rl import utils import sys import pipes import time import numpy as np import random import datetime import string import copy from rlf.exp_mgr import config_mgr from rlf.rl.loggers.base_logger import BaseLogger from collections import deque, d...
import os from pathlib import Path import json from pathlib import Path import argparse from pprint import pprint from tabulate import tabulate from app.db_connector import * at_dir = Path('frontend/src') def language_settings(): languages = [ 'en', 'ja' ] dictionary = {k: {} for k in lan...
# coding: utf-8 """ Prisma Cloud Compute API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 21.04.439 Generated by: https://openapi-generator.tech """ from __future__ import absolute_impor...
# Generated by Django 4.0.1 on 2022-03-01 21:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0007_earned_badge_visit_remove_player_badges_and_more'), ] operations = [ migrations.AddField( model_name='player', ...
# This Task is the base task that we will be executing as a second step (see task_piping.py) # In order to make sure this experiment is registered in the platform, you must execute it once. from trains import Task # Initialize the task pipe's first task used to start the task pipe task = Task.init('examples', 'Toy Ba...
from docbarcodes.zxingjpype.zxingreader import decodeURIs def test_jpype_qrcode(): file = "data/single/qr-code-wikipedia.png" results = decodeURIs([file]) assert results[0][0].text=='http://en.m.wikipedia.org'
# -*- coding: utf-8 -*- """ Created on Fri Aug 10 18:32:07 2018 @author: admin """ # import the necessary packages from pyimagesearch.shapedetector import ShapeDetector import argparse import imutils import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.a...
import pytest from aoc_cqkh42.year_2020 import day_15 @pytest.mark.parametrize( 'data, answer', [ ('1,3,2', 1), ('2,1,3', 10), ('1,2,3', 27), ('2,3,1', 78), ('3,2,1', 438), ('3,1,2', 1836), ('0,3,6', 436) ] ) def test_part_a(data, answer): asser...
from django.contrib import admin from .models import Website, DataPoint # Register your models here. admin.site.register(Website) admin.site.register(DataPoint)
from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharFiel...
from howiml.utils import utilities import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA colors = list(utilities.getColorScheme().values()) sns.set(context='paper', style='whitegrid', palette=s...
import tkinter as tk win = tk.Tk() win.title("C语言中文网") win.geometry('400x350+200+200') win.iconbitmap('C:/Users/Administrator/Desktop/C语言中文网logo.ico') win.rowconfigure(1, weight=1) win.columnconfigure(0, weight=1) # 左侧的frame frame_left = tk.LabelFrame(win, bg='red') tk.Label(frame_left, text='左侧标签1', bg='green', widt...
#!/usr/bin/env python2.3 # # Copyright (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU Lesse...
#!/usr/bin/env python3 from sys import stderr, exit from TALinputs import TALinput from multilanguage import Env, Lang, TALcolors from hanoi_lib import ConfigGenerator, HanoiTowerProblem from utils_lang import get_formatted_move # METADATA OF THIS TAL_SERVICE: args_list = [ ('v',str), ('start',str), ('f...
r1 = float(input('Insira o comprimento da primeira reta:')) r2 = float(input('Insira o comprimento da segunda reta:')) r3 = float(input('Insira o coprimento da terceira reta: ')) if r1 + r2 > r3 and r2 + r3 > r1 and r1 + r3 > r2: if r1 == r2 == r3: print(f'O seu triângulo é Equilátero.') elif r1 == r2 ...
from .page_data import PageData
# 4-4. One Million for number in range(1, 1000001): print(number)
import re import sys from collections import defaultdict from itertools import chain, count # see pyproject.toml __version__ = "0.0.9" __author__ = "Saito Tsutomu <[email protected]>" def addplus(s): return s if s.startswith(("+", "-")) else "+" + s def delplus(s): return s[1:] if s.startswith("+") el...
import json import os from catacomb.common import constants, errors from catacomb.utils import helpers def create(path, contents=None): """Creates a new file at the given path. Arguments: contents (str): The file contents. """ if os.path.exists(path): helpers.exit(errors.FILE_CREATE_...
from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.addresses import IPAddr rules = ( # ---------------------------------------- # --------DEFINE YOUR RULES BELOW--------- # ----------------------------------------- (None, None, None, 'tcp'), (IPAddr('10.0.0.3'), None,...
import argparse import numpy as np from decimal import Decimal if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-t', '--table', help='input table file') parser.add_argument('-m', '--max_value', default=1, help='the max value in the dist matrix') parser.add_argument('...
import json from typing import Optional from great_expectations.core import IDDict from great_expectations.core.util import convert_to_json_serializable from great_expectations.types.base import SerializableDotDict class ExceptionInfo(SerializableDotDict): def __init__( self, exception_traceback:...
# Enter your code here. Read input from STDIN. Print output to STDOUT def find_low_val_path(matrix,row,col): if row == len(matrix) - 1 and col == 0: return matrix[row][col] if row < len(matrix) - 1 and col > 0: return matrix[row][col] + min(find_low_val_path(matrix,row + 1,col), ...
from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.db.models import Prefetch from django.http import Http404, HttpResponseRedirect from django.utils.translation import gettext_lazy as _ from django_filters.rest_framework import DjangoFilterBackend from rest_framewo...
from reportlab.graphics import renderPM from svglib.svglib import svg2rlg from io import BytesIO import regex def convert_svg(file): # Converts a SVG file to a png file # Returns a python file object draw = svg2rlg(file) buff = BytesIO(draw.asString('png')) return buff def get_dimensions(file): ...
import parsl from parsl.dataflow.error import DependencyError from concurrent.futures import Future @parsl.python_app def copy_app(v): return v def test_future_result_dependency(): plain_fut = Future() parsl_fut = copy_app(plain_fut) assert not parsl_fut.done() message = "Test" plain_fu...
from django.urls import path, include from . import views app_name = 'accounts' urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('signup/', views.signup, name='signup'), path('skintype_test/', views.skin_type_test, name='skin_type_test'), ...
"""This module contain functions for signup.""" from django.http import JsonResponse from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from ..models import Profile from .email_sender import send_message_with_url_for_registration def signup_processing(request: object, ...
from art import logo alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] ...
# Script Name : create_dir_if_not_there.py # Author : Craig Richards # Created : 09th January 2012 # Last Modified : # Version : 1.0 # Modifications : # Description : Checks to see if a directory exists in the users home directory, if not then create it import os # Import the OS module home = os.pat...
from Tkinter import * import Image, ImageTk, ImageDraw, sys, math import phm, time class disp: """ Class for displaying items in a canvas using a global coordinate system. """ border = 2 pad = 4 bgcolor = '#dbdbdb' bordcol = '#555555' gridcol = '#e0e0e0' gridcol2 ='#e0e0e0' text...
# Pretty-printer utilities. # Copyright (C) 2013-2014 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any l...
#!/usr/bin/python3 # File name: vista.py # Version: 1.0.0 # Author: Joseph Adams # Email: [email protected] # Date created: 7/15/2020 # Date last modified: 4/19/2021 import sys import json import requests try: stdinput = sys.stdin.readline() data = json.loads(stdinput) ip = data['params']['ip'] midiport = ...
#! /usr/bin/python import hacking if __name__ == '__main__': hacking.reexec_if_needed('spartan6.py') from myhdl import Signal, SignalType, ResetSignal, instance, always_comb, intbv, always, always_seq use_xilinx = 1 _one = '1\'b1' _zero = '1\'b0' def make_params(**kwargs): params = [] for k, v in kwargs...
from docker import Client cli = Client(base_url='unix://var/run/docker.sock') print (cli.info())
# Generated by Django 3.1.7 on 2021-05-05 08:41 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app01', '0002_auto_20210426_1559'), ] operations = [ migrations.CreateModel( name='UserProfile'...
""" Public interface to OMeta, as well as the grammars used to compile grammar definitions. """ from .builder import TreeBuilder, moduleFromGrammar from .boot import BootOMetaGrammar from .bootbase import BootBase class OMeta(BootBase): """ Base class for grammar definitions. """ metagrammarClass = Boo...
from django.apps import AppConfig class ArgumentConfig(AppConfig): name = 'demoslogic.arguments'
import onnx from onnx import helper from onnx import TensorProto graph = helper.make_graph( [ # nodes # fusable, const_min_negative should be replaced helper.make_node("Conv", ["X", "W"], ["conv0_out"], "Conv0"), helper.make_node("Clip", ["conv0_out", "const_min", "const_max"], ["clip0_out...
#!/usr/bin/env python import argparse import time import subprocess import json import logging import os import sys from uuid import uuid1 import imageio from PIL import Image from ..util import get_api from .upload import upload_file logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def parse_ar...
SEARCH = "http://api.elsevier.com/content/search/scopus" SEARCH_AUTHOR = "http://api.elsevier.com/content/search/author" AUTHOR = "http://api.elsevier.com/content/author/author_id" ABSTRACT = "http://api.elsevier.com/content/abstract/scopus_id" CITATION = "http://api.elsevier.com/content/abstract/citations" SERIAL_SEAR...
import os import sys this_path = os.path.dirname(os.path.realpath(__file__)) root_path = os.path.realpath(os.path.join(this_path, '..', '..')) if root_path not in sys.path: sys.path.insert(0, root_path)
from django.db import models from mptt.models import MPTTModel, TreeForeignKey import os from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class SoftDeletableQuerySet(models.query.QuerySet): def delete(self): self.update(dele...
import json from . import models async def post_infraction( client, *, guild_id, target_id, moderator_id, reason, case_type, extras=None, cross_guild=False, pardoned=False ): if extras is None: extras = {} extras = json.dumps(extras) conn = client.da...
from pypureclient.flashblade import SyslogServerPostOrPatch # Post a syslog server using a TCP connection attr = SyslogServerPostOrPatch(uri='tcp://my_syslog_host.domain.com:541') res = client.post_syslog_servers(syslog_server=attr, names=["main_syslog"]) print(res) if type(res) == pypureclient.responses.ValidResponse...
#!/usr/bin/python # ## @file # # Joystick monitoring class specialized for a Gamepad 310 controller. # # Hazen 01/14 # import storm_control.hal4000.joystick import storm_control.sc_hardware.logitech.gamepad310 as gamepad310 # Debugging import storm_control.sc_library.hdebug as hdebug class AJoystick(joystick.Joysti...
C = int(input()) while(C > 0): N = int(input()) vector = [] for i in range(N): if i%2 == 0: vector.append(1) else: vector.append(-1) print(sum(vector)) C -= 1
from typing import List, Dict from abc import ABC, abstractmethod import numpy as np from tdw.add_ons.model_verifier.model_tests.model_test import ModelTest from tdw.librarian import ModelRecord from tdw.tdw_utils import TDWUtils from tdw.output_data import OutputData, Images class RotateObjectTest(ModelTest, ABC): ...
from typing import Dict import pytest from genshin import MultiCookieClient @pytest.mark.asyncio async def test_multicookie(cookies: Dict[str, str], uid: int): client = MultiCookieClient() client.set_cookies([cookies]) assert len(client.cookies) == 1 assert client.cookies[0] == {m.key: m.value for ...
# auth things import sys import getopt # import custom functions from scraper import load_page, minervascrape, minervaupdate, send_email arguments = sys.argv[1:] short_options = "u" long_options = ["update"] # validating command-line flags and arguments try: args, values = getopt.getopt(arguments, short_options,...
# Generated by Django 3.0 on 2020-01-16 11:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0007_auto_20200116_1648'), ] operations = [ migrations.AlterField( model_name='dailyweight', name='date_t...
############################################################################## # # Copyright (c) 2004 Zope Foundation 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 SOF...