    if (numberOfOutputChannels != null) {
      return _createScriptProcessor_1(bufferSize, numberOfInputChannels, numberOfOutputChannels);
    }
    if (numberOfInputChannels != null) {
      return _createScriptProcessor_2(bufferSize, numberOfInputChannels);
    }
    return _createScriptProcessor_3(bufferSize);
  }

  ScriptProcessorNode _createScriptProcessor_1(bufferSize, numberOfInputChannels, numberOfOutputChannels) native "AudioContext__createScriptProcessor_1_Callback";

  ScriptProcessorNode _createScriptProcessor_2(bufferSize, numberOfInputChannels) native "AudioContext__createScriptProcessor_2_Callback";

  ScriptProcessorNode _createScriptProcessor_3(bufferSize) native "AudioContext__createScriptProcessor_3_Callback";

  @DomName('AudioContext.createWaveShaper')
  @DocsEditable()
  WaveShaperNode createWaveShaper() native "AudioContext_createWaveShaper_Callback";

  @DomName('AudioContext.decodeAudioData')
  @DocsEditable()
  void _decodeAudioData(ByteBuffer audioData, AudioBufferCallback successCallback, [AudioBufferCallback errorCallback]) native "AudioContext_decodeAudioData_Callback";

  Future<AudioBuffer> decodeAudioData(ByteBuffer audioData) {
    var completer = new Completer<AudioBuffer>();
    _decodeAudioData(audioData,
        (value) { completer.complete(value); },
        (error) { completer.completeError(error); });
    return completer.future;
  }

  @DomName('AudioContext.startRendering')
  @DocsEditable()
  void startRendering() native "AudioContext_startRendering_Callback";

  @DomName('AudioContext.addEventListener')
  @DocsEditable()
  @Experimental() // untriaged
  void addEventListener(String type, EventListener listener, [bool useCapture]) native "AudioContext_addEventListener_Callback";

  @DomName('AudioContext.dispatchEvent')
  @DocsEditable()
  @Experimental() // untriaged
  bool dispatchEvent(Event event) native "AudioContext_dispatchEvent_Callback";

  @DomName('AudioContext.removeEventListener')
  @DocsEditable()
  @Experimental() // untriaged
  void removeEventListener(String type, EventListener listener, [bool useCapture]) native "AudioContext_removeEventListener_Callback";

  /// Stream of `complete` events handled by this [AudioContext].
  @DomName('AudioContext.oncomplete')
  @DocsEditable()
  Stream<Event> get onComplete => completeEvent.forTarget(this);

}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// WARNING: Do not edit - generated code.

@DocsEditable()
@DomName('AudioDestinationNode')
// https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioDestinationNode-section
@Experimental()
class AudioDestinationNode extends AudioNode {
  // To suppress missing implicit constructor warnings.
  factory AudioDestinationNode._() { throw new UnsupportedError("Not supported"); }

  @DomName('AudioDestinationNode.maxChannelCount')
  @DocsEditable()
  int get maxChannelCount native "AudioDestinationNode_maxChannelCount_Getter";

}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// WARNING: Do not edit - generated code.

@DocsEditable()
@DomName('AudioListener')
// https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioListener-section
@Experimental()


g {
  display: none;
}

.typeWindows-2-g3UY.withFrame-2dL45i {
  height: var(--window-title-bar);
  margin-top: 0;
}
.typeWindows-2-g3UY .winButton-3UMjdg {
  height: var(--window-title-bar);
  top: 0;
}
.typeWindows-2-g3UY .winButton-3UMjdg:before {
  position: absolute;
  content: " ";
  width: 12px;
  height: 12px;
  background-position: center;
  -webkit-mask-size: contain;
  mask-size: contain;
  filter: brightness(40%);
  z-index: 2;
  opacity: 0;
  transition: var(--default-time) var(--default-animation) opacity;
  pointer-events: none;
}
.typeWindows-2-g3UY .winButton-3UMjdg:hover:before {
  opacity: 1;
}
.typeWindows-2-g3UY .winButton-3UMjdg:after {
  position: absolute;
  content: " ";
  width: 16px;
  height: 16px;
  border-radius: 50%;

  transition: var(--default-time) var(--default-animation);
  pointer-events: none;
}
.typeWindows-2-g3UY .winButton-3UMjdg:active:after {
  opacity: 0.65;
}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonMinMax-3RsPUg:nth-last-of-type(2):hover:after {

}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonMinMax-3RsPUg:nth-last-of-type(2):before {

  -webkit-mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_maximize.svg);
  mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_maximize.svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonMinMax-3RsPUg:nth-last-of-type(1):hover:after {

}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonMinMax-3RsPUg:nth-last-of-type(1):before {

  -webkit-mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_minimize.svg);
  mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_minimize.svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonClose-3Q8ZH5:hover:after {

}
.typeWindows-2-g3UY .winButton-3UMjdg.winButtonClose-3Q8ZH5:before {

  -webkit-mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_close.svg);
  mask-image: url(https://capnkitten.github.io/BetterDiscord/Themes/Material-Discord/files/icons/outline/window_close.svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no


t/g.Links;for(l=0;l<g.Links;l++)0!=l?(w[l]=new mxCell("",new mxGeometry(l*U,0,U,r),"shape=partialRectangle;top=0;bottom=0;right=0;fillColor=none;"),w[l].style+=f(w[l].style,g,u,w[l])):w[l]=new mxCell("",new mxGeometry(l*
U,0,U,r),"fillColor=none;strokeColor=none;"),w[l].vertex=!0,v.insert(w[l]),w[l].style+=k(g["Link_"+(l+1)]),w[l].value=c(g["Link_"+(l+1)]);break;case "UI2BreadCrumbsBlock":v.style+="strokeColor=none;fillColor=none;";v.style+=f(v.style,g,u,v);q=[];w=[];U=t/g.Links;for(l=0;l<g.Links;l++)q[l]=new mxCell("",new mxGeometry(l*U,0,U,r),"fillColor=none;strokeColor=none;"),q[l].vertex=!0,v.insert(q[l]),q[l].style+=k(g["Link_"+(l+1)]),q[l].value=c(g["Link_"+(l+1)]);for(l=1;l<g.Links;l++)w[l]=new mxCell("",new mxGeometry(l/
g.Links,.5,6,10),"shape=mxgraph.ios7.misc.right;"),w[l].geometry.relative=!0,w[l].geometry.offset=new mxPoint(-3,-5),w[l].vertex=!0,v.insert(w[l]);break;case "UI2MenuBarBlock":v.style+="strokeColor=none;";v.style+=f(v.style,g,u,v);q=[];U=t/(g.Buttons+1);for(l=0;l<=g.Buttons-1;l++)q[l]=l!=g.Selected-1?new mxCell("",new mxGeometry(0,0,U,r),"strokeColor=none;fillColor=none;resizeHeight=1;"):new mxCell("",new mxGeometry(0,0,U,r),"fillColor=#000000;fillOpacity=25;strokeColor=none;resizeHeight=1;"),q[l].geometry.relative=
!0,q[l].geometry.offset=new mxPoint(l*U,0),q[l].vertex=!0,v.insert(q[l]),q[l].style+=k(g["MenuItem_"+(l+1)]),q[l].value=c(g["MenuItem_"+(l+1)]);break;case "UI2AtoZBlock":v.style+="fillColor=none;strokeColor=none;"+k(g.Text_0);v.value="0-9 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";break;case "UI2PaginationBlock":v.style+="fillColor=none;strokeColor=none;"+k(g.Text_prev);v.value=c(g.Text_prev)+" ";for(l=0;l<g.Links;l++)v.value+=c(g["Link_"+(l+1)])+" ";v.value+=c(g.Text_next);break;case "UI2ContextMenuBlock":v.style+=
f(v.style,g,u,v);for(var H=[],db=[],Bb=[],M=r/g.Lines,N=null,l=0;l<g.Lines;l++)null!=g["Item_"+(l+1)]&&(null==N&&(N=""+b(g["Item_"+(l+1)])+a(g["Item_"+(l+1)])+d(g["Item_"+(l+1)])),H[l]=new mxCell("",new mxGeometry(0,l*r/g


(it.destination)
          enqueued.add(it.destination)
        }
      }
    }
    return visited
  }

  fun paths(source: Vertex<T>, destination: Vertex<T>, visited: ArrayList<Vertex<T>>, pathCount: Ref<Int>) {
    visited.add(source) // 1
    if (source == destination) { // 2
      pathCount.value += 1
    } else {
      val neighbors = edges(source) // 3
      neighbors.forEach { edge ->
        // 4
        if (!visited.contains(edge.destination)) {
          paths(edge.destination, destination, visited, pathCount)
        }
      }
    }
    // 5
    visited.remove(source)
  }

  fun depthFirstSearch(source: Vertex<T>): ArrayList<Vertex<T>> {
    val stack = StackImpl<Vertex<T>>()
    val visited = arrayListOf<Vertex<T>>()
    val pushed = mutableSetOf<Vertex<T>>()

    stack.push(source)
    pushed.add(source)
    visited.add(source)

    outer@ while (true) {
      if (stack.isEmpty) break

      val vertex = stack.peek()!!
      val neighbors = edges(vertex)

      if (neighbors.isEmpty()) {
        stack.pop()
        continue
      }

      for (i in 0 until neighbors.size) {
        val destination = neighbors[i].destination
        if (destination !in pushed) {
          stack.push(destination)
          pushed.add(destination)
          visited.add(destination)
          continue@outer
        }
      }
      stack.pop()
    }

    return visited
  }

}

enum class EdgeType {
  DIRECTED,
  UNDIRECTED
}
/*
 * Copyright (c) 2021 Razeware LLC
 *
 * 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, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
 * distribute, sublicense, create a derivative work, and/or sell copies of the
 * Software in any work that is designed, intended, or marketed for pedagogical or
 * instructional purposes related to programming, coding, application development,
 * or information technology.  Permission for such use, copying, modification,
 * merger, publication, distribution, sublicensing, creation of derivative works,
 * or sale is expressly withheld.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package challenges

/*
  Challenge 2
  The current example of heap sort sorts the elements in **ascending** order. How would you sort in **descending** order?
 */
/*
 * Copyright (c) 2021 Razeware LLC
 *
 * 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, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnishe


"],[e,"M688 420h-55.2c-5.1 0-10 2.5-13 6.6L468.9 634.4l-64.7-89c-3-4.1-7.8-6.6-13-6.6H336c-6.5 0-10.3 7.4-6.5 12.7l126.4 174a16.1 16.1 0 0 0 26 0l212.6-292.7c3.8-5.4 0-12.8-6.5-12.8z"])})),t.CheckCircleTwoTone=l("check-circle",s,(function(e, t){return c(r,[e,"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"],[t,"M512 140c-205.4 0-372 166.6-372 372s166.6 372 372 372 372-166.6 372-372-166.6-372-372-372zm193.4 225.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.3 0 19.9 5 25.9 13.3l71.2 98.8 157.2-218c6-8.4 15.7-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.4 12.7z"],[e,"M699 353h-46.9c-10.2 0-19.9 4.9-25.9 13.3L469 584.3l-71.2-98.8c-6-8.3-15.6-13.3-25.9-13.3H325c-6.5 0-10.3 7.4-6.5 12.7l124.6 172.8a31.8 31.8 0 0 0 51.7 0l210.6-292c3.9-5.3.1-12.7-6.4-12.7z"])})),t.CheckSquareTwoTone=l("check-square",s,(function(e, t){return c(r,[e,"M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"],[t,"M184 840h656V184H184v656zm130-367.8h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H688c6.5 0 10.3 7.4 6.5 12.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L307.5 484.9c-3.8-5.3 0-12.7 6.5-12.7z"],[e,"M432.2 657.7a31.8 31.8 0 0 0 51.7 0l210.6-292c3.8-5.3 0-12.7-6.5-12.7h-46.9c-10.3 0-19.9 5-25.9 13.3L458 584.3l-71.2-98.8c-6-8.4-15.7-13.3-25.9-13.3H314c-6.5 0-10.3 7.4-6.5 12.7l124.7 172.8z"])})),t.ClockCircleTwoTone=l("clock-circle",s,(function(e, t){return c(r,[e,"M512 64


# -*- coding: utf-8 -*-
'''
ZettaBGP - Advanced Anomaly Detection in Internet Routing
Copyright (c) 2024 Benedikt Schwering and Sebastian Forstner

This work is licensed under the terms of the MIT license.
For a copy, see LICENSE in the project root.

Author:
    Benedikt Schwering <bes9584@thi.de>
    Sebastian Forstner <sef9869@thi.de>
'''
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
from enum import Enum

class ChangeType(Enum):
    '''
    This class represents the change type of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    ANNOUNCE = 1,
    WITHDRAW = 2,

class NLRI(BaseModel):
    '''
    This class represents the network layer reachability information of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    prefix: str
    length: int

class OriginType(Enum):
    '''
    This class represents the origin type of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    IGP = 1
    EGP = 2
    INCOMPLETE = 3

class AsPathType(Enum):
    '''
    This class represents the AS path type of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    AS_SET = 1
    AS_SEQUENCE = 2
    AS_CONFED_SET = 3
    AS_CONFED_SEQUENCE = 4

class AsPath(BaseModel):
    '''
    This class represents the AS path of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    type: AsPathType
    value: list[int]

class Aggregator(BaseModel):
    '''
    This class represents the aggregator of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    router_id: str
    router_as: int

class PathAttributes(BaseModel):
    '''
    This class represents the path attributes of a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    # origin: Optional[OriginType] = None
    as_path: Optional[list[AsPath]] = None
    # next_hop: Optional[list[str]] = None
    # multi_exit_disc: Optional[int] = None
    # local_pref: Optional[int] = None
    # atomic_aggregate: Optional[bool] = None
    # aggregator: Optional[Aggregator] = None
    # community: Optional[list[list[int]]] = None
    # large_community: Optional[list[list[int]]] = None
    # extended_community: Optional[list[str]] = None
    # orginator_id: Optional[str] = None
    # cluster_list: Optional[list[str]] = None

class RouteUpdate(BaseModel):
    '''
    This class represents a route update.

    Author:
        Benedikt Schwering <bes9584@thi.de>
    '''
    timestamp: datetime = datetime.now()
    peer_ip: str
    local_ip: str
    peer_as: int
    local_as: int
    path_attributes: PathAttributes
    change_type: ChangeType = None
    nlri: NLRI = None


zExQjRDQkIyRDJDOTdBRUI1MCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCQjg0OUYyNTZDODAxMUUzQjMwM0IwMERBNUU0ODQ5NSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCQjg0OUYyNDZDODAxMUUzQjMwM0IwMERBNUU0ODQ5NSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M2IChXaW5kb3dzKSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkI5NzE3MjFBN0E2Q0UzMTFBQjJEQjgzMDk5RTNBNTdBIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjNCNEJCNEZERTgyQ0UzMTFCNENCQjJEMkM5N0FFQjUwIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+aQvATgAAAfVJREFUeNrsmr1OwzAQxzGtkPjYEAuvVGAvfQIGRKADE49gdLwDDwBiZ2RhQUKwICQkWLsgFiRQuIBTucFJ/XFp4+hO+quqnZ4uvzj2nV2RpukCW/22yAgYNINmc7du7DcghCjrkqgOKjF1znpt6rZ0AGWQj7TvCU8d9UM+QAGDrhdyc2Bnc1WVVPBev9V8lBnY+rDwncWZThG4xk4lmxtJy2AHgoY/FySgbSBPwPZ8mEXbQx3aDERb0EbYAYFC7pcAtAvkMWwC0D3NX58S9D/YnoGC7nPWr3Dg9JTbtuHhDShBT8D2CBSK/iIEvVXxpuxSgh7DdgwUTL4iA92zmJb6lKB/YTsECmV+IgK947AGDIqgQ/LojsO135Hn51l2cWlov0JdGNrPUceueXRwilSVgkUyom9Rd6gbLfYTDeO+1v6orn0InTogYDGUkYLO3/wc9BdqqTCKP1Tfi+oTIaCBIL2TES+GTyruT9S61p6BHam+99DFEAgLFklYsIBHwSI9QY80H5ta+1rB/6ovaKihBJeEJbgLbBlQgl+j3lDPqA2tfQV1j3pVn8s+oKHGTSVJ+FqDLeR5bCqJ2E/BCycsoLZETXaKGs7rhKVt+9HZScrZNMi88V8P7LlDbvOZYaJVpMMmBCT4n0o8dTBoNgbdWPsRYACs3r7XyNfbnAAAAABJRU5ErkJggg==');
}
.xdsoft_datetimepicker  .xdsoft_prev{
    float: left;
	background-position:-20px 0px;
}
.xdsoft_datetimepicker  .xdsoft_today_button{
    float: left;
	background-position:-70px 0px;
	margin-left:5px;
}

.xdsoft_datetimepicker  .xdsoft_next{
    float: right;
	background-position:0px 0px;
}
.xdsoft_datetimepicker  .xdsoft_next:active,.xdsoft_datetimepicker  .xdsoft_prev:active{
}
.xdsoft_datetimepicker  .xdsoft_next,.xdsoft_datetimepicker  .xdsoft_prev ,.xdsoft_datetimepicker  .xdsoft_today_button{
	background-color: transparent;
	background-repeat: no-repeat;
	border: 0px none currentColor;
	cursor: pointer;
	display: block;
	height: 30px;
	opacity: 0.5;
	outline: medium none currentColor;
	overflow: hidden;
	padding: 0px;
	position: relative;
	text-indent: 100%;
	white-space: nowrap;


variantImage: entity.variantImage,
    );
  }
}// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'order_item_model.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

OrderItemModel _$OrderItemModelFromJson(Map<String, dynamic> json) =>
    OrderItemModel(
      id: json['id'] as String,
      orderId: json['orderId'] as String,
      productId: json['productId'] as String,
      variantId: json['variantId'] as String?,
      quantity: (json['quantity'] as num).toInt(),
      unitPrice: (json['unitPrice'] as num).toDouble(),
      discountAmount: (json['discountAmount'] as num).toDouble(),
      totalPrice: (json['totalPrice'] as num).toDouble(),
      notes: json['notes'] as String?,
      refundRequestId: json['refundRequestId'] as String?,
      productName: json['productName'] as String,
      productImageUrl: json['productImageUrl'] as String?,
    );

Map<String, dynamic> _$OrderItemModelToJson(OrderItemModel instance) =>
    <String, dynamic>{
      'id': instance.id,
      'orderId': instance.orderId,
      'productId': instance.productId,
      'variantId': instance.variantId,
      'quantity': instance.quantity,
      'unitPrice': instance.unitPrice,
      'discountAmount': instance.discountAmount,
      'totalPrice': instance.totalPrice,
      'notes': instance.notes,
      'refundRequestId': instance.refundRequestId,
      'productName': instance.productName,
      'productImageUrl': instance.productImageUrl,
    };
import 'package:json_annotation/json_annotation.dart';
import '../../../domain/entities/chat/chat_room_entity.dart';
import 'chat_message_model.dart';

part 'chat_room_model.g.dart';

@JsonSerializable()
class ChatRoomModel {
  final String id;
  final String userId;
  final String shopId;
  final DateTime startedAt;
  final DateTime? lastMessageAt;
  final String? relatedOrderId;
  final bool isActive;
  final String userName;
  final String? userAvatarUrl;
  final String? shopName;
  final String? shopLogoUrl;
  final ChatMessageModel? lastMessage;
  @JsonKey(defaultValue: 0)
  final int unreadCount;

  const ChatRoomModel({
    required this.id,
    required this.userId,
    required this.shopId,
    required this.startedAt,
    this.lastMessageAt,
    this.relatedOrderId,
    required this.isActive,
    required this.userName,
    this.userAvatarUrl,
    this.shopName,
    this.shopLogoUrl,
    this.lastMessage,
    this.unreadCount = 0,
  });

  factory ChatRoomModel.fromJson(Map<String, dynamic> json) => _$ChatRoomModelFromJson(json);

  Map<String, dynamic> toJson() => _$ChatRoomModelToJson(this);

  ChatRoomEntity toEntity() {
    return ChatRoomEntity(
      id: id,
      userId: userId,
      shopId: shopId,
      startedAt: startedAt,
      lastMessageAt: lastMessageAt,
      relatedOrderId: relatedOrderId,
      isActive: isActive,
      userName: userName,
      userAvatarUrl: userAvatarUrl,
      shopName: shopName,
      shopLogoUrl: shopLogoUrl,
      lastMessage: lastMessage?.toEntity(),
      unreadCount: unreadCount,
    );
  }

  factory ChatRoomModel.fromEntity(ChatRoomEntity entity) {
    return ChatRoomModel(
      id: entity.id,
      userId: entity.userId,
      shopId: entity.shopId,
      startedAt: entity.startedAt,
      lastMessageAt: entity.lastMessageAt,
      relatedOrderId: entity.relatedOrderId,


 => side == Side.white ? white : black;
}

typedef CorrespondenceForecast = IList<IList<SanMove>>;

@freezed
sealed class GameStep with _$GameStep {
  const factory GameStep({
    required Position position,
    SanMove? sanMove,
    MaterialDiff? diff,

    /// The remaining white clock time at this step. Only available when the
    /// game is finished.
    Duration? archivedWhiteClock,

    /// The remaining black clock time at this step. Only available when the
    /// game is finished.
    Duration? archivedBlackClock,
  }) = _GameStep;
}

/// Converts a list of [GameStep]s to a JSON list.
String stepsToJson(IList<GameStep> steps) {
  final objs = steps
      .mapIndexed(
        (i, e) => {
          if (i == 0) 'fen': e.position.fen,
          if (i == 0) 'rule': e.position.rule.name,
          'uci': e.sanMove?.move.uci,
          'san': e.sanMove?.san,
        },
      )
      .toList(growable: false);
  return jsonEncode(objs);
}

/// Converts a JSON list to a list of [GameStep]s.
IList<GameStep> stepsFromJson(String json) {
  final objs = jsonDecode(json) as List<dynamic>;
  final first = objs.first as Map<String, dynamic>;
  final initialFen = first['fen'] as String;
  final rule = Rule.values.byName(first['rule'] as String);
  Position position = Position.setupPosition(rule, Setup.parseFen(initialFen));
  final List<GameStep> steps = [GameStep(position: position)];
  for (final obj in objs.skip(1)) {
    final step = obj as Map<String, dynamic>;
    final uci = step['uci'] as String?;
    final san = step['san'] as String?;
    if (uci == null || san == null) {
      break;
    }
    final move = Move.parse(uci)!;
    position = position.playUnchecked(move);
    steps.add(
      GameStep(
        position: position,
        sanMove: SanMove(san, move),
        diff: MaterialDiff.fromBoard(position.board),
      ),
    );
  }
  return steps.toIList();
}
import 'dart:async';

import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lichess_mobile/src/model/auth/auth_session.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/tournament/tournament.dart';
import 'package:lichess_mobile/src/model/tournament/tournament_repository.dart';
import 'package:lichess_mobile/src/network/http.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'tournament_providers.g.dart';

@riverpod
Future<IList<LightTournament>> featuredTournaments(Ref ref) {
  // logged in users get personalized featured tournaments
  ref.watch(authSessionProvider);
  return ref.read(tournamentRepositoryProvider).featured();
}

@riverpod
Future<TournamentLists> tournaments(Ref ref) {
  return ref.read(tournamentRepositoryProvider).getTournaments();
}

@riverpod
Future<TournamentPlayer> tournamentPlayer(Ref ref, TournamentId tournamentId, UserId userId) {
  return ref.withClientCacheFor(
    (client) => ref.read(tournamentRepositoryProvider).getTournamentPlayer(tournamentId, userId),
    const Duration(seconds: 10),
  );
}
import 'dart:io' show File;

import 'package:deep_pick/deep_pick.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';


    var decoded = decoder.TryDecode(buffer, out var packets);
        decoded.Should().BeTrue();
        packets.Count.Should().Be(1);

        return (TPacket)packets[0];
    }

    public static Memory<byte> EncodePacketOnly<TPacket>(TPacket packet) where TPacket : MqttPacket
    {
        var estimatedSize = MqttPacketSizeEstimator.EstimateMqtt3PacketSize(packet);
        var buffer = new Memory<byte>(new byte[estimatedSize.TotalSize]);

        var actualBytesWritten = Mqtt311Encoder.EncodePacket(packet, ref buffer, estimatedSize);
        actualBytesWritten.Should().Be(estimatedSize.TotalSize);
        return buffer;
    }
}


.
         *
         * @author Ismail <ismaiil_0234@hotmail.com>
         *
         */
        public void DetachSeaTruckCinematic()
        {
            if (this.SeaTruckMotor.seatruckanimation)
            {
                this.SetCinematic(this.SeaTruckMotor.seatruckanimation.GetController(SeaTruckAnimation.Animation.EjectModules));
                this.SetCinematicEndMode(this.DetachSeaTruckEndMode);
                this.StartCinematicMode();
            }
        }

        /**
         *
         * Binme bittiğinde tetiklenir.
         *
         * @author Ismail <ismaiil_0234@hotmail.com>
         *
         */
        private void DetachSeaTruckEndMode()
        {
            if (this.ZeroPlayer.IsInSeaTruck)
            {
                this.ZeroPlayer.GetComponent<PlayerAnimation>().UpdateIsInSeaTruck(true);
            }
        }
    }
}


.tab
        h3 Anh #[span.check(when="map-3")]
        x-solved
        .colour-count Number of colours: #[span 0]
        include svg/colours-4.svg
        button.btn.clear Clear

---
> id: maps-2

::: column.grow
Tất cả các bản đồ ở trên đều có thể được tô với chỉ 4 màu khác nhau, và cũng không khó để tưởng tượng được rằng các bản đồ phức tạp khác có thể cần nhiều màu hơn. Thực tế một số bản đồ cần __ít nhất__ bốn màu, khi bản đồ có 4 vùng kết nối với nhau.
::: column(width=200)

    img(src="images/four-colours.png" width=200 height=120)

:::

Tương tự như trước, chúng ta có thể chuyển đổi bản đồ với vùng miền khác nhau thành một đồ thị phẳng: với mỗi vùng trở thành [[một đỉnh|một cạnh|một mặt]], và các vùng
[[có chung biên giới|có cùng một màu]] kết nối với nhau bởi một cạnh:

    .svg-block: include svg/colour-graph.svg

{.reveal(when="blank-0 blank-1")} Bây giờ chúng ta muốn tô màu các đỉnh của đồ thị,
và hai đỉnh phải có màu khác nhau nếu chúng được kết nối bằng một cạnh.

---
> id: maps-3

::: column(width=240 parent="right")

    x-img(lightbox width=240 height=320 src="images/england-counties.jpg")

::: column.grow
Năm 1852, một sinh viên thực vật học [Francis Guthrie](bio:guthrie) phải tô màu các vùng của nước Anh. Ông quan sát được rằng hầu như chỉ cần 4 màu là đủ với bất kỳ bản đồ nào Ông thử, nhưng Ông tìm được minh chứng rằng quy tắc 4 màu này áp dụng được cho _tất cả_ các bản đồ. Điều này thực ra là một bài toán cực kỳ khó, được biết đến với cái tên __định lý bốn màu__.

Trong suốt 100 năm sau đó, rất nhiều nhà toán học tìm cách công bố các chứng minh khác nhau cho định lý này, để rồi sau đó phát hiện ra nhiều lỗi. Trong số đó có những cách chứng minh có vẻ hết sức thuyết phục khiến


c-select__menu .mdc-list .mdc-list-item--selected.mdc-ripple-upgraded--background-focused::before,.mdc-select__menu .mdc-list .mdc-list-item--selected:not(.mdc-ripple-upgraded):focus::before{transition-duration:75ms;opacity:.12}.mdc-select__menu .mdc-list .mdc-list-item--selected:not(.mdc-ripple-upgraded)::after{transition:opacity 150ms linear}.mdc-select__menu .mdc-list .mdc-list-item--selected:not(.mdc-ripple-upgraded):active::after{transition-duration:75ms;opacity:.12}.mdc-select__menu .mdc-list .mdc-list-item--selected.mdc-ripple-upgraded{--mdc-ripple-fg-opacity: 0.12}.mdc-select{position:relative}.mdc-select:not(.mdc-select--disabled) .mdc-select__anchor{background-color:#f5f5f5}.mdc-select:not(.mdc-select--disabled) .mdc-select__selected-text{color:rgba(0,0,0,.87)}.mdc-select:not(.mdc-select--disabled) .mdc-floating-label{color:rgba(0,0,0,.6)}.mdc-select:not(.mdc-select--disabled) .mdc-line-ripple::before{border-bottom-color:rgba(0,0,0,.42)}.mdc-select:not(.mdc-select--disabled) .mdc-select__anchor+.mdc-select-helper-text{color:rgba(0,0,0,.6)}.mdc-select:not(.mdc-select--disabled).mdc-select--focused .mdc-line-ripple::after{border-bottom-color:#6200ee;border-bottom-color:var(--mdc-theme-primary, #6200ee)}.mdc-select:not(.mdc-select--disabled).mdc-select--focused .mdc-floating-label{color:rgba(98,0,238,.87)}.mdc-select:not(.mdc-select--disabled):hover .mdc-line-ripple::before{border-bottom-color:rgba(0,0,0,.87)}.mdc-select .mdc-floating-label{left:16px;right:initial;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%);pointer-events:none}[dir=rtl] .mdc-select .mdc-floating-label,.mdc-select .mdc-floating-label[dir=rtl]{left:initial;right:16px}.mdc-select.mdc-select--outlined .mdc-floating-label{left:4px;right:initial}[dir=rtl] .mdc-select.mdc-select--outlined .mdc-floating-label,.mdc-select.mdc-select--outlined .mdc-floating-label[dir=rtl]{left:initial;right:4px}.mdc-select .mdc-select__anchor{border-radius:4px 4px 0 0}.mdc-select .mdc-select__anchor{padding-left:16px;padding-right:0}[dir=rtl] .mdc-select .mdc-select__anchor,.mdc-select .mdc-select__anchor[dir=rtl]{padding-left:0;padding-right:16px}.mdc-select.mdc-select--with-leading-icon .mdc-select__anchor{padding-left:0;padding-right:0}[dir=rtl] .mdc-select.mdc-select--with-leading-icon .mdc-select__anchor,.mdc-select.mdc-select--with-leading-icon .mdc-select__anchor[dir=rtl]{p


cessed through the `m`-variable.
        result.push(convertor(m));
        m = regex.exec(str);
    }
    return result;
};

export const assert = (actual, expected, message: string) => {
    if (expected === actual) {
        passCount = passCount + 1;
    } else {
        failedCount = failedCount + 1;
        console.log(`error: ${message} failed.`);
        console.log(`Expected - ${expected}`);
        console.log(`Actual - ${actual}`);
    }
};

export const printSummary = () => {
    console.log(`Executed ${failedCount + passCount}, Failed ${failedCount}`);
    console.log(`Completed in ${(Date.now() - startedOn) / 1000} s`);
};

export function* breakInChunks(str, size) {
    for (let charIndex = 0; charIndex <= str.length - size; charIndex++) {
        yield str.substr(charIndex, size);
    }
}

export const flattenArrayOfArray = (arr) => arr.reduce((acc, a) => acc.concat(a));

export class LinkedList {
    private length = 0;
    private first = null;
    private last = null;

    public get count() {
        return this.length;
    }

    public get firstNode() {
        return this.first;
    }

    public append(node) {
        if (this.first === null) {
            node.prev = node;
            node.next = node;
            this.first = node;
            this.last = node;
        } else {
            node.prev = this.last;
            node.next = this.first;
            this.first.prev = node;
            this.last.next = node;
            this.last = node;
        }
        this.length++;
    }

    public appendAfter(node, marker, steps) {
        let stepsToNext = steps < this.length ? steps : ((this.length % steps) - 1);
        let direction = "next";
        if (stepsToNext > this.length / 2) {
            stepsToNext = this.length - stepsToNext;
            direction = "prev";
        }
        console.log(stepsToNext + " " + direction);
        while (stepsToNext-- > 0) {
            marker = marker[direction];
        }

        node.prev = marker;
        node.next = marker.next;

        marker.next = node;
        node.next.prev = node;
        this.length++;
    }

    public remove(node) {
        if (this.length > 1) {
            node.prev.next = node.next;
            node.next.prev = node.prev;
            if (node === this.first) {
                this.first = node.next;
            }
            if (node === this.last) {
                this.last = node.prev;
            }
        } else {
            this.first = null;
            this.last = null;
        }
        node.prev = null;
        node.next = null;
        this.length--;
    }
}

export const permutator = (input) => {
    const results = [];
    const permute = (arr, memo = []) => {
        let cur;
        for (let i = 0; i < arr.length; i++) {
            cur = arr.splice(i, 1);
            if (arr.length === 0) {
                results.push(memo.concat(cur));
            }
            permute(arr.slice(), memo.concat(cur));
            arr.splice(i, 0, cur[0]);
        }
    };
    permute(input);
    return results;
};
import { isNil, defaultTo } from 'lodash'

import type { ID, Row, Node, Exporter, Resolve } from './common/interfaces'

import { eachTree } from './helpers/tree'
import { createExporter } from './helpers/exporter'

export interface TransformOptions {
  /**
   * 行数据ID的属性名
   */
  idKey?: string

  /**
   * 上级ID的属性名
   */
  parentKey?: string

  /**
   * 顶级ID
   */
  root?: ID | Resolve
}

/**
 *


functions to implement threading.

	class thread;

	friend class thread;

	//////////////////////////////////////////////////////
	//
	// Message navigation - used by CursesMessageDisplay

	bool getNextUnreadMessage(size_t &messageNum);
	bool getNextMessage(size_t &messageNum);
	bool getPrevMessage(size_t &messageNum);

	// Open a specific message, or its message/rfc822 attachment.
	// If goMessage is not null, the new message's indicated member
	// function is invoked.

	void goMessage(size_t messageNum,
		       std::string mimeid,
		       void (myMessage::*completedFuncArg)()=NULL);

	// Download a draft, and open it.

	void goDraft();

	// View attachments to a message.
	void viewAttachments(size_t messageNum);

private:

	// Download a message, that invoke completedFuncArg

	void openMessage(size_t messageNum, std::string mimeid,
			 bool attachmentsOnly,
			 void (myMessage::*completedFuncArg)());

	size_t newMailCheckCount;
public:
	bool isCheckingNewMail();
	// TRUE if this object is busy checking for new mail.

private:
	void setSortFunctionNoSave(std::string sortBy);
	void setSortFunctionNoSort(std::string sortBy);

	bool sort_function_not;

	bool (myFolder::*sort_function)(size_t, size_t);
	std::string sort_function_name;

	bool sortByArrival(size_t, size_t);
	bool sortByDate(size_t, size_t);
	bool sortBySubject(size_t, size_t);
	bool sortByName(size_t, size_t);

};

#endif


 = "0.1"
//! ```
//!
//! # Usage
//! ```
//! use unite::unite;
//!
//! struct A;
//! struct B;
//!
//! unite! {
//!     enum Any { A, B, C = i32 }
//! }
//! ```

use heck::SnakeCase;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    braced,
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    Attribute, Ident, Token, Type, Visibility,
};

/// Helper macro to compose existing types into an enum.
///
/// # Examples
/// ```
/// use unite::unite;
///
/// pub struct One(bool);
/// pub struct Two(i32);
/// pub struct Three(f64);
///
/// unite! {
///     /// A new enum with a variant for each struct.
///     pub enum Any { One, Two, Three }
/// }
/// ```
///
/// This expands to:
///
/// ```
/// # struct One;
/// # struct Two;
/// # struct Three;
/// pub enum Any {
///     One(One),
///     Two(Two),
///     Three(Three),
/// }
/// ```
///
/// ## Renaming
/// By default the enum variants use the same name as the type, but renaming is possible.
///
/// ```
/// # use unite::unite;
/// # struct SameName;
/// unite! {
///     enum Foo {
///         SameName,
///         Renamed = i32,
///     }
/// }
/// ```
///
/// ## Helpers
/// The generated enums come with helper functions to access their variants with ease.
/// Variant names are automatically converted into `snake_case` for the function names.
///
/// ```
/// # struct One;
/// # struct Two;
/// # struct Three;
/// # unite::unite! { enum Any { One, Two, Three } }
/// let mut any: Any;
/// # any = Any::One(One);
///
/// // checks whether the enum is a specific variant
/// let is_one: bool = any.is_one();
///
/// // attempts to cast the enum to a specific variant
/// let as_two: Option<&Two> = any.as_two();
/// let as_three_mut: Option<&mut Three> = any.as_three_mut();
/// ```
///
/// The generated enums also inherently implement [`From<Variant>`].
///
/// ```
/// # struct One(bool);
/// # struct Two(i32);
/// # struct Three(f64);
/// # unite::unite! { enum Any { One, Two, Three } }
/// let any: Any = One(true).into();
/// ```
#[proc_macro]
pub fn unite(input: TokenStream) -> TokenStream {
    // parse input
    let Enum {
        attributes,
        visibility,
        name,
        variants,
    } = parse_macro_input!(input as Enum);

    // generate type information for all enum variants
    let variants_data = variants
        .into_iter()
        .map(
            |Variant {
                 attributes,
                 name,
                 ty,
             }| {
                let ty = if let Some(ty) = &ty {
                    quote! { #ty }
                } else {
                    quote! { #name }
                };
                (attributes, name, ty)
            },
        )
        .collect::<Vec<_>>();

    // generate enum variants
    let variants = variants_data.iter().map(|(attributes, variant, ty)| {
        quote! {
            #(#attributes)*
            #variant(#ty)
        }
    });

    // generate helper functions
    let funcs = variants_data.iter().map(|(_, variant, ty)| {
        // convert name to snake case
        let snake_case = variant.to_string().to_snake_case();

        // generate is check name & doc
        let is_name = format_ident!("is_{}", snake_case);
        let is_doc = format!(
            "Checks whether this [`{


2l0 17.7C124.2 63.4 18.3 161 2.1 285.9c-2 15.6 17.3 24.4 27.8 12.7C43.9 283 71.2 272 96 272c38.7 0 71 27.5 78.4 64.1c1.7 8.7 8.7 15.9 17.6 15.9s15.8-7.2 17.6-15.9C217 299.5 249.3 272 288 272s71 27.5 78.4 64.1c1.7 8.7 8.7 15.9 17.6 15.9s15.8-7.2 17.6-15.9C409 299.5 441.3 272 480 272c24.8 0 52.1 11 66.1 26.7c10.5 11.7 29.8 2.9 27.8-12.7C557.7 161 451.8 63.4 320 49.7L320 32z"]],trowel:[512,512,[],"e589",["M0 480c0 8.4 3.3 16.5 9.4 22.6s14.3 9.4 22.6 9.4c3.2 0 6.4-.5 9.5-1.5l256-80c10.7-3.3 18.9-12 21.5-22.9s-.5-22.4-8.4-30.3L245.3 312l98.6-98.6-.3-.3c-14.9-14.9-29.8-29.8-44.7-44.7l-.3-.3L200 266.7l-65.4-65.4c-7.9-7.9-19.4-11.1-30.3-8.4s-19.6 10.8-22.9 21.5l-80 256C.5 473.6 0 476.8 0 480z","M298.9 115.6c-14.6 14.6-14.6 38.2 0 52.8l44.7 44.7c14.6 14.6 38.2 14.6 52.8 0l95.4-95.4c26.9-26.9 26.9-70.5 0-97.5s-70.5-26.9-97.5 0l-95.4 95.4z"]],"horizontal-rule":[640,512,[8213],"f86c",["M0 256c0-17.7 14.3-32 32-32l576 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32z",""]],"bed-front":[512,512,["bed-alt"],"f8f7",["M0 288c0-23.7 12.9-44.4 32-55.4c9.4-5.4 20.3-8.6 32-8.6l16 0 160 0 32 0 160 0 16 0c11.7 0 22.6 3.1 32 8.6c19.1 11.1 32 31.7 32 55.4l0 32 0 32-32 0L32 352 0 352l0-32 0-32z","M32 80c0-26.5 21.5-48 48-48l352 0c26.5 0 48 21.5 48 48l0 152.6c-9.4-5.4-20.3-8.6-32-8.6l-16 0 0-64c0-17.7-14.3-32-32-32l-96 0c-17.7 0-32 14.3-32 32l0 64-32 0 0-64c0-17.7-14.3-32-32-32l-96 0c-17.7 0-32 14.3-32 32l0 64-16 0c-11.7 0-22.6 3.1-32 8.6L32 80zm0 272l448 0 32 0 0 32 0 64c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-32L64 416l0


 (!codec.isEncoder) {
                    return@forEach
                }
                codecArray.put(codecObject)
            }
        }
        val result = JSONObject()
        result.put("version", Build.VERSION.SDK_INT)
        result.put("w", w)
        result.put("h", h)
        result.put("codecs", codecArray)
        FFI.setCodecInfo(result.toString())
    }

    private fun onVoiceCallStarted() {
        var ok = false
        mainService?.let {
            ok = it.onVoiceCallStarted()
        } ?: let {
            isAudioStart = true
            ok = audioRecordHandle.onVoiceCallStarted(null)
        }
        if (!ok) {
            // Rarely happens, So we just add log and msgbox here.
            Log.e(logTag, "onVoiceCallStarted fail")
            flutterMethodChannel?.invokeMethod("msgbox", mapOf(
                "type" to "custom-nook-nocancel-hasclose-error",
                "title" to "Voice call",
                "text" to "Failed to start voice call."))
        } else {
            Log.d(logTag, "onVoiceCallStarted success")
        }
    }

    private fun onVoiceCallClosed() {
        var ok = false
        mainService?.let {
            ok = it.onVoiceCallClosed()
        } ?: let {
            isAudioStart = false
            ok = audioRecordHandle.onVoiceCallClosed(null)
        }
        if (!ok) {
            // Rarely happens, So we just add log and msgbox here.
            Log.e(logTag, "onVoiceCallClosed fail")
            flutterMethodChannel?.invokeMethod("msgbox", mapOf(
                "type" to "custom-nook-nocancel-hasclose-error",
                "title" to "Voice call",
                "text" to "Failed to stop voice call."))
        } else {
            Log.d(logTag, "onVoiceCallClosed success")
        }
    }

    override fun onStop() {
        super.onStop()
        val disableFloatingWindow = FFI.getLocalOption("disable-floating-window") == "Y"
        if (!disableFloatingWindow && MainService.isReady) {
            startService(Intent(this, FloatingWindowService::class.java))
        }
    }

    override fun onStart() {
        super.onStart()
        stopService(Intent(this, FloatingWindowService::class.java))
    }
}
package com.gmail.luizjmfilho.sevenwonders.data

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.gmail.luizjmfilho.sevenwonders.model.Match
import com.gmail.luizjmfilho.sevenwonders.ui.ResultadoDaConsultaSQLAverageScorePerPlayer
import com.gmail.luizjmfilho.sevenwonders.ui.ResultadoDaConsultaSQLBestWonder

@Dao
interface MatchDao {

    @Insert
    suspend fun addPlayer(playerMatchInfo: Match)

    @Query("SELECT MAX(matchId) FROM `Match`")
    suspend fun getLastMatchId(): Int?

    @Query("SELECT * FROM `Match` WHERE matchId = :matchId ORDER BY totalScore DESC, coinQuantity DESC")
    suspend fun getCurrentMatchList(matchId: Int): List<Match>

    @Query("DELETE FROM `Match` WHERE matchId = :matchId")
    suspend fun deleteMatchWhoseIdIs(matchId: Int)

    @Query("SELECT * FROM `Match`")
    suspend fun selectAllMatches(): List<Match>?

    @Query("UPDATE `Match` SET matchId = (matchId - 1) WHERE matchId > :idRemoved")
    suspend fun updateAllMatchesID(idRemoved: Int)

    @Query("SELECT * FROM `Match` WHERE totalScore = (SELECT MAX(totalScore) FROM `Match`) ORDER BY nickname ASC")
    suspend fun getBestScoreList(): List<Match>?

    @Query("SELECT * FROM `Match` WHERE totalScore = (SELECT MIN(totalScore) FROM `Match`) ORDER BY


8899;
}
.color-lightslategrey-20pct,
img[src~="color-lightslategrey"] {
  color: rgba(119, 136, 153, 0.2);
}
.color-lightslategrey-40pct,
img[src~="color-lightslategrey"] {
  color: rgba(119, 136, 153, 0.4);
}
.color-lightslategrey-60pct,
img[src~="color-lightslategrey"] {
  color: rgba(119, 136, 153, 0.6);
}
.color-lightslategrey-80pct,
img[src~="color-lightslategrey"] {
  color: rgba(119, 136, 153, 0.8);
}
.bg-lightslategrey,
img[src~="bg-lightslategrey"] {
  background-color: #778899;
}
.bg-lightslategrey-20pct,
img[src~="bg-lightslategrey"] {
  background-color: rgba(119, 136, 153, 0.2);
}
.bg-lightslategrey-40pct,
img[src~="bg-lightslategrey"] {
  background-color: rgba(119, 136, 153, 0.4);
}
.bg-lightslategrey-60pct,
img[src~="bg-lightslategrey"] {
  background-color: rgba(119, 136, 153, 0.6);
}
.bg-lightslategrey-80pct,
img[src~="bg-lightslategrey"] {
  background-color: rgba(119, 136, 153, 0.8);
}
.bc-lightslategrey,
img[src~="bc-lightslategrey"] {
  border-color: #778899;
}
.bc-lightslategrey-20pct,
img[src~="bc-lightslategrey"] {
  border-color: rgba(119, 136, 153, 0.2);
}
.bc-lightslategrey-40pct,
img[src~="bc-lightslategrey"] {
  border-color: rgba(119, 136, 153, 0.4);
}
.bc-lightslategrey-60pct,
img[src~="bc-lightslategrey"] {
  border-color: rgba(119, 136, 153, 0.6);
}
.bc-lightslategrey-80pct,
img[src~="bc-lightslategrey"] {
  border-color: rgba(119, 136, 153, 0.8);
}
.color-lightsteelblue,
img[src~="color-lightsteelblue"] {
  color: #B0C4DE;
}
.color-lightsteelblue-20pct,
img[src~="color-lightsteelblue"] {
  color: rgba(176, 196, 222, 0.2);
}
.color-lightsteelblue-40pct,
img[src~="color-lightsteelblue"] {
  color: rgba(176, 196, 222, 0.4);
}
.color-lightsteelblue-60pct,
img[src~="color-lightsteelblue"] {
  color: rgba(176, 196, 222, 0.6);
}
.color-lightsteelblue-80pct,
img[src~="color-lightsteelblue"] {
  color: rgba(176, 196, 222, 0.8);
}
.bg-lightsteelblue,
img[src~="bg-lightsteelblue"] {
  background-color: #B0C4DE;
}
.bg-lightsteelblue-20pct,
img[src~="bg-lightsteelblue"] {
  background-color: rgba(176, 196, 222, 0.2);
}
.bg-lightsteelblue-40pct,
img[src~="bg-lightsteelblue"] {
  background-color: rgba(176, 196, 222, 0.4);
}
.bg-lightsteelblue-60pct,
img[src~="bg-light


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore;

#nullable disable

public abstract class TransactionInterceptionSqlServerTestBase(
    TransactionInterceptionSqlServerTestBase.InterceptionSqlServerFixtureBase fixture)
    : TransactionInterceptionTestBase(fixture)
{
    public abstract class InterceptionSqlServerFixtureBase : InterceptionFixtureBase
    {
        protected override string StoreName
            => "TransactionInterception";

        protected override ITestStoreFactory TestStoreFactory
            => SqlServerTestStoreFactory.Instance;

        protected override IServiceCollection InjectInterceptors(
            IServiceCollection serviceCollection,
            IEnumerable<IInterceptor> injectedInterceptors)
            => base.InjectInterceptors(serviceCollection.AddEntityFrameworkSqlServer(), injectedInterceptors);
    }

    public class TransactionInterceptionSqlServerTest(TransactionInterceptionSqlServerTest.InterceptionSqlServerFixture fixture)
        : TransactionInterceptionSqlServerTestBase(fixture),
            IClassF


 {
			criErrorMessage = *runtimeDetails.CriErrorMessage
		}
		logger.Info("CRI error message present, skipping environment variable injection", "container", containerName, "error", criErrorMessage)
		return false
	}

	// All conditions are satisfied
	return true
}

func getContainerEnvVarPointer(containerEnv *[]corev1.EnvVar, envVarName string) *corev1.EnvVar {
	for i := range *containerEnv { // Use the index to avoid creating a copy
		if (*containerEnv)[i].Name == envVarName {
			return &(*containerEnv)[i]
		}
	}
	return nil
}

func isValueFromConfigmap(envVar *corev1.EnvVar) bool {
	return envVar.ValueFrom != nil
}

func handleValueFromEnvVar(container *corev1.Container, envVar *corev1.EnvVar, originalName, odigosValue string) {
	originalNewKey := "ORIGINAL_" + envVar.Name

	combinedValue := envOverwrite.AppendOdigosAdditionsToEnvVar(originalName, fmt.Sprintf("$(%s)", originalNewKey), odigosValue)
	if combinedValue != nil {
		envVar.Name = originalNewKey
		newEnv := corev1.EnvVar{Name: originalName, Value: *combinedValue}
		container.Env = append(container.Env, newEnv)
	}
}
package describe

import (
	"context"
	"strings"

	"k8s.io/client-go/kubernetes"

	odigosclientset "github.com/odigos-io/odigos/api/generated/odigos/clientset/versioned/typed/odigos/v1alpha1"
	odigos "github.com/odigos-io/odigos/k8sutils/pkg/describe/odigos"
)

func printClusterCollectorStatus(analyze *odigos.OdigosAnalyze, sb *strings.Builder) {
	describeText(sb, 1, false, "Cluster Collector:")
	printProperty(sb, 2, &analyze.ClusterCollector.Enabled)
	printProperty(sb, 2, &analyze.ClusterCollector.CollectorGroup)
	printProperty(sb, 2, analyze.ClusterCollector.Deployed)
	printProperty(sb, 2, analyze.ClusterCollector.DeployedError)
	printProperty(sb, 2, analyze.ClusterCollector.CollectorReady)
	printProperty(sb, 2, &analyze.ClusterCollector.DeploymentCreated)
	printProperty(sb, 2, analyze.ClusterCollector.ExpectedReplicas)
	printProperty(sb, 2, analyze.ClusterCollector.HealthyReplicas)
	printProperty(sb, 2, analyze.ClusterCollector.FailedReplicas)
	printProperty(sb, 2, analyze.ClusterCollector.FailedReplicasReason)
}

func printNodeCollectorStatus(analyze *odigos.OdigosAnalyze, sb *strings.Builder) {
	describeText(sb, 1, false, "Node Collector:")
	printProperty(sb, 2, &analyze.NodeCollector.Enabled)
	printProperty(sb, 2, &analyze.NodeCollector.CollectorGroup)
	printProperty(sb, 2, analyze.NodeCollector.Deployed)
	printProperty(sb, 2, analyze.NodeCollector.DeployedError)
	printProperty(sb, 2, analyze.NodeCollector.CollectorReady)
	printProperty(sb, 2, &analyze.NodeCollector.DaemonSet)
	printProperty(sb, 2, analyze.NodeCollector.DesiredNodes)
	printProperty(sb, 2, analyze.NodeCollector.CurrentNodes)
	printProperty(sb, 2, analyze.NodeCollector.UpdatedNodes)
	printProperty(sb, 2, analyze.NodeCollector.AvailableNodes)
}

func printOdigosPipeline(analyze *odigos.OdigosAnalyze, sb *strings.Builder) {
	describeText(s


してつ", "じてん", "じどう", "しなぎれ", "しなもの", "しなん", "しねま", "しねん", "しのぐ", "しのぶ", "しはい", "しばかり", "しはつ", "しはらい", "しはん", "しひょう", "しふく", "じぶん", "しへい", "しほう", "しほん", "しまう", "しまる", "しみん", "しむける", "じむしょ", "しめい", "しめる", "しもん", "しゃいん", "しゃうん", "しゃおん", "じゃがいも", "しやくしょ", "しゃくほう", "しゃけん", "しゃこ", "しゃざい", "しゃしん", "しゃせん", "しゃそう", "しゃたい", "しゃちょう", "しゃっきん", "じゃま", "しゃりん", "しゃれい", "じゆう", "じゅうしょ", "しゅくはく", "じゅしん", "しゅっせき", "しゅみ", "しゅらば", "じゅんばん", "しょうかい", "しょくたく", "しょっけん", "しょどう", "しょもつ", "しらせる", "しらべる", "しんか", "しんこう", "じんじゃ", "しんせいじ", "しんちく", "しんりん", "すあげ", "すあし", "すあな", "ずあん", "すいえい", "すいか", "すいとう", "ずいぶん", "すいようび", "すうがく", "すうじつ", "すうせん", "すおどり", "すきま", "すくう", "すくない", "すける", "すごい", "すこし", "ずさん", "すずしい", "すすむ", "すすめる", "すっかり", "ずっしり", "ずっと", "すてき", "すてる", "すねる", "すのこ", "すはだ", "すばらしい", "ずひょう", "ずぶぬれ", "すぶり", "すふれ", "すべて", "すべる", "ずほう", "すぼん", "すまい", "すめし", "すもう", "すやき", "すらすら", "するめ", "すれちがう", "すろっと", "すわる", "すんぜん", "すんぽう", "せあぶら", "せいかつ", "せいげん", "せいじ", "せいよう", "せおう", "せかいかん", "せきにん", "せきむ", "せきゆ", "せきらんうん", "せけん", "せこう", "せすじ", "せたい", "せたけ", "せっかく", "せっきゃく", "ぜっく", "せっけん", "せっこつ", "せっさたくま", "せつぞく", "せつだん", "せつでん", "せっぱん", "せつび", "せつぶん", "せつめい", "せつりつ", "せなか", "せのび", "せはば", "せびろ", "せぼね", "せまい", "せまる", "せめる", "せもたれ", "せりふ", "ぜんあく", "せんい", "せんえい", "せんか", "せんきょ", "せんく", "せんげん", "ぜんご", "せんさい", "せんしゅ", "せんすい", "せんせい", "せんぞ", "せんたく", "せんちょう", "せんてい", "せんと


   ["Nexus Drake Hatchling"] = "Prole de draco de El Nexo",
    ["Warmage Adami"] = "Maga de guerra Adami",
    ["Fizzcrank Fullthrottle"] = "Palanqueta Todogás",
    ["Jinky Twizzlefixxit"] = "Jinky Arreglatodo",
    ["Mordle Cogspinner"] = "Mordle Volopiñón",
    ["Crafty Wobblesprocket"] = "Ingeniosa Piñonflojo",
    ["Bonker Togglevolt"] = "Chalati Voltiflop",
    ["Bixie Wrenchshanker"] = "Bixie Patituerca",
    ["Tinky Wickwhistle"] = "Mañosa Silbatín",
    ["Jennea Cannon"] = "Jennea Cañón",
    ["Iggy \"Tailspin\" Cogtoggle"] = "Iggy \"Barrena\" Conmutador",
    ["Fizzcrank Recon Pilot"] = "Piloto de reconocimiento de Palanqueta",
    ["Jinky Wingnut"] = "Jinky Alatuerca",
    ["Abner Fizzletorque"] = "Abner Dinamométrica",
    ["King Mrgl-Mrgl"] = "Rey Mrgl-Mrgl",
    ["Scalder"] = "Escaldadora",
    ["Winterfin Tadpole"] = "Renacuajo Aleta Invernal",
    ["Cleaver Bmurglbrm"] = "Acuchillador Bmurglbrm",
    ["Keymaster Urmgrgl"] = "Maestro de llaves Urmgrgl",
    ["Nelno Copperbeam"] = "Nelno Hazdecobre",
    ["Farseer Umbrua"] = "Clarividente Umbrua",
    ["Arthur the Faithful"] = "Arthur el Leal",
    ["Katherine the Pure"] = "Katherine la Pura",
    ["Einris Brightspear"] = "Einris Lanza Reluciente",
    ["Osborne the Night Man"] = "Osborne el Nocturno",
    ["High Commander Halford Wyrmbane"] = "Alto comandante Halford Aterravermis",
    ["Gryphon Commander Urik"] = "Comandante de grifos Urik",
    ["Crypt Crawler"] = "Reptador de la cripta",
    ["Scourged Flamespitter"] = "Escupefuego plagado",
    ["Cultist Necrolyte"] = "Cultor necrólito",
    ["Skadir Raider"] = "Asaltante Skadir",
    ["Skadir Longboatsman"] = "Barquero Skadir",
    ["Gamel the Cruel"] = "Gamel el Cruel",
    ["Guard Mitchells"] = "Guardia Mitchells",
    ["Plagued Scavenger"] = "Carroñero apestado",
    ["Harvest Collector"] = "Recolector de cosecha",
    ["Loot Crazed Poacher"] = "Furtivo enloquecido despojador",
    ["Loot Crazed Diver"] = "Buzo enloquecido despojador",
    ["Wooly Rhino Matriarch"] = "Rinoceronte lanudo matriarca",
    ["Wooly Rhino Calf"] = "Cría de rinoceronte lanudo",
    ["Wooly Rhino Bull"] = "Rinoceronte lanudo dominante",
    ["Karen \"I Don't Caribou\" the Culler"] = "Karen la Asesina de Caribús",
    ["Northsea Mercenary"] = "Mercenario del Mar del Norte",
    ["Northsea Thug"] = "Matón del Mar del Norte",
    ["Beryl Mage Hunter"] = "Cazador de magos de Berilo",
    ["Beryl Sorcerer"] = "Hechicero de Berilo",
    ["Imprisoned Beryl Sorcerer"] = "Hechicero de Berilo encarcelado",
    ["Inquisitor Salrand"] = "Inquisidora Salrand",
    ["Beryl Treasure Hunter"] = "Cazatesoros de Ber


#if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
    #include <esp_heap_trace.h>
    #define NUM_RECORDS 300
    static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
#endif

extern const char *GIT_TAG;
extern const char *GIT_REV;
extern const char *GIT_BRANCH;
extern const char *BUILD_TIME;

extern std::string getFwVersion(void);
extern std::string getHTMLversion(void);
extern std::string getHTMLcommit(void);

std::vector<std::string> splitString(const std::string& str);
void migrateConfiguration(void);
bool setCpuFrequency(void);

static const char *TAG = "MAIN";

#define MOUNT_POINT "/sdcard"

bool Init_NVS_SDCard()
{
    esp_err_t ret = nvs_flash_init();

    if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }

    ESP_LOGD(TAG, "Using SDMMC peripheral");
    sdmmc_host_t host = SDMMC_HOST_DEFAULT();
    host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;

    // For SoCs where the SD power can be supplied both via an internal or external (e.g. on-board LDO) power supply.
    // When using specific IO pins (which can be used for ultra high-speed SDMMC) to connect to the SD card
    // and the internal LDO power supply, we need to initialize the power supply first.
#if SD_PWR_CTRL_LDO_INTERNAL_IO
    sd_pwr_ctrl_ldo_config_t ldo_config = {
        .ldo_chan_id = CONFIG_EXAMPLE_SD_PWR_CTRL_LDO_IO_ID,
    };
    sd_pwr_ctrl_handle_t pwr_ctrl_handle = NULL;

    ret = sd_pwr_ctrl_new_on_chip_ldo(&ldo_config, &pwr_ctrl_handle);
    if (ret != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to create a new on-chip LDO power control driver");
        return false;
    }
    host.pwr_ctrl_handle = pwr_ctrl_handle;
#endif

    // This initializes the slot without card detect (CD) and write protect (WP) signals.
    // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
#ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
    sdmmc_slot_config_t slot_config = {
        .cd = SDMMC_SLOT_NO_CD,
        .wp = SDMMC_SLOT_NO_WP,
    };
#else
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
#endif

    // Set bus width to use:
#ifdef __SD_USE_ONE_LINE_MODE__
    slot_config.width = 1;
#ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
    slot_config.clk = GPIO_SDCARD_CLK;
    slot_config.cmd = GPIO_SDCARD_CMD;
    slot_config.d0 = GPIO_SDCARD_D0;
#endif // end CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
#else  // else __SD_USE_ONE_LINE_MODE__
    slot_config.width = 4;
#ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
    slot_config.d1 = GPIO_SDCARD_D1;
    slot_config.d2 = GPIO_SDCARD_D2;
    slot_config.d3 = GPIO_SDCARD_D3;
#endif // end CONFIG_


er Programmierung, und
das Projekt in Kapitel 21 wird die Konzepte in diesem Kapitel in einer
realistischeren Situation anwenden als die hier besprochenen kleineren
Beispiele.

Wie bereits erwähnt, ist nur sehr wenig davon, wie Rust mit Nebenläufigkeit
umgeht, Teil der Sprache; viele Nebenläufigkeitslösungen sind in Kisten
(crates) implementiert. Diese entwickeln sich schneller als die
Standardbibliothek. Stelle also sicher, dass du online nach den aktuellen,
hochmodernen Kisten suchst, die in mehrsträngigen Situationen verwendet werden
können.

Die Rust-Standardbibliothek bietet Kanäle (channels) für die
Nachrichtenübermittlung und intelligente Zeigertypen wie `Mutex<T>` und
`Arc<T>`, die sicher in nebenläufigen Kontexten verwendet werden können. Das
Typsystem und der Ausleihenprüfer stellen sicher, dass der Code, der diese
Lösungen verwendet, nicht mit Daten-Wettlaufsituationen (data races) oder
ungültigen Referenzen endet. Sobald du deinen Code zum Kompilieren gebracht
hast, kannst du sicher sein, dass er problemlos mit mehreren Strängen läuft,
ohne die schwer aufspürbaren Fehler, die in anderen Sprachen üblich sind.
Nebenläufige Programmierung ist kein Konzept mehr, vor dem man sich fürchten
muss: Gehe hinaus und mache deine Programme nebenläufig – furchtlos!

[sharing-mutext]:
ch16-03-shared-state.html#gemeinsames-nutzen-eines-mutext-von-mehreren-strängen
[nomicon3]: https://doc.rust-lang.org/nomicon/index.html
# Furchtlose Nebenläufigkeit

Der sichere und effiziente Umgang mit nebenläufiger Programmierung ist ein
weiteres wichtiges Ziel von Rust. Die _nebenläufige Programmierung_ (concurrent
programming), bei der verschiedene Teile eines Programms unabhängig voneinander
ausgeführt werden, und die _parallele Programmierung_ (parallel programming),
bei der verschiedene Teile eines Programms gleichzeitig ausgeführt werden,
werden immer wichtiger, da immer mehr Computer die Vorteile mehrerer
Prozessoren nutzen. In der Vergangenheit war die Programmierung in diesen
Bereichen schwierig und fehleranfällig: Rust hofft, das ändern zu können.

Ursprünglich dachte das Rust-Team, dass das Gewährleisten von
Speichersicherheit (memory safety) und das Verhindern von
Nebenläufigkeitsproblemen (concurrency problems) zwei separate
Herausforderungen seien, die mit unterschiedlichen Methoden gelöst werden
müssten. Im Laufe der Zeit entdeckte das Team, dass Eigentümerschaft
(ownership) und Typsysteme ein leistungsstarkes Instrumentarium zur Bewältigung
von Speichersicherheits- _und_ Nebenläufigkeitsproblemen sind! Durch das Nutzen
der Eigentümerschaft und Typprüfung werden viele Nebenläufigkeitsfehler zu
Kompilierzeitfehlern in Rust anstatt Laufzeitfehlern. Anstatt dass du viel Zeit
damit verbringen musst, die genauen Umstände zu reproduzieren, unter denen ein
Laufzeit-Nebenläufigkeitsfehler auftritt, wird der fehlerhafte Code nicht
kompilieren und einen


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;

namespace Microsoft.Diagnostics.DataContractReader;

internal static class EcmaMetadataUtils
{
    internal const int RowIdBitCount = 24;
    internal const uint RIDMask = (1 << RowIdBitCount) - 1;

    internal static uint GetRowId(uint token) => token & RIDMask;

    internal static uint MakeToken(uint rid, uint table) => rid | (table << RowIdBitCount);

    // ECMA-335 II.22
    // Metadata table index is the most significant byte of


              if (this.model.chosenHasCreep()) {
                    this.sendMessage(MSG_ERROR_HASCREEP)
                    return;
                }
                if (!this.model.chosenRoadCanBuild()) {
                    this.sendMessage(MSG_ERROR_BLOCK)
                    return;
                }

                if (this.model.currentMoney >= 5) {
                    this.model.currentMoney -= 5;
                    this.sendMessage(MSG_COMMAND_BUILD, TAG_TILE_GRASS);
                }
                else {
                    this.sendMessage(MSG_ERROR_MONEY, 5);
                }

            }
        }
    }
}import { getContext } from "../Global";
import { ftom } from "./Conversions";
import { TimeBaseClass, TimeBaseUnit, TimeExpression, TimeValue } from "./TimeBase";
import { BarsBeatsSixteenths, MidiNote, Seconds, Subdivision, Ticks, Time } from "./Units";

/**
 * TimeClass is a primitive type for encoding and decoding Time values.
 * TimeClass can be passed into the parameter of any method which takes time as an argument.
 * @param  val    The time value.
 * @param  units  The units of the value.
 * @example
 * const time = Tone.Time("4n"); // a quarter note
 * @category Unit
 */
export class TimeClass<Type extends Seconds | Ticks = Seconds, Unit extends string = TimeBaseUnit>
	extends TimeBaseClass<Type, Unit> {

	readonly name: string = "TimeClass";

	protected _getExpressions(): TimeExpression<Type> {
		return Object.assign(super._getExpressions(), {
			now: {
				method: (capture: string): Type => {
					return this._now() + new (this.constructor as typeof TimeClass)(this.context, capture).valueOf() as Type;
				},
				regexp: /^\+(.+)/,
			},
			quantize: {
				method: (capture: string): Type => {
					const quantTo = new TimeClass(this.context, capture).valueOf();
					return this._secondsToUnits(this.context.transport.nextSubdivision(quantTo));
				},
				regexp: /^@(.+)/,
			},
		});
	}

	/**
	 * Quantize the time by the given subdivision. Optionally add a
	 * percentage which will move the time value towards the ideal
	 * quantized value by that percentage.
	 * @param  subdiv    The subdivision to quantize to
	 * @param  percent  Move the time value towards the quantized value by a percentage.
	 * @example
	 * Tone.Time(21).quantize(2); // returns 22
	 * Tone.Time(0.6).quantize("4n", 0.5); // returns 0.55
	 */
	quantize(subdiv: Time, percent = 1): Type {
		const subdivision = new (this.constructor as typeof TimeClass)(this.context, subdiv).valueOf();
		const value = this.valueOf();
		const multiple = Math.round(value / subdivision);
		const ideal = multiple * subdivision;
		const diff = ideal - value;
		return value + diff * percent as Type;
	}

	//-------------------------------------
	// CONVERSIONS
	//-------------------------------------
	/**
	 * Convert a Time to Notation. The notation values are will be the
	 * closest representation between 1m to 128th note.
	 * @return {Notation}
	 * @example
	 * // if the Transport is at 120bpm:
	 * Tone.Time(2).toNotation(); // returns "1m"
	 */
	toNotation(): Subdivision {
		const time = this.toSeconds();
		const testNotations: Subdivision[] = ["1m"];
		for (let power = 1; power < 9; power++) {
			const subdiv = Math.pow(2, power);
			testNotations.push(subdiv + "n." as Subdivision);
			testNotations.push(subdiv + "n" as Subdivision);
			testNotations.push(subdiv + "t" as Subdivision);
		}
		testNotations.push("0");
		// find the closets notation representation
		let closest = testNotations[0];
		let closestSeconds = new TimeClass(this.context, testNotations


{d12}, [r12]!
    VLD1.8 {d14}, [r3]!

    SUB_ZERO_POINT q4, d8, d30
    VSUBL.U8 q5, d10, d31

    VMLAL.S16 q0, d4, d6
    VMLAL.S16 q1, d5, d7

    SUB_ZERO_POINT q6, d12, d30
    VSUBL.U8 q7, d14, d31

    VMLAL.S16 q0, d8, d10
    VMLAL.S16 q1, d9, d11

    VMLAL.S16 q0, d12, d14
    VMLAL.S16 q1, d13, d15

    VCVT.F32.S32 q0, q0
    VCVT.F32.S32 q1, q1

    VMUL.F32 q0, q0, q14
    VMUL.F32 q1, q1, q14

    VMIN.F32 q0, q0, q13
    VMIN.F32 q1, q1, q13

    VMAX.F32 q0, q0, q12
    VMAX.F32 q1, q1, q12

    VADD.F32 q0, q0, q10
    VADD.F32 q1, q1, q10

    VSUB.S32 q0, q0, q11
    VSUB.S32 q1, q1, q11

    VQMOVN.S32 d0, q0
    VQMOVN.S32 d1, q1
    VQMOVUN.S16 d0, q0

    VST1.8 {d0}, [lr]!
    SUBS r0, r0, 8
    BHS 1b

2:
    CMP r0, -8
    BEQ 5f

    ADD r4, r4, r0
    ADD r5, r5, r0
    ADD r6, r6, r0
    ADD r7, r7, r0
    ADD r8, r8, r0
    ADD r9, r9, r0
    ADD r10, r10, r0
    ADD r11, r11, r0
    ADD r12, r12, r0

    LSL r0, r0, 3
    VDUP.32 d22, r0

    VLDM r3!, {d0-d3}

    VLD1.8 {d4}, [r4]!
    VLD1.8 {d6}, [r3]!
    VLD1.8 {d8}, [r5]!
    VLD1.8 {d10}, [r3]!

    VSHL.U64 d4, d4, d22

    VLD1.8 {d12}, [r6]!
    VLD1.8 {d14}, [r3]!

    SUB_ZERO_POINT q2, d4, d30
    VSUBL.U8 q3, d6, d31

    VSHL.U64 d8, d8, d22

    VLD1.8 {d16}, [r7]!
    VLD1.8 {d18}, [r3]!

    VSHL.U64 d12, d12, d22

    SUB_ZERO_POINT q4, d8, d30
    VSUBL.U8 q5, d10, d31

    VMLAL.S16 q0, d4, d6
    VMLAL.S16 q1, d5, d7

    VLD1.8 {d4}, [r8]!
    VLD1.8 {d6}, [r3]!

    VSHL.U64 d16, d16, d22

    SUB_ZERO_POINT q6, d12, d30
    VSUBL.U8 q7, d14, d31

    VMLAL.S16 q0, d8, d10
    VMLAL.S16 q1, d9, d11

    VLD1.8 {d8}, [r9]!
    VLD1.8 {d10}, [r


span>

Defined in src/databind/DeserializationFeature.ts:48

Feature that determines whether encountering of unknown properties
								(ones that do not map to a property, and there is no "any setter" or handler that can handle it)
								should result in a failure (by throwing a JacksonError) or not.
								This setting only takes effect after all other handling methods for unknown properties have been tried,
							and property remains unhandled.

Optional FAIL_<wbr>ON_<wbr>UNRESOLVED_<wbr>OBJECT_<wbr>IDS

FAIL_<wbr>ON_<wbr>UNRESOLVED_<wbr>OBJECT_<wbr>IDS: boolean

Defined in src/databind/DeserializationFeature.ts:78

Feature that determines what happens if an Object Id reference is encountered that does not refer to an actual
								Object with that id ("unresolved Object Id").
								If enabled, a JacksonError is thrown at the end of deserialization; if disabled, a null object is used instead.
								Note that if this is set to false, no further processing is done;
							specifically, if reference is defined via setter method, that method will NOT be called.

Optional SET_<wbr>DEFAULT_<wbr>VALUE_<wbr>FOR_<wbr>BIGINT_<wbr>ON_<wbr>NULL

SET_<wbr>DEFAULT_<wbr>VALUE_<wbr>FOR_<wbr>BIGINT_<wbr>ON_<wbr>NULL: boolean

Inherited from CommonFeature.SET_DEFAULT_VALUE_FOR_BIGINT_ON_NULL

Defined in <


erType.IsClass)
                        {
                            var keyValue = AddClassParameter(parameterType, arg, false, false);
                            foreach (var keyValuePair in keyValue)
                            {
                                parameters.AddIfNotExist(keyValuePair.Key, keyValuePair.Value);
                            }
                        }

                    }
                }
            }

            if (multipartAttribute != null)
            {
                requestTemplate.HttpContent = multipartFormDataContent;
            }
        }

        /// <summary>
        /// 添加类类型的参数
        /// </summary>
        /// <param name="parameterType"></param>
        /// <param name="arg">参数</param>
        /// <param name="originDictionary"></param>
        /// <param name="originEmbedded">初始是否嵌套</param>
        /// <param name="totalEmbedded">是否嵌套总开关，总开关关闭则全体不嵌套</param>
        /// <returns></returns>
        private Dictionary<string, object> AddClassParameter(Type parameterType, object arg, bool originEmbedded, bool totalEmbedded)
        {
            if (!totalEmbedded)
            {
                originEmbedded = false;
            }
            //正常返回值
            var targetDictionary = new Dictionary<string, object>();
            //如果是字典类型
            if (parameterType.IsDictionary())
            {
                if (arg is IDictionary argDictionary)
                {
                    foreach (DictionaryEntry keyValue in argDictionary)
                    {
                        var key = keyValue.Key.ToString();
                        var value = keyValue.Value?.ToString();
                        targetDictionary.AddIfNotExist(key, value);
                    }
                }
            }
            //正常类
            else
            {
                var parameterPropertyInfos = parameterType.GetProperties();
                foreach (var propertyInfo in parameterPropertyInfos)
                {
                    //判断是否序列化
                    var isEmbedded = (propertyInfo.GetCustomAttribute<EmbeddedAttribute>() != null || originEmbedded) && totalEmbedded;

                    var propertyAliasAsAttribute = propertyInfo.GetCustomAttribute<AliasAsAttribute>();

                    var key = propertyAliasAsAttribute != null
                        ? propertyAliasAsAttribute.Name
                        : propertyInfo.Name;
                    //处理常规类型
                    var value = propertyInfo.GetValue(arg);
                    if (propertyInfo.PropertyType.IsString() || propertyInfo.PropertyType.IsValueType)
                    {
                        if (value != null)
                        {
                            targetDictionary.AddIfNotExist(key, value.ToString());
                        }
                    }
                    else
                    {
                        var keyValue = AddClassParameter(propertyInfo.PropertyType, value, isEmbedded, totalEmbedded);

                        if (isEmbedded)
                        {
                            targetDictionary.AddIfNotExist(key, keyValue);
                        }
                        else
                        {
                            foreach (var keyValuePair in keyValue)
                            {
                                targetDictionary.AddIfNotExist(keyValuePair.Key, keyValuePair.Value);
                            }
                        }
                    }
                }
            }

            return targetDictionary;
        }
    }
}


ocation:的处理使得NSNull实例接受到 unknown selector 时，不做任何处理，即空操作

- 动态方法解析
</details>

### 内存管理

###  weak的实现原理？SideTable的结构是什么样的

##### 本系列关联问题

- [weak修饰的释放则自动被置为nil的实现原理](./02interview-iOS-2.md)
- [weak弱引用的代码逻辑实现?](./03interview-iOS-3.md)
- [被weak修饰的对象在被释放的时候会发生什么？是如何实现的？知道sideTable么？里面的结构可以画出来么？](./21出一套iOS高级面试题2018年7月.md)

<details>
<summary> SideTable参考内容 </summary>

- SideTable 结构体在 runtime 底层用于引用计数和弱引用关联表，其数据结构是这样：
	- 指向某个对象A的所有  weak 关键字修饰的引用都 append 到 `weak_entry_t` 结构体中的`referrers`， 同时`weak_entry_t` 的 `referent` 就是对象A，之后在dealloc 释放时遍历 `weak_table` 遍历时会判断 referent 是否为对象 A 取到 `weak_entry_t`，加入到该 SideTable 中 `weak_table` 中：

```c++
struct SideTable {

    spinlock_t slock;

    RefcountMap refcnts;

    weak_table_t weak_table;
}

struct weak_table_t {
    // 保存了所有指向指定对象的 weak 指针
    weak_entry_t *weak_entries;
    // 存储空间
    size_t    num_entries;
    // 参与判断引用计数辅助量
    uintptr_t mask;
    // hash key 最大偏移值
    uintptr_t max_hash_displacement;
};

```

```

id objc_initWeakOrNil(id *location, id newObj)
{
    if (!newObj) {
        *location = nil;
        return nil;
    }

    return storeWeak<DontHaveOld, DoHaveNew, DontCrashIfDeallocating>
        (location, (objc_object*)newObj);
}
```
</details>

###  关联对象的应用？系统如何实现关联对象的

> [应用实例代码：为UIView及子类新增点击事件Block回调处理](https://github.com/DevDragonLi/iOSDevDemo/blob/master/1-DevDemo/PodPrivate_demo/Pods/JueJinBasedComponent/JueJinBasedComponent/Classes/UIKit/UIView/UIView%2BXTHelper.m)

- [本系列面试题第八份参考：关联对象](08字节跳动面试题：2018年4月.md)

- [关联对象有什么应用，系统如何管理关联对象？其被释放的时候需要手动将所有的关联对象的指针置空么？](./21出一套iOS高级面试题2018年7月.md)

<details>
<summary> SideTable参考内容 </summary>

- 置空关联对象：赋值给与nil即可

```c++
id _object_get_associative_reference(id object, void *key) {
    id value = nil;
    uintptr_t policy = OBJC_ASSOCIATION_ASSIGN;
    {
        AssociationsManager manager;
        // manager.associations()  `AssociationsHashMap` 对象(*_map)
        AssociationsHashMap &associations(manager.associations());
        // intptr_t 是为了兼容平台，在64位的机器上，intptr_t和uintptr_t分别是long int、unsigned long int的别名；在32位的机器上，intptr_t和uintptr_t分别是int、unsigned int的别名
        // DISGUISE 内部对指针做了 ~ 取反操作
        disguised_ptr_t disguised_object = D


ccluded_east_fill(empty);

        BB(gen.0 | ((gen.0 << 1) & NOT_FILE_A.0))
    }

    pub fn occluded_north_east_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_north_east_fill(empty);

        BB(gen.0 | ((gen.0 << 9) & NOT_FILE_A.0))
    }

    pub fn occluded_north_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_north_fill(empty);

        BB(gen.0 | (gen.0 << 8))
    }

    pub fn occluded_south_east_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_south_east_fill(empty);

        BB(gen.0 | ((gen.0 >> 7) & NOT_FILE_A.0))
    }

    pub fn occluded_west_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_west_fill(empty);

        BB(gen.0 | ((gen.0 >> 1) & NOT_FILE_H.0))
    }

    pub fn occluded_south_west_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_south_west_fill(empty);

        BB(gen.0 | ((gen.0 >> 9) & NOT_FILE_H.0))
    }

    pub fn occluded_north_west_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_north_west_fill(empty);

        BB(gen.0 | ((gen.0 << 7) & NOT_FILE_H.0))
    }

    pub fn occluded_south_fill_with_occluders(self, empty: BB) -> BB {
        let gen = self.occluded_south_fill(empty);

        BB(gen.0 | (gen.0 >> 8))
    }
}

impl Shr<usize> for BB {
    type Output = BB;

    fn shr(self, amount: usize) -> BB {
        BB(self.0 >> amount)
    }
}

impl Shl<usize> for BB {
    type Output = BB;

    fn shl(self, amount: usize) -> BB {
        BB(self.0 << amount)
    }
}

impl Not for BB {
    type Output = BB;

    fn not(self) -> BB {
        BB(!self.0)
    }
}

impl BitOr for BB {
    type Output = BB;

    fn bitor(self, other: BB) -> BB {
        BB(self.0 | other.0)
    }
}

impl BitOrAssign for BB {
    fn bitor_assign(&mut self, other: BB) {
        self.0 |= other.0
    }
}

impl BitXor for BB {
    type Output = BB;

    fn bitxor(self, other: BB) -> BB {
        BB(self.0 ^ other.0)
    }
}

impl BitXorAssign for BB {
    fn bitxor_assign(&mut self, other: BB) {
        self.0 ^= other.0
    }
}

impl BitAnd for BB {
    type Output = BB;

    fn bitand(self, other: BB) -> BB {
        BB(self.0 & other.0)
    }
}

impl BitAndAssign for BB {
    fn bitand_assign(&mut self, other: BB) {
        self.0 &= other.0
    }
}

impl Sub for BB {
    type Output = BB;

    fn sub(self, other: BB) -> BB {
        BB(self.0.wrapping_sub(other.0))
    }
}

impl Add for BB {
    type Output = BB;

    fn add(self, other: BB) -> BB {
        BB(self.0.wrapping_add(other.0))
    }
}

impl Mul for BB {
    type Output = BB;

    fn mul(self, other: BB) -> BB {
        BB(self.0.wrapping_mul(other.0))
    }


Decl();
      break;
      }
    case PREFIX:{
      prefixDecl();
      break;
      }
    case IMPORT:{
      importDecl();
      break;
      }
    default:
      jj_la1[5] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
}

  final public void baseDecl() throws ParseException {String iri ;
    jj_consume_token(BASE);
    iri = IRIREF();
setBase(iri, token.beginLine, token.beginColumn) ;
}

  final public void prefixDecl() throws ParseException {Token t ; String iri ;
    jj_consume_token(PREFIX);
    t = jj_consume_token(PNAME_NS);
    iri = IRIREF();
setPrefix(t.image, iri, t.beginLine, t.beginColumn) ;
}

  final public void importDecl() throws ParseException {Token t ; String iri ;
    t = jj_consume_token(IMPORT);
    iri = iri();
imports(iri, token.beginLine, token.beginColumn) ;
}

// ----
  final public
void notStartAction() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
    case START:{
      start();
      break;
      }
    case IRIref:
    case PNAME_NS:
    case PNAME_LN:
    case BLANK_NODE_LABEL:{
      shapeExprDecl();
      break;
      }
    default:
      jj_la1[6] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
}

  final public void start() throws ParseException {
startStartClause();
    jj_consume_token(START);
    jj_consume_token(EQUALS);
    inlineShapeExpression();
finishStartClause();
}

  final public void startActions() throws ParseException {SemAct semAct;
    label_3:
    while (true) {
      semAct = codeDecl();
semActs(semAct, token.beginLine, token.beginColumn);
      switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
      case CODE_BLOCK:{
        ;
        break;
        }
      default:
        jj_la1[7] = jj_gen;
        break label_3;
      }
    }
}

  final public void statement() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
    case BASE:
    case IMPORT:
    case PREFIX:{
      directive();
      break;
      }
    case START:
    case IRIref:
    case PNAME_NS:
    case PNAME_LN:
    case BLANK_NODE_LABEL:{
      notStartAction();
      break;
      }
    default:
      jj_la1[8] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
}

// ----
  final public
void shapeExprDecl() throws ParseException {Node n;
startShapeExprDecl();
    n = shapeExprLabel();
shapeExprDecl(n, token.beginLine, token.beginColumn);
    switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
    case NOT:
    case LITERAL:
    case IRI:
    case BNODE:
    case NONLITERAL:
    case LENGTH:
    case MINLENGTH:
    case MAXLENGTH:
    case MININCLUSIVE:
    case MINEXCLUSIVE:
    case MAXINCLUSIVE:
    case MAXEXCLUSIVE:
    case TOTALDIGITS:
    case FRACTIONDIGITS:
    case CLOSED:
    case EXTRA:
    case AT:
    case DOT:
    case LPAREN:
    case LBRACE:
    case LBRACKET:
    case IRIref:
    case PNAME_NS:
    case PNAME_LN:
    case ATPNAME_NS:
    case


<ExResult<Vec<_>>>()?;

    let partial_bin_ops_of_deepex = deepex
        .bin_ops()
        .reprs
        .iter()
        .map(|repr| -> ExResult<&PartialDerivative<'a, T>> {
            partial_derivative_ops
                .iter()
                .find(|pdo| &pdo.repr == repr)
                .ok_or_else(|| {
                    format_exerr!(
                        "derivative operator of {} needed for partial derivative",
                        repr
                    )
                })
        })
        .collect::<ExResult<SmallVec<[&PartialDerivative<'a, T>; N_BINOPS_OF_DEEPEX_ON_STACK]>>>(
        )?;

    let mut num_inds = prio_indices.clone();
    let mut used_prio_indices = ExprIdxVec::new();

    for (i, &bin_op_idx) in prio_indices.iter().enumerate() {
        let num_idx = num_inds[i];
        let node_1 = nodes[num_idx].take();
        let node_2 = nodes[num_idx + 1].take();

        let pd_deepex = if let (Some(n1), Some(n2)) = (node_1, node_2) {
            let pdo = &partial_bin_ops_of_deepex[bin_op_idx];
            pdo.bin_op
                .ok_or_else(|| format_exerr!("cannot find binary op for {}", pdo.repr))?(
                n1, n2, ops,
            )
        } else {
            Err(ExError::new(
                "nodes do not contain values in partial derivative",
            ))
        }?;
        nodes[num_idx] = Some(pd_deepex);
        nodes.remove(num_idx + 1);
        // reduce indices after removed position
        for num_idx_after in num_inds.iter_mut() {
            if *num_idx_after > num_idx {
                *num_idx_after -= 1;
            }
        }
        used_prio_indices.push(bin_op_idx);
    }
    let res = nodes[0]
        .take()
        .ok_or_else(|| {
            ExError::new("node 0 needs to contain valder at the end of partial derviative")
        })?
        .der;
    let (res, _) = res.var_names_union(deepex);
    Ok(res)
}

pub fn partial_deepex<'a, T: Float + Debug>(
    var_idx: usize,
    deepex: DeepEx<'a, T>,
    ops: &[Operator<'a, T>],
) -> ExResult<DeepEx<'a, T>> {
    let partial_derivative_ops = make_partial_derivative_ops::<T>();
    let inner = partial_derivative_inner(var_idx, deepex.clone(), &partial_derivative_ops, ops)?;
    let outer = partial_derivative_outer(deepex, &partial_derivative_ops, ops)?;
    mul(inner, outer, mul_find(ops)?)
}

fn add<'a, T: Float + Debug>(
    summand_1: DeepEx<'a, T>,
    summand_2: DeepEx<'a, T>,
    add_op: BinOpsWithReprs<'a, T>,
) -> ExResult<DeepEx<'a, T>> {
    let (summand_1, summand_2) = summand_1.var_names_union(summand_2);
    Ok(if summand_1.is_zero() {
        summand_2


	}
		};

		let max_depth:u32 = match matches.opt_str("maxdepth") {
			Some(max_depth) => max_depth.parse()?,
			None => max_depth,
		};

		if max_depth <= 0 {
			return Err(ApplicationError::StartupError(String::from(
				"max_depthの設定値が不正です。"
			)));
		}

		let time_limit = config.time_limit.map_or(UsiGoTimeLimit::Infinite, |l| {
			if l == 0 && config.time_limit_byoyomi.unwrap_or(0) ==0 {
				UsiGoTimeLimit::Infinite
			} else if config.time_limit_byoyomi.unwrap_or(0) == 0 {
				UsiGoTimeLimit::Limit(Some((l,l)),None)
			} else if l == 0 {
				UsiGoTimeLimit::Limit(None,Some(UsiGoByoyomiOrInc::Byoyomi(config.time_limit_byoyomi.unwrap_or(0))))
			} else {
				UsiGoTimeLimit::Limit(Some((l,l)),Some(UsiGoByoyomiOrInc::Byoyomi(config.time_limit_byoyomi.unwrap_or(0))))
			}
		});

		let time_limit:UsiGoTimeLimit = match matches.opt_str("timelimit") {
			Some(time_limit) => {
				let l = time_limit.parse()?;
				let b = matches.opt_str("timelimit_byoyomi");

				if let Some(b) = b {
					let b = b.parse()?;

					if l == 0 && b ==0 {
						UsiGoTimeLimit::Infinite
					} else if b == 0 {
						UsiGoTimeLimit::Limit(Some((l,l)),None)
					} else if l == 0 {
						UsiGoTimeLimit::Limit(None,Some(UsiGoByoyomiOrInc::Byoyomi(b)))
					} else {
						UsiGoTimeLimit::Limit(Some((l,l)),Some(UsiGoByoyomiOrInc::Byoyomi(b)))
					}
				} else {
					if l == 0 {
						UsiGoTimeLimit::Infinite
					} else {
						UsiGoTimeLimit::Limit(Some((l,l)),None)
					}
				}
			}
			None => time_limit,
		};

		let uptime = config.uptime.map_or(None,|t| {
			if t == "" || t == "0" || t == "0s" || t == "0m" || t == "0h" || t == "0d" {
				None
			} else {
				Some(t)
			}
		});

		let uptime:Option<String> = match matches.opt_str("t") {
			Some(t) => {
				if t == "" || t == "0" || t == "0s" || t == "0m" || t == "0h" || t == "0d" {
					None
				} else {
					Some(t)
				}
			},
			None => uptime,
		};

		let uptime_none_parsed = match uptime {
			None => String::from("0s"),
			Some(ref uptime) => uptime.clone(),
		};

		let uptime = match uptime {
			None => None,
			Some(ref uptime) if uptime.ends_with("s") => {
				let len = uptime.chars().count();
				let s = uptime.chars().take(len-1).collect::<String>();
				Some(Duration::from_secs(s.parse::<u64>()?))
			},
			Some(ref uptime) if uptime.ends_with("m") => {
				let len = uptime.chars().count();
				let s = uptime.chars().take(len-1).collect::<String>();
				Some(Duration::from_secs(60 * s.parse::<u64>()?))
			},
			Some(ref uptime) if uptime.ends_with("h") => {
				let len = uptime.chars().count();
				let s = uptime.chars().take(len-1).collect::<String>();


(b []byte) []byte {
	totalLen := 0
	for _, addr := range c.AssignedAddresses {
		totalLen += addr.len()
	}

	b = quicvarint.Append(b, uint64(capsuleTypeAddressAssign))
	b = quicvarint.Append(b, uint64(totalLen))

	for _, addr := range c.AssignedAddresses {
		b = quicvarint.Append(b, addr.RequestID)
		if addr.IPPrefix.Addr().Is4() {
			b = append(b, 4)
		} else {
			b = append(b, 6)
		}
		b = append(b, addr.IPPrefix.Addr().AsSlice()...)
		b = append(b, byte(addr.IPPrefix.Bits()))
	}
	return b
}

func parseAddressRequestCapsule(r io.Reader) (*addressRequestCapsule, error) {
	var requestedAddresses []RequestedAddress
	for {
		requestID, prefix, err := parseAddress(r)
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}
		requestedAddresses = append(requestedAddresses, RequestedAddress{RequestID: requestID, IPPrefix: prefix})
	}
	return &addressRequestCapsule{RequestedAddresses: requestedAddresses}, nil
}

func (c *addressRequestCapsule) append(b []byte) []byte {
	var totalLen int
	for _, addr := range c.RequestedAddresses {
		totalLen += addr.len()
	}

	b = quicvarint.Append(b, uint64(capsuleTypeAddressRequest))
	b = quicvarint.Append(b, uint64(totalLen))

	for _, addr := range c.RequestedAddresses {
		b = quicvarint.Append(b, addr.RequestID)
		if addr.IPPrefix.Addr().Is4() {
			b = append(b, 4)
		} else {
			b = append(b, 6)
		}
		b = append(b, addr.IPPrefix.Addr().AsSlice()...)
		b = append(b, byte(addr.IPPrefix.Bits()))
	}
	return b
}

func parseAddress(r io.Reader) (requestID uint64, prefix netip.Prefix, _ error) {
	vr := quicvarint.NewReader(r)
	requestID, err := quicvarint.Read(vr)
	if err != nil {
		return 0, netip.Prefix{}, err
	}
	ipVersion, err := vr.ReadByte()
	if err != nil {
		return 0, netip.Prefix{}, err
	}
	var ip netip.Addr
	switch ipVersion {
	case 4:
		var ipv4 [4]byte
		if _, err := io.ReadFull(r, ipv4[:]); err != nil {
			return 0, netip.Prefix{}, err
		}
		ip = netip.AddrFrom4(ipv4)
	case 6:
		var ipv6 [16]byte
		if _, err := io.ReadFull(r, ipv6[:]); err != nil {
			return 0, netip.Prefix{}, err
		}
		ip = netip.AddrFrom16(ipv6)
	default:
		return 0, netip.Prefix{}, fmt.Errorf("invalid IP version: %d", ipVersion)
	}
	prefixLen, err := vr.ReadByte()
	if err != nil {
		return 0, netip.Prefix{}, err
	}
	if int(prefixLen) > ip.BitLen() {
		return 0, netip.Prefix{}, fmt.Errorf("prefix length %d exceeds IP address length (%d)", prefixLen, ip.BitLen())
	}
	prefix = netip.PrefixFrom(ip, int(prefixLen))
	if prefix != prefix.Masked() {
		return 0, netip.Prefix{}, errors.New("lower bits not covered by prefix length are not all zero")
	}
	return requestID, prefix, nil
}

// routeAdvertisementCapsule represents a ROUTE_ADVERTISEMENT capsule
type routeAdvertisementCapsule struct {
	IPAddressRanges []IPRoute


"].(string); ok {
		return nil, errors.New("testing invalid config")
	}
	if remove, ok := m["remove"].(string); ok {
		conf.removeHeader = remove
	}
	if set, ok := m["set"].(string); ok {
		conf.setHeader = set
	}
	return conf, nil
}

func (p *parser) Merge(parent interface{}, child interface{}) interface{} {
	parentConfig := parent.(*config)
	childConfig := child.(*config)

	// copy one
	newConfig := *parentConfig
	if childConfig.removeHeader != "" {
		newConfig.removeHeader = childConfig.removeHeader
	}
	if childConfig.setHeader != "" {
		newConfig.setHeader = childConfig.setHeader
	}
	return &newConfig
}
package echo

import (
	xds "github.com/cncf/xds/go/xds/type/v3"
	"google.golang.org/protobuf/types/known/anypb"

	"github.com/envoyproxy/envoy/contrib/golang/common/go/api"
	"github.com/envoyproxy/envoy/contrib/golang/filters/http/source/go/pkg/http"
)

const Name = "echo"

func init() {
	http.RegisterHttpFilterFactoryAndConfigParser(Name, filterFactory, &parser{})
}

type config struct {
	echoBody  string
	matchPath string
}

type parser struct {
}

func (p *parser) Parse(any *anypb.Any, callbacks api.ConfigCallbackHandler) (interface{}, error) {
	configStruct := &xds.TypedStruct{}
	if err := any.UnmarshalTo(configStruct); err != nil {
		return nil, err
	}

	v := configStruct.Value
	conf := &config{}
	if str, ok := v.AsMap()["echo_body"].(string); ok {
		conf.echoBody = str
	}
	if str, ok := v.AsMap()["match_path"].(string); ok {
		conf.matchPath = str
	}
	return conf, nil
}

func (p *parser) Merge(parent interface{}, child interface{}) interface{} {
	panic("TODO")
}

func filterFactory(c interface{}, callbacks api.FilterCallbackHandler) api.StreamFilter {
	conf, ok := c.(*config)
	if !ok {
		panic("unexpected config type")
	}
	return &filter{
		callbacks: callbacks,
		config:    conf,
	}
}
package metric

import (
	"google.golang.org/protobuf/types/known/anypb"

	"github.com/envoyproxy/envoy/contrib/golang/common/go/api"
	"github.com/envoyproxy/envoy/contrib/golang/filters/http/source/go/pkg/http"
)

const Name = "metric"

func init() {
	api.LogCritical("init")
	api.LogCritical(api.GetLogLevel().String())

	http.RegisterHttpFilterFactoryAndConfigParser(Name, filterFactory, &parser{})
}

type config struct {
	counter api.CounterMetric
	gauge   api.GaugeMetric
}

type parser struct {
}

func (p *parser) Parse(any *anypb.Any, callbacks api.ConfigCallbackHandler) (interface{}, error) {
	conf := &config{}
	if callbacks != nil {
		conf.counter = callbacks.DefineCounterMetric("test-counter")
		conf.gauge = callbacks.DefineGaugeMetric("test-gauge")
	}
	return conf, nil
}

func (p *parser) Merge(parent interface{}, child interface{}) interface{} {
	panic("TODO")
}

func filterFactory(c interface{}, callbacks api.FilterCallbackHandler) api.StreamFilter {
	conf, ok := c.(*config)
	if !ok {
		panic("unexpected config type")
	}
	return &filter{


o.InputStreamReader

class Utils private constructor() {

    companion object {

        @SuppressLint("StaticFieldLeak")
        private var context: Context? = null

        /**
         * 初始化工具类
         *
         * @param context 上下文
         */
        @JvmStatic
        fun init(context: Context) {
            this.context = context
        }

        /**
         * 获取ApplicationContext
         *
         * @return ApplicationContext
         */
        @JvmStatic
        fun getContext(): Context {
            if (context != null) {
                return context!!
            }
            throw NullPointerException("should be initialized in application")
        }

        private var sCurProcessName: String? = null

        @JvmStatic
        fun isMainProcess(context: Context): Boolean {
            val processName = getCurProcessName(context)
            return if (processName != null && processName.contains(":")) {
                false
            } else processName != null && processName == context.packageName
        }

        @JvmStatic
        fun isNetworkConnected(context: Context?): Boolean {
            if (context != null) {
                // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
                val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                // 获取NetworkInfo对象
                val networkInfo = manager.activeNetworkInfo
                //判断NetworkInfo对象是否为空
                if (networkInfo != null)
                    return networkInfo.isAvailable
            }
            return false
        }

        @JvmStatic
        fun getCurProcessName(context: Context): String? {
            val procName = sCurProcessName
            if (!TextUtils.isEmpty(procName)) {
                return procName
            }
            try {
                val pid = Process.myPid()
                val mActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                for (appProcess in mActivityManager.runningAppProcesses) {
                    if (appProcess.pid == pid) {
                        sCurProcessName = appProcess.processName
                        return sCurProcessName
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            sCurProcessName = getCurProcessNameFromProc()
            return sCurProcessName
        }

        @JvmStatic
        private fun getCurProcessNameFromProc(): String? {
            var cmdlineReader: BufferedReader? = null
            try {
                cmdlineReader = BufferedReader(InputStreamReader(
                        FileInputStream(
                                "/proc/" + Process.myPid() + "/cmdline"),
                        "iso-8859-1"))
                val c: Int = cmdlineReader.read()
                val processName = StringBuilder()
                while (c> 0) {
                    processName.append(c.toChar())
                }
                return processName.toString()
            } catch (e: Throwable) {
                // ignore
            } finally {
                if (cmdlineReader != null) {
                    try {
                        cmdlineReader.close()
                    } catch (e: Exception) {
                        // ignore
                    }

                }
            }
            return null
        }
    }

}package com.link.librarymodule.widgets.navgation

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import


变化。过去，录音室硬件和专业扬声设备是音色层次的基础。如今，数字音频工作站（DAW）如*Ableton Live*和*Logic Pro*结合云端协作工具，让各地艺术家远程协作、素材共享，打破了地理界限。这种分布式生产模式极大丰富了音色纹理和节奏表达。例如**Disclosure**在*Latch*等作品中，将人声处理与复杂电子编排融合，展现新时代*Deep House*更灵动、更具当代感的特质。音色设计和结构布局的变化，也冲击了过去“平缓舒适”的单一印象，带动风格向流行、R&B乃至新爵士、实验电子等边界延伸，为听众带来了更丰富的选择。

而这一切演变背后都有其社会与经济基础。城市化进程、新兴中产消费升级和“数字原住民”的审美取向，塑造了**Deep House**更个性化、生活化的使用场景。音乐节、酒廊、健身馆、创意办公空间、私人聚会，都成为风格“渗透”的新阵地。同时，全球大型品牌与音乐平台的合作推广，带动*Deep House*专辑、精选集和人物访谈席卷流媒体排行。跨界合作（如与时尚、餐饮、设计品牌联合推新）也让这一音乐类型不断吸引新的受众群体。

展望未来，随着人工智能驱动的作曲、混音和个性化推荐平台持续发展，**Deep House**的声音与结构还将在国际语境下不断进化。从芝加哥简陋工作室到多元互联的全球协作，*Deep House*已从一种舞池节拍，演变为具有包容力和多样化表达的国际音乐现象。前方的发展轨迹，仍将被技术突破、文化交融和人类情感需求所共同塑形，为全球声音地图继续增添新活力。

【本文约 917 词】

## 无声却深远：Deep House的长久影响与全球遗产

纵观近四十年国际音乐史，**Deep House**凭借其独特的音响特征和文化立场，悄然塑造了全球舞曲生态及相关生活方式。从最初只属于芝加哥与纽约地下俱乐部的专属空间，到如今渗透进不同大洲、各类场景，这一风格的持续影响已远超电子音乐范畴本身。细致分析*Deep House*的遗产，可见它在音乐表现、社会结构


.': 'サブスクリプションのURL及び情報が外部に漏れた場合にご操作ください。操作後はUUIDやURLが変更され、再度サブスクリプションのインポートが必要になります。',
  'Đặt Lại Thành Công': '変更完了',
  'Hai lần nhập Mật Khẩu Mới không giống nhau.': 'ご入力されました新しいパスワードが一致しません',
  '两次密码输入不同': 'ご入力されましたパスワードが一致しません',
  'E-Mail': 'E-mail アドレス',
  'Mã Xác Minh Email': '確認コード',
  'Gửi': '送信',
  'Mã Mời': '招待コード',
  'Mã Mời (Không Bắt Buộc)': '招待コード (オプション)',
  'Đăng Ký': '新規登録',
  'Quay Lại Đăng Nhập': 'ログインページへ戻る',
  'Tôi đã đọc và đồng ý với Điều Khoản Dịch Vụ': 'ご利用規約に同意します',
  'Vui lòng đồng ý với Điều Khoản Dịch Vụ': 'ご利用規約に同意してください',
  'Tên': '名称',
  'Nhãn': 'ラベル',
  'Trạng Thái': 'ステータス',
  'Trạng Thái Trực Tuyến của Node trong 5 Phút Gần Đây': '5分間のオンラインステータス',
  'Hệ Số': '適応レート',
  'Lưu Lượng Sử Dụng sẽ được nhân với Hệ Số để trừ đi': '通信量は該当レートに基き計算されます',
  '更多操作': 'アクション',
  'Sao Chép Thành Công': 'クリップボードにコピーされました',
  'Sao Chép Liên Kết': 'URLをコピー',
  'Gói Này Có Thời Gian Vĩnh Viễn': '時間制限なし',
  'Gói Đã Quá Hạn': '期限切れ',
  'Đã Sử Dụng {used} / Tổng Cộng {total}': '使用済み {used} / 合計 {total}',
  'Reset Liên Kết Server': 'サブスクリプションURLの変更',
  'Không có Server khả dụng, nếu bạn chưa có gói hoặc gói đã hết hạn, vui lòng': 'ご利用可能なサーバーがありません，プランの期限切れまたは購入なされていない場合は',
  'Gói Dịch Vụ': 'サブスクリプションプラン',
  'Bạn có chắc chắn muốn đặt lại lưu lư�


"""
Write a python function to check whether the given number can be represented as the difference of two squares or not.
assert dif_Square(5) == True
"""

def dif_Square(n):
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if i * i + j * j == n:
                return True
    return False

if __name__ == '__main__':
    print(dif_Square(5))
    print(dif_Square(12))
    print(dif_Square(13))
    print(dif_Square(14))
    print(dif_Square(15))
    print(dif_Square(16))
    print(dif_Square(17))
    print(dif_Square(18))
    print(dif_Square(19))
    print(dif_Square(20))
    print(dif_Square(21))
    print(dif_Square(22))
    print(dif_Square(23))
    print(dif_Square(24))
    print(dif_Square(25))
    print(dif_Square(26))
    print(dif_Square(27))
    print(dif_Square(28))
    print(dif_Square(29))
    print(dif_Square(30))
    print(dif_Square(31))
    print(dif_Square(32))
    print(dif_Square(33))
    print(dif_Square(34))
    print(dif_Square(35))
    print(dif_Square(36))
    print(dif_Square(37))
    print(dif_Square(38))
    print(dif_Square(39))
    print(dif_Square(40))
    print(dif_Square(41))
    print(dif_Square(42))
    print(dif_Square(43))
    print(dif_Square(44))
    print(dif_Square(45))
    print(dif_Square(46))
    print(dif_Square(47))
    print(dif_Square(48))
    print(dif_Square(49))
    print(dif_Square(50))
    print(dif_Square(51))
    print(dif_Square(52))
    print(dif_Square(53))
    print(dif_Square(54))
    print(dif_Square(55))
    print(dif_Square(56))
    print(dif_Square(57))
    print(dif_Square(58))
    print(dif_Square(59))
    print(dif_Square(60))
    print(dif_Square(61))
    print(dif_Square(62))
    print(dif_Square(63))
    print(dif_Square(64))
    print(dif_Square(65))
    print(dif_Square(66))
    print(dif_Square(67))
    print(dif_Square(68))
    print(dif_Square(69))
    print(dif_Square(70))
    print(dif_Square(71))
    print(dif_Square(72))
    print(dif_Square(73))
    print(dif_Square(74))
    print(dif_Square(75))
    print(dif_Square(76))
    print(dif_Square(77))
    print(dif_Square(78))
    print(dif_S