#[cfg(feature = "debugger")]
    fn get_prg_bank(&self, addr: u16) -> Option<u8> {
        match addr {
            0x8000..=0xBFFF => Some(0),
            0xC000..=0xFFFF => Some(1),
            _ => None,
        }
    }
}
<gh_stars>0
pub struct Probe {
    pub id: u32,
}
/// english_rules.rs
///
/// `EnglishTokenizer` wraps a ThompsonInterpreter around a set of regex
/// patterns for ordinary English token types. It also implements the
/// `RegexTokenizer` trait, which in turn requires it to implement
/// the `TokenReactor` and `TokenRecognizer` traits.

use crate::native::nlpsvc::regex::reinterp::ThompsonInterpreter;
use crate::native::nlpsvc::regex::reinterp::TokenRecognizer;
use crate::native::nlpsvc::regex::reinterp::MatchRecord;
use crate::native::nlpsvc::regex_tokenizer::TokenReactor;
use crate::native::nlpsvc::regex_tokenizer::ThompsonProgramBuilder;
use crate::native::nlpsvc::regex_tokenizer::RegexTokenizer;
use crate::native::nlpsvc::annotated_document::*;

pub struct EnglishTokenizer {
    matcher: ThompsonInterpreter,
}

impl EnglishTokenizer {

    pub fn new() -> EnglishTokenizer {
        let english_patterns = ThompsonProgramBuilder::new()
            .add_rule(r"(?i)[a-z]+")           // [0] words
            .add_rule(r"[0-9,.]*[0-9]+")       // [1] numbers
            .add_rule(r"[.,?!]")               // [2] punctuation
            .build();
        EnglishTokenizer {
            matcher: ThompsonInterpreter::new(english_patterns),
        }
    }

    fn word_action(&mut self, _begin: usize, _end: usize, token: &mut NodeLabel) {
        //println!("WORD [{}] at {}", &doc.get_text()[begin..end], begin);
        token.set_sym_val("toktype", "WORD");
    }

    fn num_action(&mut self, _begin:usize, _end: usize, token: &mut NodeLabel) {
        //println!("NUMBER [{}] at {}", &doc.get_text()[begin..end], begin);
        token.set_sym_val("toktype", "NUMBER");
    }

    fn punct_action(&mut self, _begin: usize, _end: usize, token: &mut NodeLabel) {
        //println!("PUNCT [{}] at {}", &doc.get_text()[begin..end], begin);
        token.set_sym_val("toktype", "PUNCT");
    }
}

impl TokenRecognizer for EnglishTokenizer {
    fn next_token(&mut self, text: &str, pos: usize) -> Option<MatchRecord> {
        self.matcher.next_token(text, pos)
    }
}

impl TokenReactor for EnglishTokenizer {
    /// Append a token
    ///
    /// Append a token starting at `begin` with text `text`, that
    /// matched rule #`rule_id`.
    fn append(&mut self,
              begin: usize,
              end:usize,
              rule_id: usize,
              doc: &mut AnnotatedDocument
    ) {
        let mut token = NodeLabel::new();
        token.set_span(begin, end);
        match rule_id {
            0 => { self.word_action(begin, end, &mut token); }
            1 => { self.num_action(begin, end, &mut token); }
            2 => { self.punct_action(begin, end, &mut token); }
            _ => { panic!("Unrecognized rule ID {} at pos {}", rule_id, begin); }
        };
        println!(
            "{} [{}] at {}",
            token.get_sym_val("toktype"),
            &doc.get_text()[begin..end],
            begin
        );
        doc.get_trees_mut().push_back(token);
    }

    /// Skip an unhandled character
    ///
    /// The character at `begin` is not the first character of any pattern
    /// that this tokenizer knows about. For symmetry with `append()`,
    /// the text i


6,$663C1800,$0000636B
	dc.l	$7F3E3600,$0000663C,$183C6600,$00006666,$663E0C78
	dc.l	$00007E0C,$18307E00,$00183C7E,$7E183C00,$18181818
	dc.l	$18181818,$007E787C,$6E660600,$08183878,$38180800
	even

DATA_HS
 DC.L H44,H44,H2,H2,H2,H80,H0,H0,H0
 DC.L H44,H44,H2,H2,H80,H0,H0,H0,H0
 DC.L H44,H44,H2,H80,H0,H0,H0,H0,H0
 DC.L H44,H44,H80,H0,H0,H0,H0,H0,H0
 DC.L H44,H24,H24,H2,H80,H0,H0,H0,H0
 DC.L H44,H24,H24,H80,H0,H0,H0,H0,H0
 DC.L H24,H2,H2,H2,H2,H2,H0,H0,H0
 DC.L H24,H2,H2,H2,H2,H0,H0,H0,H0
 DC.L H24,H2,H2,H2,H0,H0,H0,H0,H0
 DC.L H24,H2,H2,H0,H0,H0,H0,H0,H0
 DC.L H24,H2,H0,H0,H0,H0,H0,H0,H0
 DC.L H24,H0,H0,H0,H0,H0,H0,H0,H0
 DC.L H70,H44,H24,H24,H24,H80,H80,H0,H0
 DC.L H70,H44,H2,H2,H2,H80,H0,H0,H0
 DC.L H70,H44,H2,H2,H80,H0,H0,H0,H0
 DC.L H70,H44,H2,H80,H0,H0,H0,H0,H0
 DC.L H44,H2,H2,H2,H2,H2,H0,H0,H0
 DC.L H44,H2,H2,H2,H2,H0,H0,H0,H0
 DC.L H44,H2,H2,H2,H0,H0,H0,H0,H0
 DC.L H44,H2,H2,H0,H0,H0,H0,H0,H0
 DC.L H44,H2,H0,H0,H0,H0,H0,H0,H0
 DC.L H44,H0,H0,H0,H0,H0,H0,H0,H0
 DC.L H24,H24,H2,H0,H0,H0,H0,H0,H0
 DC.L H24,H24,H0,H0,H0,H0,H0,H0,H0
 DC.L H44,H44,H44,H2,H80,H0,H0,H0,H0
 DC.L H44,H44,H44,H80,H0,H0,H0,H0,H0
 DC.L H70,H70,H2,H2,H2,H80,H0,H0,H0
 DC.L H70,H70,H2,H2,H80,H0,H0,H0,H0
 DC.L H70,H70,H2,H80,H0,H0,H0,H0,H0
 DC.L H44,H24,H2,H2,H2,H2,H0,H0,H0
 DC.L H44,H24,H2,H2,H2,H0,H0,H0,H0
 DC.L H44,H24,H2,H2,H0,H0,H0,H0,H0
 DC.L H44,H24,H2,H0,H0,H0,H0,H0,H0
 DC.L H44,H24,H0,H0,H0,H0,H0,H0,H0
 DC.L H70,H0,H0,H0,H0,H0,H0,H0,H0
 DC.L H24,H24,H24,H0,H0,H0,H0,H0,H0
 DC.L H70,H44,H44,H2,H


BLUETOOTH_DRIVE("bluetooth_drive"),
    BLUETOOTH_SEARCHING("bluetooth_searching"),
    BLUR_CIRCULAR("blur_circular"),
    BLUR_LINEAR("blur_linear"),
    BLUR_OFF("blur_off"),
    BLUR_ON("blur_on"),
    BOLT("bolt"),
    BOOK("book"),
    BOOK_ONLINE("book_online"),
    BOOKMARK("bookmark"),
    BOOKMARK_ADD("bookmark_add"),
    BOOKMARK_ADDED("bookmark_added"),
    BOOKMARK_BORDER("bookmark_border"),
    BOOKMARK_OUTLINE("bookmark_outline"),
    BOOKMARK_REMOVE("bookmark_remove"),
    BOOKMARKS("bookmarks"),
    BORDER_ALL("border_all"),
    BORDER_BOTTOM("border_bottom"),
    BORDER_CLEAR("border_clear"),
    BORDER_COLOR("border_color"),
    BORDER_HORIZONTAL("border_horizontal"),
    BORDER_INNER("border_inner"),
    BORDER_LEFT("border_left"),
    BORDER_OUTER("border_outer"),
    BORDER_RIGHT("border_right"),
    BORDER_STYLE("border_style"),
    BORDER_TOP("border_top"),
    BORDER_VERTICAL("border_vertical"),
    BOY("boy"),
    BRANDING_WATERMARK("branding_watermark"),
    BREAKFAST_DINING("breakfast_dining"),
    BRIGHTNESS_1("brightness_1"),
    BRIGHTNESS_2("brightness_2"),
    BRIGHTNESS_3("brightness_3"),
    BRIGHTNESS_4("brightness_4"),
    BRIGHTNESS_5("brightness_5"),
    BRIGHTNESS_6("brightness_6"),
    BRIGHTNESS_7("brightness_7"),
    BRIGHTNESS_AUTO("brightness_auto"),
    BRIGHTNESS_HIGH("brightness_high"),
    BRIGHTNESS_LOW("brightness_low"),
    BRIGHTNESS_MEDIUM("brightness_medium"),
    BROADCAST_ON_HOME("broadcast_on_home"),
    BROADCAST_ON_PERSONAL("broadcast_on_personal"),
    BROKEN_IMAGE("broken_image"),
    BROWSE_GALLERY("browse_gallery"),
    BROWSER_NOT_SUPPORTED("browser_not_supported"),
    BROWSER_UPDATED("browser_updated"),
    BRUNCH_DINING("brunch_dining"),
    BRUSH("brush"),
    BUBBLE_CHART("bubble_chart"),
    BUG_REPORT("bug_report"),
    BUILD("build"),
    BUILD_CIRCLE("build_circle"),
    BUNGALOW("bungalow"),
    BURST_MODE("burst_mode"),
    BUS_ALERT("bus_alert"),
    BUSINESS("business"),
    BUSINESS_CENTER("business_center"),
    CABIN("cabin"),
    CABLE("cable"),
    CACHED("cached"),
    CAKE("cake"),
    CALCULATE("calculate"),
    CALENDAR_MONTH("calendar_month"),
    CALENDAR_TODAY("calendar_today"),
    CALENDAR_VIEW_DAY("calendar_view_day"),
    CALENDAR_VIEW_MONTH("calendar_view_month"),
    CALENDAR_VIEW_WEEK("calendar_view_week"),
    CALL("call"),
    CALL_END("call_end"),
    CALL_MADE("call_made"),
    CALL_MERGE("call_merge"),
    CALL_MISSED("call_missed"),
    CALL_MISSED_OUTGOING("call_missed_outgoing"),
    CALL_RECEIVED("call_received"),
    CALL_SPLIT("call_split"),
    CALL_TO_ACTION("call_to_action"),
    CAMERA("camera"),
    CAMERA_ALT("camera


x4248                ## $a3 = 42480000
/* 01BC4 80AEA004 4406B000 */  mfc1    $a2, $f22
/* 01BC8 80AEA008 26240200 */  addiu   $a0, $s1, 0x0200           ## $a0 = 00000200
/* 01BCC 80AEA00C 3C054080 */  lui     $a1, 0x4080                ## $a1 = 40800000
/* 01BD0 80AEA010 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 01BD4 80AEA014 3C0740A0 */  lui     $a3, 0x40A0                ## $a3 = 40A00000
/* 01BD8 80AEA018 4406B000 */  mfc1    $a2, $f22
/* 01BDC 80AEA01C 3C073D23 */  lui     $a3, 0x3D23                ## $a3 = 3D230000
/* 01BE0 80AEA020 34E7D70A */  ori     $a3, $a3, 0xD70A           ## $a3 = 3D23D70A
/* 01BE4 80AEA024 26240204 */  addiu   $a0, $s1, 0x0204           ## $a0 = 00000204
/* 01BE8 80AEA028 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 01BEC 80AEA02C 8E250208 */  lw      $a1, 0x0208($s1)           ## 00000208
/* 01BF0 80AEA030 4406B000 */  mfc1    $a2, $f22
/* 01BF4 80AEA034 3C073C23 */  lui     $a3, 0x3C23                ## $a3 = 3C230000
/* 01BF8 80AEA038 34E7D70A */  ori     $a3, $a3, 0xD70A           ## $a3 = 3C23D70A
/* 01BFC 80AEA03C 2624020C */  addiu   $a0, $s1, 0x020C           ## $a0 = 0000020C
/* 01C00 80AEA040 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 01C04 80AEA044 8E250210 */  lw      $a1, 0x0210($s1)           ## 00000210
/* 01C08 80AEA048 4406B000 */  mfc1    $a2, $f22
/* 01C0C 80AEA04C 3C073AC4 */  lui     $a3, 0x3AC4                ## $a3 = 3AC40000
/* 01C10 80AEA050 34E79BA6 */  ori     $a3, $a3, 0x9BA6           ## $a3 = 3AC49BA6
/* 01C14 80AEA054 26240214 */  addiu   $a0, $s1, 0x0214           ## $a0 = 00000214
/* 01C18 80AEA058 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 01C1C 80AEA05C 8E250218 */  lw      $a1, 0x0218($s1)           ## 00000218
/* 01C20 80AEA060 4406B000 */  mfc1    $a2, $f22
/* 01C24 80AEA064 4407A000 */  mfc1    $a3, $f20
/* 01C28 80AEA068 2624021C */  addiu   $a0, $s1, 0x021C           ## $a0 = 0000021C
/* 01C2C 80AEA06C 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 01C30 80AEA070 8E250220 */  lw      $a1, 0x0220($s1)           ## 00000220
/* 01C34 80AEA074 3C01447A */  lu


`|12.2| |13.0| | | | | | | |
|`cudaGraphAddNode_v2`|12.3| | | | | | | | | |
|`cudaGraphChildGraphNodeGetGraph`|10.0| | | |`hipGraphChildGraphNodeGetGraph`|5.0.0| | | | |
|`cudaGraphClone`|10.0| | | |`hipGraphClone`|5.0.0| | | | |
|`cudaGraphConditionalHandleCreate`|12.3| | | | | | | | | |
|`cudaGraphCreate`|10.0| | | |`hipGraphCreate`|4.3.0| | | | |
|`cudaGraphDebugDotPrint`|11.3| | | |`hipGraphDebugDotPrint`|5.5.0| | | | |
|`cudaGraphDestroy`|10.0| | | |`hipGraphDestroy`|4.3.0| | | | |
|`cudaGraphDestroyNode`|10.0| | | |`hipGraphDestroyNode`|5.0.0| | | | |
|`cudaGraphEventRecordNodeGetEvent`|11.1| | | |`hipGraphEventRecordNodeGetEvent`|5.0.0| | | | |
|`cudaGraphEventRecordNodeSetEvent`|11.1| | | |`hipGraphEventRecordNodeSetEvent`|5.0.0| | | | |
|`cudaGraphEventWaitNodeGetEvent`|11.1| | | |`hipGraphEventWaitNodeGetEvent`|5.0.0| | | | |
|`cudaGraphEventWaitNodeSetEvent`|11.1| | | |`hipGraphEventWaitNodeSetEvent`|5.0.0| | | | |
|`cudaGraphExecChildGraphNodeSetParams`|11.1| | | |`hipGraphExecChildGraphNodeSetParams`|5.0.0| | | | |
|`cudaGraphExecDestroy`|10.0| | | |`hipGraphExecDestroy`|4.3.0| | | | |
|`cudaGraphExecEventRecordNodeSetEvent`|11.1| | | |`hipGraphExecEventRecordNodeSetEvent`|5.0.0| | | | |
|`cudaGraphExecEventWaitNodeSetEvent`|11.1| | | |`hipGraphExecEventWaitNodeSetEvent`|5.0.0| | | | |
|`cudaGraphExecExternalSemaphoresSignalNodeSetParams`|11.2| | | |`hipGraphExecExternalSemaphoresSignalNodeSetParams`|5.7.0| | | | |
|`cudaGraphExecExternalSemaphoresWaitNodeSetParams`|11.2| | | |`hipGraphExecExternalSemaphoresWaitNodeSetParams`|5.7.0| | | | |
|`cudaGraphExecGetFlags`|12.0| | | |`hipGraphExecGetFlags`|6.3.0| | | | |
|`cudaGraphExecHostNodeSetParams`|11.0| | | |`hipGraphExecHostNodeSetParams`|5.0.0| | | | |
|`cudaGraphExecKernelNodeSetParams`|11.0| | | |`hipGraphExecKernelNodeSetParams`|4.5.0| | | | |
|`cudaGraphExecMemcpyNodeSetParams`|11.0| | | |`hipGraphExecMemcpyNodeSetParams`|5.0.0| | | | |
|`cudaGraphExecMemcpyNodeSetParams1D`|11.1| | | |`hipGraphExecMemcpyNodeSetParams1D`|5.0.0| | | | |
|`cudaGraphExecMemcpyNodeSetParamsFromSymbol`|11.1| | | |`hipGraphExecMemcpyNodeSetParamsFromSymbol`|5.0.0| | | | |
|`cudaGraph


())
										 forDelete.Add(item);

									progressDialogViewModel.Progress++;
									if (progressDialogViewModel.IsCancelled)
										break;
								}
                            }
                            catch (Exception ex)
                            {
                                throw;
                            }
                    })
                    .ContinueWith(t =>
                    {
                        foreach (var item in forDelete)
                        {
                            _resultList.Remove(item);
                        }
                        ((ICollectionView)Result).Refresh();
                        _windowService.CloseProgressWindow();
                    },TaskScheduler.FromCurrentSynchronizationContext());
                   _windowService.OpenProgressWindow(progressDialogViewModel);
                }));
            }
        }

        ICommand _showDiffrenceInPercent;


et = _objc_msgSend_151sglz(_class_MLNPointFeatureCluster, _sel_alloc);
    return MLNPointFeatureCluster.castFromPointer(_ret, retain: false, release: true);
  }

  /// self
  MLNPointFeatureCluster self$1() {
    final _ret = _objc_msgSend_151sglz(this.ref.pointer, _sel_self);
    return MLNPointFeatureCluster.castFromPointer(_ret, retain: true, release: true);
  }

  /// retain
  MLNPointFeatureCluster retain() {
    final _ret = _objc_msgSend_151sglz(this.ref.pointer, _sel_retain);
    return MLNPointFeatureCluster.castFromPointer(_ret, retain: true, release: true);
  }

  /// autorelease
  MLNPointFeatureCluster autorelease() {
    final _ret = _objc_msgSend_151sglz(this.ref.pointer, _sel_autorelease);
    return MLNPointFeatureCluster.castFromPointer(_ret, retain: true, release: true);
  }

  /// supportsSecureCoding
  static bool getSupportsSecureCoding() {
    return _objc_msgSend_91o635(_class_MLNPointFeatureCluster, _sel_supportsSecureCoding);

  }

  /// initWithCoder:
  MLNPointFeatureCluster? initWithCoder(objc.NSCoder coder) {
    final _ret = _objc_msgSend_1sotr3r(this.ref.retainAndReturnPointer(), _sel_initWithCoder_, coder.ref.pointer);
    return _ret.address == 0 ? null : MLNPointFeatureCluster.castFromPointer(_ret, retain: false, release: true);
  }

  /// The identifier for the cluster.
  int get clusterIdentifier {
    return _objc_msgSend_xw2lbc(this.ref.pointer, _sel_clusterIdentifier);

  }

  /// The number of points within this cluster
  int get clusterPointCount {
    return _objc_msgSend_xw2lbc(this.ref.pointer, _sel_clusterPointCount);

  }

  /// An object that uniquely identifies the feature in its containing content
/// source.
///
/// You can configure an ``MLNVectorStyleLayer`` object to include or exclude a
/// specific feature in an ``MLNShapeSource`` or ``MLNVectorTileSource``. In the
/// ``MLNVectorStyleLayer/predicate`` property, compare the special `$id` attribute
/// to the feature’s identifier.
///
/// In vector tiles loaded by ``MLNVectorTileSource`` objects, the identifier
/// corresponds to the
/// feature
/// identifier
/// (`id`). If the source does not specify the feature’s identifier, the value of
/// this property is `nil`. If specified, the identifier may be an integer,
/// floating-point number, or string. These data types are mapped to instances of
/// the following Foundation classes:
///
/// | In the tile source        | This property |
/// |---------------------------|-------------------------------------------------------------------------------|
/// | Integer                   | `NSNumber` (use the `unsignedLongLongValue` or `longLongValue`
/// property)      | | Floating-point number      | `NSNumber` (use the `doubleValue` property) | |
/// String                    | `NSString` |
///
/// The identifier should be set before adding the feature to an ``MLNShapeSource``
/// object; setting it afterwards has no effect on the map’s contents. While it is
/// possible to change this value on feature instances obtained from
/// ``MLNMapView/visibleFeaturesAtPoint:`` and related methods, doing so likewise
/// has no effect on the map’s contents.
  objc.ObjCObjectBase? get identifier {
    final _ret = _objc_msgSend_151sglz(this.ref.pointer, _sel_identifier);
    return _ret.address == 0 ? null


tNode; }\n  var measure = lineView.measure, maps = measure.maps;\n\n  function find(textNode, topNode, offset) {\n    for (var i = -1; i < (maps ? maps.length : 0); i++) {\n      var map$$1 = i < 0 ? measure.map : maps[i];\n      for (var j = 0; j < map$$1.length; j += 3) {\n        var curNode = map$$1[j + 2];\n        if (curNode == textNode || curNode == topNode) {\n          var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);\n          var ch = map$$1[j] + offset;\n          if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }\n          return Pos(line, ch)\n        }\n      }\n    }\n  }\n  var found = find(textNode, topNode, offset);\n  if (found) { return badPos(found, bad) }\n\n  // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n  for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n    found = find(after, after.firstChild, 0);\n    if (found)\n      { return badPos(Pos(found.line, found.ch - dist), bad) }\n    else\n      { dist += after.textContent.length; }\n  }\n  for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {\n    found = find(before, before.firstChild, -1);\n    if (found)\n      { return badPos(Pos(found.line, found.ch + dist$1), bad) }\n    else\n      { dist$1 += before.textContent.length; }\n  }\n}\n\n// TEXTAREA INPUT STYLE\n\nvar TextareaInput = function(cm) {\n  this.cm = cm;\n  // See input.poll and input.reset\n  this.prevInput = \"\";\n\n  // Flag that indicates whether we expect input to appear real soon\n  // now (after some event like 'keypress' or 'input') and are\n  // polling intensively.\n  this.pollingFast = false;\n  // Self-resetting timeout for the poller\n  this.polling = new Delayed();\n  // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n  this.hasSelection = false;\n  this.composing = null;\n};\n\nTextareaInput.prototype.init = function (display) {\n    var this$1 = this;\n\n  var input = this, cm = this.cm;\n\n  // Wraps and hides input textarea\n  var div = this.wrapper = hiddenTextarea();\n  // The semihidden textarea that is focused when the editor is\n  // focused, and receives input.\n  var te = this.textarea = div.firstChild;\n  display.wrapper.insertBefore(div, display.wrapper.firstChild);\n\n  // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n  if (ios) { te.style.width = \"0px\"; }\n\n  on(te, \"input\", function () {\n    if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }\n    input.poll();\n  });\n\n  on(te, \"paste\", function (e) {\n    if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n\n    cm.state.pasteIncoming = true;\n    input.fastPoll();\n  });\n\n  function prepareCopyCut(e) {\n    if (signalDOMEvent(


每个 type 的字段都是差不多的，但是有一些略微的差别。假设有一个 index，是订单 index，里面专门是放订单数据的。就好比说你在 mysql 中建表，有些订单是实物商品的订单，比如一件衣服、一双鞋子；有些订单是虚拟商品的订单，比如游戏点卡，话费充值。就两种订单大部分字段是一样的，但是少部分字段可能有略微的一些差别。

所以就会在订单 index 里，建两个 type，一个是实物商品订单 type，一个是虚拟商品订单 type，这两个 type 大部分字段是一样的，少部分字段是不一样的。

很多情况下，一个 index 里可能就一个 type，但是确实如果说是一个 index 里有多个 type 的情况（**注意**， `mapping types` 这个概念在 ElasticSearch 7. X 已被完全移除，详细说明可以参考[官方文档](https://github.com/elastic/elasticsearch/blob/6.5/docs/reference/mapping/removal_of_types.asciidoc)），你可以认为 index 是一个类别的表，具体的每个 type 代表了 mysql 中的一个表。每个 type 有一个 mapping，如果你认为一个 type 是具体的一个表，index 就代表多个 type 同属于的一个类型，而 mapping 就是这个 type 的**表结构定义**，你在 mysql 中创建一个表，肯定是要定义表结构的，里面有哪些字段，每个字段是什么类型。实际上你往 index 里的一个 type 里面写的一条数据，叫做一条 document，一条 document 就代表了 mysql 中某个表里的一行，每个 document 有多个 field，每个 field 就代表了这个 document 中的一个字段的值。

![es-index-type-mapping-document-field](http://cdn.jayh.club/uPic/es-index-type-mapping-document-fieldW7TVsP.png)

你搞一个索引，这个索引可以拆分成多个 `shard` ，每个 shard 存储部分数据。拆分多个 shard 是有好处的，一是**支持横向扩展**，比如你数据量是 3T，3 个 shard，每个 shard 就 1T 的数据，若现在数据量增加到 4T，怎么扩展，很简单，重新建一个有 4 个 shard 的索引，将数据导进去；二是**提高性能**，数据分布在多个 shard，即多台服务器上，所有的操作，都会在多台机器上并行分布式执行，提高了吞吐量和性能。

接着就是这个 shard 的数据实际是有多个备份，就是说每个 shard 都有一个 `primary shard` ，负责写入数据，但是还有几个 `replica shard` 。 `primary shard` 写入数据之后，会将数据同步到其他几个 `replica shard` 上去。


commission["level".$level["id"]]["option0"][$c_i ]}" style="display:inline;width: <?php echo (96 / $com_set["level"]);?>%;" placeholder="<?php echo $c_i+1;?>级"> <?php endfor;?>	{/if}{/foreach}

';
        if ($("#commission").html()=='')
        {
            $("#commission_default").html(html);
            $("#commission_default").show();
        }
        else
        {
            $("#commission_default").html('');
            $("#commission_default").show();
        }
    }
    commission_change();
    function commission_change_all() {
        var commission_level1 = $("#commission_level1").val();
        var commission_level2 = $("#commission_level2").val();
        var commission_level3 = $("#commission_level3").val();

        if (commission_level1=='')
        {
            tip.msgbox.err('请选择分销商等级');
            return false;
        }
        if (commission_level2=='')
        {
            tip.msgbox.err('请选择佣金等级');
            return false;
        }
        if (commission_level3=='')
        {
            tip.msgbox.err('请填写佣金比例');
            return false;
        }

        if (commission_level1=='default')
        {
            $(".commission_default").each(function (key,val) {
                if(key%{$com_set['level']} == commission_level2)
                {
                    $(this).val(commission_level3);
                }
            });
        }
        else
        {
            $(".commission_level"+commission_level1).each(function (key,val) {
                if(key%{$com_set['level']} == commission_level2)
                {
                    $(this).val(commission_level3);
                }
            });
        }
    }
</script>
{include file='_header'}

    当前位置：商品分类

                 设置分类层级
                <button type="button" id='btnExpand' class="btn btn-default" data-action='expand'> 折叠所有</button>
                 添加新分类

    <form action="" method="post" class="form-validate">

                {foreach name='category' item='row'}
                {if empty($row['parentid'])}

                        [ID: {$row['id']}] {$row['name']}

                            <div class='label {if $row['enabled']


     padding: .1em;
     border-radius: .3em;
     white-space: normal;
 }

 .token.comment,
 .token.prolog,
 .token.doctype,
 .token.cdata {
     color: #8292a2;
 }

 .token.punctuation {
     color: #f8f8f2;
 }

 .token.namespace {
     opacity: .7;
 }

 .token.property,
 .token.tag,
 .token.constant,
 .token.symbol,
 .token.deleted {
     color: #f92672;
 }

 .token.boolean,
 .token.number {
     color: #ae81ff;
 }

 .token.selector,
 .token.attr-name,
 .token.string,
 .token.char,
 .token.builtin,
 .token.inserted {
     color: #a6e22e;
 }

 .token.operator,
 .token.entity,
 .token.url,
 .language-css .token.string,
 .style .token.string,
 .token.variable {
     color: #f8f8f2;
 }

 .token.atrule,
 .token.attr-value,
 .token.function,
 .token.class-name {
     color: #e6db74;
 }

 .token.keyword {
     color: #66d9ef;
 }

 .token.regex,
 .token.important {
     color: #fd971f;
 }

 .token.important,
 .token.bold {
     font-weight: bold;
 }
 .token.italic {
     font-style: italic;
 }

 .token.entity {
     cursor: help;
 }
 /*
 * Payment Icons. This makes it easy for you to include a list of payment provider icons to your website or app.
 * Created by Jasper codepen.io/jasper
 *
 * Version: 0.0.1
 *
 * All icons are © to their respective owners
 * Icon designs by behance.net/spektrum44
 *
*/

.pi {
    display: inline-block;
    -webkit-font-smoothing: antialiased;
    font-style: normal;
    font-variant: normal;
    text-rendering: auto;
    width: 40px;
    min-height: 30px;
    background-origin: padding-box;

    &.pi-paypal { background: url('../svgs/paypal.svg') center center no-repeat;}
    &.pi-apple-pay { background: url('../svgs/apple-pay.svg') center center no-repeat;}
    &.pi-google-pay { background: url('../svgs/google-pay.svg') center center no-repeat;}
    &.pi-alipay { background: url('../svgs/alipay.svg') center center no-repeat;}
    &.pi-mastercard { background: url('../svgs/mastercard.svg') center center no-repeat;}
    &.pi-visa { background: url('../svgs/visa.svg') center center no-repeat;}
    &.pi-american-express { background: url('../svgs/american-express.svg') center center no-repeat;}
    &.pi-diners-club { background: url('../svgs/diners-club.svg') center center no-repeat;}
    &.pi-maestro { background: url('../svgs/maestro.svg') center center no-repeat;}
    &.pi-vpay { background: url('../svgs/vpay.svg') center center no-repeat;}
    &.pi-girocard { background: url('../svgs/girocard.svg') center center no-repeat;}
    &.pi-klarna { background: url('../svgs/klarna.svg') center center no-repeat;}
    &.pi-giropay { background: url('../svgs/giropay.svg') center center no-repeat;}
    &.pi-ideal { background: url('../svgs/ideal.svg') center center no-repeat;}
    &.pi-przelewy24 { background: url('../svgs/przelewy24.svg')


,reason):\n  super(TextTestResult,self).addSkip(test,reason)\n  if self.showAll:\n   self.stream.writeln(\"skipped {0!r}\".format(reason))\n  elif self.dots:\n   self.stream.write(\"s\")\n   self.stream.flush()\n   \n def addExpectedFailure(self,test,err):\n  super(TextTestResult,self).addExpectedFailure(test,err)\n  if self.showAll:\n   self.stream.writeln(\"expected failure\")\n  elif self.dots:\n   self.stream.write(\"x\")\n   self.stream.flush()\n   \n def addUnexpectedSuccess(self,test):\n  super(TextTestResult,self).addUnexpectedSuccess(test)\n  if self.showAll:\n   self.stream.writeln(\"unexpected success\")\n  elif self.dots:\n   self.stream.write(\"u\")\n   self.stream.flush()\n   \n def printErrors(self):\n  if self.dots or self.showAll:\n   self.stream.writeln()\n  self.printErrorList('ERROR',self.errors)\n  self.printErrorList('FAIL',self.failures)\n  \n def printErrorList(self,flavour,errors):\n  for test,err in errors:\n   self.stream.writeln(self.separator1)\n   self.stream.writeln(\"%s: %s\"%(flavour,self.getDescription(test)))\n   self.stream.writeln(self.separator2)\n   self.stream.writeln(\"%s\"%err)\n   \n   \nclass TextTestRunner(object):\n ''\n\n\n\n \n resultclass=TextTestResult\n \n def __init__(self,stream=None ,descriptions=True ,verbosity=1,\n failfast=False ,buffer=False ,resultclass=None ,warnings=None ,\n *,tb_locals=False ):\n  ''\n\n\n\n  \n  if stream is None :\n   stream=sys.stderr\n  self.stream=_WritelnDecorator(stream)\n  self.descriptions=descriptions\n  self.verbosity=verbosity\n  self.failfast=failfast\n  self.buffer=buffer\n  self.tb_locals=tb_locals\n  self.warnings=warnings\n  if resultclass is not None :\n   self.resultclass=resultclass\n   \n def _makeResult(self):\n  return self.resultclass(self.stream,self.descriptions,self.verbosity)\n  \n def run(self,test):\n  ''\n  result=self._makeResult()\n  registerResult(result)\n  result.failfast=self.failfast\n  result.buffer=self.buffer\n  result.tb_locals=self.tb_locals\n  with warnings.catch_warnings():\n   if self.warnings:\n   \n    warnings.simplefilter(self.warnings)\n    \n    \n    \n    \n    \n    if self.warnings in ['default','always']:\n     warnings.filterwarnings('module',\n     category=DeprecationWarning,\n     message=r'Please use assert\\w+ instead.')\n   startTime=time.time()\n   startTestRun=getattr(result,'startTestRun',None )\n   if startTestRun is not None :\n    startTestRun()\n   try :\n    test(result)\n   finally :\n    stopTestRun=getattr(result,'stopTestRun',None )\n    if stopTestRun is not None :\n     stopTestRun()\n   stopTime=time.time()\n  timeTaken=stopTime -startTime\n  result.printErrors()\n  if hasattr(result,'separator2'):\n   self.stream.writeln(result.separator2)\n


qfmhwkx6c' \\\n    -H 'Content-Type: application/json' \\\n    -H 'X-Requested-With: XMLHttpRequest'\n"}]}},"/channels":{"post":{"tags":["channels"],"summary":"Create a channel","description":"Create a new channel.\n##### Permissions\nIf creating a public channel, `create_public_channel` permission is required. If creating a private channel, `create_private_channel` permission is required.\n","requestBody":{"content":{"application/json":{"schema":{"type":"object","required":["name","display_name","type","team_id"],"properties":{"team_id":{"type":"string","description":"The team ID of the team to create the channel on"},"name":{"type":"string","description":"The unique handle for the channel, will be present in the channel URL"},"display_name":{"type":"string","description":"The non-unique UI name for the channel"},"purpose":{"type":"string","description":"A short description of the purpose of the channel"},"header":{"type":"string","description":"Markdown-formatted text to display in the header of the channel"},"type":{"type":"string","description":"'O' for a public channel, 'P' for a private channel"}}}}},"description":"Channel object to be created","required":true},"responses":{"201":{"description":"Channel creation successful","content":{"*/*":{"schema":{"$ref":"#/components/schemas/Channel"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"}},"x-code-samples":[{"lang":"Go","source":"import \"github.com/mattermost/mattermost-server/model\"\nClient := model.NewAPIv4Client(\"https://your-mattermost-url.com\")\nClient.Login(\"email@domain.com\", \"Password1\")\n\nchannel := &model.Channel{DisplayName: <YOUR CHANNEL DISPLAYNAME>, Name: <YOUR CHANNEL NAME>, Type: <CHANNEL TYPE OPEN/PRIVATE>, TeamId: <YOUR TEAM ID>}\n\n// CreateChannel\nrchannel, resp := Client.CreateChannel(channel)\n"}]}},"/channels/direct":{"post":{"tags":["channels"],"summary":"Create a direct message channel","description":"Create a new direct message channel between two users.\n##### Permissions\nMust be one of the two users and have `create_direct_channel` permission. Having the `manage_system` permission voids the previous requirements.\n","requestBody":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2}}},"description":"The two user ids to be in the direct message","required":true},"responses":{"201":{"description":"Direct channel creation successful","content":{"*/*":{"schema":{"$ref":"#/components/schemas/Channel"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"}},"x-code-samples":[{"lang":"Go","source":"import \"github.com/mattermost/mattermost-server/model\"\nClient := model.NewAPIv4Client(\"https://your-mattermost-url.com\")\nClient.Login(\"email@domain.com\", \"Password1\")\n\n// CreateDirectChannel\ndm, resp := Client.CreateDirectChannel(<ID OF User1>, <ID OF User2>)\n"}]}},"/channels/group":{"post":{"tags":["channels"],"summary":"Create a group message channel","description":"Create a new group message channel to group of users. If the logged in user's id is not included in the list, it will be appended to the end.\n##### Permissions\nMust have `create_group_channel` permission.\n","requestBody":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}},"description":"User ids to be in the group message channel","required":true},"responses":{"201":{"description":"Group channel creation successful","content":{"*/*":{"schema":{"$ref":"#/components/schemas/Channel"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref"


"howDoesPairingWorkAnswer": "Ag tús an chomórtais, cuirtear imreoirí le chéile bunaithe ar a rátáil.\nChomh luath agus a chríochnaíonn tú cluiche, fill ar ais chuig forhalla an chomórtais: ansin beidh tú curtha le himreoir gar do do rátáil. Cinntíonn sé seo an t-íosmhéid ama feithimh, ach b’fhéidir nach dtabharfaidh tú imir le gach imreoir eile sa chomórtas.\nImir go tapa agus filleadh chuig an forhalla chun níos mó cluichí a imirt agus níos mó pointí a bhuachan.",
  "howDoesItEnd": "Conas a chríochnaíonn sé?",
  "howDoesItEndAnswer": "Tá clog comhaireamh síos sa chomórtas. Nuair a ritheann an am amach, reoitear rátálacha an chomórtais, agus fógraítear an buaiteoir. Caithfear cluichí atá idir lámha a chríochnú, ach níl siad san áireamh don chomórtas.",
  "otherRules": "Rialacha tábhachtacha eile",
  "thereIsACountdown": "Tá comhaireamh síos ann do do chéad bheart. Mura ndéantar beart laistigh den tréimhse seo, cailllfear an cluiche do do chéile comhraic.",
  "thisIsPrivate": "Is comórtas príobháideach é seo",
  "shareUrl": "Comhroinn an URL seo chun ligean do imreoirí a bheith páirteach: %s",
  "drawStreak": "Stríocán cothroma: Nuair a bhíonn cluichí cothroma i ndiaidh a chéile ag ficheallaí i réimse, ní bheidh pointe buaite ach don céad cluiche cothrom, nó cluichí cothroma le níos mó ná %s beart. Ní féidir an stríocán cothroma a bhriseadh ach le bua, ní le caill nó cluiche cothrom.",
  "history": "Stair fadhbhanna",
  "newTeamBattle": "Cath Foirne Nua",
  "customStartDate": "Dáta tosaigh saincheaptha",
  "customStartDateHelp": "I do chrios ama áitiúil féin. Sáraíonn sé seo an socrú \"Am sula dtosaíonn an comórtas\"",
  "allowBerserk": "Lig Berserk",
  "allowBerserkHelp": "Lig d’imreoirí a gcuid ama clog a laghdú chun pointe breise a fháil",
  "allowChatHelp": "Lig d’imreoirí plé a dhéanamh i seomra comhrá",
  "arenaStreaks": "Sruthanna airéine",
  "arenaStreaksHelp": "Tar éis 2 bhua, deonaíonn 4 bhua as a chéile 4 phointe in ionad 2.",
  "drawingWithinNbMoves:one": "Ní bhfaighfaidh aon ficheallaí pointe ar bith má tá comhscór eagraithe laistigh den chéad %s beart.",
  "drawingWithinNbMoves:two": "Ní bhfaighfaidh aon ficheallaí pointe ar bith má tá comhscór eagraithe laistigh den chéad %s bheart.",
  "drawingWithinNbMoves:few": "Ní bhfaighfaidh


,
	remote: "Дұрыс мағына енгізуіңізді сұраймыз.",
	email: "Нақты электронды поштаңызды енгізуіңізді сұраймыз.",
	url: "Нақты URL-ды енгізуіңізді сұраймыз.",
	date: "Нақты URL-ды енгізуіңізді сұраймыз.",
	dateISO: "Нақты ISO форматымен сәйкес датасын енгізуіңізді сұраймыз.",
	number: "Күнді енгізуіңізді сұраймыз.",
	digits: "Тек қана сандарды енгізуіңізді сұраймыз.",
	creditcard: "Несие картасының нөмірін дұрыс енгізуіңізді сұраймыз.",
	equalTo: "Осы мәнді қайта енгізуіңізді сұраймыз.",
	extension: "Файлдың кеңейтуін дұрыс таңдаңыз.",
	maxlength: $.validator.format("Ұзындығы {0} символдан көр болмасын."),
	minlength: $.validator.format("Ұзындығы {0} символдан аз болмасын."),
	rangelength: $.validator.format("Ұзындығы {0}-{1} дейін мән енгізуіңізді сұраймыз."),
	range: $.validator.format("Пожалуйста, введите число от {0} до {1}. - {0} - {1} санын енгізуіңізді сұраймыз."),
	max: $.validator.format("{0} аз немесе тең санын енгізуіңіді сұраймыз."),
	min: $.validator.format("{0} көп немесе тең санын енгізуіңізді сұраймыз.")
});

}));(function( factory ) {
	if ( typeof define === "function" && define.amd ) {
		define( ["jquery", "../jquery.validate"], factory );
	} else {
		factory( jQuery );
	}
}(function( $ ) {

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: VI (Vietnamese; Tiếng Việt)
 */
$.extend($.validator.messages, {
	required: "Hãy nhập.",
	remote: "Hãy sửa cho đúng.",
	email: "Hãy nhập email.",
	url: "Hãy nhập URL.",
	date: "


1
    ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_ICAC_VALUE_REQ), ICACValue) }

    val TAG_IPK_VALUE_REQ: Int = 2
    tlvWriter.put(ContextSpecificTag(TAG_IPK_VALUE_REQ), IPKValue)

    val TAG_CASE_ADMIN_SUBJECT_REQ: Int = 3
    tlvWriter.put(ContextSpecificTag(TAG_CASE_ADMIN_SUBJECT_REQ), caseAdminSubject)

    val TAG_ADMIN_VENDOR_ID_REQ: Int = 4
    tlvWriter.put(ContextSpecificTag(TAG_ADMIN_VENDOR_ID_REQ), adminVendorId)
    tlvWriter.endStructure()

    val request: InvokeRequest =
      InvokeRequest(
        CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
        tlvPayload = tlvWriter.getEncoded(),
        timedRequest = timedInvokeTimeout,
      )

    val response: InvokeResponse = controller.invoke(request)
    logger.log(Level.FINE, "Invoke command succeeded: ${response}")

    val tlvReader = TlvReader(response.payload)
    tlvReader.enterStructure(AnonymousTag)
    val TAG_STATUS_CODE: Int = 0
    var statusCode_decoded: UByte? = null

    val TAG_FABRIC_INDEX: Int = 1
    var fabricIndex_decoded: UByte? = null

    val TAG_DEBUG_TEXT: Int = 2
    var debugText_decoded: String? = null

    while (!tlvReader.isEndOfContainer()) {
      val tag = tlvReader.peekElement().tag

      if (tag == ContextSpecificTag(TAG_STATUS_CODE)) {
        statusCode_decoded = tlvReader.getUByte(tag)
      }

      if (tag == ContextSpecificTag(TAG_FABRIC_INDEX)) {
        fabricIndex_decoded =
          if (tlvReader.isNull()) {
            tlvReader.getNull(tag)
            null
          } else {
            if (tlvReader.isNextTag(tag)) {
              tlvReader.getUByte(tag)
            } else {
              null
            }
          }
      }

      if (tag == ContextSpecificTag(TAG_DEBUG_TEXT)) {
        debugText_decoded =
          if (tlvReader.isNull()) {
            tlvReader.getNull(tag)
            null
          } else {
            if (tlvReader.isNextTag(tag)) {
              tlvReader.getString(tag)
            } else {
              null
            }
          }
      } else {
        tlvReader.skipElement()
      }
    }

    if (statusCode_decoded == null) {
      throw IllegalStateException("statusCode not found in TLV")
    }

    tlvReader.exitContainer()

    return NOCResponse(statusCode_decoded, fabricIndex_decoded, debugText_decoded)
  }

  suspend fun updateNOC(
    NOCValue: ByteArray,
    ICACValue: ByteArray?,
    timedInvokeTimeout: Duration? = null,
  ): NOCResponse {
    val commandId: UInt = 7u

    val tlvWriter = TlvWriter()
    tlvWriter.startStructure(AnonymousTag)

    val TAG_NOC_VALUE_REQ: Int = 0
    tlvWriter.put(ContextSpecificTag(TAG_NOC_VALUE_REQ), NOCValue)

    val TAG_ICAC_VALUE_REQ: Int = 1
    ICACValue?.let { tlvWriter.put(ContextSpecificTag(TAG_ICAC_VALUE_REQ), ICACValue) }
    tlvWriter.endStructure()

    val request: InvokeRequest =
      InvokeRequest(
        CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
        tlvPayload = tlvWriter.getEncoded(),
        timedRequest = timedInvokeTimeout,
      )

    val response: InvokeResponse = controller.invoke(request)
    logger.log(Level.FINE


 the GNU General Public
 * License in all respects for all of the code used other than "OpenSSL".  If you
 * modify file(s), you may extend this exception to your version of the file(s),
 * but you are not obligated to do so. If you do not wish to do so, delete this
 * exception statement from your version.
 */

#include "torrentfileswatcher.h"

#include <chrono>

#include <QtAssert>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileSystemWatcher>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSet>
#include <QThread>
#include <QTimer>
#include <QVariant>

#include "base/algorithm.h"
#include "base/bittorrent/torrentcontentlayout.h"
#include "base/bittorrent/session.h"
#include "base/bittorrent/torrent.h"
#include "base/exceptions.h"
#include "base/global.h"
#include "base/logger.h"
#include "base/profile.h"
#include "base/settingsstorage.h"
#include "base/tagset.h"
#include "base/utils/fs.h"
#include "base/utils/io.h"
#include "base/utils/string.h"

using namespace std::chrono_literals;

const std::chrono::seconds WATCH_INTERVAL {10};
const int MAX_FAILED_RETRIES = 5;
const QString CONF_FILE_NAME = u"watched_folders.json"_s;

const QString OPTION_ADDTORRENTPARAMS = u"add_torrent_params"_s;
const QString OPTION_RECURSIVE = u"recursive"_s;

namespace
{
    TorrentFilesWatcher::WatchedFolderOptions parseWatchedFolderOptions(const QJsonObject &jsonObj)
    {
        TorrentFilesWatcher::WatchedFolderOptions options;
        options.addTorrentParams = BitTorrent::parseAddTorrentParams(jsonObj.value(OPTION_ADDTORRENTPARAMS).toObject());
        options.recursive = jsonObj.value(OPTION_RECURSIVE).toBool();

        return options;
    }

    QJsonObject serializeWatchedFolderOptions(const TorrentFilesWatcher::WatchedFolderOptions &options)
    {
        return {{OPTION_ADDTORRENTPARAMS, BitTorrent::serializeAddTorrentParams(options.addTorrentParams)},
                {OPTION_RECURSIVE, options.recursive}};
    }
}

class TorrentFilesWatcher::Worker final : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY_MOVE(Worker)

public:
    Worker(QFileSystemWatcher *watcher);

public slots:
    void setWatchedFolder(const Path &path, const TorrentFilesWatcher::WatchedFolderOptions &options);
    void removeWatchedFolder(const Path &path);

signals:
    void torrentFound(const BitTorrent::TorrentDescriptor &torrentDescr, const BitTorrent::AddTorrentParams &addTorrentParams);

private:
    void onTimeout();
    void scheduleWatchedFolderProcessing(const Path &path);
    void processWatchedFolder(const Path &path);
    void processFolder(const Path &path, const Path &watchedFolderPath, const TorrentFilesWatcher::WatchedFolderOptions &options);
    void processFailedTorrents();
    void addWatchedFolder(const Path &path, const TorrentFilesWatcher::WatchedFolderOptions &options);
    void updateWatchedFolder(const Path &path, const TorrentFilesWatcher::WatchedFolderOptions &options);

    QFileSystemWatcher *m_watcher = nullptr;
    QTimer *m_watchTimer = nullptr;
    QHash<Path, TorrentFilesWatcher::WatchedFolderOptions> m_watchedFolders;
    QSet<Path> m_watchedByTimeoutFolders;

    // Failed torrents
    QTimer *m_retryTorrentTimer = nullptr;
    QHash<Path, QHash<Path, int>> m_fai


tor<int>* myVector = new std::vector<int>;`，这时不仅vector内部管理的元素在堆上，连vector对象本身也在堆上，因为你使用了new操作符显式地在堆上分配了vector对象的内存。

总结来说，std::vector容器本身作为对象可以存储在栈或堆上，但其包含的元素总是存储在堆上，以支持容量的动态调整。

### STL

STL（Standard Template Library）容器根据其设计目的和特性，在内存分配上有所不同，但普遍遵循以下原则：

1. 动态内存分配容器：大多数STL容器，如std::vector、std::list、std::map、std::unordered_map等，它们的元素是存储在堆上的。这是因为这些容器需要能够在运行时动态地调整大小，而堆内存是唯一能够提供这种灵活性的内存区域。容器本身（即管理元素的数据结构）如果是局部变量，则存储在栈上，但它们所持有的数据则位于堆中。

2. 静态内存分配容器：像std::array这样的容器，它是一个静态大小的数组，其元素和容器本身（因为它不是一个动态容器）都存储在栈上，或者如果它是类或结构体的成员，则存储在相应的内存区域。std::array不涉及堆分配，其大小在编译时就必须确定。

3. 容器适配器：如std::stack、std::queue和std::priority_queue等，它们不直接管理内存，而是基于其他容器（默认情况下是std::deque或std::vector）实现。因此，它们的内存分配特性跟随底层使用的容器。例如，基于std::vector的std::stack会将元素存储在堆上。

4. 内存分配器：STL容器使用一个名为Allocator的模板参数来控制内存的分配和释放，默认情况下使用的是std::allocator，它从自由存储区（即堆）分配内存。尽管如此，用户可以通过自定义Allocator来改变内存的来源，比如从栈上分配（尽管这在实践中很少见且具有挑战性，因为栈的大小限制和缺乏动态性）。

总的来说，STL容器大部分涉及动态内存分配的元素都存储在堆上，以适应元素数量的变化，而容器的管理结构如果作为局部变量，则位于栈上。
# 禁止继承或重写 = delete

从C++11开始，delete还可以用于类的定义中，以禁


or de contexto del editor para permitir el acceso al estado y las funciones del editor en los componentes hijos.
 * - Configuración de la barra de carga superior para indicar el progreso de la carga de la página.
 * - Configuración del componente Toaster para mostrar notificaciones en la aplicación.
 *
 * @param {object} props - Las propiedades del componente.
 * @param {ReactNode} props.children - Los elementos hijos que se van a renderizar dentro del layout.
 * @returns {ReactElement} El elemento del layout raíz.
 */
export default function RootLayout({ children }) {
  return (
    <ClerkProvider
      appearance={{
        variables: {
          colorPrimary: colors.neutral['900'],
          fontFamily: 'font-sans, sans-serif',
        },
      }}
    >
      <html lang="en">
        <body className={cn('font-sans', inter.variable)}>
          <NextTopLoader color={colors.yellow['400']} />
          <EditorContextProvider>
            {children}
            <Toaster />
          </EditorContextProvider>
        </body>
      </html>
    </ClerkProvider>
  );
}
'use client';

import { useEffect, useCallback, memo } from 'react';
import { useForm } from 'react-hook-form';
import { useEditor } from '@/components/hooks/use-editor.js';
import { Input } from '@/components/ui/input.js';
import { Form, FormItem, FormControl } from '@/components/ui/form.js';

const TYPE = 'TitleField';
const INITIAL_VALUE = '';
const EXTRA_ATTRIBUTES = {
  label: 'Title Field',
  placeholderText: 'Type here...',
};

const FormEditorComponent = memo(({ elementInstance: element }) => {
  const { control, getValues, setValue, register, watch, reset } = useForm({
    mode: 'onSubmit',
    defaultValues: {
      title: INITIAL_VALUE,
    },
  });

  const { updateElement } = useEditor();

  const fieldName = 'title';
  register(fieldName);
  const fieldValue = watch(fieldName);

  useEffect(() => {
    reset({ [fieldName]: element.value });
  }, [element.value, reset, fieldName]);

  const applyChanges = useCallback(() => {
    if (!element) return;

    const values = getValues();

    const updatedElement = {
      ...element,
      value: values[fieldName],
      extraAttributes: { ...element.extraAttributes },
    };
    updateElement(element.id, updatedElement);
  }, [getValues, element, updateElement, fieldName]);

  const handleChange = (e) => {
    setValue(fieldName, e.target.value);
    applyChanges();
  };

  if (!element || element.value == undefined) {
    return null;
  }

  return (
    <Form {...{ control, register, getValues, watch }}>
      <form className="w-full">
        <FormItem>
          <FormControl>
            <Input
              name={fieldName}
              value={fieldValue}
              onChange={handleChange}
              placeholder={EXTRA_ATTRIBUTES.placeholderText}
              className="resize-none focus:outline-none focus:ring-2 focus:ring-blue-400 border-0 rounded-none bg-transparent w-full min-h-min placeholder:text-neutral-400 placeholder:text-base text-2xl text-neutral-800 focus-visible:ring-offset-0 focus-visible:ring-0 "
            />
          </FormControl>
        </FormItem>
      </form>
    </Form>
  );
});

FormEditorComponent.displayName = 'FormEditorComponent';

const FormComponen


kend I/O Size Total (Read and Write)",
		Units: "KiB",
		Fam:   "workload",
		Ctx:   "scaleio.system_workload_primary_io_size_total",
		Dims: Dims{
			{ID: "system_backend_primary_io_size_read_write", Name: "io_size", Div: 1000},
		},
	},
	// Rebalance
	{
		ID:    "system_rebalance",
		Title: "Rebalance",
		Units: "KiB/s",
		Fam:   "rebalance",
		Type:  module.Area,
		Ctx:   "scaleio.system_rebalance",
		Dims: Dims{
			{ID: "system_rebalance_bandwidth_read", Name: "read", Div: 1000},
			{ID: "system_rebalance_bandwidth_write", Name: "write", Mul: -1, Div: 1000},
		},
	},
	{
		ID:    "system_rebalance_left",
		Title: "Rebalance Pending Capacity",
		Units: "KiB",
		Fam:   "rebalance",
		Ctx:   "scaleio.system_rebalance_left",
		Dims: Dims{
			{ID: "system_rebalance_pending_capacity_in_Kb", Name: "left"},
		},
	},
	{
		ID:    "system_rebalance_time_until_finish",
		Title: "Rebalance Approximate Time Until Finish",
		Units: "seconds",
		Fam:   "rebalance",
		Ctx:   "scaleio.system_rebalance_time_until_finish",
		Dims: Dims{
			{ID: "system_rebalance_time_until_finish", Name: "time"},
		},
	},
	// Rebuild
	{
		ID:    "system_rebuild",
		Title: "Rebuild Bandwidth Total (Forward, Backward and Normal)",
		Units: "KiB/s",
		Fam:   "rebuild",
		Ctx:   "scaleio.system_rebuild",
		Type:  module.Area,
		Dims: Dims{
			{ID: "system_rebuild_total_bandwidth_read", Name: "read", Div: 1000},
			{ID: "system_rebuild_total_bandwidth_write", Name: "write", Mul: -1, Div: 1000},
		},
	},
	{
		ID:    "system_rebuild_left",
		Title: "Rebuild Pending Capacity Total (Forward, Backward and Normal)",
		Units: "KiB",
		Fam:   "rebuild",
		Ctx:   "scaleio.system_rebuild_left",
		Dims: Dims{
			{ID: "system_rebuild_total_pending_capacity_in_Kb", Name: "left"},
		},
	},
	// Components
	{
		ID:    "system_defined_components",
		Title: "Components",
		Units: "components",
		Fam:   "components",
		Ctx:   "scaleio.system_defined_components",
		Dims: Dims{
			{ID: "system_num_of_devices", Name: "devices"},
			{ID: "system_num_of_fault_sets", Name: "fault_sets"},
			{ID: "system_num_of_protection_domains", Name: "protection_domains"},
			{ID: "system_num_of_rfcache_devices", Name: "rfcache_devices"},
			{ID: "system_num_of_sdc", Name: "sdc"},
			{ID: "system_num_of_sds", Name: "sds"},
			{ID: "system_num_of_snapshots", Name: "snapshots"},
			{ID: "system_num_of_storage_pools", Name: "storage_pools"},
			{ID: "system_num_of_volumes", Name: "volumes"},
			{ID: "system_num_of_vtrees", Name: "vtrees"},
		},
	},
	{
		ID:    "system


// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::prophetnet::ProphetNetConfig;
use std::borrow::Borrow;
use tch::nn::{Embedding, EmbeddingConfig};
use tch::{nn, Device, Kind, Tensor};

pub struct ProphetNetPositionalEmbeddings {
    embeddings: Embedding,
    padding_idx: i64,
}

impl ProphetNetPositionalEmbeddings {
    pub fn new<'p, P>(p: P, config: &ProphetNetConfig) -> ProphetNetPositionalEmbeddings
    where
        P: Borrow<nn::Path<'p>>,
    {
        let p = p.borrow();
        let embeddings_config = EmbeddingConfig {
            padding_idx: config.pad_token_id,
            ..Default::default()
        };
        let embeddings = nn::embedding(
            p,
            config.max_position_embeddings,
            config.hidden_size,
            embeddings_config,
        );
        ProphetNetPositionalEmbeddings {
            embeddings,
            padding_idx: config.pad_token_id,
        }
    }

    pub fn forward(
        &self,
        input_shape: &[i64],
        device: Device,
        attention_mask: Option<&Tensor>,
        prev_num_input_ids: Option<i64>,
        position_ids: Option<&Tensor>,
    ) -> (Tensor, Tensor) {
        let calc_position_ids = match position_ids {
            None => {
                if let Some(prev_num_input_ids_value) = prev_num_input_ids {
                    let num_input_ids = input_shape[1] + prev_num_input_ids_value;

                    Tensor::ones(&[1, 1], (Kind::Int64, device))
                        * (self.padding_idx + num_input_ids)
                } else {
                    let calc_attention_mask = if attention_mask.is_none() {
                        Some(Tensor::ones(input_shape, (Kind::Int64, device)))
                    } else {
                        None
                    };
                    let attention_mask =
                        attention_mask.unwrap_or_else(|| calc_attention_mask.as_ref().unwrap());
                    attention_mask.cumsum(1, Kind::Int64) * attention_mask + self.padding_idx
                }
            }
            Some(value) => value.copy(),
        };

        (calc_position_ids.apply(&self.embeddings), calc_position_ids)
    }

    pub fn _forward(&self, position_ids: &Tensor) -> Tensor {
        position_ids.apply(&self.embeddings)
    }
}
<reponame>tuoersitai/Genesis<filename>core/src/mpt/trie.rs
use super::node::*;
use db::manager::*;
use rlp::RLPSerialize;
use common::hash::*;

use std::cmp::min;
use std::marker::PhantomData;
use std::sync::Mutex;

pub struct Trie<'a, T: RLPSerialize + Clone> {
    root: TrieKey,
    db: &'a Mutex<DBManager>,
    phantom: PhantomData<T>
}

impl<'a, T> Trie<'a, T> where T: RLPSerialize + Clone {
    pub fn get(&self, path: &Vec<u8>) -> Option<T> {
        get_helper(&self.root, &vec2nibble(path), self.db)
    }

    pub fn delete(&mut sel


s-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222,


�동화된 사실 불일치 탐지의 개선의 상당한 여지를 강조한다.\n' +
      '\n' +
      '## 3 Tofuval Benchmark\n' +
      '\n' +
      '주제 중심 대화 요약 벤치마크인 TofuEval은 다음과 같이 구성된다: (1) 공개적으로 이용 가능한 두 개의 대화 요약 데이터 세트로부터 샘플 문서(섹션 3.1); (2) 샘플링된 문서에 대해 다양한 주제를 생성(섹션 3.2); 및 (3) 다양한 LLM으로 주제 중심 요약을 생성한다(섹션 3.3). 결과 벤치마크는 100개의 대화와 15개의 LLM 생성 요약을 포함한다; (4) 마지막으로 주제에 대한 세밀한 인간 주석과 생성된 요약을 사실적 일관성, 관련성 및 완전성을 포함한 차원에 대해 제공한다(3.4절). 데이터세트 구축 파이프라인이 그림 1에 나와 있다.\n' +
      '\n' +
      '### Document Selection\n' +
      '\n' +
      '우리는 공개적으로 이용 가능한 두 개의 대화 요약 데이터 세트에서 문서를 선택한다.\n' +
      '\n' +
      'MediaSumZhu et al. (2021)은 NPR 및 CNN으로부터의 공개 인터뷰 녹취록을 갖는 대규모 대화 요약 데이터세트이다. 데이터 세트는 정치, 경제 및 미국 뉴스와 같은 다양한 주제에 걸친 다자간 대화를 특징으로 한다.\n' +
      '\n' +
      'MeetingBankHu et al.(2023)은 시의회 회의를 갖는 요약 데이터세트이다. 이러한 회의에는 예산 할당, 인프라 계획 및 범죄 예방을 포함하여 지역 거버넌스


 null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
    internal_static_vector_tile_Tile_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_vector_tile_Tile_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_vector_tile_Tile_descriptor,
        new java.lang.String[] { "Layers", });
    internal_static_vector_tile_Tile_Value_descriptor =
      internal_static_vector_tile_Tile_descriptor.getNestedTypes().get(0);
    internal_static_vector_tile_Tile_Value_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_vector_tile_Tile_Value_descriptor,
        new java.lang.String[] { "StringValue", "FloatValue", "DoubleValue", "IntValue", "UintValue", "SintValue", "BoolValue", });
    internal_static_vector_tile_Tile_Feature_descriptor =
      internal_static_vector_tile_Tile_descriptor.getNestedTypes().get(1);
    internal_static_vector_tile_Tile_Feature_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_vector_tile_Tile_Feature_descriptor,
        new java.lang.String[] { "Id", "Tags", "Type", "Geometry", });
    internal_static_vector_tile_Tile_Layer_descriptor =
      internal_static_vector_tile_Tile_descriptor.getNestedTypes().get(2);
    internal_static_vector_tile_Tile_Layer_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_vector_tile_Tile_Layer_descriptor,
        new java.lang.String[] { "Version", "Name", "Features", "Keys", "Values", "Extent", });
  }

  // @@protoc_insertion_point(outer_class_scope)
}
/*
 * Copyright (c) 2015, Conveyal
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.conveyal.gtfs.error;

import java.io.Serializable;


 URL Cleaner
 * Copyright (C) 2023 Sven Jacobs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.svenjacobs.app.leon.core.domain.sanitizer.kogan

import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe

class KoganSanitizerTest :
	WordSpec({
		val sanitizer = KoganSanitizer()

		"invoke" should {
			"remove all parameters from kogan.com URL" {
				val result =
					sanitizer(
						"https://www.kogan.com/au/buy/heybattery-samsung-galaxy-watch-7-44mm-bluetooth-l310-silver-ss-l310-sv/?ssid=201.bae7632c-5c90-46cf-a071-416f0879ecb5&click_id=VWDA74xN4CIffN9Rb_8l-46p",
					)
				result shouldBe
					"https://www.kogan.com/au/buy/heybattery-samsung-galaxy-watch-7-44mm-bluetooth-l310-silver-ss-l310-sv/"
			}
		}

		"matchesDomain" should {
			"match for kogan.com" {
				sanitizer.matchesDomain("https://www.kogan.com/au/buy/kogan-4k-led-tv/") shouldBe true
			}
			"not match for other domains" {
				sanitizer.matchesDomain("https://www.example.com/product/123") shouldBe false
			}
		}
	})
/*
 * Léon - The URL Cleaner
 * Copyright (C) 2023 Sven Jacobs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.svenjacobs.app.leon.core.domain.sanitizer.wikipedia

import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe

class WikipediaSanitizerTest :
	WordSpec(
		{
			val sanitizer = WikipediaSanitizer()

			"invoke" should {

				"clean en.wikipedia.org URLs" {
					sanitizer("https://en.wikipedia.org/wiki/Kerosene?wprov=sfla1") shouldBe
						"https://en.wikipedia.org/wiki/Kerosene"
				}
			}

			"matchesDomain" should {

				"match wikipedia.org" {
					sanitizer.matchesDomain("https://wikipedia.org") shouldBe true
				}

				"match en.wikipedia.org" {
					sanitizer.matchesDomain("https://en.wikipedia.org") shouldBe true
				}

				"match m.en.wikipedia.org" {
					sanitizer.matchesDomain("https://de.m.wikipedia.org") shouldBe true
				}

				"don't match google.com" {
					sanitizer.matchesDomain("https://google.com") shouldBe false
				}
			}
		},
	)
/*
 * Léon - The URL


/**
 * Copyright 2015, SRI International.
 *
 * This file is part of LibPoly.
 *
 * LibPoly is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LibPoly is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with LibPoly.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <value.h>

void lp_value_approx(const lp_value_t* v, lp_rational_interval_t* approx);

/**
 * Case v1 and v2 to the same type.
 *
 * @param v1, v2 the values to case
 * @param v1_tmp the value to use for allocating a new value
 * @param v1_to_use, v2_to_use the cast values to use
 */
int lp_value_to_same_type(const lp_value_t* v1, const lp_value_t* v2,
    lp_value_t* v1_new, lp_value_t* v2_new,
    const lp_value_t** v1_to_use, const lp_value_t** v2_to_use);


1,
        )
        progress.stop()

def check_apps_responsive(apps):
    for app_name, instances in apps:
        if app_name == "default":
            continue
        console.print(f"[rule.line]{app_name}:[/]")

        max_name_len = max(*[len(key) for key in instances.keys() if key != "local"])
        statuses = []
        async_tasks = []

        for instance_name, instance_url in instances.items():
            if instance_name == "local":
                continue
            status = progress.Progress(
                progress.TextColumn("[rule.line]│[/]"),
                progress.SpinnerColumn(finished_text=""),
                progress.TextColumn("{task.description}"),
                console=console,
            )
            statuses.append(status)
            async_tasks.append(
                check_api(instance_name, instance_url, max_name_len, status)
            )

        overall = progress.Progress(
            progress.TextColumn("[rule.line]└[/]"),
            progress.SpinnerColumn(finished_text=""),
            progress.TextColumn("{task.description}"),
            console=console,
            transient=True,
        )

        group = Group(*statuses, overall)
        live = Live(group)
        with live:
            task = overall.add_task("Checking instances...", total=1)
            loop = asyncio.get_event_loop()
            result = loop.run_until_complete(asyncio.gather(*async_tasks))
            overall.update(task, completed=1, visible=False)

            passed = len([res for res in result if res])
            report = f"[rule.line]└[/] {passed}/{len(result)} Responding"
            if passed == len(result):
                report = "[rule.line]└[/] [green]✓ All Green![/]"
        console.print(report, highlight=False)


    circleReplay.setFillStrokeStyle(fillStyle, strokeStyle);
    circleReplay.drawCircle(geometry, feature);
  }
  var textStyle = style.getText();
  if (textStyle) {
    var textReplay = replayGroup.getReplay(
        style.getZIndex(), ol.render.ReplayType.TEXT);
    textReplay.setTextStyle(textStyle);
    textReplay.drawText(geometry.getCenter(), 0, 2, 2, geometry, feature);
  }
};

/**
 * @param {ol.render.ReplayGroup} replayGroup Replay group.
 * @param {ol.Feature|ol.render.Feature} feature Feature.
 * @param {ol.style.Style} style Style.
 * @param {number} squaredTolerance Squared tolerance.
 * @param {function(this: T, ol.events.Event)} listener Listener function.
 * @param {T} thisArg Value to use as `this` when executing `listener`.
 * @return {boolean} `true` if style is loading.
 * @template T
 */
ol.renderer.vector.renderFeature = function(
    replayGroup, feature, style, squaredTolerance, listener, thisArg) {
  var loading = false;
  var imageStyle, imageState;
  imageStyle = style.getImage();
  if (imageStyle) {
    imageState = imageStyle.getImageState();
    if (imageState == ol.ImageState.LOADED ||
        imageState == ol.ImageState.ERROR) {
      imageStyle.unlistenImageChange(listener, thisArg);
    } else {
      if (imageState == ol.ImageState.IDLE) {
        imageStyle.load();
      }
      imageState = imageStyle.getImageState();
      imageStyle.listenImageChange(listener, thisArg);
      loading = true;
    }
  }
  ol.renderer.vector.renderFeature_(replayGroup, feature, style,
      squaredTolerance);
  return loading;
};

/**
 * @param {ol.render.ReplayGroup} replayGroup Replay group.
 * @param {ol.Feature|ol.render.Feature} feature Feature.
 * @param {ol.style.Style} style Style.
 * @param {number} squaredTolerance Squared tolerance.
 * @private
 */
ol.renderer.vector.renderFeature_ = function(
    replayGroup, feature, style, squaredTolerance) {
  var geometry = style.getGeometryFunction()(feature);
  if (!geometry) {
    return;
  }
  var simplifiedGeometry = geometry.getSimplifiedGeometry(squaredTolerance);
  var renderer = style.getRenderer();
  if (renderer) {
    ol.renderer.vector.renderGeometry_(replayGroup, simplifiedGeometry, style, feature);
  } else {
    var geometryRenderer =
        ol.renderer.vector.GEOMETRY_RENDERERS_[simplifiedGeometry.getType()];
    geometryRenderer(replayGroup, simplifiedGeometry, style, feature);
  }
};

/**
 * @param {ol.render.ReplayGroup} replayGroup Replay group.
 * @param {ol.geom.Geometry} geometry Geometry.
 * @param {ol.style.Style} style Style.
 * @param {ol.Feature|ol.render.Feature} feature Feature.
 * @private
 */
ol.renderer.vector.renderGeometry_ = function(replayGroup, geometry, style, feature) {
  if (geometry.getType() == ol.geom.GeometryType.GEOMETRY_COLLECTION) {
    var geometries = /** @type {ol.geom.GeometryCollection} */ (geometry).getGeometries();
    for (var i = 0, ii = geometries.length; i < ii; ++i) {
      ol.renderer.vector.renderGeometry_(replayGroup, geometries[i], style, feature);
    }
    return;
  }
  var replay = replayGroup.getReplay(style.getZIndex(), ol.render.ReplayType.DEFAULT);
  replay.drawCustom(/** @type {ol.geom.SimpleGeomet


+"-"+d0)}function k2(J0,d0){var o2=(d0?d0.id+".":"")+J0.key;J0.id=o2}function I2(J0){C0[J0.id]=J0}function y2(J0,d0){t0&&J0.id in T0&&(d0.tag=="polygon"||d0.tag=="ellipse"||d0.tag=="path")&&(d0.tag!=J0.tag||J0.tag=="polygon")&&(d0.tag!="path"&&(J0.alternativeOld=SG(d0,J0)),J0.tag!="path"&&(J0.alternativeNew=SG(J0,d0)))}function B2(J0,d0){if(T&&d0&&(d0.tag=="path"||J0.alternativeOld&&J0.alternativeOld.tag=="path")){var o2=(J0.alternativeNew||J0).attributes.d;if(J0.alternativeOld)var E2=mk(J0.alternativeOld);else var E2=mk(d0);(J0.alternativeOld||(J0.alternativeOld={})).points=dw0(E2,o2,l0,g0)}}function Q1(J0,d0=0,o2){m2(J0,d0),k2(J0,o2);var E2=J0.id,i1=T0[E2];I2(J0),y2(J0,i1),B2(J0,i1);var $2={};J0.children.forEach(function(E1){var L1=E1.tag;(L1=="ellipse"||L1=="polygon")&&(L1="path"),$2[L1]==null&&($2[L1]=0);var bA=$2[L1]++;Q1(E1,bA,J0)})}function t1(J0){var d0=J0.tag;if(G0&&J0.parent&&J0.parent.attributes.class=="node"&&d0=="title"){if(J0.children.length>0)var o2=J0.children[0],E2=o2.text;else var E2="";M0[E2]=J0.parent}}function he(J0){var d0=J0.id,o2=J0.tag,E2=T0[d0];if(G0&&!E2&&J0.parent&&zQ(J0)&&(o2=="path"||o2=="polygon")){if(o2=="polygon"){var i1=J0.parent.children.find(function(Ue){return Ue.tag=="path"});J0.totalLength=i1.totalLength}var $2=eh0(J0),E1=$2.children[0],L1=E1.text.split("->");L1.length!=2&&(L1=E1.text.split("--"));var bA=L1[0],Y1=M0[bA],gA=e2[bA];if(gA){var M1=Y1.children.findIndex(function(Ue,N2){return Ue.tag=="g"});if(M1>=0){var GA=Y1.children[M1].children.findIndex(function(Ue,N2){return Ue.tag=="a"});Y1=Y1.children[M1].children[GA]}var M1=gA.children.findIndex(function(Ue,N2){return Ue.tag=="g"});if(M1>=0){var GA=gA.children[M1].children.findIndex(function(N2,On){return N2.tag=="a"});gA=gA.children[M1].children[GA]}for(var Ae=Y1.children,M1=0;M1<Ae.length;M1++)if(Ae[M1].tag=="polygon"||Ae[M1].tag=="ellipse"||Ae[M1].tag=="path"||Ae[M1].tag=="text"){var HA=Ae[M1];break}for(var K1=gA.children,M1=0;M1<K1.length;M1++)if(K1[M1].tag=="polygon"||K1[M1].tag=="ell


{
            entity.HasKey(e => e.GroupId)
                .HasName("groups_blacklist_pk");

            entity.ToTable("groups_blacklist");

            entity.HasIndex(e => e.GroupId)
                .HasDatabaseName("groups_blacklist_group_id_uindex")
                .IsUnique();

            entity.Property(e => e.GroupId)
                .HasColumnName("group_id")
                .ValueGeneratedNever();

            entity.Property(e => e.AddedAt)
                .HasColumnName("added_at")
                .HasColumnType("timestamp with time zone")
                .HasDefaultValueSql("timezone('utc'::text, now())");

            entity.HasOne(d => d.Group)
                .WithOne(p => p.GroupBlacklist)
                .HasForeignKey<GroupBlacklist>(d => d.GroupId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("groups_blacklist_groups_group_id_fk");
        });

        modelBuilder.Entity<User>(entity =>
        {
            entity.HasKey(e => e.UserId)
                .HasName("users_pkey");

            entity.ToTable("users");

            entity.Property(e => e.UserId)
                .HasColumnName("user_id")
                .ValueGeneratedNever();

            entity.Property(e => e.PmAllowed).HasColumnName("pm_allowed");

            entity.Property(e => e.Track).HasColumnName("track");
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}


<I>, curr:char) -> usize where I:Iterator<Item=(usize, char)> {
    let mut amount = 1;
    while code.peek().map(|v| v.1) == Some(curr) {
        amount += 1;
        code.next();
    }
    amount
}

/// Generate the IR for the brainfuck code `code` into the function `func`.
fn generate(func: &UncompiledFunction, code_text: &str) {
    // get the LibJIT equivalents of essential types.
    let cell_t = get::<Cell>();
    let cell_size = mem::size_of::<Cell>();
    let mut data = func.insn_dup(&func[0]);
    let mut current_loop = None;
    let mut code = code_text.chars().enumerate().peekable();
    extern fn put_char(c: Cell) -> () {
        let mut stdout = io::stdout();
        stdout.write_all(&[c]).unwrap();
        if c == b'\n' || c == b'\r' {
            stdout.flush().unwrap();
        }
    };
    extern fn get_char(_: ()) -> Cell {
        let next = io::stdin().bytes().next().unwrap();
        next.unwrap_or(0)
    }
    while let Some((offset, c)) = code.next() {
        match c {
            '>' => {
                let amount = count(&mut code, c);
                data += cell_size * amount;
            },
            '<' => {
                let amount = count(&mut code, c);
                data -= cell_size * amount;
            },
            '+' => {
                let amount = count(&mut code, c);
                let mut value = func.insn_load_relative(data, 0, &cell_t);
                value += cell_size * amount;
                value = func.insn_convert(value, &cell_t, false);
                func.insn_store_relative(data, 0, value)
            },
            '-' => {
                let amount = count(&mut code, c);
                let mut value = func.insn_load_relative(data, 0, &cell_t);
                value -= cell_size * amount;
                value = func.insn_convert(value, &cell_t, false);
                func.insn_store_relative(data, 0, value)
            },
            '.' => {
                let value = func.insn_load_relative(data, 0, &cell_t);
                func.insn_call_rust(Some("putchar"), put_char, &[value], CallFlags::NO_THROW);
            },
            ',' => {
                let value = func.insn_call_rust(Some("getchar"), get_char, &[], CallFlags::NO_THROW);
                func.insn_store_relative(data, 0, value);
            },
            '[' => {
                let wrapped_loop = Rc::new(RefCell::new(Loop::new(func, current_loop)));
                let tmp = func.insn_load_relative(data, 0, &cell_t);
                {
                    let mut borrow = wrapped_loop.borrow_mut();
                    func.insn_branch_if_not(tmp, &mut borrow.end);
                }
                current_loop = Some(wrapped_loop);
            },
            ']' => {
                current_loop = if let Some(ref inner_loop) = current_loop {
                    let mut borrow = inner_loop.borrow_mut();
                    borrow.end(func)
                } else {
                    println!("unmatched ] at offset {}", offset);
                    None
                }
            },
            _ => ()
        }
    };
    if current_loop.is_some() {
        panic!("unmatched [ at offset {}", code_text.len());
    }
    func.insn_default_return();
}
/// Run the brainfuck co


right: 3
suggestions
  dart:
    kind: import
  dart:async
    kind: import
  dart:async2
    kind: import
  dart:collection
    kind: import
  dart:convert
    kind: import
  dart:ffi
    kind: import
  dart:html
    kind: import
  dart:io
    kind: import
  dart:isolate
    kind: import
  dart:js
    kind: import
  dart:js_interop
    kind: import
  dart:math
    kind: import
  dart:typed_data
    kind: import
  package:
    kind: import
  package:test/
    kind: import
  package:test/test.dart
    kind: import
  dart:core
    kind: import
''');
  }

  @failingTest
  Future<void> test_018_1() async {
    await computeSuggestions('''
^part of foo;
''');
    assertResponse(r'''
replacement
  right: 4
suggestions
  part
    kind: keyword
''');
  }

  @failingTest
  Future<void> test_018_2() async {
    await computeSuggestions('''
part ^of foo;
''');
    assertResponse(r'''
replacement
  right: 2
suggestions
  of
    kind: keyword
''');
  }

  Future<void> test_019_1() async {
    allowedIdentifiers = {'true', 'truefalse', 'falsetrue'};
    await computeSuggestions('''
var truefalse = 0;
var falsetrue = 1;
void f() {
  var foo = true^
}
''');
    assertResponse(r'''
replacement
  left: 4
suggestions
  true
    kind: keyword
  falsetrue
    kind: topLevelVariable
  truefalse
    kind: topLevelVariable
''');
  }

  Future<void> test_020_1() async {
    allowedIdentifiers = {'toString'};
    await computeSuggestions('''
var x = null.^
''');
    assertResponse(r'''
suggestions
  toString
    kind: methodInvocation
''');
  }

  Future<void> test_021_1() async {
    allowedIdentifiers = {'toString'};
    await computeSuggestions('''
var x = .^
''');
    assertResponse(r'''
suggestions
''');
  }

  Future<void> test_022_1() async {
    allowedIdentifiers = {'toString'};
    await computeSuggestions('''
var x = .^;
''');
    assertResponse(r'''
suggestions
''');
  }

  Future<void> test_023_1() async {
    allowedIdentifiers = {'getKeys'};
    await computeSuggestions('''
class Map{getKeys(){}}
class X {
  static x1(Map m) {
    m.^getKeys;
  }
  x2(Map m) {
    m.getKeys;
  }
}
''');
    assertResponse(r'''
replacement
  right: 7
suggestions
  getKeys
    kind: methodInvocation
''');
  }

  Future<void> test_023_2() async {
    allowedIdentifiers = {'getKeys'};
    await computeSuggestions('''
class Map{getKeys(){}}
class X {
  static x1(Map m) {
    m.getKeys;
  }
  x2(Map m) {
    m.^getKeys;
  }
}
''');
    assertResponse(r'''
replacement
  right: 7
suggestions
  getKeys
    kind: methodInvocation
''');
  }

  Future<void> test_024_1(


    #[inline(always)]
    pub fn variant(&self) -> MUX_CSX0_A {
        match self.bits {
            0 => MUX_CSX0_A::MUX_CSX0_0,
            1 => MUX_CSX0_A::MUX_CSX0_1,
            2 => MUX_CSX0_A::MUX_CSX0_2,
            3 => MUX_CSX0_A::MUX_CSX0_3,
            4 => MUX_CSX0_A::MUX_CSX0_4,
            5 => MUX_CSX0_A::MUX_CSX0_5,
            6 => MUX_CSX0_A::MUX_CSX0_6,
            7 => MUX_CSX0_A::MUX_CSX0_7,
            _ => unreachable!(),
        }
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_0`"]
    #[inline(always)]
    pub fn is_mux_csx0_0(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_0
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_1`"]
    #[inline(always)]
    pub fn is_mux_csx0_1(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_1
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_2`"]
    #[inline(always)]
    pub fn is_mux_csx0_2(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_2
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_3`"]
    #[inline(always)]
    pub fn is_mux_csx0_3(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_3
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_4`"]
    #[inline(always)]
    pub fn is_mux_csx0_4(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_4
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_5`"]
    #[inline(always)]
    pub fn is_mux_csx0_5(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_5
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_6`"]
    #[inline(always)]
    pub fn is_mux_csx0_6(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_6
    }
    #[doc = "Checks if the value of the field is `MUX_CSX0_7`"]
    #[inline(always)]
    pub fn is_mux_csx0_7(&self) -> bool {
        *self == MUX_CSX0_A::MUX_CSX0_7
    }
}
#[doc = "Write proxy for field `MUX_CSX0`"]
pub struct MUX_CSX0_W<'a> {
    w: &'a mut W,
}
impl<'a> MUX_CSX0_W<'a> {
    #[doc = r"Writes `variant` to the field"]
    #[inline(always)]
    pub fn variant(self, variant: MUX_CSX0_A) -> &'a mut W {


e.requested = Some(xyhw);
    Some(change)
}

fn update_title(xw: &XWrap, window: xlib::Window) -> DisplayEvent {
    let title = xw.get_window_name(window);
    let handle = WindowHandle::XlibHandle(window);
    let mut change = WindowChange::new(handle);
    change.name = Some(title);
    DisplayEvent::WindowChange(change)
}
pub mod entity;
pub mod scene;

use nalgebra;
use self::entity::Entity;
use self::scene::{SceneManager, Transform};
<filename>src/inventory_menu/quest.rs
use super::{inv_menu_state, InventoryMenu};
use core::fmt::Write;
use libtww::game::Console;
use libtww::link::item::*;
use libtww::link::quest_items::*;
use libtww::link::song;
use libtww::Link;
/////

// TODO: Power Bracelet

/////
use crate::controller;
use crate::utils::*;

static mut cursor: usize = 0;
static mut scroll_offset: usize = 0;

pub fn transition_into() {}

const MENU_ITEM_SWORD: usize = 0;
const MENU_ITEM_SHIELD: usize = 1;
const MENU_ITEM_PIRATES_CHARM: usize = 2;
const MENU_ITEM_POWER_BRACELETS: usize = 3;
const MENU_ITEM_HEROS_CHARM: usize = 4;
const MENU_ITEM_WINDS_REQUIEM: usize = 5;
const MENU_ITEM_BALLAD_OF_GALES: usize = 6;
const MENU_ITEM_COMMAND_MELODY: usize = 7;
const MENU_ITEM_EARTH_GODS_LYRIC: usize = 8;
const MENU_ITEM_WIND_GODS_ARIA: usize = 9;
const MENU_ITEM_SONG_OF_PASSING: usize = 10;
const MENU_ITEM_SPACE_0: usize = 11;
const MENU_ITEM_PROGRESSION: usize = 12;

const ITEMS: [&str; 13] = [
    "Sword            ",
    "Shield           ",
    "Pirates's Charm  ",
    "Power Bracelets  ",
    "Hero's Charm     ",
    "Wind's Requiem   ",
    "Ballad of Gales  ",
    "Command Melody   ",
    "Earth God's Lyric",
    "Wind God's Aria  ",
    "Song of Passing  ",
    "",
    "Progression Items",
];

// Bomb Bag
// Quiver
// Wallet Upgrade

fn handle_item_switch() {
    let link = Link::get();
    let quest_items = QuestItems::get();
    let dpad_left = controller::DPAD_LEFT.is_pressed();
    let dpad_right = controller::DPAD_RIGHT.is_pressed();
    let index = unsafe { cursor };
    if dpad_left {
        match index {
            MENU_ITEM_SWORD => match quest_items.sword {
                Sword::None => link.set_sword(Sword::FullyChargedMasterSword),
                Sword::HerosSword => link.set_sword(Sword::None),
                Sword::UnchargedMasterSword => link.set_sword(Sword::HerosSword),
                Sword::HalfChargedMasterSword => link.set_sword(Sword::UnchargedMasterSword),
                Sword::FullyChargedMasterSword => link.set_sword(Sword::HalfChargedMasterSword),
            },
            MENU_ITEM_SHIELD => match quest_items.shield {
                Shield::None => link.set_shield(Shield::MirrorShield),
                Shield::HerosShield => link.set_shield(Shield::None),
                Shield::MirrorShield => link.set_shield(Shield::HerosShield),
            },
            MENU_ITEM_HEROS_CHARM => {
                quest_items.heros_charm = match quest_items.heros_charm {
                    HerosCharm::None


}
    elems.push_back(wbTimerNode_toJSONObject(iter));
  }
  return json11::Json(elems);
}

string wbTimer_toJSON(wbTimer_t timer) {
  if (timer == nullptr) {
    return "";
  } else if (WB_USE_JSON11) {
    json11::Json json = wbTimer_toJSONObject(timer);
    return json.string_value();
  } else {
    stringstream ss;
    wbTimerNode_t iter;
    uint64_t currentTime;

    currentTime = getTime();

    wbTimer_setEndTime(timer, currentTime);
    wbTimer_setElapsedTime(timer,
                           currentTime - wbTimer_getStartTime(timer));

    for (iter = wbTimer_getHead(timer); iter != nullptr;
         iter = wbTimerNode_getNext(iter)) {
      if (!wbTimerNode_stoppedQ(iter)) {
        wbTimerNode_setEndTime(iter, currentTime);
        wbTimerNode_setElapsedTime(
            iter, currentTime - wbTimerNode_getStartTime(iter));
      }
      ss << wbTimerNode_toJSON(iter);
      if (wbTimerNode_getNext(iter) != nullptr) {
        ss << ",\n";
      }
    }

    return ss.str();
  }
}

string wbTimer_toJSON() {
  return wbTimer_toJSON(_timer);
}

string wbTimer_toXML(wbTimer_t timer) {
  if (timer == nullptr) {
    return "";
  } else {
    stringstream ss;
    wbTimerNode_t iter;
    uint64_t currentTime;

    currentTime = getTime();

    wbTimer_setEndTime(timer, currentTime);
    wbTimer_setElapsedTime(timer,
                           currentTime - wbTimer_getStartTime(timer));

    ss << "<timer>\n";
    ss << "<start_time>" << wbTimer_getStartTime(timer)
       << "</start_time>\n";
    ss << "<end_time>" << wbTimer_getEndTime(timer) << "</end_time>\n";
    ss << "<elapsed_time>" << wbTimer_getElapsedTime(timer)
       << "</elapsed_time>\n";
    ss << "<elements>\n";
    for (iter = wbTimer_getHead(timer); iter != nullptr;
         iter = wbTimerNode_getNext(iter)) {
      if (!wbTimerNode_stoppedQ(iter)) {
        wbTimerNode_setEndTime(iter, currentTime);
        wbTimerNode_setElapsedTime(
            iter, currentTime - wbTimerNode_getStartTime(iter));
      }
      ss << wbTimerNode_toXML(iter);
    }
    ss << "</elements>\n";
    ss << "</timer>\n";

    return ss.str();
  }
}

string wbTimer_toXML() {
  return wbTimer_toXML(_timer);
}

wbTimer_t wbTimer_new(void) {
  wbTimer_t timer = wbNew(struct st_wbTimer_t);
  wbTimer_setId(timer, uuid());
  wbTimer_setSessionId(timer, sessionId());
  wbTimer_setLength(timer, 0);
  wbTimer_setHead(timer, NULL);
  wbTimer_setTail(timer, NULL);
  wbTimer_setStartTime(timer, getTime());
  wbTimer_setEndTime(timer, 0);
  wbTimer_setElapsedTime(timer, 0);

  return timer;
}

static inline wbTimerNode_t _findParent(wbTimer_t timer) {
  wbTimerNode_t iter;

  for (iter = wbTimer_getTail(timer); iter != nullptr;
       iter = wbTimerNode_getPrevious(iter)) {
    if (!wbTimerNode_stoppedQ(iter)) {
      return iter;
    }
  }
  return NULL;
}

static inline void _insertIntoList(wbTimer_


 = this.hourTo;
      json[r'time'] = this.time;
      json[r'status'] = this.status;
      json[r'statusLong'] = this.statusLong;
    if (this.comment != null) {
      json[r'comment'] = this.comment;
    } else {
      json[r'comment'] = null;
    }
      json[r'isExamLesson'] = this.isExamLesson;
      json[r'profile'] = this.profile;
      json[r'course'] = this.course;
      json[r'courseId'] = this.courseId;
      json[r'absenceId'] = this.absenceId;
      json[r'absenceSemester'] = this.absenceSemester;
    if (this.trainerAcknowledgement != null) {
      json[r'trainerAcknowledgement'] = this.trainerAcknowledgement;
    } else {
      json[r'trainerAcknowledgement'] = null;
    }
    if (this.trainerComment != null) {
      json[r'trainerComment'] = this.trainerComment;
    } else {
      json[r'trainerComment'] = null;
    }
    if (this.trainerCommentTimestamp != null) {
      json[r'trainerCommentTimestamp'] = this.trainerCommentTimestamp;
    } else {
      json[r'trainerCommentTimestamp'] = null;
    }
    return json;
  }

  /// Returns a new [AbsenceNoticeDto] instance and imports its values from
  /// [value] if it's a [Map], null otherwise.
  // ignore: prefer_constructors_over_static_methods
  static AbsenceNoticeDto? fromJson(dynamic value) {
    if (value is Map) {
      final json = value.cast<String, dynamic>();

      // Ensure that the map contains the required keys.
      // Note 1: the values aren't checked for validity beyond being non-null.
      // Note 2: this code is stripped in release mode!
      assert(() {
        requiredKeys.forEach((key) {
          assert(json.containsKey(key), 'Required key "AbsenceNoticeDto[$key]" is missing from JSON.');
          assert(json[key] != null, 'Required key "AbsenceNoticeDto[$key]" has a null value in JSON.');
        });
        return true;
      }());

      return AbsenceNoticeDto(
        id: mapValueOfType<String>(json, r'id')!,
        studentId: mapValueOfType<String>(json, r'studentId')!,
        studentReason: mapValueOfType<String>(json, r'studentReason'),
        studentReasonTimestamp: mapValueOfType<String>(json, r'studentReasonTimestamp'),
        studentIs18: mapValueOfType<bool>(json, r'studentIs18')!,
        date: mapValueOfType<String>(json, r'date')!,
        hourFrom: mapValueOfType<String>(json, r'hourFrom')!,
        hourTo: mapValueOfType<String>(json, r'hourTo')!,
        time: mapValueOfType<String>(json, r'time')!,
        status: mapValueOfType<String>(json, r'status')!,
        statusLong: mapValueOfType<String>(json, r'statusLong')!,
        comment: mapValueOfType<String>(json, r'comment'),
        isExamLesson: mapValueOfType<bool>(json, r'isExamLesson')!,
        profile: mapValueOfType<String>(json, r'profile')!,
        course: mapValueOfType<String>(json, r'course')!,
        courseId: mapValueOfType<String>(json, r'courseId')!,
        absenceId: mapValueOfType<String>(json, r'absenceId')!,
        absenceSemester: mapValueOfType<int>(json, r'absenceSemester')!,
        trainerAcknowledgement: mapValueOfType<String>(json, r'trainerAcknowledgement'),
        trainerComment


-- Global to each starfall
local checkluatype = SF.CheckLuaType
local registerprivilege = SF.Permissions.registerPrivilege

-- Register privileges
registerprivilege("light.create", "Create dynamic lights.", "Allows creation of dynamic lights.", { client = {} })

local maxSize = CreateClientConVar( "sf_light_maxsize", "1024", true, false, "Max size lights can be" )

SF.ResourceCounters.Lights = {icon = "icon16/lightbulb.png", count = function(ply)
	local total = 0
	for instance in pairs(SF.playerInstances[ply]) do
		total = total + table.Count(instance.data.light.lights)
	end
	return total
end}

local gSFLights = {}
local gGmodLights = {}
local gGmodWireLights = {}

local function getFreeSlot()
	for i=1, 65536 do
		if not gSFLights[i] and not gGmodLights[i] and not gGmodWireLights[i] then
			return i
		end
	end
end

local lightTable = {
	gmod_light = gGmodLights,
	gmod_wire_light = gGmodWireLights
}

hook.Add("NetworkEntityCreated","SF_TrackLights",function(e)
	local index = e:EntIndex()
	local ltable = lightTable[e:GetClass()]
	if ltable and not ltable[index] then
		local sfLight = gSFLights[index]
		if sfLight then
			sfLight.slot = getFreeSlot()
			if sfLight.slot then
				gSFLights[sfLight.slot] = sfLight
			end
			gSFLights[index] = nil
		end
		ltable[index] = e
	end
end)

local ENT_META = FindMetaTable("Entity")
local Ent_EntIndex = ENT_META.EntIndex
hook.Add("EntityRemoved","SF_TrackLights",function(e)
	local index = Ent_EntIndex(e)
	gGmodLights[index] = nil
	gGmodWireLights[index] = nil
end)

local lastProcess
local lightsUsed = 0
local function processLights(curtime)
	if lastProcess == curtime then return end
	lastProcess = curtime
	lightsUsed = 0
	for k, v in pairs(gGmodLights) do
		if v:GetOn() then lightsUsed = lightsUsed + 1 end
	end
	for k, v in pairs(gGmodWireLights) do
		if v:GetGlow() then lightsUsed = lightsUsed + 1 end
	end
end

local projectedLights = SF.EntManager("projectedlights", "projected lights", 20, "The number of projected light objects allowed to spawn via Starfall", 1, true)

--- Light library.
-- @name light
-- @class library
-- @libtbl light_library
SF.RegisterLibrary("light")

--- Light type
-- @name Light
-- @class type
-- @libtbl light_methods
SF.RegisterType("Light", true, false)

--- Projected Texture type
-- @name ProjectedTexture
-- @class type
-- @libtbl projectedtexture_methods
SF.RegisterType("ProjectedTexture", true, false)

return function(instance)
local checkpermission = instance.player ~= SF.Superuser and SF.Permissions.check or function() end

local light_library = instance.Libraries.light
local light_methods, light_meta, wrap, unwrap = instance.Types.Light.Methods, instance.Types.Light, instance.Types.Light.Wrap, instance.Types.Light.Unwrap
local projectedtexture_methods, projectedtexture_meta, ptwrap, ptunwrap = instance.Types.ProjectedTexture.Methods, instance.Types.ProjectedTexture, instance.Types.ProjectedTexture.Wrap, instance.Types.ProjectedTexture.Unwrap
local vec_meta, vwrap, vunwrap = instance.Types.Vector, instance.Types.Vector.Wrap, instance.Types.Vector.Unwrap
local ang_meta, awrap, aunwrap = instance.Types.Angle, instance.Types.Angle.Wrap


              Err(anyhow::anyhow!("Wrong server addr: {:?}", ip_hdr))?;
                    }
                    if ip_hdr.protocol != Ipv4Protocol2::Udp {
                        Err(anyhow::anyhow!("Wrong protocol: {:?}", ip_hdr))?;
                    }

                    let (_udp_hdr, pkt) = UdpHeader::parse(&ip_hdr, pkt, config.udp_checksum_offload)?;
                    let num_bytes = pkt.len();
                    must_let::must_let!(let DPDKBuf::Managed(mbuf) = pkt);

                    let eth_hdr = Ethernet2Header {
                        dst_addr: dst_phy_addr,
                        src_addr: src_phy_addr,
                        ether_type: EtherType2::Ipv4,
                    };
                    let ip_hdr = Ipv4Header::new(endpoint.addr, client_addr.addr, Ipv4Protocol2::Udp);
                    let udp_hdr = UdpHeader {
                        src_port: Some(endpoint.port),
                        dst_port: client_addr.port,
                    };

                    let mut mbuf_ptr = mbuf.into_raw();
                    unsafe {
                        assert!((*mbuf_ptr).data_off as usize >= HEADER_SIZE);
                        (*mbuf_ptr).data_off -= HEADER_SIZE as u16;
                        (*mbuf_ptr).data_len += HEADER_SIZE as u16;
                        (*mbuf_ptr).pkt_len += HEADER_SIZE as u32;

                        let buf_ptr = (*mbuf_ptr).buf_addr as *mut u8;
                        let data_ptr = buf_ptr.offset((*mbuf_ptr).data_off as isize);
                        let hdr_slice = slice::from_raw_parts_mut(data_ptr, (*mbuf_ptr).data_len as usize);

                        let body_ptr = data_ptr.offset(HEADER_SIZE as isize);
                        let body_slice = slice::from_raw_parts(body_ptr, num_bytes);

                        serialize(&config, hdr_slice, &eth_hdr, &ip_hdr, &udp_hdr, body_slice);

                        let num_sent = dpdk_rs::rte_eth_tx_burst(runtime.port_id(), 0, &mut mbuf_ptr, 1);
                        assert_eq!(num_sent, 1);
                    }

                    num_received += num_bytes;
                };
                if let Err(e) = r {
                    println!("Failed to process packet: {:?}", e);
                }
            }
            assert_eq!(num_received, config.buffer_size);
            stats.report_bytes(num_received);
        })
    }
    else if env::var("ECHO_CLIENT").is_ok() {
        let connect_addr = config.addr("client", "connect_to")?;
        let client_addr = config.addr("client", "client")?;

        let num_bufs = (config.buffer_size - 1) / config.mss + 1;
        let mut bufs = Vec::with_capacity(num_bufs);

        // First, setup our outgoing packets, which will be the same every round.
        for i in 0..num_bufs {
            let start = i * config.mss;
            let end = std::cmp::min(start + config.mss, config.buffer_size);
            let len = end - start;

            let eth_hdr = Ethernet2Header {
                dst_addr: dst_phy_addr,
                src_addr: src_phy_addr,
                ether_type: EtherType2::Ipv4,
            };
            let ip_hdr


er8x8Tile_Mask_FlipY(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							}
						} else {
							if (!flipy) {
								Render8x8Tile_Mask_FlipX(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							} else {
								Render8x8Tile_Mask_FlipXY(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							}
						}
					} else {
						if (!flipx) {
							if (!flipy) {
								Render8x8Tile_Mask_Clip(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							} else {
								Render8x8Tile_Mask_FlipY_Clip(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							}
						} else {
							if (!flipy) {
								Render8x8Tile_Mask_FlipX_Clip(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							} else {
								Render8x8Tile_Mask_FlipXY_Clip(pBitmap[2], code + layout[y][x], sx, sy, color, 4, 0, 0, FstarfrcSpriteTiles);
							}
						}
					}
				}
			}
		}
	}
}

inline static UINT32 CalcCol(UINT16 nColour)
{
	INT32 r, g, b;

	r = (nColour >> 0) & 0x0f;
	g = (nColour >> 4) & 0x0f;
	b = (nColour >> 8) & 0x0f;

	r = (r << 4) | r;
	g = (g << 4) | g;
	b = (b << 4) | b;

	return BurnHighCol(r,g,b,0);
}

static INT32 FstarfrcCalcPalette()
{
	INT32 i;
	UINT16* ps;
	UINT32* pd;

	for (i = 0, ps = (UINT16*)FstarfrcPaletteRam, pd = FstarfrcPalette; i < 0x2000; i++, ps++, pd++) {
		*pd = CalcCol(BURN_ENDIAN_SWAP_INT16(*ps));
	}

	return 0;
}

static void FstarfrcRenderMixBitmaps()
{
	const UINT32 *paldata = FstarfrcPalette;
	const UINT32 *palblnd = FstarfrcPalette + 0x400;

	for (INT32 y = 0; y < nScreenHeight; y++)
	{
		UINT16 *tx = pBitmap[3] + y * nScreenWidth;
		UINT16 *sp = pBitmap[2] + y * nScreenWidth;
		UINT16 *fg = pBitmap[1] + y * nScreenWidth;
		UINT16 *bg = pBitmap[0] + y * nScreenWidth;

		UINT8 *dst = pBurnDraw + (y * nScreenWidth) * nBurnBpp;

		for (INT32 x = 0; x < nScreenWidth; x++, dst += nBurnBpp)
		{
			UINT16 sprpixel = sp[x];
			UINT16 m_sprpri = (sprpixel >> 10) & 3;
			UINT16 m_sprbln = (sprpixel >> 9) & 1;

			sprpixel = sprpixel & 0xff;
			sp[x] = 0;