items:center;color:#1c8145;display:inline-flex;line-height:2em;justify-content:flex-start}.nx-routing-rules-single-preview-field-wrapper .nx-routing-rules-test-result span.x-fa{align-items:center;display:inline-flex;font-size:1.5em;padding-right:5px}.nx-routing-rules-single-preview-field-wrapper.blocked .nx-routing-rules-test-result{color:#c70000}.nx-routing-rules-single-preview-field-wrapper.blocked .nx-routing-rules-test-path-container > .x-form-item-body{border-color:#c70000}.nx-routing-rules-single-preview-field-wrapper.allowed .nx-routing-rules-test-path-container > .x-form-item-body{border-color:#1c8145}.nx-coreui-searchfeature .criteria{background-color:#fff;padding:0 0 10px 10px}.nx-coreui-searchfeature .criteria .more-criteria{margin:26px 0 0 0}.nx-user-token-field{padding:2px;font-family:"Courier New", Courier, monospace;font-size:16px}/*!
 *  Font Awesome 4.3.0 by @davegandy - http://fontawesome.io - @fontawesome
 *  License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
 */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.3.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.3.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.3.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.3.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.3.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.3.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;transform:translate(0, 0)}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframe


ate.z)
						if (fatedist <= fate.radius) then
							local dist3d = Distance3D(epos.x,epos.y,epos.z,myPos.x,myPos.y,myPos.z)
							if (not nearest or dist3d < nearestDistance) then
								nearest, nearestDistance = entity, dist3d
							end
						end
					end
				end
			end

			local fatenpc = EntityList("targetable,type=3,chartype=5")
			if (table.valid(fatenpc)) then
				for i,entity in pairs(fatenpc) do
					if entity.fateid == fateid then
						local gatherable = ffxiv_task_fate.Gatherable(Player.localmapid, fateid)
						if (gatherable) then
							local pickupitem = MEntityList("nearest,targetable,contentid="..tostring(gatherable.itemid))
							if (table.valid(pickupitem)) then
								for id,item in pairs(pickupitem) do
									local ipos = item.pos
									local dist3d = Distance3D(ipos.x,ipos.y,ipos.z,myPos.x,myPos.y,myPos.z)
									if (not nearest or dist3d < nearestDistance) then

										e_pickupItem.contentid = item.contentid
										e_pickupItem.itempos = ipos
										return true
									end
								end
							end
						end
					end
				end
			end
		end
	end
	return false
end

function e_pickupItem:execute()
	local newTask = ffxiv_task_movetointeract.Create()
	newTask.contentid = e_pickupItem.contentid
	newTask.pos = e_pickupItem.itempos
	ml_task_hub:CurrentTask():AddSubTask(newTask)
end

c_add_fatetarget = inheritsFrom( ml_cause )
e_add_fatetarget = inheritsFrom( ml_effect )
c_add_fatetarget.oocCastTimer = 0
c_add_fatetarget.throttle = 500
function c_add_fatetarget:evaluate()
	if not Player.onmesh then
		return false
	end
	if (not Player.incombat) then
		if (SkillMgr.Cast(Player, true)) then
			c_add_fatetarget.oocCastTimer = Now() + 1500
			return false
		end

		if (MIsCasting() or Now() < c_add_fatetarget.oocCastTimer) then
			return false
		end
	end

	local fate = MGetFateByID(ml_task_hub:CurrentTask().fateid)
	if (table.valid(fate)) then
		if (fate.status == 2) then
			--d("status:"..tostring(fate.status))
			--d("completion:"..tostring(fate.completion))
			--d("name:"..tostring(fate.name))

			local myPos = Player.pos
			local fatePos = {x = fate.x, y = fate.y, z = fate.z}

			local dist = PDistance3D(myPos.x,myPos.y,myPos.z,fatePos.x,fatePos.y,fatePos.z)
			if (Player.level <= fate.maxlevel or dist < fate.radius) then
				local target = GetNearestFateAttackable()
				if (table.valid(target)) then
					c_add_fatetarget.targetid = target.id
					return true
				else
					--d("no nearest fate attackable")
				end
			end
		end
	end

    return false
end
function e_add_fatetarget:execute()
	--d("Adding a new fate target.")
	local newTask = ffxiv_task_grindCombat.Create()
	newTask.betterTargetFunction = GetNearestFateAttackable
	newTask.t


.key())
            .collect::<Vec<_>>();

        let expected = items
            .iter()
            .cloned()
            .filter(|x| *x != 6)
            .collect::<Vec<_>>();
        assert_eq!(v.len(), expected.len());
        expected
            .iter()
            .zip(v.iter())
            .for_each(|(a, b)| assert!(equal_f32(*a as f32, *b)));
    }

    let t7 = t6.remove();

    assert!(equal_f32(t7.key(), 3.));

    let t8 = t7.remove();

    assert!(equal_f32(t8.key(), 1.));

    let t9 = t8.remove();

    assert!(equal_f32(t9.key(), 7.));

    let t10 = t9.remove();

    assert_eq!(true, t10.0.borrow().invalid);

    //query on empty tree
    {
        match t10.search(0.) {
            SearchResult::Empty => {}
            _ => {
                panic!("unexpected search result");
            }
        }
        let v = t10
            .query_key_range(-10., 10.)
            .iter()
            .map(|x| x.key())
            .collect::<Vec<_>>();

        assert_eq!(v.len(), 0);
    }
}

#[test]
fn test_treap_insert_remove_by_key() {
    fn equal_f32(a: f32, b: f32) -> bool {
        if a - 1e-4 < b && a + 1e-4 > b {
            true
        } else {
            false
        }
    }

    let mut t = NodePtr::new();

    {
        let v = t
            .query_key_range(-100., 100.)
            .iter()
            .map(|x| x.key())
            .collect::<Vec<_>>();

        assert_eq!(v.len(), 0);
    }

    let items = vec![56, -45, 1, 6, 9, -30, 7, -9, 12, 77, -25];
    for i in items.iter() {
        t = t.insert(*i as f32, *i).0;
    }

    let mut expected = items.clone();
    expected.sort();

    {
        let v = t
            .query_key_range(-100., 100.)
            .iter()
            .map(|x| x.key())
            .collect::<Vec<_>>();

        assert_eq!(v.len(), expected.len());

        expected
            .iter()
            .zip(v.iter())
            .for_each(|(a, b)| assert!(equal_f32(*a as f32, *b)));
    }

    let l = items.len() / 2;
    for i in expected.iter().take(l) {
        t = t.remove_by_key(*i as f32);
    }

    {
        let f = expected.iter().skip(l).cloned().collect::<Vec<_>>();

        let v = t
            .query_key_range(-100., 100.)
            .iter()
            .map(|x| x.key())
            .collect::<Vec<_>>();

        assert_eq!(v.len(), f.len());

        f.iter()
            .zip(v.iter())
            .for_each(|(a, b)| assert!(equal_f32(*a as f32, *b)));
    }
}

#[test]
fn test_treap_remove_key_range() {
    fn equal_f32(a: f32, b: f32) -> bool {
        if a - 1e-4 < b && a + 1e-4 > b {
            true
        } else {
            false
        }
    }

    let mut t = NodePtr::new();

    {
        let v = t
            .query_key_range(-100., 100.)
            .iter()
            .map(|x| x.key())
            .collect::<Vec<_>>();


(i=new _D((!u.e&&(u.e=new g_(H7e,u,7,4)),u.e));i.e!=i.i.gc();){r=bG(iyn(i),74);o=new PO(bG(Yin((!r.a&&(r.a=new gV(U7e,r,6,6)),r.a),0),166).j,bG(Yin((!r.a&&(r.a=new gV(U7e,r,6,6)),r.a),0),166).k);c=new PO(bG(Yin((!r.a&&(r.a=new gV(U7e,r,6,6)),r.a),0),166).b,bG(Yin((!r.a&&(r.a=new gV(U7e,r,6,6)),r.a),0),166).c);a=new PO(c.a-o.a,c.b-o.b);e=t.Math.atan2(a.b,a.a);bG(Yin((!r.c&&(r.c=new g_(B7e,r,5,8)),r.c),0),84).qf((IOn(),YJe),e)}}function $Xn(n,e){var r,i,a,c,u,o,s,f,h;e.Ug("Interactive Node Reorderer",1);h=(!n.a&&(n.a=new gV(ont,n,10,11)),n.a);o=new im;for(a=new _D(h);a.e!=a.i.gc();){r=bG(iyn(a),27);jnn(r,(A_n(),pZe))&&(Tm(o.c,r),true)}for(c=new nd(o);c.a<c.c.c.length;){r=bG(K3(c),27);srn(h,r)}dZ();g$(o,new Bu);for(u=new nd(o);u.a<u.c.c.length;){r=bG(K3(u),27);f=bG(YDn(r,(A_n(),pZe)),17).a;f=t.Math.min(f,h.i);Fdn(h,f,r)}s=0;for(i=new _D(h);i.e!=i.i.gc();){r=bG(iyn(i),27);Pyn(r,(A_n(),vZe),Bwn(s));++s}e.Vg()}function DXn(n,e,r){var i,a,c,u,o,s,f,h;if(t.Math.abs(e.s-e.c)<n4n||t.Math.abs(r.s-r.c)<n4n){return 0}i=GKn(n,e.j,r.e);a=GKn(n,r.j,e.e);c=i==-1||a==-1;u=0;if(c){if(i==-1){new x2((q7(),kXe),r,e,1);++u}if(a==-1){new x2((q7(),kXe),e,r,1);++u}}else{o=zwn(e.j,r.s,r.c);o+=zwn(r.e,e.s,e.c);s=zwn(r.j,e.s,e.c);s+=zwn(e.e,r.s,r.c);f=i+16*o;h=a+16*s;if(f<h){new x2((q7(),yXe),e,r,h-f)}else if(f>h){new x2((q7(),yXe),r,e,f-h)}else if(f>0&&h>0){new x2((q7(),yXe),e,r,0);new x2(yXe


enum BackupType {
  automatic('AUTOMATIC'),
  userInitiated('USER_INITIATED'),
  awsBackup('AWS_BACKUP'),
  ;

  final String value;

  const BackupType(this.value);

  static BackupType fromString(String value) => values.firstWhere(
      (e) => e.value == value,
      orElse: () => throw Exception('$value is not known in enum BackupType'));
}

class CancelDataRepositoryTaskResponse {
  /// The lifecycle status of the data repository task, as follows:
  ///
  ///

  ///

  /// PENDING - Amazon FSx has not started the task.
  ///

  ///

  /// EXECUTING - Amazon FSx is processing the task.
  ///

  ///

  /// FAILED - Amazon FSx was not able to complete the task. For
  /// example, there may be files the task failed to process. The
  /// DataRepositoryTaskFailureDetails property provides more information
  /// about task failures.
  ///

  ///

  /// SUCCEEDED - FSx completed the task successfully.
  ///

  ///

  /// CANCELED - Amazon FSx canceled the task and it did not
  /// complete.
  ///

  ///

  /// CANCELING - FSx is in process of canceling the task.
  ///

  ///

  final DataRepositoryTaskLifecycle? lifecycle;

  /// The ID of the task being canceled.
  final String? taskId;

  CancelDataRepositoryTaskResponse({
    this.lifecycle,
    this.taskId,
  });

  factory CancelDataRepositoryTaskResponse.fromJson(Map<String, dynamic> json) {
    return CancelDataRepositoryTaskResponse(
      lifecycle: (json['Lifecycle'] as String?)
          ?.let(DataRepositoryTaskLifecycle.fromString),
      taskId: json['TaskId'] as String?,
    );
  }
}

/// Provides a report detailing the data repository task results of the files
/// processed that match the criteria specified in the report Scope
/// parameter. FSx delivers the report to the file system's linked data
/// repository in Amazon S3, using the path specified in the report
/// Path parameter. You can specify whether or not a report gets
/// generated for a task using the Enabled parameter.
class CompletionReport {
  /// Set Enabled to True to generate a
  /// CompletionReport when the task completes. If set to
  /// true, then you need to provide a report Scope,
  /// Path, and Format. Set Enabled to
  /// False if you do not want a CompletionReport
  /// generated when the task completes.
  final bool enabled;

  /// Required if Enabled is set to true. Specifies the
  /// format of the CompletionReport.
  /// REPORT_CSV_20191124 is the only format currently supported.
  /// When Format is set to REPORT_CSV_20191124, the
  /// CompletionReport is provided in CSV format, and is delivered to
  /// {path}/task-{id}/failures.csv.
  final ReportFormat? format;

  /// Required if Enabled is set to true. Specifies the
  /// location of the report on the file system's linked S3 data repository. An
  /// absolute path that defines where the completion report will be stored in the
  /// destination location. The Path you provide must be located
  /// within the file system’s ExportPath. An example Path value is
  /// "s3://myBucket/my


    * @type {Object}
       */
      static get TIME_24_WITH_SHORT_OFFSET() {
        return TIME_24_WITH_SHORT_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
       * @type {Object}
       */
      static get TIME_24_WITH_LONG_OFFSET() {
        return TIME_24_WITH_LONG_OFFSET2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_SHORT() {
        return DATETIME_SHORT2;
      }
      /**
       * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_SHORT_WITH_SECONDS() {
        return DATETIME_SHORT_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED() {
        return DATETIME_MED2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED_WITH_SECONDS() {
        return DATETIME_MED_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_MED_WITH_WEEKDAY() {
        return DATETIME_MED_WITH_WEEKDAY2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_FULL() {
        return DATETIME_FULL2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_FULL_WITH_SECONDS() {
        return DATETIME_FULL_WITH_SECONDS2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_HUGE() {
        return DATETIME_HUGE2;
      }
      /**
       * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
       * @type {Object}
       */
      static get DATETIME_HUGE_WITH_SECONDS() {
        return DATETIME_HUGE_WITH_SECONDS2;
      }
    };
    function friendlyDateTime2(dateTimeish) {
      if (DateTime2.isDateTime(dateTimeish)) {
        return dateTimeish;
      } else if (dateTimeish && dateTimeish.valueOf && isNumber2(dateTimeish.valueOf())) {
        return DateTime2.fromJSDate(dateTimeish);
      } else if (dateTimeish && typeof dateTimeish === "object") {
        return DateTime2.fromObject(dateTimeish);
      } else {
        throw new InvalidArgumentError2(
          `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
        );
      }
    }
    var DEFAULT_QUERY_SETTINGS = {
      renderNullAs: "\\-",


拜访牛头人酋长乐队。如果你抵达时发现她不在身边，记得要先召唤她。"}},
[11976] = {"冰片", nil, {"将冰片交给鲁玛·天母。"}},
[11977] = {"牦牛人中的牛头人", nil, {"在西风避难营内找到特使艾米萨·闪蹄。"}},
[11978] = {"深入密林", nil, {"龙骨荒野西风避难营的特使艾米萨·闪蹄要求你找回10套部落军备。"}},
[11979] = {"牦牛人和牛头人", nil, {"在西风避难营内找到特使艾米萨·闪蹄。"}},
[11980] = {"部落的荣耀", nil, {"龙骨荒野西风避难营的血卫士洛恩基尔要求你消灭15只阿努巴尔伏击者。"}},
[11981] = {"找到库伦！", nil, {"前往俯瞰索尔莫丹的丘陵地带，在那里找到库伦。"}},
[11982] = {"巨石横飞", nil, {"在丘陵上俯瞰索尔莫丹的库伦要求你向索尔莫丹的露天区域投掷石块，以此骚扰铁矮人的挖掘工作。"}},
[11983] = {"部落的血誓", nil, {"与西风避难营的牛头人交谈，并收集5份他们对部落的效忠宣誓书。\n\n完成任务之后，带着部落的血誓向特使艾米萨·闪蹄复命。"}},
[11984] = {"抓巨魔", nil, {"岩石之泉的萨米尔希望你对被巴德打昏的达卡莱巨魔使用赏金猎人的笼子。"}},
[11985] = {"攻破防线", nil, {"库伦要你杀死指挥官阿格鲁姆，然后返回鸟瞰索尔莫丹的小山坡向他复命。"}},
[11986] = {"破损的日记", nil, {"找到8张遗失的日记书页，将它们与不完整的日记拼凑起来，然后将日记交给月溪旅营地的托尔森·迪普迪格。"}},
[11987] = {"幸运卡片：白银", nil, nil},
[11988] = {"符文钥石", nil, {"将5块符文钥石碎片交给月溪旅营地的托尔森·迪普迪格。"}},
[11989] = {"停战？", nil, {"岩石之泉的达库鲁希望你在他的笼子附近使用钝刻刀，然后和他对话。"}},
[11990] = {"幻象之瓶", nil, {"岩石之泉的达库鲁希望你把一只水晶瓶、一片水草叶和3片薄雾叶交给他。"}},
[11991] = {"解读象


UMBER = 1;
    private java.util.List<org.openkilda.server42.control.messaging.islrtt.IslRttControl.IslEndpoint> isl_;
    /**
     * repeated .org.openkilda.server42.control.messaging.islrtt.IslEndpoint isl = 1;
     */
    public java.util.List<org.openkilda.server42.control.messaging.islrtt.IslRttControl.IslEndpoint> getIslList() {
      return isl_;
    }
    /**
     * repeated .org.openkilda.server42.control.messaging.islrtt.IslEndpoint isl = 1;
     */
    public java.util.List<? extends org.openkilda.server42.control.messaging.islrtt.IslRttControl.IslEndpointOrBuilder>
        getIslOrBuilderList() {
      return isl_;
    }
    /**
     * repeated .org.openkilda.server42.control.messaging.islrtt.IslEndpoint isl = 1;
     */
    public int getIslCount() {
      return isl_.size();
    }
    /**
     * repeated .org.openkilda.server42.control.messaging.islrtt.IslEndpoint isl = 1;
     */
    public org.openkilda.server42.control.messaging.islrtt.IslRttControl.IslEndpoint getIsl(int index) {
      return isl_.get(index);
    }
    /**
     * repeated .org.openkilda.server42.control.messaging.islrtt.IslEndpoint isl = 1;
     */
    public org.openkilda.server42.control.messaging.islrtt.IslRttControl.IslEndpointOrBuilder getIslOrBuilder(
        int index) {
      return isl_.get(index);
    }

    private byte memoizedIsInitialized = -1;
    @java.lang.Override
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized == 1) return true;
      if (isInitialized == 0) return false;

      memoizedIsInitialized = 1;
      return true;
    }

    @java.lang.Override
    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      for (int i = 0; i < isl_.size(); i++) {
        output.writeMessage(1, isl_.get(i));
      }
      unknownFields.writeTo(output);
    }

    @java.lang.Override
    public int getSerializedSize() {
      int size = memoizedSize;
      if (size != -1) return size;

      size = 0;
      for (int i = 0; i < isl_.size(); i++) {
        size += com.google.protobuf.CodedOutputStream
          .computeMessageSize(1, isl_.get(i));
      }
      size += unknownFields.getSerializedSize();
      memoizedSize = size;
      return size;
    }

    @java.lang.Override
    public boolean equals(final java.lang.Object obj) {
      if (obj == this) {
       return true;
      }
      if (!(obj instanceof org.openkilda.server42.control.messaging.islrtt.IslRttControl.ListIsls)) {
        return super.equals(obj);
      }
      org.openkilda.server42.control.messaging.islrtt.IslRttControl.ListIsls other = (org.openkilda.server42.control.messaging.islrtt.IslRttControl.ListIsls) obj;

      if (!getIslList()
          .equals(other.getIslList())) return false;
      if (!unknownFields.equals(other.unknownFields)) return false;
      return true;
    }

    @java.lang.Override
    public int hashCode() {
      if (memoizedHashCode != 0) {
        return memoizedHashCode;
      }
      int hash = 41;
      hash = (19 * hash) + getDescriptor().hashCode();
      if (getIslCount() > 0) {
        hash = (37 * hash) + ISL_FIELD_NUMBER


 != nil {
            m.SetActionState(val.(*ActionState))
        }
        return nil
    }
    res["lastUpdatedDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetTimeValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetLastUpdatedDateTime(val)
        }
        return nil
    }
    res["@odata.type"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetOdataType(val)
        }
        return nil
    }
    res["startDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetTimeValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetStartDateTime(val)
        }
        return nil
    }
    return res
}
// GetLastUpdatedDateTime gets the lastUpdatedDateTime property value. Time the action state was last updated
// returns a *Time when successful
func (m *DeviceActionResult) GetLastUpdatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
    return m.lastUpdatedDateTime
}
// GetOdataType gets the @odata.type property value. The OdataType property
// returns a *string when successful
func (m *DeviceActionResult) GetOdataType()(*string) {
    return m.odataType
}
// GetStartDateTime gets the startDateTime property value. Time the action was initiated
// returns a *Time when successful
func (m *DeviceActionResult) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
    return m.startDateTime
}
// Serialize serializes information the current object
func (m *DeviceActionResult) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
    {
        err := writer.WriteStringValue("actionName", m.GetActionName())
        if err != nil {
            return err
        }
    }
    if m.GetActionState() != nil {
        cast := (*m.GetActionState()).String()
        err := writer.WriteStringValue("actionState", &cast)
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteTimeValue("lastUpdatedDateTime", m.GetLastUpdatedDateTime())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("@odata.type", m.GetOdataType())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteTimeValue("startDateTime", m.GetStartDateTime())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteAdditionalData(m.GetAdditionalData())
        if err != nil {
            return err
        }
    }
    return nil
}
// SetActionName sets the actionName property value. Action name
func (m *DeviceActionResult)


// Copyright (c) Duende Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;

namespace ResourcesScopesConsoleClient
{
    class Program
    {
        private static DiscoveryCache Cache;

        static async Task Main(string[] args)
        {
            Console.Title = "Console Token Exchange Client";
            Cache = new DiscoveryCache("https://localhost:5001");

            // initial token
            var response = await RequestTokenAsync();
            var initialToken = response.AccessToken;

            "\n\nInitial token:".ConsoleYellow();
            response.Show();
            Console.ReadLine();

            response = await DelegateToken(initialToken, "impersonation");

            "\n\nImpersonation style:".ConsoleYellow();
            response.Show();
            Console.ReadLine();

            response = await DelegateToken(initialToken, "delegation");

            "\n\nDelegation style:".ConsoleYellow();
            response.Show();
            Console.ReadLine();

            response = await DelegateToken(initialToken, "custom");

            "\n\nCustom style:".ConsoleYellow();
            response.Show();
        }

        static async Task<TokenResponse> RequestTokenAsync()
        {
            var client


a) * b;

const res = traverse(R.Applicative)(test)(['1', '2', '3'])(3);
const res1 = R.traverseArray(test)(['1', '2', '3'])(3);

const res01 = sequence(R.Applicative)([test('1'), test('2'), test('3')])(3);
const res02 = R.sequenceArray([test('1'), test('2'), test('3')])(3);

console.log(res, res1);

const test1: (b: number) => Task<number> = (b) => () =>
  new Promise<number>((r) => r(b * 2));
const res2 = traverse(T.ApplicativePar)(test1)([1, 2, 3])();
const res3 = T.traverseArray(test1)([1, 2, 3])();

const res21 = sequence(T.ApplicativePar)([test1(1), test1(2), test1(3)])();
const res22 = T.sequenceArray([test1(1), test1(2), test1(3)])();

const test22: (b: number) => Task<string> = (b) => () =>
  new Promise((r) => {
    setTimeout(() => {
      console.log('test22');
      r(String(b * 2));
    }, 200);
  });
const test23: (b: number) => Task<boolean> = (b) => () =>
  new Promise((r) => {
    setTimeout(() => {
      console.log('test23');
      r(b * 2 > 2);
    }, 100);
  });

// 依次执行
const res23 = sequenceT(T.ApplicativeSeq)(test22(1), test23(2))();

const testRE1: (a: string) => ReaderTaskEither<number, Error, string> =
  (a) => (b) =>
    tryCatch(
      () => new Promise((r) => r(String(Number(a) * b))),
      () => new Error('e')
    );
const testRE2: (a: string) => ReaderTaskEither<number, Error, number> =
  (a) => (b) =>
    tryCatch(
      () => new Promise((r) => r(Number(a) * b)),
      () => new Error('e')
    );

const resRE = sequenceT(RTE.ApplicativePar)(testRE1('1'), testRE2('2'))(2)();

// 不同返回类型无法进行，只能使用 sequenceT
// const resRE = RTE.sequenceSeqArray([testRE1('1'), testRE2('2')])(2)();

console.log(resRE);

console.log(res, res1);
import nacl from 'tweetnacl';
import type {SignKeyPair as KeyPair} from 'tweetnacl';
import type {Buffer} from 'buffer';

import {toBuffer} from './util/to-buffer';
import {PublicKey} from './publickey';

/**
 * An account key pair (public and secret keys).
 *
 * @deprecated since v1.10.0, please use {@link Keypair} instead.
 */
export class Account {
  /** @internal */
  _keypair: KeyPair;

  /**
   * Create a new Account object
   *
   * If the secretKey parameter is not provided a new key pair is randomly
   * created for the account
   *
   * @param secretKey Secret key for the account
   */
  constructor(secretKey?: Buffer | Uint8Array | Array<number>) {
    if (secretKey) {
      this._keypair = nacl.sign.keyPair.fromSecretKey(toBuffer(secretKey));
    } else {
      this._keypair = nacl.sign.keyPair();
    }
  }

  /**
   * The public key for this account
   */
  get publicKey(): PublicKey {
    return new PublicKey(this._keypair.publicKey);
  }

  /**
   * The **unencrypted** secret key for this account
   */
  get secretKey(): Buffer {
    return toBuffer(this._keypair.secretKey);
  }
}
import {Component, ComponentState} from "./Component";
import {ComponentType} from "../../Enum";

export interface TileState extends ComponentState{
  isSeen: boolean;
  isEntry: boolean;
}

export interface TileComponent extends Component<TileState>{
  state: T


 0)
SAS(SI_GROUPFINDERMEMBERALERT1, "Gruppengesuch wurde vom Gruppenleiter entfernt.", 0)
SAS(SI_GROUPFINDERMEMBERALERT2, "Gruppengesuch entfernt: Serverfehler.", 0)
SAS(SI_GROUPFINDERMEMBERALERT3, "Gruppengesuch entfernt: Nicht-öffentliches Gebiet.", 0)
SAS(SI_GROUPFINDERMEMBERALERT4, "Gruppengesuch entfernt: Ihr seid einer Warteschlange beigetreten.", 0)
SAS(SI_GROUPFINDERMEMBERALERT5, "Gruppengesuch entfernt: Gruppenleiter hat die Verbindung verloren.", 0)
SAS(SI_GROUPFINDERMEMBERALERT6, "Gruppengesuch entfernt: Der Gruppenleiter hat sich geändert.", 0)
SAS(SI_GROUPFINDERPLAYSTYLE1, "Normal", 1)
SAS(SI_GROUPFINDERPLAYSTYLE16, "Rollenspiel", 1)
SAS(SI_GROUPFINDERPLAYSTYLE2, "Lernen", 1)
SAS(SI_GROUPFINDERPLAYSTYLE32, "Erzählung", 0)
SAS(SI_GROUPFINDERPLAYSTYLE4, "Geschwindigkeit", 0)
SAS(SI_GROUPFINDERPLAYSTYLE8, "Errungenschaft", 0)
SAS(SI_GROUPINVITERESPONSE0, "Einladung fehlgeschlagen. Es konnte kein Spieler mit dem Namen „<<X:1>>“ auf dem Server gefunden werden.", 2)
SAS(SI_GROUPINVITERESPONSE1, "<<C:1>> hat Eure Guppeneinladung angenommen.", 2)
SAS(SI_GROUPINVITERESPONSE10, "Ihr habt <<1>> in die Gruppe eingeladen.", 0)
SAS(SI_GROUPINVITERESPONSE11, "Ihr könnt mit diesem Konto keine Gruppen erstellen.", 1)
SAS(SI_GROUPINVITERESPONSE12, "Ihr konntet der Gruppe nicht beitreten", 0)
SAS(SI_GROUPINVITERESPONSE13, "Ihr konntet Euch <<1>> nicht anschließen. Die Gruppe ist voll.", 0)
SAS(SI_GROUPINVITERESPONSE14, "Ihr konntet Euch <<1>> nicht anschließen. Ihr seid bereits in einer Gruppe.", 0)
SAS(SI_GROUPINVITERESPONSE15, "<<1>> ist derzeit auf einem Schlachtfeld.", 2)
SAS(SI_GROUPINVITERESPONSE16, "<<C:1>> hat Euch in eine Gruppe eingeladen. Ihr müsst Eure derzeitige Gruppe verlassen, um ihr beitreten zu können.", 1)
SAS(SI_GROUPINVITERESPONSE17, "Es ist nicht möglich, eine Einladung des Spielers anzufordern.", 1)
SAS(SI_GROUPINVITERESPONSE18, "Beitritt fehlgeschlagen. Ihr seid bereits in einer Gruppe.", 0)
SAS(SI_GROUPINVITERESPONSE19, "Einladung nicht verschickt. Bitte benutzt das Gruppen-Menü im Spiel.", 0)
SAS(SI_GROUPINVITERESPONSE2, "<<C:1>> hat Eure Gruppeneinladung abgelehnt.", 2)
SAS(SI_GROUPINVITERESPONSE20, "<<1>> hat eine offene Bewerbung für ein Gruppengesuch.", 0)
SAS(SI_GROUPINVITERESPONSE21, "<<1>> hat ein Gruppengesuch.", 0


x and #(GetEntityCoords(cache.ped) - vector3(garagecoord[tid].garage_x,garagecoord[tid].garage_y,garagecoord[tid].garage_z)) > 15 then
            SetEntityCoords(cache.ped, garagecoord[tid].garage_x,garagecoord[tid].garage_y,garagecoord[tid].garage_z, false, false, false, true)
        elseif propertyspawn.x and #(GetEntityCoords(cache.ped) - vector3(propertyspawn.x,propertyspawn.y,propertyspawn.z)) > 15 then
            SetEntityCoords(cache.ped, propertyspawn.x,propertyspawn.y,propertyspawn.z, false, false, false, true)
        end
        CloseNui()
    end

end

function OpenHeli(garageid)
    local ped = cache.ped
    while not fetchdone do
        Citizen.Wait(1)
    end
    local vehtable = {}
    for k,v2 in pairs(OwnedVehicles) do
        for k2,v in pairs(v2) do
            if vehtable[v.garage_id] == nil then
                vehtable[v.garage_id] = {}
            end
            veh = {
                brand = v.brand,
                name = v.name,
                brake = v.brake,
                handling = v.handling,
                topspeed = v.topspeed,
                power = v.power,
                torque = v.torque,
                model = v.model,
                model2 = v.model2,
                img = v.img,
                plate = v.plate,
                --props = v.props,
                fuel = v.fuel,
                bodyhealth = v.bodyhealth,
                enginehealth = v.enginehealth,
                garage_id = v.garage_id,
                impound = v.impound,
                ingarage = v.ingarage
            }
            table.insert(vehtable[v.garage_id], veh)
        end
    end
    SendNUIMessage(
        {
            garage_id = garageid,
            data = vehtable,
            type = "display",
            chopper = true
        }
    )
    SetNuiFocus(true, true)
    if not Config.Quickpick then
        for k,v in pairs(helispawn[garageid]) do
            local v = v.coords
            local dist = #(vector3(v.x,v.y,v.z) - GetEntityCoords(ped))
            if dist <= 10.0 then
                cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", v.x-8.0, v.y, v.z+0.6, 360.00, 0.00, 0.00, 60.00, false, 0)
                PointCamAtCoord(cam, v.x, v.y, v.z+2.0)
                SetCamActive(cam, true)
                RenderScriptCams(true, true, 1, true, true)
                SetFocusPosAndVel(v.x, v.y, v.z+4.0, 0.0, 0.0, 0.0)
                DisplayHud(false)
                DisplayRadar(false)
            end
        end
    end
    Wait(1000)
    inGarage = true
    while inGarage do
        Citizen.Wait(111)
        SetNuiFocusKeepInput(false)
        SetNuiFocus(true, true)
    end
    if LastVehicleFromGarage ~= nil then
        DeleteEntity(LastVehicleFromGarage)
    end
    SetNuiFocusKeepInput(false)
    SetNuiFocus(false, false)
end

function CreateDefault(default,jobonly,garage_type,garageid)
    patrolcars = {}
    local gstate = GlobalState and GlobalState.VehicleImages or {}
    for k,v in pairs(default) do
        if v.grade <= PlayerData.job.grade then
            local vehicleModel = GetHashKey(v.model)
            local pmult, tmult, handling, brake = 1000,800,GetPerformanceStats(vehicleModel).handling,GetPerformanceStats(vehicleModel).brakes


l
[mcache]: https://github.com/bytedance/gopkg/tree/develop/lang/mcache
[io_uring]: https://github.com/axboe/liburing
---
title: "Creating Service and Factory"
linkTitle: "Creating Service and Factory"
weight: 2
---

## Defining the Service and Factory
The `RoutingHandlerFactory` is responsible for creating and updating the `RoutingHandler` service instances. This factory implements the AsyncMakeService trait, allowing it to be used in a FactoryStack for service composition.

Let's start by defining the `RoutingHandler` service itself:
```rust
pub struct RoutingHandler<H> {
    inner: H,
    router: Router<RouteConfig>,
}
```
The `RoutingHandler` is responsible for matching incoming request paths against a set of predefined routes, selecting an appropriate upstream server, and forwarding the request to that server. It contains two fields:
    1. inner: The inner handler that processes requests after routing.
    2. router: A `matchit::Router` containing the routing configuration.

Now, let's look at the implementation of the RoutingHandlerFactory:
```rust
use monolake_services::http::handlers::route::{RoutingHandlerFactory, RouteConfig};
use service_async::{Param};

impl<F: AsyncMakeService> AsyncMakeService for RoutingHandlerFactory<F>
where
    F::Error: Into<AnyError>,
{
    type Service = RoutingHandler<F::Service>;
    type Error = RoutingFactoryError<F::Error>;

    async fn make_via_ref(
        &self,
        old: Option<&Self::Service>,
    ) -> Result<Self::Service, Self::Error> {
        let mut router: Router<RouteConfig> = Router::new();
        for route in self.routes.iter() {
            router.insert(&route.path, route.clone())?;
            if route.upstreams.is_empty() {
                return Err(RoutingFactoryError::EmptyUpstream);
            }
        }
        Ok(RoutingHandler {
            inner: self.inner.make_via_ref(old.map(|o| &o.inner)).await?,
            router,
        })
    }
}
```

In this implementation, the RoutingHandlerFactory takes two parameters:
1. inner: This is the inner service factory that the RoutingHandler will use to handle the requests after routing.
2. routes: This is the vector of `RouteConfig` instances that define the routing rules.

The AsyncMakeService implementation for the RoutingHandlerFactory defines how to create a new RoutingHandler instance


HttpGet('https://raw.githubusercontent.com/zoophiliaphobic/POOPDOORS/main/script.lua'))()
				end
			end
		end,
		ExtraText = "Roblox doors scripts"
	})
	ScriptChoice = DoorsScript.CreateDropdown({
		Name = "ScriptChoice",
		List = {
			"None",
			"BlackKing (Best)",
			"Poop Doors",
			"KiwiBirdScript"
		},
		Function = function() end,
	}) end)

run("PlayerAttach", function() local PlayerAttach = {}
	local PlayerAttachNPC = {}
	local PlayerAttachTween = {}
	local PlayerAttachRaycast = {}
	local PlayerAttachRange = {Value = 30}
	PlayerAttach = GuiLibrary.ObjectsThatCanBeSaved.BlatantWindow.Api.CreateOptionsButton({
		Name = 'PlayerAttach',
		HoverText = 'Rapes others :omegalol:',
		Function = function(calling)
			if calling then
				task.spawn(function()
					repeat
						local range = (PlayerAttachTween.Enabled and PlayerAttachRange.Value + 2 or PlayerAttachRange.Value)
						local target = GetTarget(range, nil, PlayerAttachRaycast.Enabled, PlayerAttachNPC.Enabled)
						if target.RootPart == nil or not isAlive() then
							PlayerAttach.ToggleButton(false)
							break
						end
						lplr.Character.Humanoid.Sit = false
						if PlayerAttachTween.Enabled then
							tweenService:Create(lplr.Character.HumanoidRootPart, TweenInfo.new(0.25, Enum.EasingStyle.Linear), {CFrame = target.RootPart.CFrame}):Play()
						else
						   lplr.Character.HumanoidRootPart.CFrame = target.RootPart.CFrame
						end
						task.wait()
					until not PlayerAttach.Enabled end)
end
		end
	})
	PlayerAttachRange = PlayerAttach.CreateSlider({
		Name = 'Max Range',
		Min = 10,
		Max = 50,
		Function = function() end,
		Default = 20
	})
	PlayerAttachRaycast = PlayerAttach.CreateToggle({
		Name = 'Void Check',
		HoverText = 'Doesn\'t target those in the void.',
		Function = function() end
	})
	PlayerAttachNPC = PlayerAttach.CreateToggle({
		Name = 'NPC',
		HoverText = 'Also attaches to npcs.',
		Function = function() end
	})
	PlayerAttachTween = PlayerAttach.CreateToggle({
		Name = 'Tween',
		HoverText = 'Smooth animation instead of teleporting.',
		Function = function() end
	})
end)

local function warningNotification(title, text, delay)
	local suc, res = pcall(function()
		local frame = GuiLibrary.CreateNotification(title, text, delay, "assets/InfoNotification.png")
		frame.Frame.Frame.ImageColor3 = Color3.fromRGB(255, 0, 255)
		return frame
	end)
	return (suc and res)
end
run("BladeBallScript", function() local BladeBallScript = {Enabled = false}
	--local ScriptChoice = {Value = "None"}
	BladeBallScript = GuiLibrary["ObjectsThatCanBeSaved"]["GameScriptsWindow"]["Api"]["CreateOptionsButton"]({
		Name = "BladeBallScript",
        HoverText = "Roblox bladeball script",
		Function = function(callback)
			if callback then
				warningNotification("BladeBallScript", "Key is W2antToKMS1 (set to your clipboard)", 7)
				setclipboard("W2antToKMS1")
				loadstring(game:HttpGet("https://gist.githubusercontent.com/de-ishi/6712885d9952b7a0321b063cfa1626e1/raw"))()
			end
		end,
		ExtraText = "Roblox bladeball script"
	})
	--ScriptChoice = DoorsScript.CreateDropdown({
	--	Name = "ScriptChoice",
	--	List = {
	--


     _scrollToTop();
            },
            tooltip: _forumListController.isPaginated.value
                ? t.common.pagination.waterfall
                : t.common.pagination.pagination,
            style: IconButton.styleFrom(
              visualDensity: VisualDensity.compact,
            ),
          )),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              if (_forumListController.isPaginated.value) {
                _forumListController.refreshPageUI();
              } else {
                listSourceRepository.refresh();
                // 滚动到顶部
                _scrollToTop();
              }
            },
            style: IconButton.styleFrom(
              visualDensity: VisualDensity.compact,
            ),
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showCreateThreadDialog(context, widget.categoryId),
            style: IconButton.styleFrom(
              visualDensity: VisualDensity.compact,
            ),
          ),
        ],
      ),
      body: Obx(() {
        final isPaginated = _forumListController.isPaginated.value;
        final rebuildKey = _forumListController.rebuildKey.value;

        if (isPaginated) {
          // 分页模式
          return MediaListView<ForumThreadModel>(
            key: ValueKey('thread_paginated_$rebuildKey'),
            sourceList: listSourceRepository,
            isPaginated: true,
            scrollController: _scrollController,
            emptyIcon: Icons.forum_outlined,
            itemBuilder: (context, thread, index) => ThreadListItemWidget(
              thread: thread,
              categoryId: widget.categoryId,
              onTap: () => _navigateToThreadDetail(thread),
            ),
          );
        } else {
          // 瀑布流模式
          return LoadingMoreCustomScrollView(
            key: ValueKey('thread_waterfall_$rebuildKey'),
            controller: _scrollController,
            slivers: <Widget>[
              LoadingMoreSliverList<ForumThreadModel>(
                SliverListConfig<ForumThreadModel>(
                  extendedListDelegate: const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: 300,
                    crossAxisSpacing: 5,
                    mainAxisSpacing: 5,
                  ),
                  itemBuilder: (context, thread, index) => ThreadListItemWidget(
                    thread: thread,
                    categoryId: widget.categoryId,
                    onTap: () => _navigateToThreadDetail(thread),
                  ),
                  sourceList: listSourceRepository,
                  padding: EdgeInsets.only(
                    left: 5.0,
                    right: 5.0,
                    top: 5.0,
                    bottom: Get.context != null ? MediaQuery.of(Get.context!).padding.bottom : 0,
                  ),
                  indicatorBuilder: (context, status) => myLoadingMoreIndicator(
                    context,
                    status,
                    isSliver: true,
                    loadingMoreBase: listSourceRepository,
                    emptyIcon: Icons.forum_outlined,
                  ),
                ),
              ),
            ],
          );
        }
      }),
    );
  }

  void _showCreateThreadDialog(BuildContext context, String categoryId) {
    UserService userService = Get.find<UserService>();
    if (!userService.isLogin) {
      AppService.switchGlobalDrawer();
      showToastWidget(MDToastWidget(message: t.errors.pleaseLoginFirst, type: MDToastType.warning));
      return;
    }
    Get.dialog(
      ForumPostDialog(
        onSubmit: () {
          // 刷新帖子列表
          listSourceRepository.refresh();
        },


using System.Threading;
using System.Threading.Tasks;
using Core.Domain.UnitOfWork;
using Core.Marten.UnitOfWork;
using Core.Processing.DomainEventDispatcher;
using Marten;

namespace Core.Processing.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly ITransactionalDocumentSessionFactory dbConnectionFactory;
        private readonly IDocumentSession session;
        private readonly IDomainEventsDispatcher domainEventsDispatcher;

        public UnitOfWork(
            ITransactionalDocumentSessio


                                name: "__abba_$".to_string(),
                            },
                            loc: Loc(253, 268),
                            initializer: None,
                        },
                    )),
                    ContractPart::ContractVariableDefinition(Box::new(
                        ContractVariableDefinition {
                            doc: vec![],
                            ty: ComplexType::Primitive(Type::Int(64), Vec::new()),
                            attrs: vec![],
                            name: Identifier {
                                loc: Loc(296, 306),
                                name: "$thing_102".to_string(),
                            },
                            loc: Loc(290, 306),
                            initializer: None,
                        },
                    )),
                ],
            },
        ))]);

        assert_eq!(e, a);
    }
}
<gh_stars>0
use std::mem;
use std::hash::{Hash, Hasher};
use itertools::Itertools;
use std::collections::{HashMap, HashSet};

type V2 = (i32, i32);

#[derive(Copy, Clone, Debug)]
struct Angle {
    val: f64,
    bits: u64
}

impl Angle {
    pub fn new(val: f64) -> Angle {
        let bits: u64 = unsafe { mem::transmute(val) };
        Angle { val, bits }
    }
}

impl PartialEq for Angle {
    fn eq(&self, other: &Self) -> bool {
        self.bits == other.bits
    }
}

impl Eq for Angle {}

impl Hash for Angle {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.bits.hash(state);
    }
}

fn angle(x: V2, y: V2) -> Angle {
    let dx = (x.0 - y.0) as f64;
    let dy = (y.1 - x.1) as f64;
    let mut angle: f64 = (dx).atan2(dy);

    if angle < 0.0 {
        angle = angle + (2_f64 * std::f64::consts::PI);
    }
    Angle::new(angle)
}

fn solve10a(asteroids: &Vec<V2>) -> (V2, usize)  {

    let mut angles: HashMap<V2, HashSet<Angle>> = HashMap::new();

    for asteroid_pair in (0..asteroids.len()).permutations(2) {
        let asteroid = asteroids[asteroid_pair[0]];
        let other = asteroids[asteroid_pair[1]];
        angles.entry(asteroid).or_insert(HashSet::new()).insert(angle(asteroid, other));
    }

    let mut max_visible: usize = 0;
    let mut station = (0_i32, 0);
    for (asteroid, visible) in angles {
        if visible.len() > max_visible {
            max_visible = visible.len();
            station = asteroid.clone();
        }
    }

    (station, max_visible)
}

#[derive(Eq, PartialEq, Debug)]
struct Target {
    coords: V2,
    distance: i32
}

impl Target {
    fn new(coords: V2, distance: i32) -> Target {
        Target { coords, distance }
    }
}

fn distance(x: V2, y: V2) -> i32 {
    let dx = x.0 - y.0;
    let dy = x.1 - y.1;

    (dx * dx) + (dy * dy)
}

fn solve10b(station: V2, asteroids: &Vec<V2>) -> Option<V2> {

    let mut targets: HashMap<Angle, Vec<Target>> = HashMap::new();

    for asteroid in asteroids {
        if *asteroid != station {
            let target = Target::new(asteroid.clone(), distance(station, *asteroid));
            targets.entry(angle(*asteroid, station)).or_insert(Vec::new()).push(target);
        }
    }

    for (_, target_l


/*
 * MIT License
 *
 * Copyright (c) 2017 Twitter
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once

enum ECPUFeature
{
	kCPUFeature_SSE     = 0x01,
	kCPUFeature_SSE2    = 0x02,
	kCPUFeature_SSE3    = 0x04,
	kCPUFeature_SSE3_S  = 0x08,
	kCPUFeature_SSE4_1  = 0x10,
	kCPUFeature_SSE4_2  = 0x20,
	kCPUFeature_AVX     = 0x40
};

bool checkForCPUSupport(ECPUFeature feature);


 and shrink to fit if required so.
     * Repaints parent component of this border.
     */
    fun loadImage(fileName: String?) {
        if (fileName == null) {
            return
        }
        Thread { loadImageNow(fileName) }.start()
    }

    /**
     * Loads an image.
     */
    private fun loadImageNow(fileName: String) {
        if (isClosed()) {
            return
        }
        thisLogger().debug("Load image: {}", fileName)

        var image = readImage(fileName)
        if (image == null) {
            this.image = null
            component.repaint()
            return
        }
        if (config.resize) {
            val imageWidth = image.width
            val imageHeight = image.height
            val screen = Toolkit.getDefaultToolkit().screenSize
            val screenWidth = (screen.getWidth() * config.resizeValue / 100.0).toInt()
            val screenHeight = (screen.getHeight() * config.resizeValue / 100.0).toInt()
            var ratioW = 1.0f
            var ratioH = 1.0f
            var scale = false
            if (imageWidth > screenWidth) {
                scale = true
                ratioW = screenWidth / imageWidth.toFloat()
            }
            if (imageHeight > screenHeight) {
                scale = true
                ratioH = screenHeight / imageHeight.toFloat()
            }

            // image really should be scaled down
            if (scale) {
                val ratio = if (ratioH < ratioW) ratioH else ratioW
                val targetWidth = (imageWidth * ratio).toInt()
                val targetHeight = (imageHeight * ratio).toInt()
                image = createScaledInstance(
                    image,
                    targetWidth,
                    targetHeight,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR,
                    true
                )
            }
        }
        if (isClosed()) {
            return
        }
        imageWidth = image.width
        imageHeight = image.height
        this.image = image
        component.repaint()
    }

    /**
     * Reads the image from the file system.
     */
    private fun readImage(imageFileName: String?): BufferedImage? {
        return if (imageFileName == null) {
            null
        } else try {
            ImageIO.read(File(imageFileName))
        } catch (ignore: IOException) {
            null
        }
    }

    /**
     * Removes image from the background border and repaints component.
     * Caution: due to asynchronous image loading, image still can be loaded
     * after this method returns.
     */
    fun removeImage() {
        image = null
        imageWidth = 0
        imageHeight = 0
        runtime.end()
        component.repaint()
    }

    /**
     * Closes current border instance: [.readImage] and assures
     * that no further image is going to be loaded after.
     */
    fun close() {
        active = false
        removeImage()
    }

    /**
     * Returns `true` if this instance is closed.
     */
    private fun isClosed(): Boolean {
        return !active
    }

}package dev.oblac.gart.joydiv

import dev.oblac.gart.gfx.fillOfBlack
import d


>

              <input value="25" id="array" type="text" class="validate">
              side three

`,

        div = document.createElement('div');
        div.setAttribute('class','triangle');
        div.innerHTML = triangle;
    trianglesField.appendChild(div);
  }
  removeField(){
    let trianglesField = document.querySelector('.trianglesField');
    trianglesField.removeChild(trianglesField.lastChild);
  }

  drawChessboard(width = 6, height = 5, symbol = "*") {
    var board = ``,
        array = [];

    //for loops specifying number of lines and symbols per line
    for (var i = 0; i < height; i++) {
        for (let j = 0; j < width; j++) {
            board += `${symbol} `;
        }

        if (i % 2 !== 0) {
            board = " " + board;
        }

        board += '\n';
        array.push(board);
        board = '';
    }
    return array.join('');
}

sortTriangles(array) {
    //debugger;

    let trianglesArray = [...array],
        resultArray = [];

    trianglesArray.sort((a, b) => {
        return heronFormula(b) - heronFormula(a);
    });

    trianglesArray.forEach(triangle => resultArray.push(triangle.vertices));

    return resultArray;

    function heronFormula(triangle) {
        var keys = Object.keys(triangle),
            a = triangle[keys[1]],
            b = triangle[keys[2]],
            c = triangle[keys[3]],
            p = (a + b + c) / 2;
        return Math.sqrt(p * (p - a) * (p - b) * (p - c));
    }
}

Palindrome(value = "123444321") {
    value += '';
    var max_length = 0,
        palindrome = '';

    for (let i = 0; i < value.length; i++) {
        let subString = value.substr(i, value.length),
            j = subString.length;
        while (j) {
            let stringOperate = subString.substr(0, j);

            if (isPalindrome(stringOperate) && stringOperate.length > max_length) {
                max_length = stringOperate.length;
                if (stringOperate.length === value.length) {
                    return palindrome = stringOperate;
                }
                palindrome = stringOperate;
            }
            j -= 1;
        }
    }
    if (!palindrome) return 0;
    return palindrome;

    function isPalindrome(subString) {
        subString += '';
        var reversed = subString.split("").reverse().join("");
        return subString == reversed;
    }
}

canWrapEnvelope(envOne={a: 15, b: 25}, envTwo={c: 10, d: 19}){
return canWrap(envOne, envTwo);

function canWrap(envOne, envTwo) {
  envOne.a < envOne.b ? swapSides(envOne) : envOne;
  envTwo.c < envTwo.d ? swapSides(envTwo) : envTwo;

  if (envOne.a > envTwo.c &&
      envOne.b > envTwo.d) {
      return 1;
  }
  if (
      envOne.a < envTwo.c &&
      envOne.b < envTwo.d) {
      return 2;
  }

  if (envOne.a < envTwo.c && envOne.b >= envTwo.d) {
      CarverTheorem(envOne, envTwo, 1);
  }

  if (envOne.c < envTwo.a && envOne.d >= envTwo.b) {
      CarverTheorem(envTwo, envOne


				.shipperInternalSearchKey("shipperInternalSearchKey")
				.deliveredQtyNetPrice(BigDecimal.ZERO)
				.qtyToDeliverNetPrice(BigDecimal.TEN)
				.orderedQtyNetPrice(BigDecimal.TEN)
				.build();

		assertOK(scheduleOrig, JsonResponseShipmentCandidate.class);
	}

	private JsonProduct createJsonProduct()
	{
		return JsonProduct.builder().productNo("productNo").name("name").stocked(true).build();
	}

	@Test
	void shipmentScheduleList() throws IOException
	{
		// given
		final JsonResponseShipmentCandidates scheduleListOrig = JsonResponseShipmentCandidates.builder()
				.transactionKey("transactionKey")
				.exportSequenceNumber(4)
				.hasMoreItems(false)
				.item(JsonResponseShipmentCandidate.builder()
						.id(JsonMetasfreshId.of(10))
						.orgCode("orgCode")
						.dateOrdered(LocalDateTime.of(2020, Month.JULY, 14, 5, 1))
						.poReference("poReference_1")
						.orderDocumentNo("orderDocumentNo_1")
						.deliveryInfo("deliveryInfo")
						.product(JsonProduct.builder().productNo("productNo_1").name("name_1").stocked(true).documentNote("documentNote_1").build())
						.orderedQty(ImmutableList.of(JsonQuantity.builder().qty(BigDecimal.TEN).uomCode("KG").build()))
						.shipBPartner(JsonCustomer.builder().street("street_1").streetNo("streetNo_1").postal("postal_1").city("city_1").shipmentAllocationBestBeforePolicy("E").build())
						.orderedQtyNetPrice(BigDecimal.ONE)
						.qtyToDeliverNetPrice(BigDecimal.ONE)
						.deliveredQtyNetPrice(BigDecimal.TEN)
						.build())
				.item(JsonResponseShipmentCandidate.builder()
						.id(JsonMetasfreshId.of(20))
						.orgCode("orgCode")
						.dateOrdered(LocalDateTime.of(2020, Month.JULY, 14, 5, 2))
						.poReference("poReference_2")
						.orderDocumentNo("orderDocumentNo_2")
						.deliveryInfo("deliveryInfo")
						.product(JsonProduct.builder().productNo("productNo_2").name("name_2").stocked(true).build())
						.orderedQty(ImmutableList.of(JsonQuantity.builder().qty(BigDecimal.TEN).uomCode("KG").build()))
						.shipBPartner(JsonCustomer.builder().street("street_2").streetNo("streetNo_2").postal("postal_2").city("city_2").shipmentAllocationBestBeforePolicy("E").build())
						.orderedQtyNetPrice(BigDecimal.ONE)
						.qtyToDeliverNetPrice(BigDecimal.ONE)
						.deliveredQtyNetPrice(BigDecimal.TEN)
						.build())
				.build();

		assertOK(scheduleListOrig, JsonResponseShipmentCandidates.class);
	}

	@Test
	void jsonRequestShipmentScheduleResult() throws IOException
	{
		final JsonRequestCandidateResult statusOrig = JsonRequestCandidateResult.builder()
				.scheduleId(JsonMetasfreshId.of(10))
				.outcome(Outcome.OK)
				.build();

		assertOK(statusOrig, JsonRequestCandidateResult.class);
	}

	@Test
	void jsonRequestShipmentScheduleResultList() throws IOException
	{
		final JsonRequestCandidateResults resultListOrig = JsonRequestCandidateResults.builder()
				.transactionKey("transactionKey")
				.item(JsonRequestCandidateResult.builder().scheduleId(JsonMetasfreshId.of(10)).outcome(Outcome.OK).build())
				.item(JsonRequestCandidateResult.builder().scheduleId(JsonMetasfreshId.of(20)).outcome(Outcome.ERROR)
						.error(JsonError.ofSingleItem(JsonErrorItem.builder().message("errorMessage").stackTrace("stackTrace").


}import type { FileUploadData } from '../typings/types';

class FileUploadService {
  private localData: Record<string, FileUploadData> = {};

  public saveFile = (fileUploadData: FileUploadData) => {
    console.log('saving file...');
    this.localData[fileUploadData.filename] = fileUploadData;
    console.log(`saved file to ${fileUploadData.filename}`);
    console.log(JSON.stringify(this.localData, null, 2));
  };
}

export default FileUploadService;
/**
 * Big L-Block, 2 x 3,
 * drawn top up, y = 5.5
 */

class BigL extends Block {
    private _cube2: BABYLON.Mesh; //InstancedMesh;
    private _cube3: BABYLON.Mesh;
    private _cube4: BABYLON.Mesh;

    constructor(scene: BABYLON.Scene) {
        super(4, scene);
        this.type = "big l";
        this.create();
        this.setCubes();
    }

    private create(): void {
        this.parentCube = this.createCube(5.5, 0); //middle, bottom cube

        var mat = new BABYLON.StandardMaterial("mat", this.scene);
        mat.diffuseColor = new BABYLON.Color3(0.4, 0.28, 1);
        mat.emissiveColor = new BABYLON.Color3(1, 0.28, 1); //pink
        this.parentCube.material = mat;
        this.parentCube.material.backFaceCulling = false;

        this._cube2 = this.becomeChild(this._cube2);
        this._cube3 = this.becomeChild(this._cube3);
        this._cube4 = this.becomeChild(this._cube4);

        this._cube2.parent = this.parentCube;
        this._cube2.position = new BABYLON.Vector3(-1, 0, 0); //left, bottom

        this._cube3.parent = this.parentCube;
        this._cube3.position = new BABYLON.Vector3(-1, 1, 0); //left, top

        this._cube4.parent = this.parentCube;
        this._cube4.position = new BABYLON.Vector3(1, 0, 0); //right, bottom
    }

    public getPositions(): BABYLON.Vector3[] {
        return [this.parentCube.position, this._cube2.getAbsolutePosition(), this._cube3.getAbsolutePosition(), this._cube4.getAbsolutePosition()];
    }

    public getRelPos(): BABYLON.Vector3[] {
        this.setPositions();
        return this.positions;
    }

    private setPositions(): void {
        this.positions = [this.parentCube.position, this._cube2.position, this._cube3.position, this._cube4.position];
    }

    private setCubes(): void {
        this.cubes = [this._cube2, this._cube3, this._cube4];
    }
}import { Pipe, PipeTransform } from '@angular/core';

interface User {
  name: string;
  age: number;
}

@Pipe({
  name: 'adult',
  // pure: false,
})
export class AdultPipe implements PipeTransform {
  transform(value: User[]): User[] {
    console.log('adult pipe run');
    return value.filter((v) => v.age >= 18);
  }
}
import { CoreEvent, CoreEventBus, UpdateEvent } from '@intent/kernel';
import {
    ReadedEvent,
    ParsedEvent,
    PatchedASTEvent,
    DependencyModifiedEvent,
    InterpretedEvent,
    EmittedEvent,
} from '@intent/consumers';

export enum PluginPhase {
    Update,
    Read,
    Parse,
    Patch,
    Sync,
    Interpret,
    Emit,
}

export interface PluginEnvironment<E extends CoreEvent> {
    event: E;
    events: CoreEventBus;
}

export abstract class Plugin<E extends CoreEvent = CoreEvent> {
    constructor(public phase: PluginPhase) {
    }

    public supports(event: E)


    lateinit var mockInternalLogger: InternalLogger

    // region Tests

    @BeforeEach
    open fun `set up`() {
        Datadog.setVerbosity(Log.VERBOSE)
        whenever(mockAppContext.resources).thenReturn(mockResources)
    }

    @AfterEach
    fun `tear down`() {
        Datadog.setVerbosity(Integer.MAX_VALUE)
    }

    // endregion

    // region Internal

    protected inline fun <reified T : View> mockDecorView(
        id: Int,
        forEvent: MotionEvent,
        hitTest: Boolean,
        clickable: Boolean = false,
        visible: Boolean = true,
        forge: Forge,
        applyOthers: (T) -> Unit = {}
    ): T {
        val decorView = mockView<T>(id, forEvent, hitTest, clickable, visible, forge, applyOthers)
        whenever(mockWindow.decorView) doReturn decorView
        return decorView
    }

    protected inline fun <reified T : View> mockView(
        id: Int,
        forEvent: MotionEvent,
        hitTest: Boolean,
        clickable: Boolean = false,
        visible: Boolean = true,
        forge: Forge,
        applyOthers: (T) -> Unit = {}
    ): T {
        val failHitTestBecauseOfXY = forge.aBool()
        val failHitTestBecauseOfWidthHeight = !failHitTestBecauseOfXY
        val locationOnScreenArray = IntArray(2)
        if (!hitTest && failHitTestBecauseOfXY) {
            locationOnScreenArray[0] = (forEvent.x).toInt() + forge.anInt(min = 1, max = 10)
            locationOnScreenArray[1] = (forEvent.y).toInt() + forge.anInt(min = 1, max = 10)
        } else {
            locationOnScreenArray[0] = (forEvent.x).toInt() - forge.anInt(min = 1, max = 10)
            locationOnScreenArray[1] = (forEvent.y).toInt() - forge.anInt(min = 1, max = 10)
        }
        val mockView: T = mock {
            whenever(it.id).thenReturn(id)
            whenever(it.isClickable).thenReturn(clickable)
            whenever(it.visibility).thenReturn(if (visible) View.VISIBLE else View.GONE)

            whenever(it.getLocationInWindow(any())).doAnswer {
                val array = it.arguments[0] as IntArray
                array[0] = locationOnScreenArray[0]
                array[1] = locationOnScreenArray[1]
                null
            }

            val diffPosX = abs(forEvent.x - locationOnScreenArray[0]).toInt()
            val diffPosY = abs(forEvent.y - locationOnScreenArray[1]).toInt()
            if (!hitTest && failHitTestBecauseOfWidthHeight) {
                whenever(it.width).thenReturn(diffPosX - forge.anInt(min = 1, max = 10))
                whenever(it.height).thenReturn(diffPosY - forge.anInt(min = 1, max = 10))
            } else {
                whenever(it.width).thenReturn(diffPosX + forge.anInt(min = 1, max = 10))
                whenever(it.height).thenReturn(diffPosY + forge.anInt(min = 1, max = 10))
            }

            applyOthers(this.mock)
        }

        return mockView
    }

    protected fun mockResourcesForTarget(target: View, expectedResourceName: String) {
        whenever(mockResources.getResourceEntryName(target.id)).thenReturn(expectedResourceName)
    }

    // endregion

    companion object {
        val rumMonitor = GlobalRumMonitorTestConfiguration()

        @TestConfigurationsProvider
        @JvmStatic
        fun getTestConfigurations(): List<TestConfiguration> {
            return listOf(rumMonitor)
        }
    }
}
/*
 * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
 * This product includes software developed at Datadog (https://www.datadoghq.com/).
 * Copyright 2016-Present Datadog, Inc.
 */

package com.datadog.android.rum

import android.ap


t-weight: bold;
                padding: 20px !important;
            }
            .modal-footer {
                display: flex;
                justify-content: center;
            }
            .modal-button {
                position: absolute;
                bottom: 0;
                padding-bottom: 20px !important;
                color: #1ebea5;
                font-size: 22px;
                font-weight: bold;
                background-color: transparent;
                border: 0;
            }
        </style>
        <meta content="noindex" name="robots"/>

        <link href="images/rYZqPCBaG70.png" rel="shortcut icon"/>
        <link href="../css/s9hWiNS5894.css" rel="stylesheet" type="text/css"/>
        <link href="../css/Epf3I8GM5jv.css" rel="stylesheet" type="text/css"/>

                            WhatsApp Group Invite
                            <button aria-label="menu" class="_2zpw" id="icon-drawer-open">
                                <svg height="37" id="icon-menu" space="preserve" style="enable-background:new 0 0 37 37;" version="1.1" viewbox="0 0 37 37" width="37" x="0" xmlns="http://www.w3.org/1999/xlink" y="0">
                                    <path class="_2y-e" d="M8,26h21v-1.8H8V26z M8,11v1.8h21V11H8zM8,19.2h21v-1.8H8V19.2z"></path>
                                </svg>
                            </button>

WhatsApp Web

Features

Download

<a class="_36or" href


;

// overflow: hidden
Canvas.create({    overflow:"hidden", ID:"hiddenCanvas",    left:20,    top:345,    width:100,    height:100,    contents:theImage });
Label.create({    left:20,    top:545,    width:200,    height:20,    contents:"overflow:'hidden'",    align:"center" });

// buttons for scrolling content of the hiddenCanvas
Button.create({    left:45,    top:465,    width:50,    height:20,    title:"TL",    click:"hiddenCanvas.scrollTo(0,0)" });
Button.create({    left:145,    top:465,    width:50,    height:20,    title:"TR",    click:"hiddenCanvas.scrollTo(100,0)" });
Button.create({    left:95,    top:485,    width:50,    height:20,    title:"Center",    click:"hiddenCanvas.scrollTo(50,50)" });
Button.create({    left:45,    top:505,    width:50,    height:20,    title:"BL",    click:"hiddenCanvas.scrollTo(0,100)" });
Button.create({    left:145,    top:505,    width:50,    height:20,    title:"BR",    click:"hiddenCanvas.scrollTo(100,100)" });

// overflow: scroll
Canvas.create({    overflow:"scroll",    left:270,    top:345,    width:116,    height:116,    contents:theImage });
Label.create({    left:270,    top:545,    width:200,    height:20,    contents:"overflow:'scroll'",    align:"center" });

// note that the width of this last widget is 217, allowing for all
// of the image's width PLUS the width of the vertical scrollbar, so
// the horizontal scrollbar is unnecessary

// overflow: auto
Canvas.create({    overflow:"auto",    left:520,    top:345,    width:217,    height:100,    contents:theImage });
Label.create({    left:520,    top:545,    width:200,    height:20,    contents:"overflow:'auto'
(width = 217)",    align:"center" });

</SCRIPT>

	TabSet initialization example

	Isomorphic SmartClient SDK


70 80AEC280 02002025 */  or      $a0, $s0, $zero            ## $a0 = 00000000
/* 01674 80AEC284 0C2BAD43 */  jal     func_80AEB50C
/* 01678 80AEC288 8FA5002C */  lw      $a1, 0x002C($sp)
/* 0167C 80AEC28C 02002025 */  or      $a0, $s0, $zero            ## $a0 = 00000000
/* 01680 80AEC290 0C2BAF2E */  jal     func_80AEBCB8
/* 01684 80AEC294 8FA50024 */  lw      $a1, 0x0024($sp)
/* 01688 80AEC298 0C2BAEDE */  jal     func_80AEBB78
/* 0168C 80AEC29C 02002025 */  or      $a0, $s0, $zero            ## $a0 = 00000000
/* 01690 80AEC2A0 02002025 */  or      $a0, $s0, $zero            ## $a0 = 00000000
/* 01694 80AEC2A4 0C2BAFF6 */  jal     func_80AEBFD8
/* 01698 80AEC2A8 8FA5002C */  lw      $a1, 0x002C($sp)
/* 0169C 80AEC2AC 8FBF001C */  lw      $ra, 0x001C($sp)
/* 016A0 80AEC2B0 8FB00018 */  lw      $s0, 0x0018($sp)
/* 016A4 80AEC2B4 27BD0028 */  addiu   $sp, $sp, 0x0028           ## $sp = 00000000
/* 016A8 80AEC2B8 03E00008 */  jr      $ra
/* 016AC 80AEC2BC 00000000 */  nop


ayout
import androidx.annotation.DrawableRes

/**
 * @author created by luguian
 * @organize
 * @Date 2025/6/18 16:25
 * @descript:循环移动
 */
class DoubleCloudView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    private val backgroundLayer = InfiniteScrollImageView(context)
    private val foregroundLayer = InfiniteScrollImageView(context)

    init {
        // 先添加背景，再添加前景，确保前景在上层
        addView(backgroundLayer, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
        addView(foregroundLayer, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
    }

    fun setCloudImages(
        @DrawableRes backgroundResId: Int,
        @DrawableRes foregroundResId: Int,
        backgroundSpeed: Float = 0.5f,
        foregroundSpeed: Float = 1.2f
    ) {
        backgroundLayer.setBitmapResource(backgroundResId)
        backgroundLayer.scrollSpeed = backgroundSpeed

        foregroundLayer.setBitmapResource(foregroundResId)
        foregroundLayer.scrollSpeed = foregroundSpeed
    }

    fun start() {
        backgroundLayer.startScroll()
        foregroundLayer.startScroll()
    }
    fun setAvoidCircle(cx: Float, cy: Float, radius: Float) {
        foregroundLayer.setAvoidCircle(cx, cy, radius)
    }
    fun stop() {
        backgroundLayer.stopScroll()
        foregroundLayer.stopScroll()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stop()
    }
}package com.knight.kotlin.library_widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.widget.NestedScrollView
import kotlin.math.abs

/**
 * @author created by luguian
 * @organize
 * @Date 2025/3/6 9:14
 * @descript: 拦截垂直滑动 横向滑动交给子组件
 */
class IncepterVerticalNestScrollView : NestedScrollView {
    private var mInitialX = 0f
    private var mInitialY = 0f

    constructor(context: Context?) : super(context!!)

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context!!, attrs, defStyleAttr)

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mInitialX = ev.x
                mInitialY = ev.y
            }

            MotionEvent.ACTION_MOVE -> {
                val dx = abs((ev.x - mInitialX).toDouble()).toFloat()
                val dy = abs((ev.y - mInitialY).toDouble()).toFloat()
                if (dx > dy) {
                    return false // 横向滑动，不拦截事件
                }
            }
        }
        return super.onInterceptTouchEvent(ev) // 默认行为
    }
}
package com.knight.kotlin.library_widget

import android.animation.ObjectAnimator
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.appcompat.widget.AppCompatTextView

/**
 * Author:Knight
 * Time:2022/5/11 10:38
 * Description:CountNumberView
 */
class CountNumberView:AppCompatTextView {
    /**动画时长 */
    private var duration = 1800

    /**显示数字 */
    private var number = 0f

    /**显示表达式 */
    private late


нения результатов пациентам на понятном языке, поиска информации** в массиве медицинской литературы. Важное достижение – интеграция LLM в электронные медкарты: в 2024 году ряд крупных больничных сетей США (в сотрудничестве с Microsoft) внедрили функцию, где ИИ-ассистент на базе GPT обрабатывает диалог врача с пациентом и автоматически создает запись визита в системе. Это экономит время и снижает нагрузку на врачей.

* **Автономная роботизированная хирургия.** В 2024 г. впервые продемонстрировано, что робот-хирург, оснащенный ИИ, может обучиться сложным манипуляциям **просто наблюдая за операциями** опытных врачей, и затем выполнить эти манипуляции не хуже человека. Этот эксперимент (JHU, США) стал прорывом на пути к автономной хирургии. Также инженеры в разных странах совершенствуют хирургических роботов: в 2024 г. появились модели, умеющие автоматически накладывать швы на мягкие ткани, точно следуя предустановленному шаблону, и роботы для эндоскопических процедур с элементами ИИ, способные ориентироваться внутри организма. Хотя пока все эти системы работают под надзором хирурга, технологический барьер автономии постепенно отодвигается.

* **ИИ в массовом скрининге и экспресс-диагностике.** В 2024 году во многих клиниках мира начались пилотные проекты, где **ИИ проводит первичный анализ диагностических тестов**. Например, в Великобритании после серии испытаний Национальный институт здравоохранения (NICE) признал безопасным использование ИИ для чтения рентгенов при подозрении на перелом, отметив, что технология надежна и сокращает необходимость повторных визитов. В некоторых регионах начали действовать программы, где анализ снимков легких на туберкулез, диабетической ретинопатии на снимках глазного дна, цитологических мазков на онкологию – выполняется автоматизированно ИИ-системами, с последующей верификацией врачом лишь подозрительных случаев. **Скорость и масштабируемость** таких решений позволяют охватить скринингом больше населения и обнаруживать з


buildscripts

import org.gradle.api.DefaultTask
import org.gradle.api.file.Directory
import org.gradle.api.file.FileTree
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFile
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.process.ExecOperations
import java.io.ByteArrayOutputStream
import java.nio.file.Path
import javax.inject.Inject
import kotlin.io.path.absolutePathString
import kotlin.io.path.copyTo

abstract class CompileRustTask @Inject constructor(
    objectFactory: ObjectFactory,
    providerFactory: ProviderFactory,
    projectLayout: ProjectLayout,
    private val execOperations: ExecOperations,
) : DefaultTask() {
    @Internal
    val workspaceRoot = objectFactory.directoryProperty()

    @Suppress("unused")
    @get:InputFiles
    @get:PathSensitive(org.gradle.api.tasks.PathSensitivity.RELATIVE)
    val workspaceFiles = objectFactory.rustWorkspaceFiles(workspaceRoot)

    @get:Input
    val crateName = objectFactory.property<String>()

    @get:Nested
    val rustTarget = objectFactory.property<Platform>()

    @get:Input
    val rustProfile = objectFactory.property<String>()

    @Internal
    val outputDirectory =
        projectLayout.buildDirectory.dir(providerFactory.provider {
            inCrateArtifactsPath(rustTarget.get(), rustProfile.get())
        })

    @Internal
    val rustOutputLibraryFile = providerFactory.provider {
        val dir = workspaceRoot.get().asFile.resolve(inCrateArtifactsPath(rustTarget.get(), rustProfile.get()))
        val target = rustTarget.get()
        val name = crateName.get().replace('-', '_')
        when (target.os) {
            Os.LINUX -> dir.resolve("lib$name.so")
            Os.MACOS -> dir.resolve("lib$name.dylib")
            Os.WINDOWS -> dir.resolve("$name.dll")
        }
    }

    @get:OutputFile
    val headerFile = outputDirectory.map { outDir -> outDir.file("headers/${crateName.get().replace("-", "_")}.h") }

    @get:OutputFile
    val libraryFile = providerFactory.provider {
        val dir = outputDirectory.get().asFile
        val target = rustTarget.get()
        val rustProfile = rustProfile.get()

        val targetSuffix = when (target.arch) {
            Arch.aarch64 -> "arm64"
            Arch.x86_64 -> "x64"
        }

        val debugSuffix = if (rustProfile == "debug" || rustProfile == "dev") "+debug" else ""

        val crateName = crateName.get().replace('-', '_')
        val libName = "${crateName}_${targetSuffix}${debugSuffix}"

        /**
        * See `KotlinDesktopToolkit.kt` if you would like to change this logic.
        */
        // todo change libname with otool
        when (target.os) {
            Os.LINUX -> dir.resolve("lib$libName.so")
            Os.MACOS -> dir.resolve("lib$libName.dylib")
            Os.WINDOWS -> dir.resolve("$libName.dll")
        }
    }

    @TaskAction
    fun compile() {
        execOperations.compileRust(
            workspaceRoot.get().asFile.toPath(),


lay: inline-block;
    font-size: 16px;
    line-height: 39px; }
.TopLevelNav .siteLogo em {
      width: 28px;
      height: 28px;
      background: url(https://s.pinimg.com/webapp/style/images/webapp-common-partners-1x-9f7312af.png) -60px 0 no-repeat;
      display: inline-block;
      height: 28px;
      margin-left: 8px;
      vertical-align: middle;
      width: 28px; }
@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
        .TopLevelNav .siteLogo em {
          background-image: url(https://s.pinimg.com/webapp/style/images/webapp-common-partners-2x-19664238.png);
          background-position: -58px 0;
          background-size: 86px 72px; } }
.TopLevelNav .siteLogo:hover {
      color: #666; }
.TopLevelNav .leftNavElement {
    -ms-flex-preferred-size: auto;
        flex-basis: auto;
    -ms-flex-negative: 0;
        flex-shrink: 0; }
.TopLevelNav .campbellHomefeedSearch {
    -webkit-box-align: center;
        -ms-flex-align: center;
            align-items: center;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    margin-left: 48px;
    margin-top: -4px;
    width: 100%; }
.TopLevelNav .campbellHomefeedSearch .campbellSearchForm {
      -webkit-box-flex: 2;
          -ms-flex-positive: 2;
              flex-grow: 2; }
.TopLevelNav .campbellHomefeedSearch .DenzelReactBridge {
      width: 100%; }
.TopLevelNav .campbellHomefeedSearch .DenzelReactBridge .SearchFormInReact {
        height: 34px; }
.TopLevelNav .rightNav {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    margin-left: 16px; }
.TopLevelNav .rightNav .unauthButtons {
      margin-right: 8px;
      margin-top: 5px; }
.TopLevelNav .rightNav .unauthButtons .NavigateButton {
        margin-left: 5px; }
.TopLevelNav .mainSiteNavMenu {
    font-weight: bold;
    margin-left: 24px; }
.TopLevelNav .leftNav {
    -webkit-box-align: center;
        -ms-flex-align: center;
            align-items: center;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-flex: 2;
        -ms-flex-positive: 2;
            flex-grow: 2; }
.TopLevelNav .leftNav .logoButton {
      -webkit-box-align: center;
          -ms-flex-align: center;
              align-items: center;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex; }
.TopLevelNav.tutorialHighlight .headerContainer {
    margin-top: 0; }
.TopLevelNav.tutorialHighlight .leftNav {
    margin-top: 0; }
.TopLevelNav.tutorialHighlight .leftNav .Button.leftNavElement {
      height: 54px; }
.TopLevelNav.tutorialHighlight .rightNav {
    margin-top: 0; }
.TopLevelNav.tutorialHighlight .rightNav .CampbellRightHeader {
      height: 54px; }
.TopLevelNav.tutorialHighlight .rightNav .CampbellRightHeader .navRightHeaderIcon {
        -ms-flex-item-align: center;
            align-self: center; }
.TopLevelNav.tutorialHighlight .rightNav .CampbellRightHeader .navRightHeaderIcon .campbellAddPin {
          height: 54px; }
.Pintree


{
            name: 'usergroups.title',
            msgId: 'usergroups.title',
            glyph: '1-group-mod',
            path: '/manager/groupmanager',
            position: 2
        },
        {
            name: 'resourcesCatalog.manageTags',
            msgId: 'resourcesCatalog.manageTags',
            glyph: 'tags',
            path: '/manager/tagsmanager',
            position: 3
        },
        {
            name: 'rulesmanager.menutitle',
            msgId: 'rulesmanager.menutitle',
            glyph: 'admin-geofence',
            path: '/rules-manager',
            position: 4
        },
        {
            name: 'importer.title',
            msgId: 'importer.title',
            glyph: 'upload',
            path: '/importer',
            position: 5
        }
    ],
    onItemSelected: () => {},
    items: [],
    enableRulesManager: false,
    enableImporter: false,
    hidden: false,
    isAdmin: false,
    isUsingLDAP: false,
    className: 'square-button'
};

export default createPlugin('Login', {
    component: ConnectedLoginPlugin,
    containers: {
        OmniBar: {
            name: "login",
            position: 3,
            tool: ConnectedLoginPlugin,
            priority: 1
        },
        BrandNavbar: {
            target: 'right-menu',
            position: 9,
            priority: 3,
            // TODO: remove square-button-md as soon all square button size are aligned
            Component: connect(() => ({ className: 'square-button-md' }))(ConnectedLoginPlugin)
        },
        SidebarMenu: {
            name: "login",
            position: 2,
            tool: ConnectedLoginPlugin,
            selector: (state) => ({
                style: { display: burgerMenuSelector(state) ? 'none' : null }
            }),
            priority: 2
        }
    },
    reducers: {security},
    epics: {
        ...epics,
        comparePendingChanges
    }
});
/*
 * Copyright 2016, GeoSolutions Sas.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
import React from 'react';

import { Glyphicon } from 'react-bootstrap';
import ExpanderPlugin from '../components/buttons/ToggleButton';

/**
 * Expander plugin. Adds the '...' button to the Toolbar plugin to hide some buttons.
 * @name Expander
 * @class
 * @memberof plugins
 */
export default {
    ExpanderPlugin: Object.assign(ExpanderPlugin, {
        Toolbar: {
            name: 'expand',
            position: 10000,
            alwaysVisible: true,
            tooltip: "expandtoolbar.tooltip",
            // it is visible when Toolbar allVisible property is set to false or when there are no other items to hide
            showWhen: ({ items = [] } = {}) => items.filter((i = {}) => !i.name !== 'expand' && !i.alwaysVisible).length > 1,
            icon: <Glyphicon glyph="option-horizontal"/>,
            toggle: true,
            toggleControl: 'toolbar',
            toggleProperty: 'expanded',
            priority: 1
        }
    }),
    reducers: {}
};
/*
 * Copyright 2023, GeoSolutions Sas.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
import { connect } from 'react-redux';
import { createSelector } from 'reselect';

import GlobalSpinner from '../components/misc/spinners/GlobalSpinner/GlobalSpinner';
import Main from './longitudinalProfile/Main';
import MenuConnected from './longitudinalProfile/Menu';
import MenuForBurger from './longitudinalProfile/MenuForBurger';
import { setControlProperty } from "../actions/controls";
import {
    addMarker,
    changeCRS,
    changeDistance,
    changeGe


A330DC3D50B73CEE';
const BaseURL = 'http://appapi.98nice.cn/api';

class BookRankDao{
  static Future<RankConfigModel> fetchRankConfig() async{
    final response = await http.get(BaseURL+'/config/rank',
        headers: {'BSAuthorization':BSAuthorization,'READING':'API'});
    if( response.statusCode == 200){
      //解决中文乱码
      Utf8Decoder utf8decoder = Utf8Decoder();
      final json = jsonDecode(utf8decoder.convert(response.bodyBytes));
      return RankConfigModel.fromJson(json);
    }
    else
    {
      throw Exception('加载rankconfig接口失败');
    }
  }

  static Future<RankDetailModel> fetchRankDetail(String channel,int id,int page) async{
    final response = await http.get(BaseURL+'/rank/one?channel=${channel}&id=${id}&page=${page}&format=full',
        headers: {'BSAuthorization':BSAuthorization,'READING':'API'});
    if( response.statusCode == 200){
      //解决中文乱码
      Utf8Decoder utf8decoder = Utf8Decoder();
      final json = jsonDecode(utf8decoder.convert(response.bodyBytes));
      return RankDetailModel.fromJson(json);
    }
    else
    {
      throw Exception('加载rankdetail接口失败');
    }
  }
}
class CheckConfigModel {
  bool _success;
  CheckConfigData _data;

  CheckConfigModel({bool success, CheckConfigData data}) {
    this._success = success;
    this._data = data;
  }

  bool get success => _success;
  set success(bool success) => _success = success;
  CheckConfigData get data => _data;
  set data(CheckConfigData data) => _data = data;

  CheckConfigModel.fromJson(Map<String, dynamic> json) {
    _success = json['success'];
    _data = json['data'] != null ? new CheckConfigData.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['success'] = this._success;
    if (this._data != null) {
      data['data'] = this._data.toJson();
    }
    return data;
  }
}

class CheckConfigData {
  int _coin;
  CheckConfigDaily _daily;
  int _gift;
  ConfigConfigNewData _newData;

  CheckConfigData({int coin, CheckConfigDaily daily, int gift, ConfigConfigNewData newData}) {
    this._coin = coin;
    this._daily = daily;
    this._gift = gift;
    this._newData = newData;
  }

  int get coin => _coin;
  set coin(int coin) => _coin = coin;
  CheckConfigDaily get daily => _daily;
  set daily(CheckConfigDaily daily) => _daily = daily;
  int get gift => _gift;
  set gift(int gift) => _gift = gift;
  ConfigConfigNewData get newData => _newData;
  set newData(ConfigConfigNewData newData) => _newData = newData;

  CheckConfigData.fromJson(Map<String, dynamic> json) {
    _coin = json['coin'];
    _daily = json['daily'] != null ? new CheckConfigDaily.fromJson(json['daily']) : null;
    _gift = json['gift'];
    _newData =
    json['new'] != null ? new ConfigConfigNewData.fromJson(json['new']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['coin'] = this._coin;
    if (this._daily != null) {
      data['daily'] = this._dail


tring("vd-lavc-film-grain", "cpu")

        setupSubtitlesOptions()
        setupAudioOptions()
    }

    override fun observeProperties() {
        for ((name, format) in observedProps) MPVLib.observeProperty(name, format)
    }

    override fun postInitOptions() {
        advancedPreferences.playerStatisticsPage().get().let {
            if (it != 0) {
                MPVLib.command(arrayOf("script-binding", "stats/display-stats-toggle"))
                MPVLib.command(arrayOf("script-binding", "stats/display-page-$it"))
            }
        }
    }

    fun onKey(event: KeyEvent): Boolean {
        if (event.action == KeyEvent.ACTION_MULTIPLE || KeyEvent.isModifierKey(event.keyCode)) {
            return false
        }

        var mapped = KeyMapping.map.get(event.keyCode)
        if (mapped == null) {
            // Fallback to produced glyph
            if (!event.isPrintingKey) {
                if (event.repeatCount == 0) {
                    logcat(LogPriority.DEBUG) { "Unmapped non-printable key ${event.keyCode}" }
                }
                return false
            }

            val ch = event.unicodeChar
            if (ch.and(KeyCharacterMap.COMBINING_ACCENT) != 0) {
                return false // dead key
            }
            mapped = ch.toChar().toString()
        }

        if (event.repeatCount > 0) {
            return true // eat event but ignore it, mpv has its own key repeat
        }

        val mod: MutableList<String> = mutableListOf()
        event.isShiftPressed && mod.add("shift")
        event.isCtrlPressed && mod.add("ctrl")
        event.isAltPressed && mod.add("alt")
        event.isMetaPressed && mod.add("meta")

        val action = if (event.action == KeyEvent.ACTION_DOWN) "keydown" else "keyup"
        mod.add(mapped)
        MPVLib.command(arrayOf(action, mod.joinToString("+")))

        return true
    }

    private val observedProps = mapOf(
        "chapter" to MPVLib.mpvFormat.MPV_FORMAT_INT64,
        "chapter-list" to MPVLib.mpvFormat.MPV_FORMAT_NONE,
        "track-list" to MPVLib.mpvFormat.MPV_FORMAT_NONE,

        "time-pos" to MPVLib.mpvFormat.MPV_FORMAT_INT64,
        "demuxer-cache-time" to MPVLib.mpvFormat.MPV_FORMAT_INT64,
        "duration" to MPVLib.mpvFormat.MPV_FORMAT_INT64,
        "volume" to MPVLib.mpvFormat.MPV_FORMAT_INT64,
        "volume-max" to MPVLib.mpvFormat.MPV_FORMAT_INT64,

        "sid" to MPVLib.mpvFormat.MPV_FORMAT_STRING,
        "secondary-sid" to MPVLib.mpvFormat.MPV_FORMAT_STRING,
        "aid" to MPVLib.mpvFormat.MPV_FORMAT_STRING,

        "speed" to MPVLib.mpvFormat.MPV_FORMAT_DOUBLE,
        "video-params/aspect" to MPVLib.mpvFormat.MPV_FORMAT_DOUBLE,

        "hwdec-current" to MPVLib.mpvFormat.MPV_FORMAT_STRING,
        "hwdec" to MPVLib.mpvFormat.MPV_FORMAT_STRING,

        "pause" to MPVLib.mpvFormat.MPV_FORMAT_FLAG,
        "paused-for-cache" to MPVLib.mpvFormat.MPV_FORMAT_FLAG,
        "seeking" to MPVLib.mpvFormat.MPV_FORMAT_FLAG,
        "eof-reached" to MPVLib.mpvFormat.MPV_FORMAT_FLAG,

        "user-data/aniyomi/show_text" to MPVLib.mpvFormat.MPV_FORMAT_STRING,
        "user-data/aniyomi/toggle_ui" to MPVLib.mpvFormat.MPV_FORMAT_STRING,
        "user-


eRegion(pDestTexture, 10, 20, 0, pSourceTexture, &sourceRegion);

```

Notice, that for a 2D texture, front and back are set to 0 and 1 respectively.

#### Examples

The <b>HelloTriangle</b> sample uses <b>ID3D12GraphicsCommandList::CopyTextureRegion</b> as follows:

```cpp
inline UINT64 UpdateSubresources(
    _In_ ID3D12GraphicsCommandList* pCmdList,
    _In_ ID3D12Resource* pDestinationResource,
    _In_ ID3D12Resource* pIntermediate,
    _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
    _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,
    UINT64 RequiredSize,
    _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts,
    _In_reads_(NumSubresources) const UINT* pNumRows,
    _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes,
    _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData)
{
    // Minor validation
    D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc();
    D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc();
    if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
        IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
        RequiredSize > (SIZE_T)-1 ||
        (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER &&
            (FirstSubresource != 0 || NumSubresources != 1)))
    {
        return 0;
    }

    BYTE* pData;
    HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast<void**>(&pData));
    if (FAILED(hr))
    {
        return 0;
    }

    for (UINT i = 0; i < NumSubresources; ++i)
    {
        if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0;
        D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] };
        MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth);
    }
    pIntermediate->Unmap(0, NULL);

    if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
    {
        CD3DX12_BOX SrcBox( UINT( pLayouts[0].Offset ), UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ) );
        pCmdList->CopyBufferRegion(
            pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width);
    }
    else
    {
        for (UINT i = 0; i < NumSubresources; ++i)
        {
            CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource);
            CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]);
            pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr);
        }
    }
    return RequiredSize;
}

```

See Example Code in the D3D12 Reference.

## -see-also

CopyBufferRegion

ID3D12GraphicsCommandList---
description:


ool:
        """일일 주가 데이터 업데이트"""
        try:
            if target_date is None:
                target_date = datetime.now().strftime('%Y-%m-%d')

            logger.info(f"=== 일일 주가 업데이트 시작: {target_date} ===")

            # 누락된 종목 찾기
            missing_stocks = self.quality_checker.find_missing_stocks_for_date(target_date)

            if not missing_stocks:
                logger.info(f"{target_date} 모든 종목 데이터가 최신 상태입니다.")
                return True

            logger.info(f"업데이트 대상: {len(missing_stocks)}개 종목")

            success_count = 0
            for i, stock_code in enumerate(missing_stocks):
                logger.info(f"진행: {i+1}/{len(missing_stocks)} - {stock_code}")

                if self._update_single_stock_price(stock_code, target_date, target_date):
                    success_count += 1

                time_module.sleep(0.1)  # API 호출 제한

            logger.info(f"일일 주가 업데이트 완료: {success_count}/{len(missing_stocks)}")
            return success_count > 0

        except Exception as e:
            logger.error(f"일일 주가 업데이트 실패: {e}")
            return False

    def update_period_stock_prices(self, start_date: str, end_date: str, stock_codes: List[str] = None) -> bool:
        """특정 기간 주가 데이터 업데이트"""
        try:
            logger.info(f"=== 기간 주가 업데이트: {start_date} ~ {end_date} ===")

            # 종목 목록 가져오기
            if stock_codes is None:
                with get_db_connection('stock') as conn:
                    stock_df = pd.read_sql("SELECT stock_code FROM company_info", conn)
                    stock_codes = stock_df['stock_code'].tolist()

            total_count = len(stock_codes)
            success_count = 0

            for i, stock_code in enumerate(stock_codes):
                logger.info(f"진행: {i+1}/{total_count} - {stock_code}")

                # 누락된 날짜 찾기
                missing_dates = self.quality_checker.find_missing_dates(stock_code, start_date, end_date)

                if missing_dates:
                    logger.info(f"{stock_code}: {len(missing_dates)}개 날짜 누락")

                    if self._update_single_stock_price(stock_code, start_date, end_date):
                        success_count += 1
                else:
                    logger.debug(f"{stock_code}: 데이터 완료")
                    success_count += 1

                time_module.sleep(0.1)

            logger.info(f"기간 주가 업데이트 완료: {success_count}/{total_count}")
            return success_count > 0

        except Exception as e:
            logger.error(f"기간 주가 업데이트 실패: {e}")
            return False

    def _update_single_stock_price(self, stock_code: str, start_date: str, end_date: str) -> bool:
        """단일 종목 주가 데이터 업데이트"""
        try:
            # 주가 데이터 수집
            df = fdr.DataReader(stock_code, start_date, end_date)

            if df.empty:
                logger.warning(f"주가 데이터 없음: {stock_code}")
                return False

            # 데이터 정리
            df = df.reset_index()
            df['stock_code'] = stock_code
            df = df.rename(columns={
                'Date': 'date',
                'Open': 'open_price',
                'High': 'high_price',
                'Low': 'low_price',
                'Close': 'close_price',
                'Volume': 'volume'
            })

            # 필요한 컬럼만 선택
            required_columns = [
                'stock_code', 'date', 'open_price', 'high_price',
                'low_price', 'close_price', 'volume'
            ]
            df = df[required_columns]

            # 추가 계산
            df['adjusted_close'] = df['close_price']
            df['amount'] = df['volume'] * df['close_price']
            df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y-%m-%d')

            # 데이터베이스 저장
            with get_db_connection('stock') as conn:
                # 기존 데이터 삭제 (중복 방지)
                conn.execute(
                    "DELETE FROM stock_prices WHERE stock_code = ? AND date BETWEEN ? AND ?",
                    (stock_code, start_date, end_date)
                )

                # 새 데이터 삽입
                df.to_sql('stock_prices', conn, if_exists='append', index=False)