content
stringlengths
5
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import json from ..models import PermissionModel as Model from ..models import GroupPermissionModel from .base_dao import BaseDao class PermissionDao(BaseDao): def add_permission(self, permission): # 如果存在相同app codename,...
from itertools import permutations with open("input.txt") as f: data = [int(i) for i in f.read().split("\n")] preamble = 25 for d in range(preamble + 1, len(data)): numbers = data[d - (preamble + 1):d] target = data[d] sol = [nums for nums in permutations(numbers, 2) if sum(nums) == target] ...
import collections import pathlib import time from multiprocessing import Process from typing import Any, Callable, Dict, List, Optional, Tuple, Union from omegaconf import OmegaConf from gdsfactory import components from gdsfactory.config import CONFIG, logger from gdsfactory.doe import get_settings_list from gdsfac...
#!/usr/bin/env python import os import sys import logging import requests import time from extensions import valid_tagging_extensions from readSettings import ReadSettings from autoprocess import plex from tvdb_mp4 import Tvdb_mp4 from mkvtomp4 import MkvtoMp4 from post_processor import PostProcessor from logging.confi...
def do_print(): print "hello world" def add(a, b): return a + b def names_of_three_people(a, b, c): return a['name'] + " and " + b['name'] + " and " + c['name'] def divide(a, b): return a / b def float_divide(a, b): return float(a) / float(b) def func_return_struct(name, age, hobby1, hobb...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- from marshmallow import fields, post_load, validate from typing import Optional from ..schema import PatchedSchemaMeta from ..fields...
from typing import Union, List, Dict from py_expression_eval import Parser # type: ignore import math from . import error def add(num1: Union[int, float], num2: Union[int, float], *args) -> Union[int, float]: """Adds given numbers""" sum: Union[int, float] = num1 + num2 for num in args: ...
# # This file is part of DroneBridge: https://github.com/seeul8er/DroneBridge # # Copyright 2017 Wolfgang Christl # # 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.apac...
import errno import gc # from collections import namedtuple import math import os import os.path import time from functools import lru_cache from pathlib import Path import numpy as np import pandas as pd import artistools as at @lru_cache(maxsize=8) def get_modeldata(inputpath=Path(), dimensions=None, get_abundanc...
#Codeacademy's Madlibs from datetime import datetime now = datetime.now() print(now) story = "%s wrote this story on a %s line train to test Python strings. Python is better than %s but worse than %s -------> written by %s on %02d/%02d/%02d at %02d:%02d" story_name = raw_input("Enter a name: ") story_line = raw_inpu...
import logging import os import json from pprint import pformat import pysftp from me4storage.common.exceptions import ApiError logger = logging.getLogger(__name__) def save_logs(host, port, username, password, output_file): cnopts = pysftp.CnOpts(knownhosts=os.path.expanduser(os.path.join('~','.ssh','known_hos...
import builtins import traceback from os.path import relpath def dprint(*args, **kwargs): """Pre-pends the filename and linenumber to the print statement""" stack = traceback.extract_stack()[:-1] i = -1 last = stack[i] if last.name in ('clearln', 'finish'): return builtins.__dict__['oldp...
import config_cosmos import azure.cosmos.cosmos_client as cosmos_client import json from dateutil import parser def post_speech(speech_details, category): speech_details = speech_details.copy() collection_link = "dbs/speakeasy/colls/" + category speech_details["id"] = speech_details["user_name"] + "_" + sp...
#!/usr/bin/env python # Outputs the relative error in a particular stat for deg1 and deg2 FEM. # Output columns: # mesh_num medianEdgeLength deg1Error deg2Error import sys, os, re, numpy as np from numpy.linalg import norm resultDir, stat = sys.argv[1:] # Input data columns meshInfo = ["mesh_num", "corner_angle", "me...
""" Here we implement some simple policies that one can use directly in simple tasks. More complicated policies can also be created by inheriting from the Policy class """ import logging import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical, Normal, Bernoulli c...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('person', '__first__'), ] operations = [ migrations.CreateModel( name='Attendee', fields=[ ...
class GPSlocation: """used to translate the location system""" _prop_ = 'GPSlocation' import math pi = 3.1415926535897932384626 a = 6378245.0 ee = 0.00669342162296594323 def gcj02_to_wgs84(self, lng, lat): """GCJ02 system to WGS1984 system""" dlat = self._transformlat(lng - 1...
# -*- coding: utf-8 - import re import copy import urllib import urllib3 import string import dateutil.parser from iso8601 import parse_date from robot.libraries.BuiltIn import BuiltIn from datetime import datetime, timedelta import pytz TZ = pytz.timezone('Europe/Kiev') def get_library(): return BuiltIn().get_l...
import sys sys.path.append("C:\Program Files\Vicon\Nexus2.1\SDK\Python") import ViconNexus import numpy as np import smooth vicon = ViconNexus.ViconNexus() subject = vicon.GetSubjectNames()[0] print 'Gap filling for subject ', subject markers = vicon.GetMarkerNames(subject) frames = vicon.GetFram...
from jinja2 import DictLoader, Environment import argparse import json import importlib import random import string HEADER = """ #pragma once #include <rapidjson/rapidjson.h> #include <rapidjson/writer.h> #include <rapidjson/reader.h> #include <iostream> #include <string> #include <vector> #include <map> struct...
def summary(p,c=10,x=5): print('-' * 30) print(f'Value Summary'.center(30)) print('-' * 30) print(f'{"analyzed price:"} \t{coins(p)}') print(f"{'Half-price: '} \t{half(p, True)}") print(f'{"double the price: "}\t{double(p, True)}') print(f'{c}% {"increase: ":} \t{increase(p, c, True)...
from ._sha512 import sha384
from app import app, api from flask import request from flask_restful import Resource import json import pprint import os import subprocess import traceback import logging class WelcomeController(Resource): def get(self): return {'welcome': "welcome, stranger!"} api.add_resource(WelcomeController, '/')
import os from dotenv import dotenv_values config = { **dotenv_values(os.path.join(os.getcwd(), ".env")), **os.environ } VERSION = "0.0.0-alfa" APP_HOST = config['APP_HOST'] APP_PORT = int(config['APP_PORT']) APP_DEBUG = bool(config['APP_DEBUG'])
# -*- coding: utf-8 -*- """ Views for the stats application. """ # standard library # django # models from .models import Stat # views from base.views import BaseCreateView from base.views import BaseDeleteView from base.views import BaseDetailView from base.views import BaseListView from base.views import BaseUpdat...
"""Session class and utility functions used in conjunction with the session.""" from .session import Session from .session_manager import SessionManager __all__ = ["Session", "SessionManager"]
''' 046 Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0 , com um pausa de 1 seg entre eles''' from time import sleep for c in range(10, -1, -1): print(c) sleep(1) print('Fogos !!!!!')
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Shun Arahata """ Imitation learning environment """ import pathlib # import cupy as xp import sys import numpy as xp current_dir = pathlib.Path(__file__).resolve().parent sys.path.append(str(current_dir) + '/../mpc') sys.path.append(str(current_dir) + '/../') from ...
# -*- Python -*- # Copyright 2021 The Verible 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 applicable la...
# https://github.com/ArtemNikolaev/gb-hw/issues/23 def run(array): return [ array[i] for i in range(1, len(array)) if array[i] > array[i-1] ] test_input = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] print(run(test_input))
import glob from hdf5_getters import * import os import numpy as np from collections import Counter from music_utils import * tags_list = [] data_path = "/mnt/snap/data/" count = 0 for root, dirs, files in os.walk(data_path): files = glob.glob(os.path.join(root, '*h5')) #if count > 1000: break for f in fi...
#!/usr/bin/env python3 import time from data_output import DataOutput from html_downloader import HtmlDownloader from html_parser import HtmlParser __author__ = 'Aollio Hou' __email__ = 'aollio@outlook.com' class Spider: def __init__(self): self.downloader = HtmlDownloader() self.parser = HtmlPa...
from django import forms from .models import Project class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ["title", "describe", "technology"]
#!/usr/bin/env python # encoding: utf-8 """Terminal UI for histdata_downloader project.""" import os import sys import logging import subprocess from datetime import date import time import npyscreen from histdata_downloader.logger import log_setup from histdata_downloader.histdata_downloader import load_available_p...
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Jython example AMF server and client with Swing interface. @see: U{Jython<http://pyamf.org/wiki/JythonExample>} wiki page. @since: 0.5 """ import logging from wsgiref.simple_server import WSGIServer, WSGIRequestHandler from pyamf.remoting.gatewa...
from autodisc.systems.lenia.classifierstatistics import LeniaClassifierStatistics from autodisc.systems.lenia.isleniaanimalclassifier import IsLeniaAnimalClassifier from autodisc.systems.lenia.lenia import *
# MIT License # # Copyright (c) 2017 Anders Steen Christensen # # 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, mo...
import dash, os, itertools, flask from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html from pandas_datareader import data as web from datetime import datetime as dt import plotly.graph_objs as go import pandas as pd from random import randint import p...
import tanjun import typing from hikari import Embed from modules import package_fetcher component = tanjun.Component() @component.with_command @tanjun.with_argument("repo_n", default="main") @tanjun.with_argument("arch_n", default="aarch64") @tanjun.with_argument("pkg_n", default=None) @tanjun.with_parser @tanjun.a...
# Copyright 2020 The FastEstimator 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 appl...
import data from base import nbprint from tokenizer.main import run_tokenizer def check_requirements(info): # Check if tokens file exists if not data.tokenized_document_exists(info): # Run Tokenizer nbprint('Tokens missing.') run_tokenizer(info) # Check if it was successfull ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
import numpy as np a = input("enter the matrix with ; after each row : ") m =np.matrix(a) b = input("enter the matrix 2 with row matching with matrix 1 : ") n =np.matrix(b) print(m) print(n) m3 = np.dot(m,n) print(m3)
#//////////////#####/////////////// # # ANU u6325688 Yangyang Xu # Supervisor: Dr.Penny Kyburz # SPP used in this scrip is adopted some methods from : # https://github.com/yueruchen/sppnet-pytorch/blob/master/cnn_with_spp.py #//////////////#####/////////////// """ Policy Generator """ import torch.nn as nn from GAIL....
#!/usr/bin/env python3 from __future__ import print_function import sys import os import time sys.path.append('..') import childmgt.ChildMgt def create_children(num_children=5): for child_num in range(0, num_children): child_pid = os.fork() if child_pid == 0: time.sleep(3) s...
#!/usr/bin/env python import rospy from week2.srv import roboCmd, roboCmdResponse import math as np class Unicycle: def __init__(self, x, y, theta, dt=0.05): self.x = x self.y = y self.theta = theta self.dt = dt self.x_points = [self.x] self.y_points = [self.y] ...
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 """ Get Jc, RA, etc from measured parameter DB BB, 2015 """ import sqlite3 import numpy as np import matplotlib.pyplot as plt # display units unit_i = 1e-6 # uA unit_v = 1e-6 # uV unit_r = 1 # Ohm unit_i1 = 1e-3 # mA; control I unit_v1 = 1e-3 # mV; cont...
# # PySNMP MIB module ZHONE-COM-IP-DHCP-SERVER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-DHCP-SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:40:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
"""Implementation classes that are used as application configuration containers parsed from files. """ __author__ = 'Paul Landes' from typing import Dict, Set import logging import re import collections from zensols.persist import persisted from . import Configurable, ConfigurableError logger = logging.getLogger(__n...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 from test_utils.label_to_str_voc import convert_label_to_str def render_boxs_info_for_display(image, net_out, select_index, net_score, image_size, label_out = None): v...
import unittest import numpy as np from sca.analysis import nicv class TestNicvUnit(unittest.TestCase): def test_calculate_mean_x_given_y_matrix(self): """ Tests whether the calculations of means work properly""" traces = np.array([[1, 2, 3], [4, 5, 6], [7, 0.4, 9], [2, 3, 12]]) plain = ...
# coding: utf-8 # In[ ]: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn import tree get_ipython().run_line_magic('matplotlib', 'inline') # In[ ]: def maybe_load_loan_data(threshold=1, path='../input/loan.csv', force='n'): def load_data(): da...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as torch_models class PerceptualLoss(nn.Module): def __init__(self, rank): super(PerceptualLoss, self).__init__() self.rank = rank self.vgg19 = torch_models.vgg19(pretrained=True) self.vgg...
""" Generates a powershell script to install Windows agent - dcos_install.ps1 """ import os import os.path import gen.build_deploy.util as util import gen.template import gen.util import pkgpanda import pkgpanda.util def generate(gen_out, output_dir): print("Generating Powershell configuration files for DC/OS"...
#!/usr/bin/python3 #Self Written Module to Decrypt Files #========================================================= #This Module is Written to Reverse_Attack of Ransomeware #========================================================= # Reverse_Attack # |____*****TAKES 1 ARGUMENTS, i.e. KEY ***** # |____Initia...
#! /usr/bin/env python # -*- coding: utf-8 -*- # ****************************************************** # @author: Haifeng CHEN - optical.dlz@gmail.com # @date (created): 2019-12-12 09:07 # @file: memory_monitor.py # @brief: A tool to monitor memory usage of given process # @internal: ...
##序列解包 dict={"name":"jim","age":"1","sex":"male"} key,value=dict.popitem(); print(key,value) #使用*号收集多余的值 a,b,*rest=[1,2,3,4]; print(a,b,rest) ##链式赋值 x=y=somfunction() ##增强赋值 x+=1 ###代码块
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pydoc import subprocess import sys import signal from pkg_resources import get_distribution from termcolor import colored from projects import config from projects import gui from projects import paths from projects import projectfile __version__ = get_...
"""Frigate API client.""" from __future__ import annotations import asyncio import logging import socket from typing import Any, Dict, List, cast import aiohttp import async_timeout from yarl import URL TIMEOUT = 10 _LOGGER: logging.Logger = logging.getLogger(__name__) HEADERS = {"Content-type": "application/json;...
import jieba import jieba.posseg as pseg #词性标注 import jieba.analyse as anls #关键词提取 class Fenci: def __init__(self): pass #全模式和精确模式 def cut(self,word,cut_all=True): return jieba.cut(word, cut_all=True) #搜索引擎模式 # def cut_for_search(self,word): # return jieba.cut_for_search(w...
''' Unit tests for the environments.py module. ''' import boto3 import json import pytest from mock import patch from moto import ( mock_ec2, mock_s3 ) from deployer.exceptions import ( EnvironmentExistsException, InvalidCommandException) import depl...
#!/usr/bin/env python3 # coding: utf-8 # print の出力時に日本語でもエラーが出ないようにするおまじない import sys import io sys.stdout = io.TextIOWrapper( sys.stdout.buffer, encoding='utf-8' ) # CGIとして実行した際のフォーム情報を取り出すライブラリ import cgi form_data = cgi.FieldStorage( keep_blank_values = True ) # MySQLデータベース接続用ライブラリ import MySQLdb con = None cur =...
#!/usr/bin/env python3 # coding: utf-8 import os import sys import re import numpy as np #==============================================================================# def atomgroup_header(atomgroup): """ Return a string containing info about the AtomGroup containing the total number of atoms, th...
from pydantic import BaseModel class ConsumerResponse(BaseModel): topic: str timestamp: str product_name: str product_id: int success: bool
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `te_python` module.""" import pytest import requests from te_python import te_python def test_te_python_initialization(): response = te_python.email_get_details('a53b7747d6bd3f59076d63469d92924e00f407ff472e5a539936453185ecca6c') assert isinstance(re...
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=64) surname = models.CharField(max_length=64) class Meta: app_label = 'person' db_table = 'person' ordering = ('surname', 'first_name')
from util.Tile import Tile from util.Button import Button from util.Maze import Maze from algorithms.BFS import BFS from algorithms.DFS import DFS from algorithms.GFS import GFS from algorithms.AStar import AStar from math import floor import pygame class Grid: def __init__(self, width, height, tile...
# Copyright 2021 Google LLC # # 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 writing, ...
from discord.ext import commands from discord_bot.bot import Bot class Admin(commands.Cog): """Admin commands that only bot owner can run""" def __init__(self, bot: Bot): self.bot = bot @commands.command(name="shutdown", hidden=True) @commands.is_owner() async def shutdow(self, ctx: com...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
from ctypes import CDLL, sizeof, create_string_buffer def test_hello_world(workspace): workspace.src('greeting.c', r""" #include <stdio.h> void greet(char *somebody) { printf("Hello, %s!\n", somebody); } """) workspace.src('hello.py', r""" import ctypes lib = ctypes.CDLL('./g...
from gui import GUI program = GUI() program.run()
#!/usr/bin/env python3 # # RoarCanvasCommandsEdit.py # Copyright (c) 2018, 2019 Lucio Andrés Illanes Albornoz <lucio@lucioillanes.de> # from GuiFrame import GuiCommandDecorator, GuiCommandListDecorator, GuiSelectDecorator import wx class RoarCanvasCommandsEdit(): @GuiCommandDecorator("Hide assets window", "Hide a...
#!/usr/bin/python3 """ Module installation file """ from setuptools import Extension from setuptools import setup extension = Extension( name='fipv', include_dirs=['include'], sources=['fipv/fipv.c'], extra_compile_args=['-O3'], ) setup(ext_modules=[extension])
import os import time import hashlib import gzip import shutil from subprocess import run from itertools import chain CACHE_DIRECTORY = "downloads_cache" def decompress_gzip_file(filepath): decompressed = filepath + ".decompressed" if not os.path.exists(decompressed): with gzip.open(filepath, 'rb') ...
from MainWindow import Ui_MainWindow from PyQt6 import QtWidgets import sys class CalcWindow(Ui_MainWindow, QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.equalButton.clicked.connect(self.calculation) self.cBu...
from tornado.web import HTTPError class APIError(HTTPError): def __init__( self, status_code: int, reason: str, message: str = None, details: dict = None, ): log_message = ': '.join(map(str, filter(None, [message, details]))) or None super().__init__( ...
#!/usr/bin/python # Report generator import api import fn import sys import dumper def main(argv): config = {} config["usagetext"] = ("repgen.py (-s SEARCHPREFIX|-a) [-c CONFIGFILE]\n"+ " This script generates a report for all servers if -a is used,\n"+ "or just the servers with SEARCH...
import os import logging import json from codecs import open from collections import Counter import numpy as np import spacy from tqdm import tqdm """ The content of this file is mostly copied from https://github.com/HKUST-KnowComp/R-Net/blob/master/prepro.py """ nlp = spacy.blank("en") def word_tokenize(sent): ...
''' Clase principal, contiene la logica de ejecución del servidor y rutas para consumo de la API ''' from entities.profile import Profile from flask import Flask, jsonify, request from flask_restful import Resource, Api from flask_httpauth import HTTPBasicAuth from datetime import datetime import pandas as pd import nu...
from glitchtip.permissions import ScopedPermission class ReleasePermission(ScopedPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin", "project:releases"], "POST": ["project:write", "project:admin", "project:releases"], "PUT": ["project:write", "project:admin...
# StandAlone Version """ Created on Thu Apr 2 19:28:15 2020 @author: Yao Tang """ import arcpy import os arcpy.env.overwriteOutput = True arcpy.env.addOutputsToMap = True ## Specify workspace(Usually the folder of the .mxd file) arcpy.env.workspace = "L:/Projects/3020/006-01/6-0 DRAWINGS AND FIGURES/6-...
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="crudini", version="0.9.3", author="Pádraig Brady", author_email="P@draigBrady.com", description=("A utility for manipulating ini fi...
def abc209d(): from collections import deque n, Q = map(int, input().split()) g = [list() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a, b = a - 1, b - 1 g[a].append(b) g[b].append(a) c = [-1] * n q = deque([0]) c[0] = 0 whil...
from sim.agents.agents import * from sim.agents.multiagents import *
# -*- coding: utf-8 -*- # Copyright (c) 2016, French National Center for Scientific Research (CNRS) # Distributed under the (new) BSD License. See LICENSE for more info. from pyqtgraph.Qt import QtCore import pyqtgraph as pg from pyqtgraph.util.mutex import Mutex import numpy as np from ..core import (Node, register_...
""" Copyright 2018 The Johns Hopkins University Applied Physics Laboratory. 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 applicabl...
"Thread safe RLock defined for lru cache." # https://stackoverflow.com/questions/16567958/when-and-how-to-use-pythons-rlock def RLock(): """ Make the container thread safe if running in a threaded context. """ import threading return threading.RLock()
import logging _LOGGER = logging.getLogger(__name__) def decode(packet): """ https://github.com/telldus/telldus/blob/master/telldus-core/service/ProtocolEverflourish.cpp """ data = packet["data"] house = data & 0xFFFC00 house >>= 10 unit = data & 0x300 unit >>= 8 unit += 1 ...
# script to copy history from a FITS table to the FITS header # FITS images only, works in current directory # Argument: # 1) Name of input FITS # example: # Python scriptHi2Header.py myImage.fits import sys, Obit, Image, History, OSystem, OErr # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Hi2Header", 1, 100,...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'superDigit' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. STRING n # 2. INTEGER k # def superDigit(n, k): if((len(n) == 1)and(k>1)): n,k = str...
# # Copyright 2015-2020 Andrey Galkin <andrey@futoin.org> # # 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 applicabl...
import stringcase from importlib import import_module from .metadata import Metadata from .resource import Resource from .package import Package from . import helpers from . import errors class Pipeline(Metadata): """Pipeline representation API | Usage -------- | -------- Public | `from fricti...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import re from contextlib import contextmanager from dataclasses import dataclass from textwrap import dedent from typing import Any from pants.engine.internals.engine_testutil import ( ...
# Copyright 2016 Pavle Jonoski # # 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 writing...
f = open('3_input.txt').read().splitlines() def life_support_rating(o2, co2): return o2 * co2 def filter(list, i=0, co2=False): # where `i` is the bit position if len(list) == 1: return list[0] count = 0 for item in list: count += int(item[i]) dom_num = 1 if count >= len(list) / 2 ...
import pytest import numpy from thinc.layers import Embed from ...layers.uniqued import uniqued from numpy.testing import assert_allclose from hypothesis import given from hypothesis.strategies import integers, lists, composite ROWS = 10 # This test uses a newer hypothesis feature than the skanky flatmap-style # I us...
from datasets.SOT.dataset import SingleObjectTrackingDatasetSequence_MemoryMapped from ._common import _check_bounding_box_validity class SOTSequenceSequentialSampler: def __init__(self, sequence: SingleObjectTrackingDatasetSequence_MemoryMapped): assert len(sequence) > 0 self.sequence = sequence ...
from django.db import models from django.urls import reverse class ImportantDate(models.Model): date = models.DateField() desc = models.CharField(max_length=100) def __str__(self): return "{} - {}".format(self.date, self.desc) def get_absolute_url(self): return reverse('formschapter:...
from django.contrib import admin from purchasing.models import PurchasedOrder class PurchasedOrderAdmin(admin.ModelAdmin): readonly_fields = ['expiration_date'] admin.site.register(PurchasedOrder)