content
stringlengths
5
1.05M
from typing import List, Optional, Union from fedot.core.dag.graph_node import GraphNode from fedot.core.data.data import InputData, OutputData from fedot.core.log import Log, default_log from fedot.core.operations.factory import OperationFactory from fedot.core.operations.operation import Operation, get_default_param...
from django.urls import path from .views import email_list_signup, contact_form, subscribe urlpatterns = [ # path('email-signup/', email_list_signup, name='email-list-signup'), path('subscribe/', email_list_signup, name='subscribe'), path('contact/', contact_form, name='contact') ]
import code.main as cm def test_correctness(): assert cm.inc(3) == 4 def test_incorrectness(): assert not cm.inc(3) == 5
from Model.filemodel import file_model import tkinter.messagebox from Encryption.crypto import encrypter from tkinter import * from tkinter.filedialog import askdirectory, askopenfilenames from GUI.ContextMenuListBox import ContextMenuListBox from tkinter import ttk from os.path import * from os import path class Main...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Template' db.create_table('django_template', ( ('id', self.gf('django.db.models.field...
"""Kaptos schema module.""" import roax.schema as s class bearing(s.float): """Bearing, in degrees.""" def __init__(self, **kwargs): super().__init__(**kwargs) def validate(self, value): if value < 0.0 or value >= 360.0: raise SchemaError("invalid bearing; must be 0.0 ≤ degr...
from aoc2021.util import get_input from aoc2021.day02 import submarine def solve_part1(entries): sub = submarine.Submarine() sub.navigate(entries) return sub.position.horizontal * sub.position.depth def solve_part2(entries): sub = submarine.Submarine2() sub.navigate(entries) return sub.posit...
# Copyright (C) 2017 Nippon Telegraph and Telephone Corporation. # # 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 appli...
__author__ = 'Sean Yu' '''created @2015/10/26''' # -*- coding: UTF-8 -*- __author__ = 'Sean Yu' __mail__ = 'try.dash.now@gmail.com' ''' created 2015/9/18  ''' import unittest import os import sys pardir =os.path.dirname(os.path.realpath(os.getcwd())) #pardir= os.path.sep.join(pardir.split(os.path.sep)[:-1]) sys.path.a...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-31 21:14 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20171031_2019'), ] operations ...
from PyQt4 import QtCore, QtGui import thread import tensorflow as tf from rospy import Time from keras.models import load_model from keras.backend import set_session from Model.WorldModel import WorldModel from Model.EgoVehicle import EgoVehicle from Model.TargetVehicle import TargetVehicle from Model.Road import Roa...
from wok.contrib.hooks import HeadingAnchors hooks = { 'page.template.post': [ HeadingAnchors() ], }
#setup.py build --compiler=mingw32 from distutils.core import setup, Extension setup (name = '_omniscience', ext_modules = [Extension('_omniscience',sources = ['_omniscience.c'],extra_compile_args=['-std=gnu99','-Ofast'])]) import shutil shutil.copy("./build/lib.win32-2.7/_omniscience.pyd",".")
import os from setuptools import setup import xenon with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fobj: readme = fobj.read() with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as fobj: reqs = fobj.read().splitlines() setup(name='xenon', version=xenon.__version...
""" Solves a variation of optimization problem of targeted Pagerank. It solves the targeted optimization problem as described in "Fairness-Aware Link Analysis"[1] paper but for the topk of the pagerank algorithm. It also preserve the order of these nodes compare to simple targeted. Makes use of cvx optimization p...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: attestation.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf...
from flask_jwt_extended import jwt_required from {{cookiecutter.app_name}}.commons.resource import BaseResource from {{cookiecutter.app_name}}.models import User from {{cookiecutter.app_name}}.extensions import ma, db from {{cookiecutter.app_name}}.commons.pagination import paginate # Note, when developing v2, v3, e...
from django.core.checks.messages import Error from django.shortcuts import render from groups.db.group_forum_data_fetch import GroupDataFetch from groups.models import Group, GroupUser from groups.models import GroupComment from groups.db.groups_data_fetch import Groups def groups(request): context = { "t...
# helper function that waits for a given txid to be confirmed by the network def wait_for_confirmation(client, transaction_id, timeout): start_round = client.status()["last-round"] + 1 current_round = start_round while current_round < start_round + timeout: try: pending_txn = client.pen...
from db_analysis import *
# This file is part of the Blockchain Data Trading Simulator # https://gitlab.com/MatthiasLohr/bdtsim # # Copyright 2021 Matthias Lohr <mail@mlohr.com> # # 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...
class Node: def __init__(self,data=None,next_node=None): self.data = data self.next_node = next_node def get_data(self): return self.data def get_next(self): return self.next_node def set_next(self,new_node): self.next_node = new_node class Queue:...
# Copyright (c) 2013 The SAYCBridge Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core.position import * from core.call import Call from suit import SUITS import copy import math import operator # I'm not sure this needs to b...
import numpy as np import os data = np.genfromtxt(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'stockholm_td_adj.tsv')) mask_feb = data[:,1] == 2 # La temperatura está en la columna 3 np.mean(data[mask_feb,3]) # -3.2121095707365961 # Podemos hasta graficarlo import matplotlib.pyplot as plt mon...
from typing import List from sqlmodel import Session from models.permission import Permission, PermissionCreate, PermissionRead, PermissionUpdate from models.user import UserSession from services.base import BaseService from helpers.exceptions import ApiException from repositories.permission import PermissionRepository...
#!/usr/bin/env python3 from hpecp import ContainerPlatformClient import time client = ContainerPlatformClient(username='admin', password='admin123', api_host='127.0.0.1', api_port=8080, u...
import sys from queue import PriorityQueue v, e = map(int, sys.stdin.readline().split()) k = int(sys.stdin.readline()) inf = float('inf') graph = [[] for _ in range(v)] # 간선의 도착점을 입력하기 위한 list (노드수가 20000이기 때문에 v*v 행렬은 약 1.6GB로 메모리 초과) # 출발점과 도착점이 같고 비용이 다른 경우를 위해서도 v*v를 사용하지 않는다. cost = [[] for _ in range(v)] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helpers for checking if possible to move forward to next page.""" # pylint: disable=invalid-name,broad-except import math import re def get_pages(pagination, verbose=False): """Get current page#, page# of the displayed listings and all pages.""" # Total ...
from vit.formatter.entry import Entry class EntryRemaining(Entry): def format(self, entry, task): return self.remaining(entry)
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: proto/position.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.proto...
""" Generic has no implementation in Python """
#!/usr/bin/python # -*- coding: utf-8 -*- # # Initial implementation of The Matrix # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. ...
from flask import Flask, request from implement2D import Calc from numpy import random from pprint import pprint import webbrowser import json app = Flask(__name__) def checkContours(cItem): if cItem == 'isolado': return None else: return float(cItem) @app.route("/") def root(): return app.send_static...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from django.views.generic.base import TemplateView class DeviceManagementView(TemplateView): template_name = "device_management.html"
# Hangman import random # Needed to get a random word from the list of words from functions import split # Needed to store functions in a separate file # Error message for when the user enters an invalid number invalidNumber = "Your number must be an integer equal to or greater than 1." # List of words words = ["d...
import javabridge import matplotlib matplotlib.use("module://backend_swing") import matplotlib.figure import backend_swing import numpy as np import threading import matplotlib.pyplot as plt def popup_script_dlg(canvas): joptionpane = javabridge.JClassWrapper("javax.swing.JOptionPane") jresult = joptionpane.sh...
import time import stacktrain.config.general as conf import stacktrain.batch_for_windows as wbatch # ----------------------------------------------------------------------------- # Conditional sleeping # ----------------------------------------------------------------------------- def conditional_sleep(seconds): ...
from flask import Flask from flask_restful import Api, Resource app = Flask(__name__) api = Api(app) names = {"tim": {"age": 19, "gender":"male"}, "bill": {"age": 70, "gender":"male"}} class HelloWorld(Resource): def get(self, name): return names[name] api.add_resource(HelloWorld, "/hello...
import random from typing import Tuple, List import PySimpleGUI as sg from omegaconf import DictConfig import openFACS PROTOTYPICAL_EXPRESSIONS_NORMALIZED: dict = { "anger": [0.0, 0.0, 1.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.6, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "contempt": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0...
import torch import torch.nn as nn from torch.nn.init import xavier_uniform_ from models.topic import MultiTopicModel from others.vocab_wrapper import VocabWrapper from others.id_wrapper import VocIDWrapper class Model(nn.Module): def __init__(self, args, device, vocab, checkpoint=None): super(Model, se...
import pandas def load(path: str) -> pandas.DataFrame: rows = [] with open(path, "r", encoding="latin-1") as data_in: for line in data_in: fine_category, input = line.split(None, 1) coarse_category, _ = fine_category.split(":") rows.append({ ...
import sys from twisted.internet import defer, reactor, error from twisted.python.failure import Failure from twisted.python.filepath import FilePath from twisted.conch.endpoints import SSHCommandClientEndpoint, _CommandChannel from twisted.internet.protocol import Factory, Protocol from blinker import signal from p...
from mock import MagicMock, patch from tornado_sqlalchemy_login.utils import ( parse_body, construct_path, safe_get, safe_post, safe_post_cookies, ) def foo(*args, **kwargs): raise ConnectionRefusedError() class TestUtils: def test_parse_body(self): m = MagicMock() m.body...
def count_substring(string, sub_string): start_list = [i for i, e in enumerate(string) if e == sub_string[0]] result = 0 for idx in start_list: if idx + len(sub_string) <= len(string): if string[idx:idx+len(sub_string)] == sub_string: result = result + 1 return result...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from osintsan import menu from osintsan import main1 from plugins.maildb import maildb from plugins.macaddress import MacAddressLookup from prompt_toolkit import prompt from plugins.bear import google # Банеры from module.utils.banner import show_banner f...
from __future__ import annotations import uvicore import inspect from copy import copy from functools import partial from uvicore.contracts import Router as RouterInterface from uvicore.contracts import Package as PackageInterface from uvicore.contracts import Routes as RoutesInterface from uvicore.support.module impor...
import json from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship db = SQLAlchemy() association_table = db.Table( 'usergroups', db.metadata, db.Column('uid', db.Integer, db.ForeignKey('users.id')), db.Column('gid', db.Integer, db.ForeignKey('groups.id')) ) class User(db.Mode...
# coding=utf-8 """ Inception-v3, model from the paper: "Rethinking the Inception Architecture for Computer Vision" http://arxiv.org/abs/1512.00567 Original source: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/imagenet/classify_image.py License: http://www.apache.org/licenses/LICENSE-2.0 ...
# user defined class that makes use of the sub classes of the CalculatorError class # CalculatorError class has the OperandError and OperatorError extending it # Calculator class uses these two subclasses to check for errors (operand and operator errors) from operanderror import OperandError from operatorerror import O...
# -*- coding: utf-8 -*- ''' Follows the analyzer faithfully. '''
# -*- coding: utf-8 -*- """ :Module: freshpy.utils.version :Synopsis: This simple script contains the package version :Created By: Jeff Shurtliff :Last Modified: Jeff Shurtliff :Modified Date: 04 Jan 2022 """ from . import log_utils # Initialize logging logger = log_utils.initialize...
from django.db import models # Create your models here. class Autor(models.Model): nome = models.CharField(max_length=255) endereco = models.CharField(max_length=255) site = models.URLField(blank=True, null=True) email = models.EmailField() def __str__(self): return self.nome + ' - ' + sel...
class TestCase(object): def __init__(self, parameters): """ :param parameters: A list containing TestFactor objects :return: this """ self.components = parameters self.tc_len = len(parameters) self.tc_array = [None] * self.tc_len self.val_to_index_ma...
''' - Leetcode problem: 39 - Difficulty: Medium - Brief problem description: Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates ...
# Copyright 2004-present, Facebook. All Rights Reserved. from django import forms class CreateProductForm(forms.Form): title = forms.CharField( label="Product Title", max_length=255, widget=forms.TextInput( attrs={"class": "mx-4 p-2 border rounded border-gray-300 text-gray-400"...
from functools import partial from uuid import uuid1, uuid4, UUID from annotator import annotation, document from annotator.auth import DEFAULT_TTL from horus.models import ( get_session, BaseModel, ActivationMixin, GroupMixin, UserMixin, UserGroupMixin, ) import transaction from pyramid_bas...
import finding_hidden_messages_in_dna import sys def main(): input_file = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') pattern = input_file.readline().strip() text = input_file.readline().strip() expected_hamming_distance = int(input_file.readline().strip()) approximate_occurr...
# coding: utf-8 # In[1]: from magma import * class FullAdder(Circuit): name = "FullAdder" IO = ["a", In(Bit), "b", In(Bit), "cin", In(Bit), "out", Out(Bit), "cout", Out(Bit)] @classmethod def definition(io): # Generate the sum _sum = io.a ^ io.b ^ io.cin wire(_sum, io.out) ...
import json from django.core.serializers import serialize from django.db.models.query import QuerySet from django.template import Library register = Library() @register.filter() def jsonify(obj): if isinstance(obj, QuerySet): return serialize('json', obj) return json.dumps(obj)
from unittest import TestCase from mock import patch, Mock from tables.rows.builders import MovieSearchRowBuilder class MockMovie: def __init__(self, name, rotten_tomatoes_score, year, cast): self.name = name self.rotten_tomatoes_score = rotten_tomatoes_score self.year = year sel...
#!/usr/bin/env python3 """ A python package for climate scientists. """ # Global constants # NOTE: Keep databases here so that autoreload doesn't break everything DERIVATIONS = {} TRANSFORMATIONS = {} # Import functions to top-level. Recommended syntax for registries is one of: # NOTE: Submodules are for organization ...
from .base_page import BasePage from .locators import BasketPageLocators class BasketPage(BasePage): def should_be_empty_basket_message(self): assert self.is_element_present(*BasketPageLocators.BASKET_EMPTY_MESSAGE), \ "Empty basket message element not found on page" assert self.brows...
# -*- coding: utf-8 -*- """Tests for HighRes3DNet.""" import numpy as np import tensorflow as tf from nobrainer.models.highres3dnet import HighRes3DNet def test_highres3dnet(): shape = (1, 5, 5, 5) X = np.random.rand(*shape, 1).astype(np.float32) y = np.random.randint(0, 9, size=(shape), dtype=np.int32)...
import re class LEDTester(): def __init__(self, N): self.N = N self.dataGrid = [[False]*self.N for i in range(self.N)] def apply(self,i): pat = re.compile( ".*(turn on|turn off|switch)\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*through\s*([+-]?\d+)\s*,\s*([+-]?\d+).*") commands...
from discord.errors import ClientException class UnableToBuildAudioFileException(ClientException): '''Exception that's thrown when when the bot is unable to build an audio file for playback.''' def __init__(self, message): super(UnableToBuildAudioFileException, self).__init__(message) class Buildin...
import peewee as pw class Object1(pw.Model): field_1 = pw.TextField(null=True) class Object2(pw.Model): field_2 = pw.TextField(null=True)
#!/usr/bin/python # # Copyright 2015 Google Inc. 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 b...
""" Tests for protocol interaction """ import pytest from computable.helpers.transaction import call def test_w3(w3): """ Is web3 correctly setup for testing? """ assert w3.eth.defaultAccount == w3.eth.accounts[0] def test_ether_token_deploy(ether_token): """ did the ether token deploy correct...
from __future__ import unicode_literals from django.apps import AppConfig class SampleTicketConfig(AppConfig): name = 'sample_ticket'
import plotly.graph_objects as go import pandas as pd from datetime import * from Constants import * import seaborn as sns import matplotlib.pyplot as plt import numpy as np import matplotlib def dukascopy_filter_date(list_of_currencies, from_date, to_date): filtered_by_data = [] num = 0 for df in list...
"""mdsp_color_sr dataset.""" import tensorflow_datasets as tfds from . import mdsp_color_sr class MdspColorSrTest(tfds.testing.DatasetBuilderTestCase): """Tests for mdsp_color_sr dataset.""" DATASET_CLASS = mdsp_color_sr.MdspColorSr SPLITS = { "test": 1, } DL_EXTRACT_RESULT = {"face_adyo...
import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd import pickle from scipy import linalg from scipy import polyfit sns.set_context("talk") def add_season(df, copy=False): """ Add a season column to the DataFrame df from its indexes. copy: Boolean, default Fa...
# -*- coding: utf-8 -*- from .board import * from .banner import * from .post import * def all(): result = [] models = [board, banner, post] for m in models: result += m.__all__ return result __all__ = all()
import random import copy import wx import numpy from keras import backend from keras.models import Model from keras.layers import Dense, Activation, Input from main import DATASETS_NUM, DEFAULT_MODEL, INPUTS from main import TRAIN_DATASETS_FORM, DATASETS_FORM, MODE from main import OPTIMIZERS_LIST, DATASETS_LIST, A...
import numpy as np import tensorflow as tf from absl.testing import parameterized from model.architectures.transformations import spatial_dropout, compose_transformation, \ history_crop, add_normal_bias, history_cutout class TransformationTest(parameterized.TestCase, tf.test.TestCase): def assert_not_nan(se...
import argparse import torch import torch.nn as nn from torch.backends import cudnn from torch.utils import data import numpy as np import time import os, sys sys.path.append("..") import datetime import cv2 from src.networks import UNet_inpainter, Accumulate_LSTM_no_loss from src.data import Fusion_dataset_smpl_te...
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, \ RidgeRegression from sklearn.linear_mode...
# Importing needed libs import httplib # importing beautiful soup for parsing html tags from bs4 import BeautifulSoup as BS # setting up the connecting using get request conn = httplib.HTTPSConnection("www.sslproxies.org") conn.request("GET", "/") # getting the response and storing it in data response = conn.getrespon...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
""" Preprocess SUN RGB-D before training a segmentation model. https://rgbd.cs.princeton.edu/ how to run run: python -m sun.preprocess preprocess-sun python -m sun.preprocess preprocess-sun-obj-masks """ from collections import Counter import argh import scipy.io import os from tqdm import tqdm from PIL import Ima...
from spike import simulator import machine,time class ForceSensor: #If ISDEBUG is true. then all modules send debug information through console ISDEBUG = True #The PIN for Force Sensor (Potentiometer) ADC0 FORCE_PIN_PORTA = 36 FORCE_PIN_PORTB = 36 FORCE_PIN_PORTC = 36 FORCE_PIN_PORTD = 36 ...
from flask import Flask #Make the actual Application app = Flask(__name__) #Make the route @app.route("/") #Define a function def hello(): return "Hello beautiful world!"
# !/usr/bin/env python3 # encoding: utf-8 """ @version: 0.1 @author: feikon @license: Apache Licence @contact: crossfirestarer@gmail.com @site: https://github.com/feikon @software: PyCharm @file: problen_0007.py @time: 2017/6/15 9:19 """ # Problem describe:count code lines,inlude comment and blank lines # Problem s...
# expose the code in the file qcSTR/qcSTR.py # through the statement import qcSTR # instead of through import qcSTR.qcSTR from qcSTR.qcSTR import *
#!python #-*- coding:utf-8 -*- import os,sys,base64,hashlib,time from Crypto import Random from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 def KeysNew(bit = 2048): rnd_generator = Random.new().read rsa = RSA.generate(bit,rnd_generator) secret_pem = rsa.exportKey() public_pem ...
import logging import pytest import peewee from playhouse.sqlite_ext import SqliteExtDatabase test_db = SqliteExtDatabase(':memory:') peewee_logger = logging.getLogger('peewee') peewee_logger.addHandler(logging.StreamHandler()) peewee_logger.setLevel(logging.INFO) import censere.models.triggers as TRIGGERS import c...
from . models import Quote import urllib.request,json from .email import mail_message base_url=None def configure_request(app): global base_url base_url=app.config['QUOTE_BASE_URL'] # base_url='http://quotes.stormconsultancy.co.uk/random.json' def get_quote(): ''' Function that gets a random quote ''' p...
class Backend(object): """The backend is responsible for finding and creating DS4 devices.""" __name__ = "backend" def __init__(self, manager): self.logger = manager.new_module(self.__name__) def setup(self): """Initialize the backend and make it ready for scanning. Raises Ba...
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from . import config from . import helpers from . import exceptions # Module API def validate(source, scheme=None, format=None): """https:/...
from output.models.nist_data.list_pkg.g_month_day.schema_instance.nistschema_sv_iv_list_g_month_day_length_2_xsd.nistschema_sv_iv_list_g_month_day_length_2 import NistschemaSvIvListGMonthDayLength2 __all__ = [ "NistschemaSvIvListGMonthDayLength2", ]
# ------------------------------- /usr/bin/g++-7 ------------------------------# # ------------------------------- coding: utf-8 -------------------------------# # Criado por: Jean Marcelo Mira Junior # Lucas Daniel dos Santos # Versão: 1.0 # Criado em: 13/04/2021 # Sistema operacional: Linux - Ubuntu 2...
""" # Albatross DevNet scripts ## Usage 1. Run `devnet_create.py NUM_VALIDATORS`. This will create keys and configurations for multiple validator nodes. 2. Copy genesis config from `/tmp/nimiq-devnet-RANDOM/dev-albatross.toml` to `core-rs/genesis/src/genesis/dev-albatross.toml`. 3. Build core-rs:...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode) -> [[int]]: queue = [root] res = [] if not root: return [] while q...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-07-15 21:48 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import simple_history.models class Migration(migrations.Migration): dependencies = [ ...
# Copyright 2014 Knowledge Economy Developments Ltd # # Henry Gomersall # heng@kedevelopments.co.uk # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must ret...
from typing import Union, List from collections import Iterable from .filters import FilterCollection, FilterCondition from .types import * class Handler: def __init__(self,func): self.func = func self.handlers.add(func) def run(self, update): for func in self.handlers: f...
''' Given an integer n, return the next bigger permutation of its digits. If n is already in its biggest permutation, rotate to the smallest permutation. case 1 n= 5342310 ans=5343012 case 2 n= 543321 ans= 123345 ''' n = 5342310 # case 1 # n = 543321 # case 2 a = list(map(int, str(n))) i = len(a)-...
class Foo: pass f = Foo() f.bar = {} #f.bar("A") #del f.bar("A") #f.bar("A") = 1 del [1]
class Reverse: """Iterator for looping over a sequence backward.""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration else: self....
from contextlib import contextmanager from unittest.mock import MagicMock from glue import core from glue.core.application_base import Application from glue.tests.helpers import make_file @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. st...