using Grand.Core.Caching;
using Grand.Domain.Data;
using Grand.Domain.Customers;
using Grand.Core.Tests.Caching;
using Grand.Services.Events;
using Grand.Services.Tests;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Grand.Services.Customers.Tests
{
    [TestClass()]
    public class CustomerActionServiceTests
    {
        private IRepository<CustomerAction> _customerActionRepository;
        private IRepository<CustomerActionType> _customerActionTypeRepository;
        private IRepository<CustomerActionHistory> _customerActionHistoryRepository;
        private IMediator _eventPublisher;
        private ICustomerActionService _customerActionService;
        private string _Id_CustomerAction;
        private string _Id_CustomerActionType;

        [TestInitialize()]
        public void TestInitialize()
        {
            var eventPublisher = new Mock<IMediator>();
            _eventPublisher = eventPublisher.Object;

            _customerActionRepository = new MongoDBRepositoryTest<CustomerAction>();
            _customerActionTypeRepository = new MongoDBRepositoryTest<CustomerActionType>();
            _customerActionHistoryRepository = new MongoDBRepositoryTest<CustomerActionHistory>();

            _Id_CustomerActionType = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
            var customerActionType = new List<CustomerActionType>()
            {
                new CustomerActionType()
                {
                    Id = _Id_CustomerActionType,
                    Name = "Add to cart",
                    SystemKeyword = "AddToCart",
                    Enabled = true,
                    ConditionType = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
                },
                new CustomerActionType()
                {
                    Name = "Add order",
                    SystemKeyword = "AddOrder",
                    Enabled = true,
                    ConditionType = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
                },
                new CustomerActionType()
                {
                    Name = "Viewed",
                    SystemKeyword = "Viewed",
                    Enabled = false,
                    ConditionType = {1, 2, 3, 7, 8, 9, 10}
                },
                new CustomerActionType()
                {
                    Name = "Url",
                    SystemKeyword = "Url",
                    Enabled = false,
                    ConditionType = {7, 8, 9, 10, 11, 12}
                },
                new CustomerActionType()
                {
                    Name = "Customer Registration",
                    SystemKeyword = "Registration",
                    Enabled = false,
                    ConditionType = {7, 8, 9, 10}
                }
            };
            _customerActionTypeRepository.Insert(customerActionType);
            _Id_CustomerAction = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
            var customerActions = new List<CustomerAction>()
            {
                new CustomerAction()
                {
                    Id = _Id_CustomerAction,
                    Active = true,
                    StartDateTimeUtc = DateTime.UtcNow,
                    EndDateTimeUtc = DateTime.UtcNow.AddMonths(1),
                    Name = "Test action",


, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
      "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
      "};",
      NoBinPacking);

  NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
  verifyFormat("static uint8 CddDp83848Reg[] = {\n"
               "    CDDDP83848_BMCR_REGISTER,\n"
               "    CDDDP83848_BMSR_REGISTER,\n"
               "    CDDDP83848_RBR_REGISTER};",
               "static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
               "                                CDDDP83848_BMSR_REGISTER,\n"
               "                                CDDDP83848_RBR_REGISTER};",
               NoBinPacking);

  // FIXME: The alignment of these trailing comments might be bad. Then again,
  // this might be utterly useless in real code.
  verifyFormat("Constructor::Constructor()\n"
               "    : some_value{         //\n"
               "                 aaaaaaa, //\n"
               "                 bbbbbbb} {}");

  // In braced lists, the first comment is always assumed to belong to the
  // first element. Thus, it can be moved to the next or previous line as
  // appropriate.
  verifyFormat("function({// First element:\n"
               "          1,\n"
               "          // Second element:\n"
               "          2});",
               "function({\n"
               "    // First element:\n"
               "    1,\n"
               "    // Second element:\n"
               "    2});");
  verifyFormat("std::vector<int> MyNumbers{\n"
               "    // First element:\n"
               "    1,\n"
               "    // Second element:\n"
               "    2};",
               "std::vector<int> MyNumbers{// First element:\n"
               "                           1,\n"
               "                           // Second element:\n"
               "                           2};",
               getLLVMStyleWithColumns(30));
  // A trailing comma should still lead to an enforced line break and no
  // binpacking.
  verifyFormat("vector<int> SomeVector = {\n"
               "    // aaa\n"
               "    1,\n"
               "    2,\n"
               "};",
               "vector<int> SomeVector = { // aaa\n"
               "    1, 2, };");

  // C++11 brace initializer list l-braces should not be treated any differently
  // when breaking before lambda bodies is enabled
  FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
  BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
  BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
  BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
  verifyFormat(
      "std::runtime_error{\n"
      "    \"Long string which will force a break onto the next line...\"};",
      BreakBeforeLambdaBody);

  FormatStyle ExtraSpaces = getLLVMStyle();
  ExtraSpaces.Cpp11BracedListStyle = false;
  ExtraSpaces.ColumnLimit = 75;
  verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
  verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
  verifyFormat("f({ 1, 2 });", ExtraSpaces);
  verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
  verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
  verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
  verifyFormat("new vector<int>{ 1, 2, 3 };


, im));
}
return res;`);
const czeta_helper_2 = new ZetaHelper2('czeta_helper_2', // ASSUME DOWNCONVERTED
`mat4 phases = z.y*bases;
vec2 res = vec2(0);
for (int row = 0; row < 4; row++) {
  vec4 mags = exp(z.x*bases[row]) * coeffs[row];
  vec4 re = cos(phases[row]);
  vec4 im = sin(phases[row]);
  res += vec2(dot(mags, re), dot(mags, im));
}
return res;`,
`mat4 phases = z.y*bases;
vec3 res = vec3(0);
for (int row = 0; row < 4; row++) {
  vec4 mags = exp(z.x*bases[row]) * coeffs[row];
  vec4 re = cos(phases[row]);
  vec4 im = sin(phases[row]);
  res += vec3(dot(mags, re), dot(mags, im), 0);
}
return res;`);

// Riemann-Siegel Formula
const czeta_strip = new ComplexFunction('czeta_strip', // ASSUME DOWNCONVERTED
`vec4 zeta_est = vec4(1., 0, 1., 0); // Estimate of zeta(z), zeta(1-z)

zeta_est += czeta_helper(z,
mat4(2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.,13.,14.,15.,16.,17.),
mat4(-0.693147180560,-1.098612288668,-1.386294361120,-1.609437912434,-1.791759469228,-1.945910149055,-2.079441541680,-2.197224577336,-2.302585092994,-2.397895272798,-2.484906649788,-2.564949357462,-2.639057329615,-2.708050201102,-2.772588722240,-2.833213344056));
zeta_est += czeta_helper(z,
mat4(18.,19.,20.,21.,22.,23.,24.,25.,26.,27.,28.,29.,30.,31.,32.,33.),
mat4(-2.890371757896,-2.944438979166,-2.995732273554,-3.044522437723,-3.091042453358,-3.135494215929,-3.178053830348,-3.218875824868,-3.258096538021,-3.295836866004,-3.332204510175,-3.367295829986,-3.401197381662,-3.433987204485,-3.465735902800,-3.496507561466));

VEC_TYPE zetaA = vec3(zeta_est.xy, 0).COMPONENTS;
VEC_TYPE zetaB = vec3(zeta_est.zw, 0).COMPONENTS;
zetaB = cmul(zetaB, cconj(zeta_character(ONE - cconj(z))));

if (z.y < 120.) {
    // Interpolate between the two estimates of zeta(z)
    float t = 1.0 - min(z.x, 1.0);
    float alpha = t*t * (3.0 - 2.0*t); // Hermite interpolation (smoothstep)
    return mix(zetaA, zetaB, alpha);
} else {
    return cadd(zetaA, zetaB);
}`, ['conj', 'zeta_character', 'czeta_helper', 'add']);

const ceta_right = new ComplexFunction('ceta_right', // ASSUME DOWNCONVERTED
`if (z.x < 3.0 && z.y > 54.) {return ceta_strip(z);}
VEC_TYPE result = ONE;
result += czeta_helper_2(z,
mat4(-0.69314718055995,-1.09861228866811,-1.386294


fsCopy) defs[opt] = defsCopy[opt];
    place.removeChild(cm.getWrapperElement());
  }
});

testCM("lineInfo", function(cm) {
  eq(cm.lineInfo(-1), null);
  var mark = document.createElement("span");
  var lh = cm.setGutterMarker(1, "FOO", mark);
  var info = cm.lineInfo(1);
  eq(info.text, "222222");
  eq(info.gutterMarkers.FOO, mark);
  eq(info.line, 1);
  eq(cm.lineInfo(2).gutterMarkers, null);
  cm.setGutterMarker(lh, "FOO", null);
  eq(cm.lineInfo(1).gutterMarkers, null);
  cm.setGutterMarker(1, "FOO", mark);
  cm.setGutterMarker(0, "FOO", mark);
  cm.clearGutter("FOO");
  eq(cm.lineInfo(0).gutterMarkers, null);
  eq(cm.lineInfo(1).gutterMarkers, null);
}, {value: "111111\n222222\n333333"});

testCM("coords", function(cm) {
  cm.setSize(null, 100);
  addDoc(cm, 32, 200);
  var top = cm.charCoords(Pos(0, 0));
  var bot = cm.charCoords(Pos(200, 30));
  is(top.left < bot.left);
  is(top.top < bot.top);
  is(top.top < top.bottom);
  cm.scrollTo(null, 100);
  var top2 = cm.charCoords(Pos(0, 0));
  is(top.top > top2.top);
  eq(top.left, top2.left);
});

testCM("coordsChar", function(cm) {
  addDoc(cm, 35, 70);
  for (var i = 0; i < 2; ++i) {
    var sys = i ? "local" : "page";
    for (var ch = 0; ch <= 35; ch += 5) {
      for (var line = 0; line < 70; line += 5) {
        cm.setCursor(line, ch);
        var coords = cm.charCoords(Pos(line, ch), sys);
        var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
        eqCharPos(pos, Pos(line, ch));
      }
    }
  }
}, {lineNumbers: true});

testCM("coordsCharBidi", function(cm) {
  addDoc(cm, 35, 70);
  // Put an rtl character into each line to trigger the bidi code path in coordsChar
  cm.setValue(cm.getValue().replace(/\bx/g, 'و'))
  for (var i = 0; i < 2; ++i) {
    var sys = i ? "local" : "page";
    for (var ch = 2; ch <= 35; ch += 5) {
      for (var line = 0; line < 70; line += 5) {
        cm.setCursor(line, ch);
        var coords = cm.charCoords(Pos(line, ch), sys);
        var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
        eqCharPos(pos, Pos(line, ch));
      }
    }
  }
}, {lineNumbers: true});

testCM("badBidiOptimization", function(cm) {
  if (window.automatedTests) return
  var coords = cm.charCoords(Pos(0, 34))
  eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34))
}, {value: "----------
هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟
"})


 케어\n'
          ' 10 Shot\n'
          ' *반대쪽도 동일하게 사용\n'
          ' ※ 안구 사용 금지\n'
          ' 눈가 뼈 라인 밑 안쪽에서 바깥쪽으로 한 칸씩 이동하며 1샷씩 쏘세요\n'
          ' 좁은 부위이므로 세밀하게 사용해야 합니다\n'
          '\n'
          ' 5. 팔자주름 케어\n'
          ' 15 Shot\n'
          ' *반대쪽도 동일하게 사용\n'
          ' ※ 입술 사용 금지\n'
          ' 팔자부위의 안쪽에서 바깥쪽으로 한 칸씩 이동하며 1샷씩 쏘세요\n'
          ' 좁은 부위이므로 세밀하게 사용해야 합니다\n'
          '\n'
          ' 6. 이마 케어\n'
          ' 70 Shot\n'
          ' ※ 눈썹 위 1cm / 미간 중앙 사용 금지\n'
          ' 제품을 화면과 같이 눕힌 다음, 눈썹 끝 위에서 헤어라인 방향으로 1샷씩 쏘세요\n'
          ' 미간 중앙을 제외하고 조금씩 제품을 이동하며 케어하세요\n'
    },
    {
      'url': 'https://nuuz-image-storage.s3.amazonaws.com/videos/Guide_03_2mm_IntensiveCare.mp4',
      'header': "Prog_Titl_0007",
      'text': '집중케어 프로그램 2mm\n'
          '*1주 1회 권장\n'
          '\n'
          ' 사용 전 주의사항\n'
          ' 1. 시술 시 에너지 강도를 조절하여 사용하시고, 같은 곳에 중복으로 사용하지 마십시오.\n'
          ' 2. 반드시 젤 크림을 도포 후 사용하시고, 카트리지 검정 필름 부분과 피부를 밀착하여 사용하십시오. (젤 크림 미사용 시 화상 유발 가능)\n'
          '\n'
          ' ※ 2mm 카트리지 사용 시에는 SHOT 버튼을 누르고 있는 동안에만 초음파가 조사되며, 반드시 기기를 이동하면서 SHOT을 적용하시기 바랍니다


try {
      window.iLogger = iLogger;
      window.__wpk = iLogger.iLoggerIntegrate({
        pid: 'irmajibm-qikbi6z1',
        sampleRate: 0.3,
        category: 100
      });
       window.addEventListener('unhandledrejection', (event) => {
        event.preventDefault();
        console.log('unhandledrejection fired: ', event);
        console.log('unhandledrejection reason: ', event.reason);
        window.__wpk &&
          window.__wpk.report &&
          window.__wpk.report({
            bid: 'irmajibm-qikbi6z1',
            category: 110,
            msg: 'unhandledrejection-stack-report',
            c1: event.type,
            c2: event.reason,
            c3: JSON.stringify(event.reason),
          });
        return true;
      });

      window.lzdiTraceLifeCircle = {};
      window.lzdiTraceLifeCircle.lzdiTraceBeforeSend = function (logData) {
        var logDataTemp = logData || {};
        logDataTemp.w_url = window.location.origin + '/search';
        logDataTemp.w_query = '';
        logDataTemp.w_ref = "searchList";
        logDataTemp.w_c4 = window.location.href;
        logDataTemp.w_c5 = 2;
        logDataTemp.w_c6 = "";
        logDataTemp.w_bl1 = window.location.href;
        return logDataTemp;
      }
    } catch (e) {
      console.error('init wpkReporter fail', e);
    }
</script>


result PG::RecoveryState::Active::react(const AdvMap& advmap)
{
  PG *pg = context< RecoveryMachine >().pg;
  ldout(pg->cct, 10) << "Active advmap" << dendl;
  if (!pg->pool.newly_removed_snaps.empty()) {
    pg->snap_trimq.union_of(pg->pool.newly_removed_snaps);
    ldout(pg->cct, 10) << *pg << " snap_trimq now " << pg->snap_trimq << dendl;
    pg->dirty_info = true;
    pg->dirty_big_info = true;
  }

  for (size_t i = 0; i < pg->want_acting.size(); i++) {
    int osd = pg->want_acting[i];
    if (!advmap.osdmap->is_up(osd)) {
      pg_shard_t osd_with_shard(osd, shard_id_t(i));
      assert(pg->is_acting(osd_with_shard) || pg->is_up(osd_with_shard));
    }
  }

  bool need_publish = false;
  /* Check for changes in pool size (if the acting set changed as a result,
   * this does not matter) */
  if (advmap.lastmap->get_pg_size(pg->info.pgid.pgid) !=
      pg->get_osdmap()->get_pg_size(pg->info.pgid.pgid)) {
    if (pg->get_osdmap()->get_pg_size(pg->info.pgid.pgid) <= pg->actingset.size()) {
      pg->state_clear(PG_STATE_UNDERSIZED);
    } else {
      pg->state_set(PG_STATE_UNDERSIZED);
    }
    // degraded changes will be detected by call from publish_stats_to_osd()
    need_publish = true;
  }

  // if we haven't reported our PG stats in a long time, do so now.
  if (pg->info.stats.reported_epoch + pg->cct->_conf->osd_pg_stat_report_interval_max < advmap.osdmap->get_epoch()) {
    ldout(pg->cct, 20) << "reporting stats to osd after " << (advmap.osdmap->get_epoch() - pg->info.stats.reported_epoch)
		       << " epochs" << dendl;
    need_publish = true;
  }

  if (need_publish)
    pg->publish_stats_to_osd();

  return forward_event();
}

boost::statechart::result PG::RecoveryState::Active::react(const ActMap&)
{
  PG *pg = context< RecoveryMachine >().pg;
  ldout(pg->cct, 10) << "Active: handling ActMap" << dendl;
  assert(pg->is_primary());

  if (pg->have_unfound()) {
    // object may have become unfound
    pg->discover_all_missing(*context< RecoveryMachine >().get_query_map());
  }

  if (pg->cct->_conf->osd_check_for_log_corruption)
    pg->check_log_for_corruption(pg->osd->store);

  uint64_t unfound = pg->missing_loc.num_unfound();
  if (unfound > 0 &&
      pg->all_unfound_are_queried_or_lost(pg->get_osdmap())) {
    if (pg->cct->_conf->osd_auto_mark_unfound_lost) {
      pg->osd->clog->error() << pg->info.pgid.pgid << " has " << unfound
			    << " objects unfound and apparently lost, would automatically "
			    << "mark these objects lost but this feature is not yet implemented "
			    << "(osd_auto_mark_unfound_lost)";
    } else
      pg->osd->clog->error() << pg->info.pgid.pgid << " has "
                             << unfound << " objects unfound and apparently lost";
  }


using System.Numerics;
using Content.Shared.Inventory;
using Content.Shared.Movement.Systems;

namespace Content.Shared.Camera;

/// <summary>
///     Raised directed by-ref when <see cref="SharedContentEyeSystem.UpdateEyeOffset"/> is called.
///     Should be subscribed to by any systems that want to modify an entity's eye offset,
///     so that they do not override each other.
/// </summary>
/// <param name="Offset">
///     The total offset to apply.
/// </param>
/// <remarks>
///     Note that in most cases <see cref="Offset"/> should be incremented or decremented by subscribers, not set.
///     Otherwise, any offsets applied by previous subscribing systems will be overridden.
/// </remarks>
[ByRefEvent]


3(0, 0, 0),
          offset = ccp(0, 2)
        }
      }
    },
    {
      t = "Sprite",
      base = {
        name = "rmb_icon",
        res = "UI/alpha/HVGA/task_rmb_icon_2.png"
      },
      layout = {
        position = ccp(620, 100)
      },
      config = {}
    },
    {
      t = "Label",
      base = {
        name = "rmb",
        text = self.rmbCost,
        size = 18
      },
      layout = {
        anchor = ccp(1, 0.5),
        position = ccp(715, 100)
      },
      config = {
        shadow = {
          color = ccc3(0, 0, 0),
          offset = ccp(0, 2)
        }
      }
    },
    {
      t = "Scale9Sprite",
      base = {
        name = "faststren",
        res = "UI/alpha/HVGA/herodetail-upgrade.png",
        capInsets = CCRectMake(20, 20, 53, 29)
      },
      layout = {
        position = ccp(666, 60)
      },
      config = {
        scaleSize = CCSizeMake(125, 45)
      }
    },
    {
      t = "Scale9Sprite",
      base = {
        name = "faststren_press",
        res = "UI/alpha/HVGA/herodetail-upgrade-mask.png",
        capInsets = CCRectMake(20, 20, 53, 29),
        parent = "faststren"
      },
      layout = {
        anchor = ccp(0, 0),
        position = ccp(0, 0)
      },
      config = {
        visible = false,
        scaleSize = CCSizeMake(125, 45)
      }
    },
    {
      t = "Label",
      base = {
        name = "faststren_label",
        text = T(LSTR("EQUIPSTRENGTHEN.ONECLICK_ENCHANTING")),
        fontinfo = "ui_normal_button",
        parent = "faststren"
      },
      layout = {
        position = ccp(62, 21)
      },
      config = {
        color = ccc3(234, 225, 205)
      }
    }
  }
  readNode:addNode(ui_info)
  self.strenui = strenui
  self:refreshFastStrenButton()
end
class.createStrenButton = createStrenButton
local function refreshFastStrenButton(self)
  local ui = self.strenui or {}
  if tolua.isnull(ui.fsContainer) then
    return
  end
  local showvip = ed.playerlimit.getAreaShowvip("Item One-Click-Upgrade")
  if showvip <= ed.player:getvip() then
    ui.fsContainer:setVisible(true)
  else
    ui.fsContainer:setVisible(false)
  end
end
class.refreshFastStrenButton = refreshFastStrenButton
local function initBar(self)
  local slot = self.slot
  local level, exp, mlevel, mexp = self:getEquipLevel(slot)
  self.oriExp = self:getItemExp(slot)
  self.oriLevel = level
  self.targetExp = self.oriExp
  local nl = math.min(level + 1, mlevel)
  local ui = self.barui
  ed.setString(ui.b_lv, res.enhance_level_res[level] or "")
  ed.setString(ui.n_lv, res.enhance_level_res[nl] or "")
  ed.setString(ui.ehc, string.format("%d/%d", exp, mexp))
  ui.bar:setVisible(true)
  ui.anim_bar:setVisible(false)
  if not tolua.isnull(ui.bar) then
    ui.bar:setTextureRect(CCRectMake(0, 0, 655 * exp / mexp, 18))
  end


 => {
                    let self_ty = proj.projection_ty.self_ty();
                    debug!(
                        "mark_used_by_predicates: (projection) self_ty={:?} proj.ty={:?}",
                        self_ty, proj.ty
                    );

                    // Consider `T` used if `I` is used in predicates of the form
                    // `<I as Iterator>::Item = T`
                    debug!("mark_used_by_predicates: checking self");
                    if is_ty_used(unused_parameters, self_ty) {
                        debug!("mark_used_by_predicates: used!");
                        mark_ty(unused_parameters, proj.ty);

                        // No need to check for projection type being used if `self_ty` was used.
                        continue;
                    }

                    // Consider `I` used if `T` is used in predicates of the form
                    // `<I as Iterator>::Item = &'a (T, E)` (see rust-lang/rust#75326)
                    debug!("mark_used_by_predicates: checking projection ty");
                    if is_ty_used(unused_parameters, proj.ty) {
                        debug!("mark_used_by_predicates: used!");
                        mark_ty(unused_parameters, self_ty);
                    }
                }
                ty::PredicateAtom::RegionOutlives(..)
                | ty::PredicateAtom::TypeOutlives(..)
                | ty::PredicateAtom::WellFormed(..)
                | ty::PredicateAtom::ObjectSafe(..)
                | ty::PredicateAtom::ClosureKind(..)
                | ty::PredicateAtom::Subtype(..)
                | ty::PredicateAtom::ConstEvaluatable(..)
                | ty::PredicateAtom::ConstEquate(..) => (),
            }
        }
    }

    if let Some(parent) = predicates.parent {
        mark_used_by_predicates(tcx, parent, unused_parameters);
    }
}

/// Emit errors for the function annotated by `#[rustc_polymorphize_error]`, labelling each generic
/// parameter which was unused.
fn emit_unused_generic_params_error<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    generics: &'tcx ty::Generics,
    unused_parameters: &FiniteBitSet<u32>,
) {
    debug!("emit_unused_generic_params_error: def_id={:?}", def_id);
    let base_def_id = tcx.closure_base_def_id(def_id);
    if !tcx
        .get_attrs(base_def_id)
        .iter()
        .any(|a| tcx.sess.check_name(a, sym::rustc_polymorphize_error))
    {
        return;
    }

    debug!("emit_unused_generic_params_error: unused_parameters={:?}", unused_parameters);
    let fn_span = match tcx.opt_item_name(def_id) {
        Some(ident) => ident.span,
        _ => tcx.def_span(def_id),
    };

    let mut err = tcx.sess.struct_span_err(fn_span, "item has unused generic parameters");

    let mut next_generics = Some(generics);
    while let Some(generics) = next_generics {
        for param in &generics.params {
            if unused_parameters.contains(param.index).unwrap_or(false) {
                debug!("emit_unused_generic_params_error: param={:?}", param);
                let def_span = tcx.def_span(param.def_id);
                err.span_label(def_span, &format!("generic parameter `{}` is unused", param.name));
            }
        }

        next_generics = generics.parent.map(|did| tcx.generics_of(did));
    }

    err.emit();
}

/// Visitor used to aggregate generic parameter uses.
struct MarkUsedGeneric


ndblock %}
{% extends 'manage/manage_base.html' %}
{% set page='authmigrate' -%}

{% block manage_title %}
  Authentication Migration
{% endblock %}

{% block manage_content %}

    It must be .csv file that looks like this example:

ALIAS,ACTUAL
alias@example.com,flastname@example.com
...

{% if results %}
  {% if dry_run %}

In DRY-RUN mode

  {% else %}

NOT in dry-run mode

  {% endif %}

Keys

Neither found

Neither the alias or real email was found as a user

Nothing to do

Didn't exist as an alias anyway

Moved over

Only existed as alias, email address simply changed

Merged

Objects belonging to the old user account moved

        Alias

        Real

        Notes

    {% for result in results %}

        {{ result.alias }}
        {% if result.old and not result.old.is_active %}
          Inactive
        {% endif %}

        {{ result.real }}
        {% if result.new and not result.new.is_active %}
          Inactive
        {% endif %}

        {{ result.notes | carefulnl2br | safe }}

    {% endfor %}

{% endif %}

  {% set submit_text = 'Upload and Process' %}
  {% include "manage/_default_form_upload.html" %}

{% endblock %}
<!DOCTYPE html>

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
    <title>Air Mozilla Temporarily Unavailable</title>

Air Mozilla Temporarily Unavailable

Please try again in a couple of seconds. It's probably just a temporary glitch.

Automatically trying again in  seconds.

<!DOCTYPE


_tester.InvalidTestCaseError{
				{
					MessageId: "primitiveOverridden",
					Column:    15,
				},
			},
		},
		{
			Code: "type T = -1n & bigint;",
			Errors: []rule_tester.InvalidTestCaseError{
				{
					MessageId: "primitiveOverridden",
					Column:    16,
				},
			},
		},
		{
			Code: `
        type T = 'a' | 'b';
        type U = T & string;
      `,
			Errors: []rule_tester.InvalidTestCaseError{
				{
					MessageId: "primitiveOverridden",
					Column:    18,
				},
			},
		},
		{
			Code: `
        type S = 1 | 2;
        type T = 'a' | 'b';
        type U = S & T & string & number;
      `,
			Errors: []rule_tester.InvalidTestCaseError{
				{
					MessageId: "primitiveOverridden",
					Column:    18,
				},
				{
					MessageId: "primitiveOverridden",
					Column:    22,
				},
			},
		},
	})
}
package no_unsafe_member_access

import (
	"fmt"

	"github.com/microsoft/typescript-go/shim/ast"
	"github.com/microsoft/typescript-go/shim/checker"
	"github.com/typescript-eslint/tsgolint/internal/rule"
	"github.com/typescript-eslint/tsgolint/internal/utils"
)

func buildUnsafeComputedMemberAccessMessage(property, t string) rule.RuleMessage {
	return rule.RuleMessage{
		Id:          "unsafeComputedMemberAccess",
		Description: fmt.Sprintf("Computed name %v resolves to an %v value.", property, t),
	}
}
func buildUnsafeMemberExpressionMessage(property, t string) rule.RuleMessage {
	return rule.RuleMessage{
		Id:          "unsafeMemberExpression",
		Description: fmt.Sprintf("Unsafe member access %v on an %v value.", property, t),
	}
}
func buildUnsafeThisMemberExpressionMessage(property string) rule.RuleMessage {
	return rule.RuleMessage{
		Id: "unsafeThisMemberExpression",
		Description: fmt.Sprintf("Unsafe member access %v on an `any` value. `this` is typed as `any`.", property) +
			"You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.",
	}
}

type state uint8

const (
	stateUnsafe state = iota
	stateSafe   state = iota
)

func createDataType(t *checker.Type) string {
	if utils.IsIntrinsicErrorType(t) {
		return "`error` typed"
	}
	return "`any`"
}

var NoUnsafeMemberAccessRule = rule.Rule{
	Name: "no-unsafe-member-access",
	Run: func(ctx rule.RuleContext, options any) rule.RuleListeners {
		compilerOptions := ctx.Program.Options()
		isNoImplicitThis := utils.IsStrictCompilerOptionEnabled(
			compilerOptions,
			compilerOptions.NoImplicitThis,
		)

		stateCache := map[*ast.Node]state{}

		var checkMemberExpression func(node *ast.Node) state
		checkMemberExpression = func(node *ast.Node) state {
			cachedState, ok := stateCache[node]
			if ok {
				return cachedState
			}

			// TODO(port-perf): couldn't it be done at visitchildren phase?
			parent := node.Parent
			for !ast.IsSourceFile(parent) {
				// ignore MemberExpressions with ancestors of type `TSClassImplements` or `TSInterfaceHeritage`
				if ast.IsHeritageClause(parent) {
					return stateSafe
				}
				parent = parent.Parent
			}

			expression := node.Expression()
			if ast.IsAccessExpression(expression) {
				objectState := checkMemberExpression(expression)
				if objectState == stateUnsafe {
					// if


Theme,
      "whiteOnBlack": TerminalThemes.whiteOnBlack
    };
    final manifestJson = await rootBundle.loadString('AssetManifest.json');
    final keys = json
        .decode(manifestJson)
        .keys
        .where((String key) => key.startsWith('assets/colors/schemes'));
    for (var k in keys) {
      var name = k.substring(k.lastIndexOf("/") + 1);
      var lines = await rootBundle
          .loadString(k)
          .then<List<String>>((value) => value.split("\n"));
      var variables = {};
      List.from(lines)
          .where((element) => element.startsWith("#define"))
          .map((event) => event.split(" "))
          .map((event) => event.map((e) => e.trim()).toList())
          .map((event) => {event[1]: event[2]})
          .forEach((element) {
        if (element.isNotEmpty) {
          for (var element in element.entries) {
            variables[element.key] = element.value;
          }
        }
      });
      var values = <String, String>{};
      List.from(lines)
          .where((x) => x.startsWith('*.'))
          .map((x) => x.substring(2))
          .map<List<dynamic>>((x) => x.split(':').map((v) => v.trim()).toList())
          .forEach((element) {
        if (element.length > 1) {
          if (variables.isNotEmpty) {
            var newV = variables[element[1]];
            values[element[0]] = newV ?? element[1];
          } else {
            values[element[0]] = element[1];
          }
        }
      });
      // print(values);
      Color cursorColor = TerminalThemes.defaultTheme.cursor;
      Color selection = TerminalThemes.defaultTheme.selection;
      Color foreground = TerminalThemes.defaultTheme.foreground;
      Color background = TerminalThemes.defaultTheme.background;

      Color black = TerminalThemes.defaultTheme.black;
      Color red = TerminalThemes.defaultTheme.red;
      Color green = TerminalThemes.defaultTheme.green;
      Color yellow = TerminalThemes.defaultTheme.yellow;
      Color blue = TerminalThemes.defaultTheme.blue;
      Color magenta = TerminalThemes.defaultTheme.magenta;
      Color cyan = TerminalThemes.defaultTheme.cyan;
      Color white = TerminalThemes.defaultTheme.white;

      Color brightBlack = TerminalThemes.defaultTheme.brightBlack;
      Color brightRed = TerminalThemes.defaultTheme.brightRed;
      Color brightGreen = TerminalThemes.defaultTheme.brightGreen;
      Color brightYellow = TerminalThemes.defaultTheme.brightYellow;
      Color brightBlue = TerminalThemes.defaultTheme.brightBlue;
      Color brightMagenta = TerminalThemes.defaultTheme.brightMagenta;
      Color brightCyan = TerminalThemes.defaultTheme.brightCyan;
      Color brightWhite = TerminalThemes.defaultTheme.brightWhite;

      Color searchHitBackground =
          TerminalThemes.defaultTheme.searchHitBackground;
      Color searchHitBackgroundCurrent =
          TerminalThemes.defaultTheme.searchHitBackgroundCurrent;
      Color searchHitForeground =
          TerminalThemes.defaultTheme.searchHitForeground;
      for (var e in values.entries) {
        var color = Color(int.parse(e.value.replaceFirst("#", ""), radix: 16))
            .withAlpha(255);
        if (e.key == "foreground") {
          foreground = color;
        } else if (e.key == "background") {
          background = color;
        } else if (e.key == "cursorColor") {
          cursorColor = color;
        } else if (e.key == "colorBD") {
        } else


#ifndef _EVENTPIPE_TESTS_H
#define _EVENTPIPE_TESTS_H

#include <eglib/test/test.h>

// Container type tests.
DEFINE_TEST_GROUP_INIT_H(dn_vector_tests_init);
DEFINE_TEST_GROUP_INIT_H(dn_vector_ptr_tests_init);
DEFINE_TEST_GROUP_INIT_H(dn_fwd_list_tests_init);
DEFINE_TEST_GROUP_INIT_H(dn_list_tests_init);
DEFINE_TEST_GROUP_INIT_H(dn_queue_tests_init);
DEFINE_TEST_GROUP_INIT_H(dn_umap_tests_init);

// EventPipe tests.
DEFINE_TEST_GROUP_INIT_H(ep_setup_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_rt_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_fastserializer_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_provider_callback_data_queue_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_file_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_session_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_thread_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_buffer_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_buffer_manager_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_tests_init);
DEFINE_TEST_GROUP_INIT_H(fake_tests_init);
DEFINE_TEST_GROUP_INIT_H(ep_teardown_tests_init);

const
static Group test_groups [] = {
	{"vector", dn_vector_tests_init},
	{"ptr-vector", dn_vector_ptr_tests_init},
	{"fwd_list", dn_fwd_list_tests_init},
	{"list", dn_list_tests_init},
	{"queue", dn_queue_tests_init},
	{"umap", dn_umap_tests_init},
	{"setup", ep_setup_tests_init},
	{"rt", ep_rt_tests_init},
	{"fastserializer", ep_fastserializer_tests_init},
	{"provider-callback-dataqueue", ep_provider_callback_data_queue_tests_init},
	{"file", ep_file_tests_init},
	{"session", ep_session_tests_init},
	{"thread", ep_thread_tests_init},
	{"buffer", ep_buffer_tests_init},
	{"buffer-manager", ep_buffer_manager_tests_init},
	{"eventpipe", ep_tests_init},
	{"fake", fake_tests_init},
	{"teardown", ep_teardown_tests_init},
	{NULL, NULL}
};

#endif /* _EVENTPIPE_TESTS_H */


F20A57E85D2FD17F46CB5C65541879C215C827430772443E91546E8EB22494AD539680A5914938A3B22C0996FDA1A90F2C8F1128DE6DC58293EE835DC664AA657D77435D9B2F4FB56E60A7CF65E5934941C9D1563EAD0BD6A8C9D`),
        Qx: toBigint(`6B94E216DFF462C8E9E2BA3BFA05B0A36958865878C1CE295B6A92E0EA88EBDD7FC8F2E`),
        Qy: toBigint(`7489C36CBF3AB2DB16DF75B8ECA5DBA6501017344BCF63E321B6BCBDE78B623119F35B7`),
        R:  toBigint(`B6FF3D6558154BEFF2B106EEE06BB2095C5EB7EDC955950AF748ACA75704A23E`),
        S:  toBigint(`01FAF5C5259BE504F4435A3F398227FC5D02F8B95EF9CD8D37FD6BAD6C6F0437E3DC924E`),
    },
    {
        M:  fromHex(`B5EF1498708F4C136710CA0408B0B4DECF06B7C73F2340121921786584BB12747E256CBA54BF12136ED225AA35FEB00D5C8477F04F06416521FD2B09A27407020B46533EE270CCCF82B832D8EE3B26F3531CD767EBEA573198F64830FA36CD6742E355BE967545254126088987AC8D704E44B9C77FC6DF9C51D3B95953E8EB48`),
        Qx: toBigint(`18621050E672CAFBEA2C51E09CC6AEE8BFAD581F497225F9D78D94A004533ABFF89AF8E`),
        Qy: toBigint(`81F5122C2060E9AD5BC5693FECD9B9DAEFAA4F571718281606831A973BA689FAADA045`),
        R:  toBigint(`55C45B384104B0F62952099025FFA063A266EC590D9E6FC96A4845B9FCE09BA7`),
        S:  toBigint(`01C691388154EF3D79FD0A31B5D4A7865BDF2105B1BBA64871B93D38F7AF7F3563B139C2`),
    },

    // EC-KCDSA_(K-283)(SHA-256)_SVT.txt
    {
        M:    fromHex(`279C63A0B12C0AF5D928093DDF6A7E8CC9A1953B599647E8BA45B857721726E7AE3888BE5465C3540423AB8D73BCA5F83BF42277A0E1CED453B7AC8DBA15EF6FCB95D420FA21475445EF99C5EB81159FC89FB47FF5B0B9B89C5186FE949B6622D0029D0722288076599CE0FB4DE39174D3B4547729D1E53AE367881FDB57C298`),
        Qx:   toBigint(`5DE9FEA9AA2F0A0F4BEC73AEC94AD1277E3CA16A1EDD501B841A4D57D228B0C5B4F7FC7`),
        Qy:   toBigint(`17F9AB8F1D19C80CD241845564FA8EC1BBB6FBBA048435D2489A4E07E80F3F16D1AB435`),
        R:


ot-NUM_BANKGENERIC_SLOTS)]);
		end
	elseif ( event == "PLAYERREAGENTBANKSLOTS_CHANGED" ) then
		local slot = ...;
		BankFrameItemButton_Update(ReagentBankFrame["Item"..(slot)]);
	elseif ( event == "PLAYER_MONEY" or event == "PLAYERBANKBAGSLOTS_CHANGED" ) then
		UpdateBagSlotStatus();
	elseif ( event == "INVENTORY_SEARCH_UPDATE" ) then
		ContainerFrame_UpdateSearchResults(self);
		ContainerFrame_UpdateSearchResults(ReagentBankFrame);
	end
end

function BankFrame_OnShow (self)
	PlaySound("igMainMenuOpen");

	self:RegisterEvent("ITEM_LOCK_CHANGED");
	self:RegisterEvent("PLAYERBANKSLOTS_CHANGED");
	self:RegisterEvent("PLAYERREAGENTBANKSLOTS_CHANGED");
	self:RegisterEvent("PLAYERBANKBAGSLOTS_CHANGED");
	self:RegisterEvent("PLAYER_MONEY");
	self:RegisterEvent("BAG_UPDATE_COOLDOWN");
	self:RegisterEvent("INVENTORY_SEARCH_UPDATE");

	local button;
	for i=1, NUM_BANKGENERIC_SLOTS, 1 do
		button = BankSlotsFrame["Item"..i];
		BankFrameItemButton_Update(button);
	end

	for i=1, NUM_BANKBAGSLOTS, 1 do
		button = BankSlotsFrame["Bag"..i];
		BankFrameItemButton_Update(button);
	end
	UpdateBagSlotStatus();
	OpenAllBags(self);

	if(not GetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_REAGENT_BANK_UNLOCK)) then
		local numSlots,full = GetNumBankSlots();
		if (full and not IsReagentBankUnlocked()) then
			ReagentBankHelpBox:Show();
		else
			ReagentBankHelpBox:Hide();
		end
	else
		ReagentBankHelpBox:Hide();
	end
end

function BankFrame_OnHide (self)
	PlaySound("igMainMenuClose");

	self:UnregisterEvent("ITEM_LOCK_CHANGED");
	self:UnregisterEvent("PLAYERBANKSLOTS_CHANGED");
	self:UnregisterEvent("PLAYERREAGENTBANKSLOTS_CHANGED");
	self:UnregisterEvent("PLAYERBANKBAGSLOTS_CHANGED");
	self:UnregisterEvent("PLAYER_MONEY");
	self:UnregisterEvent("BAG_UPDATE_COOLDOWN");
	self:UnregisterEvent("INVENTORY_SEARCH_UPDATE");

	StaticPopup_Hide("CONFIRM_BUY_BANK_SLOT");
	CloseAllBags(self);
	CloseBankBagFrames();
	CloseBankFrame();
	UpdateContainerFrameAnchors();
end

function BankFrameItemButtonGeneric_OnClick (self, button)
	local container = self:GetParent():GetID();
	if ( button == "LeftButton" ) then
		PickupContainerItem(container, self:GetID());
	else
		UseContainerItem(container, self:GetID());
	end
end

function BankFrameItemButtonGeneric_OnModifiedClick (self, button)
	local container = self:GetParent():GetID();
	if ( self.isBag ) then
		return;
	end
	if ( HandleModifiedItemClick(GetContainerItemLink(container, self:GetID())) ) then
		return;
	end
	if ( IsModifiedClick("SPLITSTACK") ) then
		local texture, itemCount, locked = GetContainerItemInfo(container, self:GetID());
		if ( not locked and itemCount > 1) then
			OpenStackSplitFrame(self.count, self, "BOTTOMLEFT", "TOPLEFT");
		end
		return;
	end
end


，然后使用受损系统的流量对内部网络上的其他工作站和服务器发起额外攻击，Pivoting 可以实现这一点。这将使 IPS 和防火墙日志显示攻击者的内部 IP 地址，而不是外部 IP。

![Creating a pivot](img/3183OS_09_02.jpg)

现在，你可能会问自己，如果不能保护我的网络，我到底为什么要购买 IDS 或 IPS？嗯，在网络上激活 ID 或 IP 不仅很重要，而且每天对其进行监控和审查也很重要。如果没有人正确地监视或检查 ID 或 IP，那么您可能已经有人在您不知情的情况下潜伏在您的网络上。

让我们花一些时间讨论为什么 IDS 或 IPS 是很重要的：

*   Physical security:

    *   您如何知道您的网络中没有人？

    他们现在可能正在访问敏感数据

    *   在防火墙上工作时是否忘记禁用 SSH？

    攻击者只需打开一个漏洞即可获得访问权限，然后可能获得对其他内容的访问权限

*   可靠性和稳定性：

    *   风险管理
    *   对业务运营的影响较小
    *   业务连续性
    *   业务停机时间较短

*   灵活性：

    *   访问其他
    *   无法访问的安全控制功能，提供额外的安全控制层

*   放心：

    *   当其他安全控制意外失败时，IDS 可以提供额外的安全服务
    *   知道谁和什么进入您的网络来访问数据是非常重要的，特别是当它包含客户数据或其他敏感信息

    时

![Creating a pivot](img/3183OS_09_03.jpg)

总之，安全性越来越成为企业的一项要求。企业之所以亏损，是因为他们没有采取额外的安全措施来保护客户的个人数据。在某些情况下，这些信息可以公开发布。公开发布后，企业可能会失去现有客户和新客户。

关于 ID 和 IP 的讨论已经够多了，是时候开始本章的旋转演示了。在开始之前，我们必须已经破坏了一个可以访问 MeterMeter 会话的系统。如果您还没有这样做，请参考[第 8 章](08.html "Chapter 8. Data Capture and Exploitation")、*数据捕获和利用*。

开始吧！

1.  Access Meterpreter and type:

    ```
    ipconfig

    ```

    这将显示内部 IP 地址：

    ![Creating a pivot](img/3183OS_09_05.jpg)

2.  Run a network scan and type:

    ```
    run arp_scanner –r 192.168.


//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//

#import <iWorkImport/TSCH3DChartAnimationClip.h>

__attribute__((visibility("hidden")))
@interface TSCH3DChartAlphaBlendAnimationClip : TSCH3DChartAnimationClip
{
    id mLayerKey;
    _Bool mDelayOpaque;
    _Bool mBlendOpaque;
    _Bool mAlwaysRender;
}

@property(nonatomic) _Bool alwaysRender; // @synthesize alwaysRender=mAlwaysRender;
@property(nonatomic) _Bool blendOpaque; // @synthesize blendOpaque=mBlendOpaque;
@property(nonatomic) _Bool delayOpaque; // @synthesize delayOpaque=mDelayOpaque;
@property(retain, nonatomic) id layerKey; // @synthesize layerKey=mLayerKey;
- (void)didUpdateAnimationTimeForContext:(id)arg1 layers:(id)arg2;
- (void)willRunWithScene:(id)arg1 context:(id)arg2 layers:(id)arg3;
- (void)p_updateOpacityForLayers:(id)arg1 context:(id)arg2;
- (_Bool)willSubmitLabelForSceneObject:(id)arg1 labelRenderInfo:(const struct ChartLabelsContainingLabelRenderInfo *)arg2 context:(id)arg3;
- (void)didTransformElement:(const struct RenderElementInfo *)arg1 sceneObject:(id)arg2 context:(id)arg3;
- (struct ElementRenderPass)renderPassForElement:(const struct RenderElementInfo *)arg1 sceneObject:(id)arg2 context:(id)arg3;
- (struct ElementRenderPass)renderPassForSceneObject:(id)arg1;
- (_Bool)renderPassDelayDisallowedForSceneObject:(id)arg1 pipeline:(id)arg2;
- (void)didSubmitSceneObject:(id)arg1 pipeline:(id)arg2;
- (_Bool)willSubmitSceneObject:(id)arg1 pipeline:(id)arg2 context:(id)arg3;
- (void)didGenerateShaderEffects:(id)arg1 sceneObject:(id)arg2 pipeline:(id)arg3 context:(id)arg4;
- (_Bool)willSubmitElement:(const struct RenderElementInfo *)arg1 sceneObject:(id)arg2 context:(id)arg3;
- (void)didGenerateShaderEffectsForSeriesAtIndex:(const tvec2_3b141483 *)arg1 effects:(id)arg2 sceneObject:(id)arg3 pipeline:(id)arg4 context:(id)arg5;
- (float)p_updateUniform:(id)arg1 context:(id)arg2;
- (float)protected_elementAlphaForContext:(id)arg1;
- (void)protected_addShaderEffect:(id)arg1;
- (void)dealloc;

@end


o">  189

  191 bool is_signed_integer(NumericTypeID type);

  192

  194 bool is_unsigned_integer(NumericTypeID type);

  195

  197 bool is_float_type(NumericTypeID type);

  198

  200 char const *to_string(Status status, bool pretty = false);

  201

  203 char const *to_string(LayoutTypeID layout, bool pretty = false);

  204

  206 template <> <a class="code" href="namespacecutlass_1_1library.html#aa863c416529


Type.unspecified,
  }) {
    final result = V1IconBuilder();
    final serializedList = (serialized as Iterable<Object?>).toList();
    final unhandled = <Object?>[];
    _deserializeProperties(
      serializers,
      serialized,
      specifiedType: specifiedType,
      serializedList: serializedList,
      unhandled: unhandled,
      result: result,
    );
    return result.build();
  }
}

//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18

// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars

import 'package:openapi/api.dart';
import 'package:test/test.dart';

/// tests for MetadataApi
void main() {
  // final instance = MetadataApi();

  group('tests for MetadataApi', () {
    // List all assets by asset ID
    //
    //Future<List<V1Asset>> v1AssetsAssetIdGet(String assetId) async
    test('test v1AssetsAssetIdGet', () async {
      // TODO
    });

    // List all assets
    //
    // Retrieves all assets.              :::info Our asset identifiers are aligned with the ISO 4217 currency codes standard only for fiat money (government or law regulated currency). :::              :::info Properties of the output are providing aggregated information from across all symbols related to the specific asset. If you need to calculate your aggregation (e.g., limiting only the particular type of symbols), you should use /v1/symbols endpoint as a data source. :::
    //
    //Future<List<V1Asset>> v1AssetsGet({ String filterAssetId }) async
    test('test v1AssetsGet', () async {
      // TODO
    });

    // List all asset icons
    //
    // Gets the list of icons (of the given size) for all the assets.
    //
    //Future<List<V1Icon>> v1AssetsIconsSizeGet(int size) async
    test('test v1AssetsIconsSizeGet', () async {
      // TODO
    });

  });
}
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18

// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars

part of openapi.api;

class ApiKeyAuth implements Authentication {
  ApiKeyAuth(this.location, this.paramName);

  final String location;
  final String paramName;

  String apiKeyPrefix = '';
  String apiKey = '';

  @override
  Future<void> applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams,) async {
    final paramValue = apiKeyPrefix.isEmpty ? apiKey : '$apiKeyPrefix $apiKey';

    if (paramValue.isNotEmpty) {
      if (location == 'query') {
        queryParams.add(QueryParam(paramName, paramValue));
      } else if (location == 'header') {
        headerParams[paramName] = paramValue;
      } else if (location == 'cookie') {
        headerParams.update(
          'Cookie',
          (existingCookie) => '$existingCookie; $paramName=$paramValue',
          ifAbsent: () => '$paramName=$paramValue',
        );
      }
    }
  }
}
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.18

// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_f


on.imageCache as sCache
import com.hippo.ehviewer.EhDB
import com.hippo.ehviewer.Settings
import com.hippo.ehviewer.client.EhEngine
import com.hippo.ehviewer.client.EhUtils.getSuitableTitle
import com.hippo.ehviewer.client.ehRequest
import com.hippo.ehviewer.client.getImageKey
import com.hippo.ehviewer.coil.read
import com.hippo.ehviewer.coil.suspendEdit
import com.hippo.ehviewer.download.DownloadManager
import com.hippo.ehviewer.download.downloadLocation
import com.hippo.ehviewer.download.tempDownloadDir
import com.hippo.ehviewer.image.PathSource
import com.hippo.ehviewer.jni.archiveFdBatch
import com.hippo.ehviewer.util.FileUtils
import com.hippo.ehviewer.util.copyTo
import com.hippo.ehviewer.util.sha1
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsChannel
import io.ktor.client.statement.request
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
import kotlinx.coroutines.CancellationException
import okio.Path

class SpiderDen(val info: GalleryInfo) {
    private val gid = info.gid
    var downloadDir: Path? = null
        private set

    private var tempDownloadDir: Path? = null
    private val saveAsCbz = Settings.saveAsCbz.value
    private val archiveName = "$gid.cbz"

    private val lock = ReentrantReadWriteLock()

    // Search in both directories to maintain compatibility
    private val fileCache by lazy {
        listOfNotNull(tempDownloadDir, downloadDir).map(Path::list).flatten().associateBy { it.name } as MutableMap
    }

    private val imageDir
        get() = tempDownloadDir.takeIf { saveAsCbz } ?: downloadDir

    constructor(info: GalleryInfo, dirname: String) : this(info) {
        downloadDir = downloadLocation / dirname
    }

    @Volatile
    @SpiderQueen.Mode
    var mode = SpiderQueen.MODE_READ
        private set

    suspend fun setMode(value: Int) {
        mode = value
        if (mode == SpiderQueen.MODE_DOWNLOAD) {
            if (downloadDir == null) {
                downloadDir = getGalleryDownloadDir(info).apply { mkdirs() }
            }
            if (saveAsCbz && tempDownloadDir == null) {
                tempDownloadDir = info.tempDownloadDir!!.apply { mkdirs() }
            }
        }
    }

    private fun containInCache(index: Int): Boolean {
        val key = getImageKey(gid, index)
        return sCache.read(key) {} != null
    }

    private fun findImageFile(index: Int, temp: Boolean = false) = lock.read {
        val head = perFilename(index)
        fileCache.entries.firstOrNull { (name) -> name.startsWith(head) && temp == name.endsWith(TEMP_SUFFIX) }?.value
    }

    private fun containInDownloadDir(index: Int): Boolean = findImageFile(index) != null

    private fun copyFromCacheToDownloadDir(index: Int): Boolean {
        val dir = imageDir ?: return false
        val key = getImageKey(gid, index)
        return runCatching {
            sCache.read(key) {
                val extension = metadata.toFile().readText()
                val file = dir.findDownloadFileForIndex(index, extension)
                data sendTo file
            } != null
        }.onFailure {
            logcat(it)
        }.getOrDefault(false)
    }

    operator fun contains(index: Int): Boolean = when (mode


tatic const struct cpg_mssr_info r8a77995_cpg_mssr_info = {
	.core_clk		= r8a77995_core_clks,
	.core_clk_size		= ARRAY_SIZE(r8a77995_core_clks),
	.mod_clk		= r8a77995_mod_clks,
	.mod_clk_size		= ARRAY_SIZE(r8a77995_mod_clks),
	.mstp_table		= r8a77995_mstp_table,
	.mstp_table_size	= ARRAY_SIZE(r8a77995_mstp_table),
	.reset_node		= "renesas,r8a77995-rst",
	.reset_modemr_offset	= CPG_RST_MODEMR,
	.mod_clk_base		= MOD_CLK_BASE,
	.clk_extal_id		= CLK_EXTAL,
	.clk_extalr_id		= ~0,
	.get_pll_config		= r8a77995_get_pll_config,
};

static const struct udevice_id r8a77995_cpg_ids[] = {
	{
		.compatible	= "renesas,r8a77995-cpg-mssr",
		.data		= (ulong)&r8a77995_cpg_mssr_info
	},
	{ }
};

U_BOOT_DRIVER(cpg_r8a77995) = {
	.name		= "cpg_r8a77995",
	.id		= UCLASS_NOP,
	.of_match	= r8a77995_cpg_ids,
	.bind		= gen3_cpg_bind,
};


]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	bne _0220A430
	b _0220A284
_0220A404:
	ldr r0, [sp, #0x44]
	ldr r3, _0220B00C ; =ov04_0220FAAC
	str r0, [sp]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	beq _0220A284
_0220A430:
	ldr sl, [r4, #0x10]
	cmp sb, sl
	ble _0220A474
	subs r0, sb, sl
	beq _0220A4A0
	str r0, [sp]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	ldr r3, [r4, #0x24]
	add r3, r3, sl
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	bne _0220A4A0
	b _0220A284
_0220A474:
	ldr r0, [sp, #0x2c]
	ldr r3, _0220B010 ; =ov04_0220FAB4
	str r0, [sp]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	beq _0220A284
_0220A4A0:
	ldr r0, [sp, #0x4c]
	ldr r3, _0220B014 ; =ov04_0220FAB8
	str r0, [sp]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	beq _0220A284
	ldr r0, [r4, #8]
	ldr r3, _0220B018 ; =ov04_0220FAC4
	cmp r0, #0
	ldrne r0, [sp, #0x50]
	mov r1, r5
	ldreq r0, [sp, #0x54]
	mov r2, r8
	str r0, [sp, #0x10c]
	ldr r0, [sp, #0x58]
	str r0, [sp]
	mov r0, r4
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	beq _0220A284
	ldr sb, [sp, #0x10c]
	ldr r0, [r4, #0xc]
	subs r0, r0, sb
	beq _0220A548
	str r0, [sp]
	mov r0, r4
	mov r1, r5
	mov r2, r8
	ldr r3, [r4, #0x24]
	add r3, r3, sb
	bl ov04_0220B490
	cmp r0, #0
	blt _0220B348
	cmp r0, #0
	beq _0220A284
_0220A548:
	ldr r3, _0220B01C ; =ov04_0220FACC
	mov r0, r4
	mov r1, r5
	mov


0xfa,0x10,0x68 = mov	e6, d10, d15
0x3b,0x70,0x06,0x10 = mov	d1, #0x67
0x61,0xff,0xd2,0xd8 = fcall	#-0x4e5c
0x67,0xaa,0xbf,0xaf = insn.t	d10, d10, #0x1f, d10, #0x1f
0x8b,0x0f,0x03,0x40 = add	d4, d15, #0x30
0x01,0xe2,0x00,0x26 = addsc.a	a2, a14, d2, #0
0x8f,0x71,0x01,0x20 = sh	d2, d1, #0x17
0x06,0x62           = sh	d2, #0x6
0xd9,0xdd,0xe4,0x10 = lea	a13, [a13]#0xc64
0x0b,0x82,0x50,0x01 = ge.u	d0, d2, d8
0x5f,0xef,0x6c,0x00 = jeq	d15, d14, #0xd8
0x3c,0xff           = j	#-0x2
0x6e,0x0f           = jz	d15, #0x1e
0x02,0x12           = mov	d2, d1
0x5f,0x0f,0xf1,0xff = jne	d15, d0, #-0x1e
0x37,0x0f,0x61,0xf2 = extr.u	d15, d15, #0x4, #0x1
0x7b,0x00,0xf8,0xb3 = movh	d11, #0x3f80
0x49,0xa5,0x0c,0x0a = lea	a5, [sp]#0xc
0x76,0x8c           = jz	d8, #0x18
0x03,0x6d,0x0a,0x90 = madd	d9, d0, d13, d6
0xbe,0x41           = jeq	d15, d4, #0x22
0x57,0x00,0x62,0xff = extr.u	d15, d0, d15, #0x2
0xb7,0x00,0x89,0xfb = insert	d15, d0, #0, #0x17, #0x9
0x6d,0xff,0x86,0xff = call	#-0xf4
0x6d,0xff,0xa9,0xf4 = call	#-0x16ae
0x37,0x04,0x68,0x40 = extr.u	d4, d4, #0, #0x8
0x3b,0x00,0x16,0x50 = mov	d5, #0x160
0x6d,0xff,0x13,0xfa = call	#-0xbda
0xd9,0xff,0xb0,0xda = lea	a15, [a15]#-0x5490
0x7d,0xef,0x03,0x00 = jeq.a	a15, a14, #0x6
0x9a,0x49           = add	d15, d9, #0x4
0xd9,0x22,0x36,0x61 = lea	a2, [a2]#0x11b6
0x91,0x40,0x00,0xf6 = movh.a	a15, #0x6004
0xd9,0xff,0x30,0xf0 = lea	a15, [a15]#0x3f0
0x8f,0x3f,0x00,0x10 = sh	d1, d15, #0x3
0x6f,0x5a,0


 f32, y as f32) * 10240.0;
                let cell_value = cell_value_f as i32;

                if noise_areas.contains_key(&cell_value) {
                    noise_areas.get_mut(&cell_value).unwrap().push(idx);
                } else {
                    noise_areas.insert(cell_value, vec![idx]);
                }
            }
        }
    }

    noise_areas
}

pub fn draw_corridor(map: &mut Map, x1:i32, y1:i32, x2:i32, y2:i32) {
    let mut x = x1;
    let mut y = y1;

    while x != x2 || y != y2 {
        if x < x2 {
            x += 1;
        } else if x > x2 {
            x -= 1;
        } else if y < y2 {
            y += 1;
        } else if y > y2 {
            y -= 1;
        }

        let idx = map.xy_idx(x, y);
        map.tiles[idx] = TileType::Floor;
    }
}

pub fn paint(map: &mut Map, mode: Symmetry, brush_size: i32, x: i32, y:i32) {
    match mode {
        Symmetry::None => apply_paint(map, brush_size, x, y),
        Symmetry::Horizontal => {
            let center_x = map.width / 2;
            if x == center_x {
                apply_paint(map, brush_size, x, y);
            } else {
                let dist_x = i32::abs(center_x - x);
                apply_paint(map, brush_size, center_x + dist_x, y);
                apply_paint(map, brush_size, center_x - dist_x, y);
            }
        }
        Symmetry::Vertical => {
            let center_y = map.height / 2;
            if y == center_y {
                apply_paint(map, brush_size, x, y);
            } else {
                let dist_y = i32::abs(center_y - y);
                apply_paint(map, brush_size, x, center_y + dist_y);
                apply_paint(map, brush_size, x, center_y - dist_y);
            }
        }
        Symmetry::Both => {
            let center_x = map.width / 2;
            let center_y = map.height / 2;
            if x == center_x && y == center_y {
                apply_paint(map, brush_size, x, y);
            } else {
                let dist_x = i32::abs(center_x - x);
                apply_paint(map, brush_size, center_x + dist_x, y);
                apply_paint(map, brush_size, center_x - dist_x, y);
                let dist_y = i32::abs(center_y - y);
                apply_paint(map, brush_size, x, center_y + dist_y);
                apply_paint(map, brush_size, x, center_y - dist_y);
            }
        }
    }
}

fn apply_paint(map: &mut Map, brush_size: i32, x: i32, y: i32) {
    match brush_size {
        1 => {
            let digger_idx = map.xy_idx(x, y);
            map.tiles[digger_idx] = TileType::Floor;
        }

        _ => {
            let half_brush_size = brush_size / 2;
            for brush_y in y-half_brush_size .. y+half_brush_size {
                for brush_x in x-half_brush_size .. x+half_brush_size {
                    if brush_x > 1 && brush_x < map.width-1 && brush_y


10##AIR::1.5##"> 	FlowElementMouseEvent	 A link element dispatches this event when it detects mouse activity.

 	FlowOperationEvent	 A TextFlow instance dispatches this event just before an operation commences
	 and again just after an operation completes.

 	ScrollEvent
      Represents events that are dispatched when the TextFlow does automatic scrolling.

 	ScrollEventDirection
      Constants for the values of the direction property
      of a ScrollEvent.

 	SelectionEvent
	 A TextFlow instance dispatches a SelectionEvent object when
	 an EditManager or SelectionManager changes or selects a range of text.

 	StatusChangeEvent
	 A TextFlow instance dispatches this event when the status of a FlowElement changes.

 	TextLayoutEvent
	 A TextLayoutEvent instance represents an event, such as the
	 TextLayoutEvent.SCROLL event, that does not require
	 custom properties.

 	UpdateCompleteEvent
	 A TextFlow instance dispatches this event after any of its containers completes
	 an update.

 © 2015 Adobe Systems Incorporated. All rights reserved.
Thu Dec 6 2018, 01:47 PM -08:00


す。

## 機能概要

-   **試験項目書解析:** Excel形式の試験項目書を読み込み、個々のテストケースの結果を抽出します。
-   **集計:** 試験結果を日別、担当者別に集計し、進捗状況を把握できるようにします。
-   **可視化:** 集計結果をWeb UI上でグラフや表として表示し、視覚的に分かりやすくします。

## 解答例

### 1. 集計処理

試験項目書を読み込み、集計処理を行うNode.jsスクリプトです。

-   **`01_解答例_追加仕様_集計_1`**: 基本的な集計処理と、Excel日付の表示用日付への変換を行います。
    -   **技術要素:** Node.js, `xlsx`, `date-format`, `yargs`
    -   **使い方:** `node convert.js -i <入力Excelフォルダ> -o <出力JSONファイル>`
-   **`02_解答例_追加仕様_集計_2`**: (`01`と同様の機能を持つと推測されます。詳細な違いはコード比較が必要です。)

### 2. UI表示

集計されたデータをWeb UIで表示する例です。

-   **`10_解答例_追加仕様_UI_1`**: EJSテンプレートとjQuery DataTable, Chart.jsを用いてHTMLを生成します。
    -   **技術要素:** Node.js, EJS, HTML, CSS, JavaScript, jQuery DataTable, Chart.js
    -   **使い方:** `node create-index.js` を実行し、`index.html`を生成します。
-   **`11_解答例_追加仕様_UI_2`**: (`10`と同様の機能を持つと推測されます。詳細な違いはコード比較が必要です。)
-   **`12_解答例_追加仕様_UI_3`**: ReactとMaterial-UIを用いたダッシュボード形式のUIです。
    -   **技術要素:** React, Material-UI, Chart.js
    -   **使い方:** `npm start` で開発サーバーを起動します。

## 開発環境

-   Node.js
-   （React版はCreate React App環境）

## 関連ドキュメント

-   [課題](./00_docs/%E6%A6%82%E8%A6%81.md)

## スクリーンショット

![日別・人別集計](./00_docs/images/%E6%97%A5%E5%88%A5%E3%83%BB%E4%BA%BA%E5%88%A5%E9%9B%86%E8%A8%88.png)

![バーンダウンチャート](./00_docs/images/%E3%83%90%E3%83%BC%E3%83%B3%E3%83%80%E3%82%A6%E3%83%B3%E3%83%81%E3%83%A3%E3%83%BC%E3%83%88.png)

![React Dashboard](./00_docs/images/react-dashboard.png)# 投票率データ処理スクリプト

このプロジェクトは、特定のExcelファイルから過去の選挙における�


3,4 3,6 4,8 5,9 12,13 13,14 14,16 14,18 13,20 11,21 9,20 8,18 8,16 9,13 11,10 16,3 18,1 20,0 22,0 23,1 23,2&10; 5,19 4,20 5,21 6,20 6,18 5,16 4,15514; 11,25 9,23 7,20 5,16 4,11 4,7 5,2 7,-2 9,-5 11,-7514; 3,25 5,23 7,20 9,16 10,11 10,7 9,2 7,-2 5,-5 3,-7$16; 8,21 8,9; 3,18 13,12; 13,18 3,1226; 13,18 13,0; 4,9 22,9&10; 6,1 5,0 4,1 5,2 6,1 6,-1 5,-3 4,-426; 4,9 22,910; 5,2 4,1 5,0 6,1 5,222; 20,25 2,-7X20; 9,21 6,20 4,17 3,12 3,9 4,4 6,1 9,0 11,0 14,1 16,4 17,9 17,12 16,17 14,20 11,21 9,2120; 6,17 8,18 11,21 11,0O20; 4,16 4,17 5,19 6,20 8,21 12,21 14,20 15,19 16,17 16,15 15,13 13,10 3,0 17,0O20; 5,21 16,21 10,13 13,13 15,12 16,11 17,8 17,6 16,3 14,1 11,0 8,0 5,1 4,2 3,420; 13,21 3,7 18,7; 13,21 13,020; 18,7 3,7 13,21, 13,0X20; 15,21 5,21 4,12 5,13 8,14 11,14 14,13 16,11 17,8 17,6 16,3 14,1 11,0 8,0 5,1 4,2 3,4z20; 16,18 15,20 12,21 10,21 7,20 5,17 4,12 4,7 5,3 7,1 10,0 11,0 14,1 16,3 17,6 17,7 16,10 14,12 11,13 10,13 7,12 5,10 4,720; 17,21 7,0; 3,21 17,2120; 7,0 17,21, 3,2120; 8,21 5,20 4,18 4,16 5,14 7,13 11,12 14,11 16,9 17,7 17,4 16,2 15,1 12,0 8,0 5,1 4,2 3,4 3,7 4,9 6,11 9,12 13,13 15,14 16,16 16,18 15,20 12,21 8,21w20; 16,14 15,11 13,9 10,8 9,8 6,9 4,11 3,14 3,15 4,18 6,20 9,21 10,21 13,20 15,18 16,14 16,9 15,4 13,1 10,0 8,0 5,1 4,3110; 5,14 4,13 5,12 6,13 5,14; 5,2 4,1 5,0 6,1 5,2@10; 5,14 4,13 5,12 6,13 5,14; 6,1 5,0 4,1 5,2 6,1 6,-1 5,-3 4,-424; 20,18 4,9 20,026; 4,12 22,12; 4,6 22,624; 4,18 20,9 4,0e18; 3,16 3,17 4,19 5,20 7,21 11,21 13,20 14,19 15,17 15,15


rminalEvent(100, TimeUnit.MILLISECONDS)
    }

    "SingleK should suspend" {
      fun getSingle(): Single<Int> = Single.just(1)

      SingleK.fx {
        val s = effect { getSingle().k().suspended() }.bind()

        s shouldBe 1
      }.unsafeRunSync()
    }

    "Error SingleK should suspend" {
      val error = IllegalArgumentException()

      SingleK.fx {
        val s = effect { Single.error<Int>(error).k().suspended() }.attempt().bind()

        s shouldBe error.left()
      }.unsafeRunSync()
    }
  }
}

private fun <A> Gen.Companion.singleK(gen: Gen<A>): Gen<SingleK<A>> =
  Gen.oneOf(
    gen.map { Single.just(it) },
    Gen.throwable().map { Single.error<A>(it) }
  ).map {
    it.k()
  }

private fun SingleK.Companion.genK() = object : GenK<ForSingleK> {
  override fun <A> genK(gen: Gen<A>): Gen<Kind<ForSingleK, A>> =
    Gen.singleK(gen) as Gen<Kind<ForSingleK, A>>
}

private fun <T> SingleK.Companion.eq(): Eq<SingleKOf<T>> = object : Eq<SingleKOf<T>> {
  override fun SingleKOf<T>.eqv(b: SingleKOf<T>): Boolean =
    unsafeRunEq(
      {
        this.value().timeout(5, TimeUnit.SECONDS).blockingGet()
      },
      {
        b.value().timeout(5, TimeUnit.SECONDS).blockingGet()
      }
    )
}

private fun SingleK.Companion.eqK() = object : EqK<ForSingleK> {
  override fun <A> Kind<ForSingleK, A>.eqK(other: Kind<ForSingleK, A>, EQ: Eq<A>): Boolean =
    (this.fix() to other.fix()).let {
      SingleK.eq<A>().run {
        it.first.eqv(it.second)
      }
    }
}
package arrow.reflect

import arrow.core.NonEmptyList
import arrow.core.Validated
import arrow.core.ValidatedPartialOf
import arrow.core.extensions.nonemptylist.semigroup.semigroup
import arrow.core.extensions.validated.applicative.applicative
import arrow.typeclasses.Applicative
import kotlin.reflect.KClass

private val lineSeparator: String = System.getProperty("line.separator")

private val moduleNames: Map<String, String> = mapOf(
  "arrow.aql" to "arrow-aql",
  "arrow.aql.extensions" to "arrow-aql",
  "arrow.core.extensions" to "arrow.core",
  "arrow.core.internal" to "arrow.core",
  "arrow.core" to "arrow-core-data",
  "arrow.typeclasses" to "arrow-core-data",
  "arrow.typeclasses.internal" to "arrow-core-data",
  "arrow.typeclasses.suspended" to "arrow-core-data",
  "arrow.free.extensions" to "arrow-free",
  "arrow.free" to "arrow-free-data",
  "arrow.fx" to "arrow-fx",
  "arrow.fx.extensions" to "arrow-fx",
  "arrow.fx.internal" to "arrow-fx",
  "arrow.fx.typeclasses" to "arrow-fx",
  "arrow.fx.mtl" to "arrow-fx-mtl",
  "arrow.fx.reactor" to "arrow-fx-reactor",
  "arrow.fx.reactor.extensions" to "arrow-fx-reactor",
  "arrow.fx.rx2" to "arrow-fx-rx2",
  "arrow.fx.rx2.extensions" to "arrow-fx-rx2",
  "arrow.mtl.extensions" to "arrow-mtl",
  "arrow.mtl" to "arrow-mtl-data",
  "arrow.mtl.typeclasses" to "arrow-mtl-data",
  "arrow.optics" to "arrow-optics",
  "arrow.optics.dsl" to "arrow-optics",
  "arrow.optics.extensions" to "arrow-optics",
  "arrow.optics.std" to "arrow-optics",
  "arrow.optics.typeclasses" to "arrow-optics",


ext, error, stackTrace) {
          failImages.add(path);
          return Container(
            color: _UIColors.white.withOpacity(0.2),
          );
        }));
  }

  Future<bool> checkPermission() async {
    var granted = (await Permission.camera.status) == PermissionStatus.granted;
    if (!granted) {
      granted = await PermissionHelper.requestPermissionSingle(
          context,
          Permission.camera,
          '',
          NEMeetingUIKit.instance.getUIKitLocalizations().meetingCamera);
      if (!granted && ModalRoute.of(context)?.isActive == true)
        UINavUtils.pop(context);
    }
    return granted;
  }

  Future<void> _initVirtualBackgroundPictures() async {
    Directory? cache;
    if (Platform.isAndroid) {
      cache = await getExternalStorageDirectory();
    } else {
      cache = await getApplicationDocumentsDirectory();
    }

    builtinVirtualBackgroundList =
        await _settingsService.getBuiltinVirtualBackgroundList();
    if (builtinVirtualBackgroundList.isNotEmpty) {
      builtinVirtualBackgroundList =
          replaceBundleId(cache!.path, builtinVirtualBackgroundList);
      _settingsService
          .setBuiltinVirtualBackgroundList(builtinVirtualBackgroundList);
    }

    externalVirtualBackgroundList =
        await _settingsService.getExternalVirtualBackgroundList();
    if (externalVirtualBackgroundList.length > 0) {
      externalVirtualBackgroundList =
          replaceBundleId(cache!.path, externalVirtualBackgroundList);
      _settingsService
          .setExternalVirtualBackgroundList(externalVirtualBackgroundList);
    }
    currentSelectedPath = await _settingsService.getCurrentVirtualBackground();
    if (currentSelectedPath != null) {
      currentSelectedPath =
          replaceBundleIdByStr(currentSelectedPath!, cache!.path);
      _settingsService.setCurrentVirtualBackground(currentSelectedPath);
    }
    if (currentSelectedPath != null) {
      /// 已经开启的默认直接开启
      enableVirtualBackground(true, currentSelectedPath!, force: true);
    }
    if (mounted) setState(() {});
  }

  List<String> replaceBundleId(String replaceStr, List<String> list) {
    if (Platform.isIOS) {
      List<String> convertList = [];
      for (var e in list) {
        if (e == virtualNone) {
          convertList.add(virtualNone);
        } else {
          convertList.add(replaceBundleIdByStr(e, replaceStr));
        }
      }
      return convertList;
    }
    return list;
  }

  void selectVirtualBackground(String? path) {
    if (currentSelectedPath == path && virtualBackgroundIsEnable) {
      return;
    }
    currentSelectedPath = path;
    if (path == null) {
      enableVirtualBackground(false, '');
    } else {
      Alog.i(
          tag: _tag,
          moduleName: _moduleName,
          content:
              'getVirtualBackgroundSupportedType ret supportedType: $supportedType');

      switch (supportedType) {
        case NERoomVirtualBackgroundSupportedType
              .kNEVirtualBackgroundSupportFull:
          enableVirtualBackground(true, path);
          break;
        case NERoomVirtualBackgroundSupportedType
              .kNEVirtualBackgroundSupportHardwareLimit:
          ToastUtils.showToast(
              context,
              NEMeetingUIKit.instance
                  .getUIKitLocalizations()
                  .virtualBackgroundImageDeviceNotSupported);
          break;
        case NERoomVirtualBackgroundSupportedType
              .kNEVirtualBackgroundSupportPerformanceLimit:
          if (!virtualBackgroundIsEnable) {
            DialogUtils.showVirtualBackgroundAlertDialog(
                context: context,
                onCancelCallback: () {
                  Navigator.of(context).pop();
                },
                onForceOpenCallback: () {
                  enableVirtualBackground(true, path, force: true);
                  Navigator.of(context).pop();


Listener, DownloadManagerPieceListener, DownloadManagerPeerListener
{
	public static final String VIEW_ID = MultipleDocumentInterface.SIDEBAR_SECTION_ALLPIECES;

	private CopyOnWriteList<PEPeerManager> peer_managers = new CopyOnWriteList<PEPeerManager>();

	public PiecesSuperView() {
		super( VIEW_ID );
	}

	@Override
	protected
	String getTableID()
	{
		return(TableManager.TABLE_ALL_PIECES );
	}

	@Override
	public TableViewSWT<PEPiece> initYourTableView()
	{
		return( initYourTableView( TableManager.TABLE_ALL_PIECES ));
	}

	@Override
	public void
	tableLifeCycleEventOccurred(
		TableView tv, int eventType, Map<String, Object> data)
	{
		super.tableLifeCycleEventOccurred(tv, eventType, data);

		switch (eventType) {
		case EVENT_TABLELIFECYCLE_INITIALIZED:

			CoreFactory.addCoreRunningListener(new CoreRunningListener() {

				@Override
				public void coreRunning(Core core) {
					registerGlobalManagerListener(core);
				}
			});
			break;

		case EVENT_TABLELIFECYCLE_DESTROYED:
			unregisterListeners();
			break;
		}
	}

	private void
	registerGlobalManagerListener(
		Core core )
	{
		core.getGlobalManager().addListener(this);

		tv.processDataSourceQueue();
	}

	private void
	unregisterListeners()
	{
		try {
			GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();

			gm.removeListener(this);

			Iterator<?> itr = gm.getDownloadManagers().iterator();

			while(itr.hasNext()){

				DownloadManager dm = (DownloadManager)itr.next();

				downloadManagerRemoved(dm);
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void
	downloadManagerAdded(
		DownloadManager dm )
	{
		dm.addPieceListener( this, true );
		dm.addPeerListener( this, true );
	}

	@Override
	public void
	downloadManagerRemoved(
		DownloadManager dm )
	{
		dm.removePieceListener(this);
		dm.removePeerListener(this);
	}

	@Override
	protected List<PEPeerManager>
	getPeerManagers()
	{
		return( peer_managers.getList());
	}

	@Override
	public void
	destroyInitiated()
	{
	}

	@Override
	public void
	destroyed()
	{
	}

	@Override
	public void
	seedingStatusChanged(
		boolean seeding_only_mode, boolean b)
	{
	}

	public void
	peerManagerWillBeAdded(
		PEPeerManager	manager )
	{
	}

	public void
	peerManagerAdded(
		PEPeerManager	manager )
	{
		peer_managers.add( manager );
	}

	public void
	peerManagerRemoved(
		PEPeerManager	manager )
	{
		peer_managers.remove( manager );
	}

	public void
	peerAdded(
		PEPeer 	peer )
	{
	}

	public void
	peerRemoved(
		PEPeer	peer )
	{
	}

	@Override
	public void
	pieceAdded(
		PEPiece created )
	{
		tv.addDataSource( created );
	}

	@Override
	public void
	pieceRemoved(
		PEPiece removed )
	{
		tv.removeDataSource(removed);
	}

	protected void
	updateSelectedContent()
	{
		Object[] dataSources = tv.getSelectedDataSources(true);

		SelectedContent[] sc = new SelectedContent[dataSources.length];

		for ( int i=0;i<sc.length;i++){
			Object ds = dataSources[i];
			if (ds instanceof PEPiece) {
				sc[i] = new SelectedContent( "p


                | 当`T`有一个或两个实参时定义的类型。如果`T`只有一个实参，则`argument_type`              |
| `first_argument_type`           | 第一个实参的类型                                                                       |
| `second_argument_type`          | 第二个实参的类型                                                                       |

- 例如：声明一个`function`类型，它可以表示接受两个`int`，返回一个`int`的可调用对象。`function<int(int, int)>`

## 重载、类型转换、运算符

### 类型转换运算符

- 类型转换运算符是类的一种特殊成员函数，它负责将一个类类型的值转换成其他类型。类型转换函数的一般形式如下：`operator type() const;`
- 一个类型转换函数必须是类的成员函数；它不能声明返回类型，形参列表也必须为空。类型转换函数通常应该是`const`。
- 避免过度使用类型转换函数。
- C++11 引入了显式的类型转换运算符。
- 向`bool`的类型转换通常用在条件部分，因此`operator bool`一般定义成`explicit`的。

### 避免有二义性的类型转换

- 通常，不要为类第几个亿相同的类型转换，也不要在类中定义两个及以上转换源或转换目标是算术类型的转换。
- 在调用重载函数时，如果需要额外的标准类型转换，则该转换的级别只有当所有可行函数都请求同一个用户定义的类型转换时才有用。如果所需的用户定义的类型转换不止一个，则该调用具有二义性。

### 函数匹配与重载运算符

- 如果`a`是一种类型，则表达式`a sym b`可能是：
  - `a.operatorsym(b);`
  - `operatorsym(a,b);`
- 如果我们队同一个类既提供了转换目标是算术类型的类型转换，也提供了重载的运算符，则将会遇到重载运算符与内置运算符的二义性问题。
# 第十七章 标准库特殊设施

## tuple 类型

- `tuple`是类似`pair`的模板，每个成员类型都可以不同，但`tuple`可以有任意数量的成员。
- 但每个确定的`tuple`类型的成员数目是固定的。
- 我们可以将`tuple`看做一个“快速而随意”的数据结构。

**tuple 支持的操作**：

| 操作                                         | 解释                                                                                |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tuple<T1, T2, ..., Tn> t;`                  | `t`是一个`tuple`，成员数为`n`，第`i`个成员的类型是`Ti`所有成员都进行值初始化。                                                                         |
| `tuple<T1, T2, ..., Tn> t(v1, v2, ..., vn);` | 每个成员用对应的初始值`vi`进行初始化。此构造函数是`explicit`的。                                                                                |


using System.Globalization;
using Client.Localization;
using Core;
using JetBrains.Annotations;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Client
{
    public sealed class TooltipItemSpell : TooltipItem<SpellInfo>
    {
        [SerializeField, UsedImplicitly] private RenderingReference rendering;
        [SerializeField, UsedImplicitly] private LocalizationReference localization;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellDescription;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellName;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellRange;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellCastTime;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellCost;
        [SerializeField, UsedImplicitly] private TextMeshProUGUI spellCooldown;
        [SerializeField, UsedImplicitly] private LocalizedString rangeFormatString;
        [SerializeField, UsedImplicitly] private LocalizedString cooldownFormatString;
        [SerializeField, UsedImplicitly] private LocalizedString castTimeFormatString;
        [SerializeField, UsedImplicitly] private LocalizedString castTimeInstantString;
        [SerializeField, UsedImplicitly] private Image spellIcon;

        private readonly object[] descriptionArguments = new object[SpellTooltipInfo.MaxArguments];
        private readonly object[] unknownArguments = { 'X', 'Y', 'Z', 'N', 'K' };

        private readonly NumberFormatInfo tooltipNumberFormat = new NumberFormatInfo {PercentPositivePattern = 1, PercentNegativePattern = 1};

        public override bool ModifyContent(SpellInfo spellInfo)
        {
            spellIcon.sprite = rendering.SpellVisuals.ContainsKey(spellInfo.Id)
                ? rendering.SpellVisuals[spellInfo.Id].SpellIcon
                : rendering.DefaultSpellIcon;

            if (localization.TooltipInfoBySpell.TryGetValue(spellInfo, out SpellTooltipInfo tooltipInfo))
            {
                spellName.text = tooltipInfo.SpellNameString.Value;

                // update spell description with configured arguments
                for (int i = 0; i < tooltipInfo.ArgumentSettings.Count; i++)
                    descriptionArguments[i] = tooltipInfo.ArgumentSettings[i].Resolve() ?? unknownArguments[i];

                for (int i = tooltipInfo.ArgumentSettings.Count; i < unknownArguments.Length; i++)


   Returns:
        Merged segments
    """
    if not segments:
        return segments

    merged = []
    current = segments[0].copy()

    for segment in segments[1:]:
        current_length = len(current.get('text', ''))

        if current_length < min_length:
            # Merge with next segment
            current['end'] = segment['end']
            current['text'] = current.get('text', '') + ' ' + segment.get('text', '')

            # Keep same speaker if they match
            if current.get('speaker') != segment.get('speaker'):
                current['speaker'] = 'Multiple'
        else:
            # Save current and start new
            merged.append(current)
            current = segment.copy()

    # Don't forget the last segment
    merged.append(current)

    return merged

def format_transcript_for_display(segments: List[Dict]) -> str:
    """
    Format transcript segments for display

    Args:
        segments: List of transcript segments

    Returns:
        Formatted transcript text
    """
    lines = []

    for segment in segments:
        timestamp = format_timestamp(segment.get('start', 0))
        speaker = segment.get('speaker', 'Unknown')
        text = segment.get('text', '')

        line = f"[{timestamp}] {speaker}: {text}"
        lines.append(line)

    return '\n\n'.join(lines)

def calculate_reading_time(text: str, wpm: int = 200) -> float:
    """
    Calculate estimated reading time

    Args:
        text: Input text
        wpm: Words per minute reading speed

    Returns:
        Reading time in minutes
    """
    word_count = len(text.split())
    return word_count / wpm

def highlight_keywords(text: str, keywords: List[str]) -> str:
    """
    Highlight keywords in text (for HTML display)

    Args:
        text: Input text
        keywords: List of keywords to highlight

    Returns:
        Text with highlighted keywords
    """
    for keyword in keywords:
        pattern = re.compile(re.escape(keyword), re.IGNORECASE)
        text = pattern.sub(f'<mark>{keyword}</mark>', text)

    return text

def remove_filler_words(text: str) -> str:
    """
    Remove common filler words from transcript

    Args:
        text: Input text

    Returns:
        Text with filler words removed
    """
    filler_words = [
        'um', 'uh', 'ah', 'er', 'hmm', 'like', 'you know',
        'I mean', 'sort of', 'kind of', 'basically', 'actually'
    ]

    for filler in filler_words:
        # Case-insensitive replacement
        pattern = re.compile(r'\b' + re.escape(filler) + r'\b', re.IGNORECASE)
        text = pattern.sub('', text)

    # Clean up multiple spaces
    text = re.sub(r'\s+', ' ', text)

    return text.strip()

def get_word_frequency(text: str, top_n: int = 20) -> List[Tuple[str, int]]:
    """
    Get word frequency distribution

    Args:
        text: Input text
        top_n: Number of top words to return

    Returns:
        List of (word, count) tuples
    """
    # Extract words
    words = re.findall(r'\b[a-z]+\b', text.lower())

    # Count frequency
    word_freq = {}
    for word in words:
        if len(word) > 3:  # Skip short words
            word_freq[word] = word_freq.get(word, 0) + 1

    # Sort by frequency
    sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)

    return sorted_words[:top_n]


 [Mashed Potatoes With Lemon And Chives 5821](../../index/m/mashed-potatoes-with-lemon-and-chives-5821.json)
 * [Mashed Potatoes With Thyme Lemon Butter 105818](../../index/m/mashed-potatoes-with-thyme-lemon-butter-105818.json)
 * [Melon And Pineapple With Lemon Mint Syrup 13134](../../index/m/melon-and-pineapple-with-lemon-mint-syrup-13134.json)
 * [Meyer Lemon And Dried Blueberry Scones 236780](../../index/m/meyer-lemon-and-dried-blueberry-scones-236780.json)
 * [Meyer Lemon And Thyme Truffles 236802](../../index/m/meyer-lemon-and-thyme-truffles-236802.json)
 * [Meyer Lemon And Vanilla Bean Marmalade 231586](../../index/m/meyer-lemon-and-vanilla-bean-marmalade-231586.json)
 * [Meyer Lemon Bars 51256850](../../index/m/meyer-lemon-bars-51256850.json)
 * [Meyer Lemon Budino 235859](../../index/m/meyer-lemon-budino-235859.json)
 * [Meyer Lemon Buttermilk Pudding Cake With Fresh Berries 231451](../../index/m/meyer-lemon-buttermilk-pudding-cake-with-fresh-berries-231451.json)
 * [Meyer Lemon Jam 102745](../../index/m/meyer-lemon-jam-102745.json)
 * [Meyer Lemon Marmalade 102746](../../index/m/meyer-lemon-marmalade-102746.json)
 * [Meyer Lemon Shortcakes With Meyer Curd And Mixed Citrus 357535](../../index/m/meyer-lemon-shortcakes-with-meyer-curd-and-mixed-citrus-357535.json)
 * [Milk Braised Pork With Lemon And Sage Recipe](../../index/m/milk-braised-pork-with-lemon-and-sage-recipe.json)
 * [Minted Radish Tea Sandwiches With Lemon Mayonnaise 11856](../../index/m/minted-radish-tea-sandwiches-with-lemon-mayonnaise-11856.json)
 * [Mixed Seafood Grill With Paprika Lemon Dressing 238229](../../index/m/mixed-seafood-grill-with-paprika-lemon-dressing-238229.json)
 * [Molasses Cookie Baskets With Lemon Sorbet And Gingered Fruit 2399](../../index/m/molasses-cookie-baskets-with-lemon-sorbet-and-gingered-fruit-2399.json)
 * [Moroccan Chicken With Green Olives And Lemon 352532](../../index/m/moroccan-chicken-with-green-olives-and-lemon-352532.json)
 * [Moroccan Lemon Chicken 14106](../../index/m/moroccan-lemon-chicken-14106.json)
 * [No Bake Lemon Cream Tart 105707](../../index/n/no-bake-lemon-cream-tart-105707.json)
 * [Old Fashioned Lemon Almond Cookies Bruber 10284](../../index/o/old-fashioned-lemon-almond-cookies-bruber-10284.json)
 * [Orange Lemon Pudding Cakes 5868](../../index/o/orange-lemon-pudding-cakes-5868.json)
 * [Orecchiette With Savoy Cabbage Peas And Lemon Cream 107202](../../index/o/orecchiette-with-savoy-cabbage-peas-and-lemon-cream-107202.json)
 * [Oven Baked Chicken Breasts With Lemon Mustard Arugula Salad 352669](../../index/o/oven-baked-chicken-breasts-with-lemon-mustard-arugula-s


true");
assert.throws(TypeError, () => monthsInYear.call(""), "empty string");
assert.throws(TypeError, () => monthsInYear.call(Symbol()), "symbol");
assert.throws(TypeError, () => monthsInYear.call(1), "1");
assert.throws(TypeError, () => monthsInYear.call({}), "plain object");
assert.throws(TypeError, () => monthsInYear.call(Temporal.PlainYearMonth), "Temporal.PlainYearMonth");
assert.throws(TypeError, () => monthsInYear.call(Temporal.PlainYearMonth.prototype), "Temporal.PlainYearMonth.prototype");
// Copyright (C) 2020 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-temporal.plainyearmonth.prototype.valueof
description: Temporal.PlainYearMonth.prototype.valueOf.length is 0
info: |
    Every built-in function object, including constructors, has a "length" property whose value is
    an integer. Unless otherwise specified, this value is equal to the largest number of named
    arguments shown in the subclause headings for the function description. Optional parameters
    (which are indicated with brackets: [ ]) or rest parameters (which are shown using the form
    «...name») are not included in the default argument count.

    Unless otherwise specified, the "length" property of a built-in function object has the
    attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.
includes: [propertyHelper.js]
features: [Temporal]
---*/

verifyProperty(Temporal.PlainYearMonth.prototype.valueOf, "length", {
  value: 0,
  writable: false,
  enumerable: false,
  configurable: true,
});
// Copyright (C) 2024 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-temporal.plainyearmonth.prototype.since
description: ISO strings at the edges of the representable range
features: [Temporal]
---*/

const instance = new Temporal.PlainYearMonth(1970, 1);

// Note, these limits are different than other PlainYearMonth conversions
// because the difference is taken between the first days of the two months, so
// the first day of the month of the argument must be within the representable
// range

const validStrings = [
  "-271821-05",
  "-271821-05-01",
  "-271821-05-01T00:00",
  "+275760-09",
  "+275760-09-30",
  "+275760-09-30T23:59:59.999999999",
];

for (const arg of validStrings) {
  instance.since(arg);
}

const invalidStrings = [
  "-271821-04",
  "-271821-04-30",
  "-271821-04-30T23:59:59.999999999",
  "+275760-10",
  "+275760-10-01",
  "+275760-10-01T00:00",
];

for (const arg of invalidStrings) {
  assert.throws(
    RangeError,
    () => instance.since(arg),
    `"${arg}" is outside the representable range of PlainYearMonth`
  );
}
// Copyright (C) 2022 Igalia, S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-temporal.plainyearmonth.prototype.since
description: Tests calculations with roundingMode "expand".
includes: [temporalHelpers.js]
features: [Temporal]
---*/

const earlier = new Temporal.PlainYearMonth(2019, 1);
const later = new Temporal.PlainYearMonth(2021, 9);

const expected = [
  ["years", [3], [-3]],
  ["months", [2, 8],


12px 0 0 -12px;
        @apply richtext-animate-spin richtext-border-current richtext-border-t-transparent richtext-rounded-full richtext-border-[3px] richtext-inline-block;
      }
    }

    .tableWrapper {
      margin: 1em 0;
      @apply richtext-overflow-x-auto;

      table {
        overflow: hidden;
        display: table;
        width: 100%;

        .column-resize-handle {
          @apply richtext-bottom-[-2px] richtext-absolute richtext-right-[-2px] richtext-top-0 richtext-w-1 richtext-z-10 richtext-pointer-events-none richtext-bg-primary;
        }
        .resize-cursor {
          cursor: 'col-resize';
        }

        .selectedCell {
          @apply richtext-bg-black/5 richtext-border-black/20 richtext-border-double;
          @apply dark:richtext-bg-white/10 dark:richtext-border-white/20;
        }
      }
    }

    [data-type='horizontalRule'] {
      @apply richtext-transition-all richtext-duration-100 richtext-ease-in-out richtext-cursor-pointer;

      &.ProseMirror-selectednode {
        @apply richtext-bg-black/5 dark:richtext-bg-white/10;

        hr {
          @apply richtext-border-t-black/30 dark:richtext-border-t-white/30;
        }
      }

      &:hover:not(&.ProseMirror-selectednode) {
        @apply richtext-bg-black/5;
        @apply dark:richtext-bg-white/10;
      }
    }
    :not(.dragging) .ProseMirror-selectednode:not(.image-view) {
      @apply richtext-outline-none richtext-bg-black/10 dark:richtext-bg-white/20 richtext-shadow-none richtext-transition-colors;
    }

    .selection:not(.image-view),
    *:not(.image-view)::selection {
      @apply richtext-bg-black/10 dark:richtext-bg-white/20;
    }

    .is-empty::before {
      content: attr(data-placeholder);
      float: left;
      color: #adb5bd;
      pointer-events: none;
      width: 100%;
      height: 0;
    }

    .columns.is-empty::before {
      display: none !important;
    }

    .is-editor-empty:first-child::before {
      content: attr(data-placeholder);
      float: left;
      color: #adb5bd;
      pointer-events: none;
      width: 100%;
      height: 0;
    }
    p.is-editor-empty:first-child::before {
      float: left;
      height: 0;
      color: #adb5bd;
      pointer-events: none;
      width: 100%;
      content: attr(data-placeholder);
    }
    .ProseMirror-gapcursor {
      @apply richtext-relative richtext-w-full richtext-max-w-2xl richtext-mx-auto;

      &:after {
        @apply richtext-border-t-black/40 dark:richtext-border-t-white/40 richtext-w-full richtext-top-[-1.5em] richtext-max-w-2xl richtext-mx-auto richtext-left-0 richtext-right-0;
      }
    }

    .image-view {
      $root: &;

      display: inline-block;
      float: none;
      max-width: 100%;
      line-height: 0;
      vertical-align: baseline;
      user-select: none;

      &__body {
        position: relative;


FieldReferencedByInsn = constantPool[opcode - Opcodes.ICONST_0]
            }

            if (opcode == Opcodes.ARETURN && maybeConstantFieldReferencedByInsn != null) {
              val relationship = Relationship(method, maybeConstantFieldReferencedByInsn!!, Relationship.Type.Reads)
              logger.debug("Adding relationship: {}", relationship)
              outRelationships.add(relationship)
              maybeConstantFieldReferencedByInsn = null
            }
            super.visitInsn(opcode)
          }

          override fun visitJumpInsn(opcode: Opcode, label: Label?) {
            logger.debug("Visiting jump instruction: {}", opcode.insn)

            if (maybeConstantFieldReferencedByInsn != null) {
              val relationship = Relationship(method, maybeConstantFieldReferencedByInsn!!, Relationship.Type.Reads)

              logger.debug("Adding relationship: {}", relationship)
              outRelationships.add(relationship)
              maybeConstantFieldReferencedByInsn = null
            }
            super.visitJumpInsn(opcode, label)
          }
        }
      }

      override fun visitInnerClass(name: String, outerName: String?, innerName: String?, access: Int) {
        logger.debug("Visiting inner class: {}", name)
        val innerClassFile = getInnerClassFile(name)

        if (innerClassFile.exists() && innerClassFile !in visitedClassFiles) {
          logger.debug("Adding new file to scan: ${innerClassFile.canonicalPath}")
          classFilesToScanQueue.addLast(innerClassFile)
        }
      }

      private fun getInnerClassFile(name: String): File {
        val innerClassFilename = "${name.substring(name.lastIndexOf('/') + 1)}.class"
        return classFile.parentFile.resolve(innerClassFilename)
      }
    }

    ClassReader(BufferedInputStream(classFile.inputStream())).accept(classVisitor, 0)

    return ClassStructure(
      classInfo.packageName,
      classInfo.className,
      superClass,
      outInterfaces.toList(),
      outFields,
      outMethods,
      outRelationships.toList(),
      topLevelType,
    )
  }
}

val Opcode.isIntInsn: Boolean
  get() {
    return this == Opcodes.ICONST_M1 ||
      this == Opcodes.ICONST_0 ||
      this == Opcodes.ICONST_1 ||
      this == Opcodes.ICONST_2 ||
      this == Opcodes.ICONST_3 ||
      this == Opcodes.ICONST_4 ||
      this == Opcodes.ICONST_5
  }

@Suppress("MagicNumber")
internal val Opcode.insn: String
  get() {
    return when (this) {
      Opcodes.RETURN -> "return"
      Opcodes.GETSTATIC -> "getstatic"
      Opcodes.PUTSTATIC -> "putstatic"
      Opcodes.PUTFIELD -> "putfield"
      Opcodes.GETFIELD -> "getfield"
      Opcodes.INVOKESPECIAL -> "invokespecial"
      Opcodes.INVOKEVIRTUAL -> "invokevirtual"
      Opcodes.INVOKESTATIC -> "invokestatic"
      Opcodes.INVOKEINTERFACE -> "invokeinterface"
      Opcodes.BIPUSH -> "bipush"
      Opcodes.ICONST_M1 -> "iconst_m1"
      Opcodes.ICONST_0 -> "iconst_0"
      Opcodes.ICONST_1 -> "iconst_1"
      Opcodes.ICONST_2 -> "iconst_2"
      Opcodes.ICONST_3 -> "iconst_3"
      Opcodes.ICONST_4 -> "iconst_4"
      Opcodes.ICONST_5 -> "iconst_5"
      Opcodes.IF_ICMPNE -> "if_icmpne"
      Opcodes.ARETURN -> "areturn"
      else -> "unmapped (${"0x%02x".format(this)})"
    }
  }
package com.legendsayantan.adbtools.lib

/**
 * @author legendsayantan
 */
import moe.shizuku.server.IShizukuService
import rikka.shizuku.Shizuku
import java.io.BufferedReader
import java.io.FileInputStream
import java.io.InputStreamReade


// SPDX-License-Identifier: GPL-2.0+
/*
 * This file contains the jiffies based clocksource.
 *
 * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
 */
#include <linux/clocksource.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/init.h>

#include "timekeeping.h"
#include "tick-internal.h"

static u64 jiffies_read(struct clocksource *cs)
{
	return (u64) jiffies;
}

/*
 * The Jiffies based clocksource is the lowest common
 * denominator clock source which should function on
 * all systems. It has the same coarse resolution as
 * the timer interrupt frequency HZ and it suffers
 * inaccuracies caused by missed or lost timer
 * interrupts and the inability for the timer
 * interrupt hardware to accurately tick at the
 * requested HZ value. It is also not recommended
 * for "tick-less" systems.
 */
static struct clocksource clocksource_jiffies = {
	.name			= "jiffies",
	.rating			= 1, /* lowest valid rating*/
	.uncertainty_margin	= 32 * NSEC_PER_MSEC,
	.read			= jiffies_read,
	.mask			= CLOCKSOURCE_MASK(32),
	.mult			= TICK_NSEC << JIFFIES_SHIFT, /* details above */
	.shift			= JIFFIES_SHIFT,
	.max_cycles		= 10,
};

__cacheline_aligned_in_smp DEFINE_RAW_SPINLOCK(jiffies_lock);
__cacheline_aligned_in_smp seqcount_raw_spinlock_t jiffies_seq =
	SEQCNT_RAW_SPINLOCK_ZERO(jiffies_seq, &jiffies_lock);

#if (BITS_PER_LONG < 64)
u64 get_jiffies_64(void)
{
	unsigned int seq;
	u64 ret;

	do {
		seq = read_seqcount_begin(&jiffies_seq);
		ret = jiffies_64;
	} while (read_seqcount_retry(&jiffies_seq, seq));
	return ret;
}
EXPORT_SYMBOL(get_jiffies_64);
#endif

EXPORT_SYMBOL(jiffies);

static int __init init_jiffies_clocksource(void)
{
	return __clocksource_register(&clocksource_jiffies);
}

core_initcall(init_jiffies_clocksource);

struct clocksource * __init __weak clocksource_default_clock(void)
{
	return &clocksource_jiffies;
}

static struct clocksource refined_jiffies;

int register_refined_jiffies(long cycles_per_second)
{
	u64 nsec_per_tick, shift_hz;
	long cycles_per_tick;

	refined_jiffies = clocksource_jiffies;
	refined_jiffies.name = "refined-jiffies";
	refined_jiffies.rating++;

	/* Calc cycles per tick */
	cycles_per_tick = (cycles_per_second + HZ/2)/HZ;
	/* shift_hz stores hz<<8 for extra accuracy */
	shift_hz = (u64)cycles_per_second << 8;
	shift_hz += cycles_per_tick/2;
	do_div(shift_hz, cycles_per_tick);
	/* Calculate nsec_per_tick using shift_hz */
	nsec_per_tick = (u64)NSEC_PER_SEC << 8;
	nsec_per_tick += (u32)shift_hz/2;
	do_div(nsec_per_tick, (u32)shift_hz);

	refined_jiffies.mult = ((u32)nsec_per_tick) << JIFFIES_SHIFT;

	__clocksource_register(&refined_jiffies);
	return 0;
}


nh 1:** Hình dạng đường cong phân phối Gaussian với các cặp tham số $(\mu, \sigma^2)$ khác nhau. Source: [wikipedia - Normal Distribution](https://en.wikipedia.org/wiki/Normal_distribution)

Đồng thời theo phương pháp ước lượng hợp lý tối đa [MLE](https://phamdinhkhanh.github.io/deepai-book/ch_ml/NaiveBayes.html#) ta cũng chứng minh được rằng $\hat{\mu} = \mathbb{E}(x)$ và $\hat{\sigma}^2 = \mathbb{Var}(x)$ là những ước lượng tham số phù hợp nhất đối với phân phối theo Gaussian của biến $x$ mà theo đó xác suất xảy ra của dữ liệu là lớn nhất.

Phân phối Gaussian là phân phối đối với dữ liệu một chiều. Trong trường hợp dữ liệu nhiều hơn một chiều thì chúng ta sẽ khái quát hoá phân phối Gaussian dưới dạng _phân phối Gaussian đa chiều_ (_Multivariate Gaussian Distribution_). Cụ thể là trong không gian $d$ chiều thì một biểu diễn _phân phối Gaussian đa chiều_ của véc tơ $\mathbf{x} = (x_1, x_2, \dots, x_d)$ được định nghĩa là:

$$f_{\mathbf{x}}(x_1, x_2, \dots, x_d) = \frac{1}{(2\pi)^{d/2}\sqrt{|\mathbf{\Sigma}|}} \exp{ \left( -\frac{1}{2}(\mathbf{x}-\mu)^{\intercal} \mathbf{\Sigma}^{-1}(\mathbf{x}-\mu) \right) }$$

Hoặc chúng ta cũng có thể viết:

$$N(\mathbf{x} | \mu, \mathbf{\Sigma}) = \frac{1}{(2\pi)^{d/2}\sqrt{|\mathbf{\Sigma}|}} \exp{ \left( -\frac{1}{2}(\mathbf{x}-\mu)^{\intercal} \mathbf{\Sigma}^{-1}(\mathbf{x}-\mu) \right) }$$

Trong đó $\mu$ là véc tơ kì vọng theo các chiều của $\mathbf{x}$ và $\mathbf{\Sigma}$ là _ma trận hiệp phương sai_ (_covariance matrix_). _Ma trận hiệp phương sai_ của véc tơ ngẫu nhiên $\mathbf{x} = (x_1, x_2, \dots, x_d)$ có công thức như sau:

+++ {"id": "Kj3TmdM8kll_"}

$$\mathbb{Cov}(\mathbf{x}) = \begin{bmatrix}
\mathbb{Cov}(x_1, x_1) & \mathbb{Cov}(x_1, x_2) & \dots & \mathbb{Cov}(x_1, x_d) \\
\mathbb{Cov}(x_2, x_1) & \mathbb{Cov}(x_2, x_2) & \dots & \mathbb{Cov}(x_2, x_d) \\
\vdots & \vdots & \ddots & \vdots \\
\mathbb{Cov}(x_d, x_1) & \mathbb{Cov}(x_d, x_2) & \dots & \mathbb{Cov}(x_d, x_d) \\
\end{bmatrix}$$

+++ {"id": "zo


 int power_supply_property_is_writeable(struct power_supply *psy,
					enum power_supply_property psp);
extern void power_supply_external_power_changed(struct power_supply *psy);

extern struct power_supply *__must_check
power_supply_register(struct device *parent,
				 const struct power_supply_desc *desc,
				 const struct power_supply_config *cfg);
extern struct power_supply *__must_check
power_supply_register_no_ws(struct device *parent,
				 const struct power_supply_desc *desc,
				 const struct power_supply_config *cfg);
extern struct power_supply *__must_check
devm_power_supply_register(struct device *parent,
				 const struct power_supply_desc *desc,
				 const struct power_supply_config *cfg);
extern struct power_supply *__must_check
devm_power_supply_register_no_ws(struct device *parent,
				 const struct power_supply_desc *desc,
				 const struct power_supply_config *cfg);
extern void power_supply_unregister(struct power_supply *psy);
extern int power_supply_powers(struct power_supply *psy, struct device *dev);

#define to_power_supply(device) container_of(device, struct power_supply, dev)

extern void *power_supply_get_drvdata(struct power_supply *psy);
/* For APM emulation, think legacy userspace. */
extern struct class *power_supply_class;

static inline bool power_supply_is_amp_property(enum power_supply_property psp)
{
	switch (psp) {
	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
	case POWER_SUPPLY_PROP_CHARGE_EMPTY_DESIGN:
	case POWER_SUPPLY_PROP_CHARGE_FULL:
	case POWER_SUPPLY_PROP_CHARGE_EMPTY:
	case POWER_SUPPLY_PROP_CHARGE_NOW:
	case POWER_SUPPLY_PROP_CHARGE_AVG:
	case POWER_SUPPLY_PROP_CHARGE_COUNTER:
	case POWER_SUPPLY_PROP_PRECHARGE_CURRENT:
	case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT:
	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT:
	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
	case POWER_SUPPLY_PROP_CURRENT_MAX:
	case POWER_SUPPLY_PROP_CURRENT_NOW:
	case POWER_SUPPLY_PROP_CURRENT_AVG:
	case POWER_SUPPLY_PROP_CURRENT_BOOT:
		return 1;
	default:
		break;
	}

	return 0;
}

static inline bool power_supply_is_watt_property(enum power_supply_property psp)
{
	switch (psp) {
	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
	case POWER_SUPPLY_PROP_ENERGY_EMPTY_DESIGN:
	case POWER_SUPPLY_PROP_ENERGY_FULL:
	case POWER_SUPPLY_PROP_ENERGY_EMPTY:
	case POWER_SUPPLY_PROP_ENERGY_NOW:
	case POWER_SUPPLY_PROP_ENERGY_AVG:
	case POWER_SUPPLY_PROP_VOLTAGE_MAX:
	case POWER_SUPPLY_PROP_VOLTAGE_MIN:
	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
	case POWER_SUPPLY_PROP_VOLTAGE_AVG:
	case POWER_SUPPLY_PROP_VOLTAGE_OCV:
	case POWER_SUPPLY_PROP_VOLTAGE_BOOT:
	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
	case POWER_SUPPLY_PROP_POWER_NOW:
		return 1;
	default:
		break;
	}

	return 0;
}

#endif /* __LINUX_POWER_SUPPLY_H__ */


lineByPropertyName = true, Position = 0)]
        public Uri ServiceName
        {
            get;
            set;
        }

        [Parameter(Mandatory = false)]
        public SwitchParameter Force
        {
            get;
            set;
        }

        protected override void ProcessRecord()
        {
            if (this.ShouldProcess(this.ServiceName.OriginalString))
            {
                if (this.Force || this.ShouldContinue(string.Empty, string.Empty))
                {
                    this.RemoveServiceGroup(this.ServiceName);
                }
            }
        }
    }
}


#include <cxxtest/TestSuite.h>

//
// A simple test suite that cannot be parsed with the default test discovery mechanism
//

class BadTest
    :
public CxxTest::TestSuite
{
public:
    void testEquality()
    {
        TS_ASSERT_EQUALS(1, 1);
        TS_ASSERT_EQUALS(1, 2);
        TS_ASSERT_EQUALS('a', 'A');
        TS_ASSERT_EQUALS(1.0, -12345678900000000000000000000000000000000000000000.1234);
    }

    void testAddition()
    {
        TS_ASSERT_EQUALS(1 + 1, 2);
        TS_ASSERT_EQUALS(2 + 2, 5);
    }

    void TestMultiplication()
    {
        TS_ASSERT_EQUALS(2 * 2, 4);
        TS_ASSERT_EQUALS(4 * 4, 44);
        TS_ASSERT_DIFFERS(-2 * -2, 4);
    }

    void testComparison()
    {
        TS_ASSERT_LESS_THAN((int)1, (unsigned long)2);
        TS_ASSERT_LESS_THAN(-1, -2);
    }

    void testTheWorldIsCrazy()
    {
        TS_ASSERT_EQUALS(true, false);
    }

    void test_Failure()
    {
        TS_FAIL("Not implemented");
        TS_FAIL(1569779912);
    }

    void test_TS_WARN_macro()
    {
        TS_WARN("Just a friendly warning");
        TS_WARN("Warnings don't abort the test");
    }
};