At, keybase1.ToTime(cachedAt))
	require.Equal(t, results[0].FullName.Status, keybase1.StatusCode_SCOk)

	// Same as above, but give enough time to refresh the name from the server
	hit = false
	setCachedAt = true
	results, err = uidMap.MapUIDsToUsernamePackages(context.TODO(), tc.G, uids, time.Second, 0, false)
	require.NoError(t, err)
	require.True(t, hit)
	require.Equal(t, results[0].NormalizedUsername, libkb.NewNormalizedUsername("t_kb"))
	require.Equal(t, results[0].FullName.FullName, keybase1.FullName("Joe Keybaser"))
	require.Equal(t, results[0].FullName.EldestSeqno, keybase1.Seqno(1))
	require.Equal(t, results[0].FullName.CachedAt, keybase1.ToTime(cachedAt))
	require.Equal(t, results[0].FullName.Status, keybase1.StatusCode_SCOk)

	// In this case, there's not enough time to make any fetches, but it doesn't matter, since our
	// previous fetch is fresh enough. We should never even hit testBatchIterHook
	fakeClock.Advance(time.Minute)
	hit = false
	setCachedAt = false
	results, err = uidMap.MapUIDsToUsernamePackages(context.TODO(), tc.G, uids, time.Hour, time.Nanosecond, false)
	require.NoError(t, err)
	require.False(t, hit)
	require.Equal(t, results[0].NormalizedUsername, libkb.NewNormalizedUsername("t_kb"))
	require.Equal(t, results[0].FullName.FullName, keybase1.FullName("Joe Keybaser"))
	require.Equal(t, results[0].FullName.EldestSeqno, keybase1.Seqno(1))
	require.Equal(t, results[0].FullName.CachedAt, keybase1.ToTime(cachedAt))
	require.Equal(t, results[0].FullName.Status, keybase1.StatusCode_SCOk)

	// Do a happy path for several users:
	uids = []keybase1.UID{mikemUID, tKB, maxUID}
	results, err = uidMap.MapUIDsToUsernamePackages(context.TODO(), tc.G, uids, 0, 0, false)
	require.NoError(t, err)

	// Everyone gets back a normalized username
	require.Equal(t, results[0].NormalizedUsername, libkb.NewNormalizedUsername("mikem"))
	require.Equal(t, results[1].NormalizedUsername, libkb.NewNormalizedUsername("t_kb"))
	require.Equal(t, results[2].NormalizedUsername, libkb.NewNormalizedUsername("max"))

	// But only t_kb has a fullname that's found
	require.Nil(t, results[0].FullName)
	require.Equal(t, results[1].FullName.FullName, keybase1.FullName("Joe Keybaser"))
	require.Equal(t, results[1].FullName.CachedAt, keybase1.ToTime(cachedAt))
	require.Equal(t, results[1].FullName.EldestSeqno, keybase1.Seqno(1))
	require.Equal(t, results[1].FullName.Status, keybase1.StatusCode_SCOk)
	require.Nil(t, results[2].FullName)

	// We should get same results from offline call
	uidMap.testBatchIterHook = func() {
		require.Fail(t, "unexpected network activity during offline uidmap call")
	}

	resultsCached, err := uidMap.MapUIDsToUsernamePackagesOffline(context.TODO(), tc.G, uids, 0)
	require.NoError(t, err)
	require.Equal(t, results, resultsCached)
}

func TestOfflineUIDMap


menu_list_items>:last-child a,.hover_menu .menu_list_items>:last-child .completed{border-radius:0 0 3px 3px}.hover_menu .menu_list_items>:only-child a,.hover_menu .menu_list_items>:only-child .completed{border-radius:3px}.hover_menu .menu_list_items>div{position:relative}.hover_menu .menu_list_item{position:relative}.hover_menu .menu_list_item.selected{color:#333}.hover_menu .menu_list_item.selected:after{content:"";position:absolute;left:6px;top:50%;margin-top:-6px;display:inline-block;width:12px;height:12px;background-size:12px 12px;background-repeat:no-repeat;background-image:url(//qsf.fs.quoracdn.net/-4-images.icons.blue_check.svg-26-73dd61a441377532.svg)}.hover_menu .menu_list_item a,.hover_menu .menu_list_item.radio_group,.hover_menu .menu_list_item .completed{position:relative;cursor:pointer;display:block;padding:5px 15px 6px 24px}.hover_menu .menu_list_item a:hover,.hover_menu .menu_list_item.radio_group:hover,.hover_menu .menu_list_item .completed:hover{text-decoration:none;background-color:#dfeffa}.hover_menu .menu_list_item .completed{color:#949494;cursor:default}.hover_menu .menu_list_item .completed:hover{background-color:transparent}.hover_menu .menu_list_item.radio_group input[type='radio']{margin-left:-18px}.hover_menu .menu_list_item .checkable_item input[type='checkbox']{pointer-events:none;margin-left:-18px}.hover_menu .menu_list_item .checkable_item span{margin-left:6px}.hover_menu.show_nub:not(.hover_menu_above):before{content:'';display:block;width:0;height:0;border-color:rgba(204,204,204,0);border-left:7.5px solid transparent;border-right:7.5px solid transparent;border-bottom:7px solid #ccc;left:14px;margin-top:-7px}.hover_menu.show_nub:not(.hover_menu_above):after{content:'';display:block;width:0;height:0;border-color:rgba(204,204,204,0);border-left:7.5px solid transparent;border-right:7.5px solid transparent;border-bottom:7px solid #f7f7f7;left:14px;margin-top:-6px;position:absolute}.hover_menu.show_nub:not(.hover_menu_above).white_bg:after{content:'';display:block;width:0;height:0;border-color:rgba(204,204,204,0);border-left:7.5px solid transparent;border-right:7.5px solid transparent;border-bottom:7px solid #fff}.hover_menu.show_nub:not(.hover_menu_above).center_align:before,.hover_menu.show_nub:not(.hover_menu_above).center_align:after{left:calc(50% - 7.5px)}.hover_menu.show_nub:not(.hover_menu_above).right_align:before,.hover_menu.show_nub:not(.hover_menu_above).right_align:after{left:auto;right:9px}.hover_menu.show_nub:not(.hover_menu_above) .menu_list_items>.menu_list_item:first-child:hover:before,.hover_menu.show_nub:not(.hover_menu_above) .menu_list_items>div:first-child:hover:before{content:'';display:block;width:0;height:0;border-color:rgba(20


.sjs?file=";
  // append the file that should be served
  src += escape("tests/dom/security/test/csp/file_strict_dynamic_default_src.html");
  // append the CSP that should be used to serve the file
  src += "&csp=" + escape(curTest.policy);

  document.getElementById("testframe").addEventListener("load", checkResults);
  document.getElementById("testframe").src = src;
}

function checkResults() {
  try {
    var testframe = document.getElementById("testframe");
    testframe.removeEventListener('load', checkResults);

    // check if script loaded
    var divcontent = testframe.contentWindow.document.getElementById('testdiv').innerHTML;
    var imgcontent = testframe.contentWindow.document.getElementById('testimage').dataset.result;
    if (curTest.script_result === "blocked") {
      todo_is(divcontent, curTest.script_result, curTest.script_desc);
    }
    else {
      is(divcontent, curTest.script_result, curTest.script_desc);
    }

    // check if image loaded
    var testimg = testframe.contentWindow.document.getElementById("testimage");
    if (curTest.img_result === "allowed") {
      todo_is(imgcontent, curTest.img_result, curTest.img_desc);
    }
    else {
      is(imgcontent, curTest.img_result, curTest.img_desc);
    }
  }
  catch (e) {
    ok(false, "ERROR: could not access content for test: '" + curTest.script_desc + "'");
  }

  loadNextTest();
}

// start running the tests
loadNextTest();

</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
  <title>Bug 1299483 - CSP: Implement 'strict-dynamic'</title>
  <!-- Including SimpleTest.js so we can use waitForExplicitFinish !-->
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
  <iframe style="width:100%;" id="testframe"></iframe>

<script class="testbody" type="text/javascript">

SimpleTest.waitForExplicitFinish();
SpecialPowers.setBoolPref("security.csp.enableStrictDynamic", true);

/* Description of the test:
 * We load scripts with a CSP of 'strict-dynamic' with valid
 * and invalid nonces and make sure scripts are allowed/blocked
 * accordingly. Different tests load inline and external scripts
 * also using a CSP including http: and https: making sure
 * other srcs are invalided by 'strict-dynamic'.
 */

var tests = [
  {
    desc: "strict-dynamic with valid nonce should be allowed",
    result: "allowed",
    file: "file_strict_dynamic_script_extern.html",
    policy: "script-src 'strict-dynamic' 'nonce-foo' https: 'none' 'self'"
  },
  {
    desc: "strict-dynamic with invalid nonce should be blocked",
    result: "blocked",
    file: "file_strict_dynamic_script_extern.html",
    policy: "script-src 'strict-dynamic' 'nonce-bar' http: http://example.com"
  },
  {
    desc: "strict-dynamic, allowlist and invalid nonce should be blocked",
    result: "blocked",
    file: "file_strict_dynamic_script_extern.html",
    policy: "script-src 'strict-dynamic' 'nonce-bar' 'unsafe-inline' http: http://example.com"
  },
  {
    desc: "strict-dynamic with no 'nonce-' should be blocked",
    result: "blocked",
    file: "file_strict_dynamic_script_extern.html",
    policy:


 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.faendir.acra.persistence.bug

import com.faendir.acra.dataprovider.AcrariumDataProvider
import com.faendir.acra.dataprovider.AcrariumSort
import com.faendir.acra.jooq.generated.tables.references.BUG
import com.faendir.acra.jooq.generated.tables.references.BUG_IDENTIFIER
import com.faendir.acra.jooq.generated.tables.references.REPORT
import com.faendir.acra.persistence.*
import com.faendir.acra.persistence.app.AppId
import com.faendir.acra.persistence.version.VersionKey
import jakarta.validation.constraints.Size
import org.jooq.DSLContext
import org.springframework.security.access.prepost.PostAuthorize
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
import java.util.stream.Stream

@Repository
class BugRepository(
    private val jooq: DSLContext,
) {

    @PreAuthorize("isReporter() || hasViewPermission(#identifier.appId)")
    fun findId(identifier: BugIdentifier): BugId? =
        jooq.select(BUG_IDENTIFIER.BUG_ID).from(BUG_IDENTIFIER).where(BUG_IDENTIFIER.matches(identifier)).fetchValue()

    @PostAuthorize("returnObject == null || hasViewPermission(returnObject.appId)")
    fun find(bugId: BugId): Bug? =
        jooq.selectFrom(BUG).where(BUG.ID.eq(bugId)).fetchValueInto()

    fun findInRange(appId: AppId, range: ClosedRange<Instant>): List<Bug> =
        jooq.selectFrom(BUG)
            .where(
                BUG.APP_ID.eq(appId),
                BUG.LATEST_REPORT.greaterOrEqual(range.start),
                BUG.LATEST_REPORT.lessOrEqual(range.endInclusive)
            )
            .fetchListInto()

    fun getIdentifiers(bugId: BugId): List<BugIdentifier> =
        jooq.select(BUG_IDENTIFIER.fields().toList() - BUG_IDENTIFIER.BUG_ID)
            .from(BUG_IDENTIFIER)
            .where(BUG_IDENTIFIER.BUG_ID.eq(bugId))
            .fetchListInto()

    @PreAuthorize("hasViewPermission(#appId)")
    fun getAllIds(appId: AppId): List<BugId> =
        jooq.select(BUG.ID.NOT_NULL).from(BUG).where(BUG.APP_ID.eq(appId)).fetchList()

    @PreAuthorize("isReporter()")
    fun create(identifier: BugIdentifier, title: String): BugId {
        val bugId = jooq.insertInto(BUG)
            .set(BUG.APP_ID, identifier.appId)
            .set(BUG.TITLE, title)
            .returningResult(BUG.ID)
            .fetchValue()!!
        jooq.insertInto(BUG_IDENTIFIER)
            .set(BUG_IDENTIFIER.BUG_ID, bugId)
            .set(BUG_IDENTIFIER.APP_ID, identifier.appId)


.GetControllerName())
		t.Logf("rm 2 instance id: %v", rsc2.GetControllerName())

		assert.NotEqual(t, rsc1.GetControllerName(), rsc2.GetControllerName())
		controllerInstanceList2, err := client2.CoreV1().ControllerInstances().List(metav1.ListOptions{})
		assert.Nil(t, err)
		assert.NotNil(t, controllerInstanceList2)
		assert.Equal(t, 2, len(controllerInstanceList2.Items), "number of controller instance")
		t.Logf("new rms [%#v]", controllerInstanceList2)

		rsControllerInstanceRead1, err := client2.CoreV1().ControllerInstances().Get(rsc1.GetControllerName(), metav1.GetOptions{})
		assert.Nil(t, err)
		rsControllerInstanceRead2, err := client2.CoreV1().ControllerInstances().Get(rsc2.GetControllerName(), metav1.GetOptions{})
		assert.Nil(t, err)

		instance1 := getInstanceFromControllerInstancesAndExpectedPos(0, rsControllerInstanceRead1, rsControllerInstanceRead2)
		instance2 := getInstanceFromControllerInstancesAndExpectedPos(1, rsControllerInstanceRead1, rsControllerInstanceRead2)
		t.Logf("sorted instance 1 %s controllerKey %v", instance1.Name, instance1.ControllerKey)
		t.Logf("sorted instance 2 %s controllerKey %v", instance2.Name, instance2.ControllerKey)
		// check controller instance updates
		assert.Equal(t, rsControllerInstance1.ControllerType, instance1.ControllerType)
		assert.Equal(t, rsControllerInstance1.ControllerType, instance2.ControllerType)

		assert.Equal(t, int64(4611686018427387904), instance1.ControllerKey) // consistent hash
		assert.Equal(t, int64(math.MaxInt64), instance2.ControllerKey)

		// case 3. start controller manager 3
		cim3, rsc3, informers3, client3 := RmSetupControllerMaster(t, s)
		stopCh3 := RunControllerAndInformers(t, cim3, rsc3, informers3, 0)
		defer close(stopCh3)
		time.Sleep(5 * time.Second)
		t.Logf("rm 3 instance id: %v", rsc3.GetControllerName())
		rsc1.ReportHealth(client1)
		rsc2.ReportHealth(client2)
		rsc3.ReportHealth(client3)

		// check replicaset controller status in controller manager 2
		assert.NotEqual(t, rsc1.GetControllerName(), rsc3.GetControllerName())
		assert.NotEqual(t, rsc2.GetControllerName(), rsc3.GetControllerName())
		controllerInstanceList3, err := client2.CoreV1().ControllerInstances().List(metav1.ListOptions{})
		assert.Nil(t, err)
		assert.NotNil(t, controllerInstanceList3)
		assert.Equal(t, 3, len(controllerInstanceList3.Items), "number of controller instance")

		rsControllerInstanceRead1, err = client3.CoreV1().ControllerInstances().Get(rsc1.GetControllerName(), metav1.GetOptions{})
		assert.Nil(t, err)
		rsControllerInstanceRead2, err = client3.CoreV1().ControllerInstances().Get(rsc2.GetControllerName(), metav1.GetOptions{})
		assert.Nil(t, err)
		rsControllerInstanceRead3, err := client3.CoreV1().ControllerInstances().Get(rsc3.GetControllerName(), metav1.GetOptions{})
		assert.Nil(t, err)

		instance1 = getInstanceFromControllerInstancesAndExpectedPos(0, rsControllerInstanceRead1, rsControllerInstanceRead2, rsControllerInstanceRead3)
		instance2 = getInstanceFromControllerInstancesAndExpectedPos(1, rsControllerInstanceRead1, rsControllerInstanceRead2, rsControllerInstanceRead3)
		instance3 := getInstanceFromControllerInstancesAndExpectedPos(2, rsControllerInstanceRead1, rsControllerInstanceRead2, rsControllerInstanceRead3)
		t.Logf("sorted instance 1 %s controllerKey


Tabs))
		})

		// set (and clamp) main window size to fit on the current screen
		clampAndApplyWindowSize(w, "MainWindowWidth", "MainWindowHeight", 1200, 600)

		// show main window
		fyne.Do(func() {
			w.Show()
		})

		// set websocket client to configured ip+port
		WebsocketClient.Addr = Settings.Config.Websocket_ip + ":" + strconv.Itoa(Settings.Config.Websocket_port)

		go WebsocketClient.Start()

		fyne.CurrentApp().Preferences().SetFloat("ProfileWindowWidth", float64(profileWindow.Canvas().Size().Width))
		fyne.CurrentApp().Preferences().SetFloat("ProfileWindowHeight", float64(profileWindow.Canvas().Size().Height))

		// close profile window
		profileWindow.SetOnClosed(func() {}) // disable quit handler for programmatic close
		profileWindow.Close()
	}

	profilePage := Pages.CreateProfileWindow(onProfileClose)
	profileWindow.SetContent(profilePage)
	// quit application if profile window is closed without using the button
	profileWindow.SetOnClosed(func() {
		fyne.CurrentApp().Quit()
	})
	// set (and clamp) profile window size to fit on the current screen
	clampAndApplyWindowSize(profileWindow, "ProfileWindowWidth", "ProfileWindowHeight", 1400, 600)

	profileWindow.CenterOnScreen()
	profileWindow.Show()

	exePath, err := os.Executable()

	go func() {
		if err == nil && exePath != "" {
			exeDir := filepath.Dir(exePath)
			// check if enough free space is available if no whisper executable is found
			if !Utilities.FileExists("audioWhisper/audioWhisper.exe") && !Utilities.FileExists("audioWhisper.py") {
				checkFreeSpace(profileWindow, exeDir, minFreeSpace)
			}

			// priority: warn if running from temp directory, then ask about error reporting
			if strings.HasPrefix(strings.ToLower(exeDir), strings.ToLower(os.TempDir())) {
				//goland:noinspection GoErrorStringFormat
				dlg := dialog.NewError(
					errors.New(lang.L("It looks like you are running Whispering Tiger from a temporary directory. Please extract the application and run it from a different folder.")),
					profileWindow,
				)
				dlg.SetOnClosed(func() {
					requestErrorReporting(profileWindow)
					startBackgroundTasks()
				})

				fyne.Do(func() {
					dlg.Show()
				})
			} else {
				requestErrorReporting(profileWindow)
				startBackgroundTasks()
			}
		} else {
			requestErrorReporting(profileWindow)
			startBackgroundTasks()
		}
	}()

	a.Lifecycle().SetOnStopped(func() {
		// after run (app exit), send whisper process signal to stop
		if len(RuntimeBackend.BackendsList) > 0 {
			RuntimeBackend.BackendsList[0].Stop()
			RuntimeBackend.BackendsList[0].WriterBackend.Close()
			RuntimeBackend.BackendsList[0].ReaderBackend.Close()
		}
	})

	a.Run()
}

// new helper – ask about error reporting once, then start background tasks
func requestErrorReporting(parentWindow fyne.Window) {
	if !fyne.CurrentApp().Preferences().BoolWithFallback("SendErrorsToServerInit", false) {
		fyne.Do(func() {
			dialog.NewConfirm(
				lang.L("Automatically Report Errors"),
				lang.L("Do you want to automatically report errors?"),
				func(b bool) {
					Logging.EnableReporting(b)
					fyne.CurrentApp().Preferences().SetBool("SendErrorsToServerInit", true)
				},
				parentWindow,
			).Show()
		})
	}
}

func checkFreeSpace(window fyne.Window, directory string, spaceRequired uint64) {
	// check free space
	if fre


// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;

namespace StringInterpolation
{
    class LambdaExpressions
    {
        static void Main()
        {
            // Braces for multiple statements aren't allowed...
            // Console.WriteLine($"{{Console.WriteLine("hello"); return "y";}}");

            // Lambda expressions don't have a type...
            // Console.WriteLine($"{() => "won't work"}");

            // ... but you can cast lambda expressions to specifi


 NULL, &count, NULL);

	if (count == 0)
		goto next;

	for (i = 0, buf = isoc->i_buf;
	     i < ax->ax_nframes;
	     ++i, buf += ax->ax_uframe_len) {
		status = auvitek_isoc_process(sc, buf, isoc->i_frlengths[i]);
		if (status == USBD_IOERROR)
			break;
	}

next:
	auvitek_isoc_start1(isoc);
}

static int
auvitek_isoc_process(struct auvitek_softc *sc, uint8_t *buf, uint32_t len)
{
	struct video_payload payload;
	bool submit = false;

	if (buf[0] & 0x80) {
		sc->sc_ax.ax_frinfo = buf[0];
		if (sc->sc_ax.ax_frinfo & 0x40) {
			sc->sc_ax.ax_frno = !sc->sc_ax.ax_frno;
			submit = true;
		}
		buf += 4;
		len -= 4;
	}
	buf += 4;
	len -= 4;

	auvitek_videobuf_weave(sc, buf, len);

	if (submit) {
		payload.end_of_frame = 1;
		payload.data = sc->sc_ax.ax_av.av_buf;
		payload.size = sizeof(sc->sc_ax.ax_av.av_buf);
		payload.frameno = -1;

		video_submit_payload(sc->sc_videodev, &payload);

		sc->sc_ax.ax_av.av_el = sc->sc_ax.ax_av.av_ol = 0;
		sc->sc_ax.ax_av.av_eb = sc->sc_ax.ax_av.av_ob = 0;
	}

	return USBD_NORMAL_COMPLETION;
}

static void
auvitek_videobuf_weave(struct auvitek_softc *sc, uint8_t *buf, uint32_t len)
{
	struct auvitek_videobuf *av = &sc->sc_ax.ax_av;
	uint32_t resid, wlen;
	uint32_t *l, *b;
	uint8_t *vp;

	if (sc->sc_ax.ax_frinfo & 0x40) {
		l = &av->av_ol;
		b = &av->av_ob;
		vp = av->av_buf;
	} else {
		l = &av->av_el;
		b = &av->av_eb;
		vp = av->av_buf + av->av_stride;
	}

	resid = len;
	while (resid > 0) {
		if (*b == av->av_stride) {
			*l = *l + 1;
			*b = 0;
		}
		if (*l >= 240) {
			break;
		}
		wlen = min(resid, av->av_stride - *b);
		memcpy(vp + (av->av_stride * 2 * *l) + *b, buf, wlen);
		*b += wlen;
		buf += wlen;
		resid -= wlen;
	}
}


CodeMirror

Home

Manual

Code

Language modes

SLIM

SLIM mode

  <form><textarea id="code" name="code">
body
  table
    - for user in users
      td id="user_#{user.id}" class=user.role
        a href=user_action(user, :edit) Edit #{user.name}
        a href=(path_to_user user) = user.name
body
  h1(id="logo") = page_logo
  h2[id="tagline" class="small tagline"] = page_tagline

h2[id="tagline"
   class="small tagline"] = page_tagline

h1 id = "logo" = page_logo
h2 [ id = "tagline" ] = page_tagline

/ comment
  second line
/! html comment
   second line

link
a.slim href="work" disabled=false running==:atom Text bold
.clazz data-id="test" == 'hello' unless quark
 | Text mode #{12}
   Second line
= x ||= :ruby_atom
#menu.left
  - @env.each do |x|
    li: a = x
*@dyntag attr="val"
.first *{:class => [:second, :third]} Text
.second class=["text","more"]
.third class=:text,:symbol

  </textarea></form>

MIME types defined: application/x-slim.

    Parsing/Highlighting Tests:
    normal,
    verbose.

<!doctype html>

<title>CodeMirror: TiddlyWiki mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">
<link rel="stylesheet" href="tiddlywiki.css">


setfield(L, mt, "Div");
	lua_pushcfunction(L, createMul); lua_setfield(L, mt, "Mul");
	lua_pushcfunction(L, createRem); lua_setfield(L, mt, "Rem");
	lua_pushcfunction(L, createNeg); lua_setfield(L, mt, "Neg");
	lua_pushcfunction(L, createNot); lua_setfield(L, mt, "Not");
	lua_pushcfunction(L, createCmpEQ); lua_setfield(L, mt, "CmpEQ");
	lua_pushcfunction(L, createCmpNE); lua_setfield(L, mt, "CmpNE");
	lua_pushcfunction(L, createCmpLE); lua_setfield(L, mt, "CmpLE");
	lua_pushcfunction(L, createCmpLT); lua_setfield(L, mt, "CmpLT");
	lua_pushcfunction(L, createCmpGE); lua_setfield(L, mt, "CmpGE");
	lua_pushcfunction(L, createCmpGT); lua_setfield(L, mt, "CmpGT");
	lua_pushcfunction(L, createFToI); lua_setfield(L, mt, "FToI");
	lua_pushcfunction(L, createIToF); lua_setfield(L, mt, "IToF");
	lua_pushcfunction(L, createBitCast); lua_setfield(L, mt, "BitCast");
	lua_pushcfunction(L, createCall); lua_setfield(L, mt, "Call");
	lua_pushcfunction(L, createExtractValue); lua_setfield(L, mt, "ExtractValue");
	lua_pushcfunction(L, createInsertValue); lua_setfield(L, mt, "InsertValue");
	lua_pushcfunction(L, createAlloca); lua_setfield(L, mt, "Alloca");
	lua_pushcfunction(L, createLoad); lua_setfield(L, mt, "Load");
	lua_pushcfunction(L, createStore); lua_setfield(L, mt, "Store");
	lua_pushcfunction(L, createGEP); lua_setfield(L, mt, "GEP");
}

extern "C" int luaopen_llvm(lua_State * L) {
	lua_newtable(L);

	Glue<Module>::define(L);

	Glue<Type>::define(L);
	Glue<StructType>::define(L);
	Glue<SequentialType>::define(L);
	Glue<PointerType>::define(L);
	Glue<ArrayType>::define(L);
	Glue<VectorType>::define(L);
	Glue<OpaqueType>::define(L);
	Glue<FunctionType>::define(L);

	Glue<Value>::define(L);
	Glue<Argument>::define(L);
	Glue<Instruction>::define(L);
	Glue<PHINode>::define(L);
	Glue<BasicBlock>::define(L);
	Glue<Constant>::define(L);
	Glue<GlobalValue>::define(L);
	Glue<Function>::define(L);

	Glue<IRBuilder<> >::define(L);

	Glue<Module>::register_ctor(L);

	Glue<StructType>::register_ctor(L);
	Glue<PointerType>::register_ctor(L);
	Glue<ArrayType>::register_ctor(L);
	Glue<VectorType>::register_ctor(L);
	Glue<OpaqueType>::register_ctor(L);
	Glue<FunctionType>::register_ctor(L);

	Glue<Constant>::register_ctor(L);
	Glue<Function>::register_ctor(L);
	Glue<BasicBlock>::register_ctor(L);

	Glue<IRBuilder<> >::register_ctor(L);

	//lua_pushcfunction(L, constant_Double); lua_setfield(L, -2, "

	Glue<Type>::push(L, (Type *)Type::getVoidTy(getGlobalContext())); lua_setfield(L, -2, "Void");
	Glue<Type>::push


용한다.

**그러나** HTTP 2.0이 발전되면서 HTTPS가 HTTP 보다 빠르다는 사실이 나왔다. 다음 링크를 통해 보다 자세한 내용을 확인할 수 있다.
관련 링크: [HTTPS가 HTTP보다 빠르다.](https://tech.ssut.me/https-is-faster-than-http/)
# 트랜잭션

데이터베이스의 상태를 변환시키는 하나의 논리적 기능을 수행하기 위한 작업의 단위 또는 한꺼번에 모두 수행되어야 할 일련의 연산들을 의미.

## 트랜잭션의 특징

1. 트랜잭션은 데이터 베이스 시스템에서 병행제어 및 회복 작업 시 처리되는 **작업의 논리적인 단위** 이다.
2. 사용자가 시스템에 대한 서비스 요구 시 시스템이 응답하기 위한 상태 변환 과정의 작업단위 이다.
3. 하나의 트랜잭션은 Commit되거나 Rollback된다.

## 트랜잭션의 성질

**Atomicity(원자성)**

1. 트랜잭션의 연산은 데이터베이스에 모두 반영되든지 아니면 전혀 반영되지 않아야 한다.

2. 트랜잭션 내의 모든 명령은 반드시 완벽히 수행되어야 하며, 모두가 완벽히 수행되지 않고 어느하나라도 오류가 발생하면 트랜잭션 전부가 취소되어야 한다.

**Consistency(일관성)**

1. 트랜잭션이 그 실행을 성공적으로 완료하면 언제나 **일관성 있는 데이터베이스 상태로 변환** 한다.
   * 여기서 일관성이 있어야 한다는 것은 트랜잭션의 작업 처리결과


rovided when registering the test
  */
export declare type testFixtureFunc = (fixture: Object, userData: Object | null) => void;
/**
  * The type used for test case functions.
  */
export declare type testFunc = () => void;
/**
  * Specifies the prototype of fatal log handler functions.
  * @param logDomain the log domain of the message
  * @param logLevel the log level of the message (including the fatal and recursion flags)
  * @param message the message to process
  * @param userData user data, set in g_test_log_set_fatal_handler()
  * @returns True if the program should abort, False otherwise
  */
export declare type testLogFatalFunc = (logDomain: string, logLevel: import('../GLib').LogLevelFlags, message: string, userData: Object | null) => boolean;
/**
  * Specifies the type of the func functions passed to g_thread_new() or g_thread_try_new().
  * @param data data passed to the thread
  * @returns the return value of the thread
  */
export declare type threadFunc = (data: Object | null) => Object | null;
/**
  * The type of functions which are used to translate user-visible strings, for –help output.
  * @param str the untranslated string
  * @param data user data specified when installing the function, e.g. in GLib.OptionGroup.set_translate_func()
  * @returns a translation of the string for the current locale. The returned string is owned by GLib and must not be freed.
  */
export declare type translateFunc = (str: string, data: Object | null) => string;
/**
  * Specifies the type of function passed to g_tree_traverse(). It is passed the key and value of each node, together with the user_data parameter passed to g_tree_traverse(). If the function returns True, the traversal is stopped.
  * @param key a key of a GLib.Tree node
  * @param value the value corresponding to the key
  * @param data user data passed to g_tree_traverse()
  * @returns True to stop the traversal
  */
export declare type traverseFunc = (key: Object | null, value: Object | null, data: Object | null) => boolean;
/**
  * The type of functions to be called when a UNIX fd watch source triggers.
  * @param fd the fd that triggered the event
  * @param condition the IO conditions reported on fd
  * @param userData user data passed to g_unix_fd_add()
  * @returns False if the source should be removed
  */
export declare type unixFdSourceFunc = (fd: number, condition: import('../GLib').IOCondition, userData: Object | null) => boolean;
/**
  * Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to GLib.atexit().
  */
export declare type voidFunc = () => void;
import 'jest'
import { elevate, init } from '../src'

describe('elevate', () => {
  it('should create a higher order reducer from reducer', () => {
    interface S {
      foo?: boolean
      bar?: boolean
    }
    const reducer = (state: S | undefined): S => ({ ...state,  foo: true })
    const hor = elevate(reducer)
    const finalReducer = hor(init<S>({ bar: true }))
    expect(finalReducer(undefined, { type: 'foo' })).toEqual({ foo: true, bar: true })
  })
})
import { parseExpression } from "@babel/parser";
import { cloneDeepWithoutLoc } from "@babel/types";
import { getLocationInJSONAst } from "./get-location-in-json-ast";

describe("util/get-location-in-json-ast", () => {
  test("should throw an object if root ast is not an object", () => {
    const source = JSON.stringify(123);
    const ast = parseExpression(source);

    expect(() =>
      getLocationInJSONAst(ast, ["any"])
    ).toThrowErrorMatchingInlineSnapshot(
      `"Expected ast root node to be ObjectExpression for current path: any"`
    );


*3/4 3*8/5*3/4', x: 1461, z: -925},
	{desc: 'mbottl 4*3/4 3*8/5*3/4', x: 1270, z: -1009},
	{desc: 'rdrone 1 4/3 5/3 + 1', x: 17, z: 583},
	{desc: 'rdrone 2/3 2/3 7/6 + 1', x: -189, z: 255},
	{desc: 'rdrone 4/3 16/9 20/9 + 1', x: -63, z: -599},
	{desc: 'rdrone 3/2 3/4 9/4', x: 1514, z: -1256},
	{desc: 'rdrone 1 1/2 3/2', x: 393, z: 24},
	{desc: 'vib 6 19/4', x: 528, z: -106},
	{desc: 'cbass 3/5 + 0.7', x: 509, z: -325},
	{desc: 'cbass 1 + 0.5', x: 874, z: -338},
	{desc: 'cbass 7/6 + 1 360', x: 1192, z: -483},
	{desc: 'cbass 1 + 0.6', x: 1223, z: -283},
	{desc: 'sdrone 4*3/4 3*8/5*3/4', x: 1363, z: -574},
	{desc: 'sdrone 4 6', x: 1120, z: -178},
	{desc: 'vtone 2/3', x: 43, z: 80},
	{desc: 'cbass 2/3 + 0.4', x: 24, z: -187},
	{desc: 'rdrone 2/3 2/3 7/6', x: 226, z: -194},
	{desc: 'vib 24/9 30/9', x: -62, z: -832},
	{desc: 'vtone 2/6', x: 140, z: -451},
	{desc: 'vtone 1/3', x: -114, z: -1081},
	{desc: 'cbass 1 + 0.5 600', x: 57, z: -1283},
	{desc: 'cbass 1/3 + 0.3', x: 133, z: -1042},
	{desc: 'vib 8/3 2', x: 262, z: -1056},
	{desc: 'cbass 3/4 + 0.5 600', x: 1136, z: -768},
	{desc: 'vtone 1 3/4', x: 1320, z: -43},
	{desc: 'vtone 8/9', x: 1288, z: 348},
	{desc: 'sdrone 6 8', x: 969, z: 1189},
	{desc: 'vtone 1/2 10/9', x: 1464, z: 623},
	{desc: 'cbass 1 + 0.5', x: 1475, z: 316},
	{desc: 'cbass 1/2 + 0.5', x: 1244, z: 119},
	{desc: 'cbass 3/4 + 0.5 600', x: 1226, z: 658},
	{desc: 'vtone 1 3/4', x: 1492, z: 960},
	{desc: 'sdrone 4 6', x: 1197, z: 1155},
	{desc: 'cbass 1 + 0.5', x: 1279, z: 965},
	{desc: 'msop 6 8', x: 1036, z: 966},
	{desc: 'vib 5/2 8/3', x: 630, z: 829},
	{desc: 'cbass 1/2 + 0.5', x: 452, z: 905},
	{desc: 'cbass 1/2 + 0.5', x: 798, z: 961},
	{desc: 'cbass 3/4 + 0.5', x: 224, z: 874},
	{desc: 'vib 6/4 4', x: 329, z: 991},

	/* 01 */ {desc: 'wbell 4/3', x: 430, z: 4680, floor: 1},
	/* 02 */ {desc: 'wbell 2', x: 89, z: 4899, floor: 1},
	/* 03 */ {desc: 'wbell 2*3/4', x: 891, z: 4845, floor: 1},
	/* 04 */ {desc: 'wbell 2*4/3', x: 549, z: 5134, floor: 1},
	/* 05 */ {desc: 'wbell 3', x: 176, z: 5442, floor: 1},
	/* 06 */


valid-tooltip{display:block}.was-validated .form-control:valid,.form-control.is-valid{border-color:#28a745;padding-right:calc(1.5em + .75rem);background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.was-validated .form-control:valid:focus,.form-control.is-valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,0.25)}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.was-validated .custom-select:valid,.custom-select.is-valid{border-color:#28a745;padding-right:calc(.75em + 2.3125rem);background:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") no-repeat right .75rem center/8px 10px,url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.was-validated .custom-select:valid:focus,.custom-select.is-valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,0.25)}.was-validated .form-check-input:valid ~ .form-check-label,.form-check-input.is-valid ~ .form-check-label{color:#28a745}.was-validated .form-check-input:valid ~ .valid-feedback,.was-validated .form-check-input:valid ~ .valid-tooltip,.form-check-input.is-valid ~ .valid-feedback,.form-check-input.is-valid ~ .valid-tooltip{display:block}.was-validated .custom-control-input:valid ~ .custom-control-label,.custom-control-input.is-valid ~ .custom-control-label{color:#28a745}.was-validated .custom-control-input:valid ~ .custom-control-label::before,.custom-control-input.is-valid ~ .custom-control-label::before{border-color:#28a745}.was-validated .custom-control-input:valid:checked ~ .custom-control-label::before,.custom-control-input.is-valid:checked ~ .custom-control-label::before{border-color:#34ce57;background-color:#34ce57}.was-vali


            BooleanType(),
                IntType(),
                FloatType(),
                CustomDataType(dataTypeId = firstDataType.id),
            )
        }
    }
}

private fun <E : Enum<E>> KClass<E>.getFirstEnumValue(): E? {
    // Handle known EnumWrapper types
    return when (this.simpleName) {
        "TextDecorationWrapper" -> TextDecorationWrapper.None as? E
        "TextStyleWrapper" -> TextStyleWrapper.DisplayLarge as? E
        "FontStyleWrapper" -> FontStyleWrapper.Normal as? E
        "TextAlignWrapper" -> TextAlignWrapper.Left as? E
        "TextOverflowWrapper" -> TextOverflowWrapper.Clip as? E
        "ContentScaleWrapper" -> ContentScaleWrapper.Crop as? E
        "TextFieldColorsWrapper" -> TextFieldColorsWrapper.Default as? E
        "NodeVisibility" -> NodeVisibility.AlwaysVisible as? E
        else -> null
    }
}

fun ComposeFlowType.convertCodeFromType(
    inputType: ComposeFlowType,
    codeBlock: CodeBlockWrapper,
): CodeBlockWrapper = this.convertCodeFromType(inputType, codeBlock)

val emptyDocumentIdType = ComposeFlowType.DocumentIdType(Uuid.random().toString())

package io.github.composefluent.icons.regular

import androidx.compose.ui.graphics.vector.ImageVector
import io.github.composefluent.icons.Icons
import io.github.composefluent.icons.fluentIcon
import io.github.composefluent.icons.fluentPath

public val Icons.Regular.DocumentDataLink: ImageVector
    get() {
        if (_documentDataLink != null) {
            return _documentDataLink!!
        }
        _documentDataLink = fluentIcon(name = "Regular.DocumentDataLink") {
            fluentPath {
                moveTo(12.0f, 12.0f)
                curveToRelative(0.41f, 0.0f, 0.75f, 0.34f, 0.75f, 0.75f)
                verticalLineToRelative(4.98f)
                arcToRelative(4.76f, 4.76f, 0.0f, false, false, -1.5f, -2.16f)
                verticalLineToRelative(-2.82f)
                curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
                close()
                moveTo(18.0f, 20.5f)
                horizontalLineToRelative(-5.17f)
                curveToRelative(-0.14f, 0.55f, -0.39f, 1.05f, -0.7f, 1.5f)
                lineTo(18.0f, 22.0f)
                arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, -2.0f)
                lineTo(20.0f, 9.83f)
                arcToRelative(2.0f, 2.0f, 0.0f, false, false, -0.59f, -1.42f)
                lineTo(13.6f, 2.6f)
                arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.05f, -0.04f)
                arcToRelative(2.07f, 2.07f, 0.0f, false, false, -0.34f, -0.25f)
                lineToRelative(-0.05f, -0.03f)
                lineToRelative(-0.05f, -0.03f)
                lineToRelative(-0.16f, -0.09f)
                curveToRelative(-0.2f, -0.08f, -0.41f, -0.12f, -0.63f, -0.14f)
                horizontalLineToRelative(-0.06f)
                arcToRelative(0.6f, 0.6f, 0.0f, false, false, -0.08f, -0.01f)
                lineTo(6.0f, 2.01f)
                arcToRelative(2.0f, 2.0f, 0.0f, false, false, -2.0f, 2.0f)
                verticalLineToRelative(10.56f)
                curveToRelative(0.24f, -0.04f, 0.5f, -0.06f, 0.75f, -0.06f)
                horizontalLineToRelative(0.75f)
                lineTo(5.5f, 4.0f)
                curveToRelative(0.0f, -0.27f, 0.22f, -0.5f, 0.5f, -0.5f)
                horizontalLineToRelative(6.0f)
                lineTo(12


//Compile with:
//gcc -o bubble_example_01 bubble_example_01.c -g `pkg-config --cflags --libs elementary`

#include <Elementary.h>

void
_bla(void *data EINA_UNUSED, Evas_Object *obj, void *event_info EINA_UNUSED)
{
   static unsigned char corner = 0;
   ++corner;
   if (corner > 3)
     elm_bubble_pos_set(obj, ELM_BUBBLE_POS_TOP_LEFT);
   else
     elm_bubble_pos_set(obj, corner);

}

EAPI_MAIN int
elm_main(int argc EINA_UNUSED, char **argv EINA_UNUSED)
{
   Evas_Object *win, *bubble, *label, *icon;

   elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED);

   win = elm_win_util_standard_add("bubble", "Bubble");
   elm_win_autodel_set(win, EINA_TRUE);

   label = elm_label_add(win);
   elm_object_text_set(label, "This is the CONTENT of our bubble");
   evas_object_show(label);

   icon = evas_object_rectangle_add(evas_object_evas_get(win));
   evas_object_color_set(icon, 0, 0, 255, 255);
   evas_object_show(icon);

   bubble = elm_bubble_add(win);
   elm_object_part_content_set(bubble, "icon", icon);
   elm_object_part_text_set(bubble, "info", "INFO");
   elm_object_text_set(bubble, "LABEL");
   elm_object_content_set(bubble, label);
   evas_object_resize(bubble, 300, 100);
   evas_object_show(bubble);

   evas_object_smart_callback_add(bubble, "clicked", _bla, NULL);

   label = elm_label_add(win);
   elm_object_text_set(label, "Bubble with no icon, info or label");
   evas_object_show(label);

   bubble = elm_bubble_add(win);
   elm_object_content_set(bubble, label);
   evas_object_resize(bubble, 200, 50);
   evas_object_move(bubble, 0, 110);
   evas_object_show(bubble);

   evas_object_resize(win, 300, 200);
   evas_object_show(win);

   elm_run();

   return 0;
}
ELM_MAIN()


if System::block_number() > 1 {
            System::on_finalize(System::block_number());
        }
        System::on_initialize(System::block_number());
        System::set_block_number(System::block_number() + 1);
    }
}<gh_stars>0
/*!
This module defines helper types for using `traitcast` along with the
`inventory` crate. Requires the `use_inventory` feature.
*/
use crate::{CastIntoTrait, ImplEntry, Registry};

/// Makes a trait registry by collecting EntryBuilders with the `inventory`
/// crate.
pub fn build_registry() -> Registry {
    let mut reg = Registry::new();
    for builder in inventory::iter::<EntryBuilder> {
        (builder.insert)(&mut reg);
    }
    reg
}

/// This is instantiated once for each castable trait. It describes how a trait
/// can insert itself into the global table.
pub struct EntryBuilder {
    pub insert: Box<Fn(&mut Registry)>,
}

impl EntryBuilder {
    /// Constructs a EntryBuilder for trait `To` by collecting ImplEntry<To> from
    /// `inventory`. If the table for `To` exists already, overwrites it.
    pub fn collecting_entries<To, Entry>() -> EntryBuilder
    where
        Entry: inventory::Collect + AsRef<ImplEntry<To>>,
        To: 'static + ?Sized,
    {
        use std::iter::FromIterator;
        EntryBuilder {
            insert: Box::new(|master| {
                master.insert(CastIntoTrait::from_iter(
                    inventory::iter::<Entry>
                        .into_iter()
                        .map(|x| x.as_ref().clone()),
                ))
            }),
        }
    }

    /// Constructs a trait builder that enters a single 'from' entry into the
    /// table for a particular target.
    ///
    /// If the does not exist already, creates a new table. If it exists
    /// already, modifies the existing table by inserting the new entry.
    pub fn inserting_entry<To>(entry: ImplEntry<To>) -> EntryBuilder
    where
        To: 'static + ?Sized,
    {
        EntryBuilder {
            insert: Box::new(move |master| {
                let table: &mut CastIntoTrait<To> =
                    master.tables
                    .entry::<CastIntoTrait<To>>()
                    .or_insert(CastIntoTrait::new());

                table.map.insert(entry.tid, entry.clone());
            })
        }
    }
}

inventory::collect!(EntryBuilder);

/// Macro for registering traitcast entries with inventory. Requires the
/// "use_inventory" feature.
///
/// `traitcast!(struct Bar)` registers a struct to allow it to be cast into.
///
/// `traitcast!(impl Foo for Bar)` allows casting into dynamic `Foo` trait
/// objects, from objects whose concrete type is `Bar`.
///
/// `traitcast!(struct Bar: Foo1, Foo2)` registers a struct to allow it to be
/// cast into, and further allows casting into dynamic `Foo1` or `Foo2` trait
/// objects, from objects whose concrete type is `Bar`.
#[cfg(feature = "use_inventory")]
#[macro_export]
macro_rules! traitcast {
    (struct $type:ty) => {
        $crate::traitcast!($type => $type);
    };
    (struct $type:ty : $($trait:path),+) => {
        $crate::traitcast!(struct $type);
        $(
            $crate::traitcast!(impl $trait; for $type);
        )+
    };
    (impl $trait:path; for $source:ty) => {
        $crate::traitcast!($source => dyn $trait);
    };
    ($source:ty => $target:ty) => {
        inventory::submit! {
            $crat


 = mEditPreviewViewModel.getEditor();
        other.setVisibility(View.GONE);
        mSeekBar.setMinProgress(0);
        mSeekBar.setMaxProgress(100);
        mSeekBar.setAnchorProgress(0);
    }

    @Override
    protected void initData() {
        mProgress = (int) (getTransparency() * 100);
        mSeekBar.setProgress(mProgress);
    }

    @Override
    protected void initEvent() {
        HuaweiVideoEditor editor = mEditPreviewViewModel.getEditor();
        if (editor == null) {
            return;
        }

        mSeekBar.setOnProgressChangedListener(progress -> {
            mProgress = progress;
            mEditPreviewViewModel.setToastTime(String.valueOf(mProgress));
            setTransparency((float) BigDecimalUtils.round(BigDecimalUtils.div(mProgress, 100f), 2));
        });

        mSeekBar.setcTouchListener(isTouch -> {
            mEditPreviewViewModel.setToastTime(isTouch ? (int) mSeekBar.getProgress() + "" : "");
        });

        mCertainTv.setOnClickListener(view -> {
            mActivity.onBackPressed();
        });
    }

    @Override
    protected int setViewLayoutEvent() {
        return FIXED_HEIGHT_210;
    }

    private float getTransparency() {
        HVEAsset asset = mEditPreviewViewModel.getSelectedAsset();
        if (asset == null) {
            asset = mEditPreviewViewModel.getMainLaneAsset();
            if (asset == null) {
                return 1f;
            }
        }
        if (asset instanceof HVEVideoAsset) {
            return ((HVEVideoAsset) asset).getOpacityValue();
        } else if (asset instanceof HVEImageAsset) {
            return ((HVEImageAsset) asset).getOpacityValue();
        }
        return 1f;
    }

    private void setTransparency(float value) {
        HVEAsset asset = mEditPreviewViewModel.getSelectedAsset();
        if (asset == null || mEditor == null) {
            asset = mEditPreviewViewModel.getMainLaneAsset();
            if (asset == null) {
                return;
            }
        }
        if (asset instanceof HVEVideoAsset) {
            ((HVEVideoAsset) asset).setOpacityValue(value);
        } else if (asset instanceof HVEImageAsset) {
            ((HVEImageAsset) asset).setOpacityValue(value);
        }
        if (mEditor != null) {
            HVETimeLine timeLine = mEditor.getTimeLine();
            if (timeLine != null) {
                mEditor.seekTimeLine(timeLine.getCurrentTime());
            }
        }
    }

}

/*
 *   Copyright 2021. Huawei Technologies Co., Ltd. All rights reserved.
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package com.huawei.hms.videoeditor.ui.mediaeditor.menu;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

public class VideoClipsPlayViewModel extends AndroidViewModel {
    private final MutableLiveData<Long> videoDuration = new MutableLiveData<>();

    private final MutableLiveData<Long> currentTime = new MutableLiveData<>();

    priva


static int read_descr_len(uint8_t **buffer)
{
	int len = 0;
	int count = 4;
	while (count--)
	{
		int c = *(*buffer)++;
		len = (len << 7) | (c & 0x7f);
		if (!(c & 0x80))
			break;
	}
	return len;
}

// based off of mov_mp4_read_descr from mov.c in ffmpeg's libavformat
static int read_descr(uint8_t **buffer, int *tag)
{
	*tag = *(*buffer)++;
	return read_descr_len(buffer);
}

// based off of mov_read_esds from mov.c in ffmpeg's libavformat
static void read_esds_desc_ext(uint8_t* desc_ext, vector<uint8_t> &buffer,
		bool version_flags)
{
	uint8_t *esds = desc_ext;
	int tag, len;

	if (version_flags)
		esds += 4; // version + flags

	read_descr(&esds, &tag);
	esds += 2;     // ID
	if (tag == MP4ESDescrTag)
		esds++;    // priority

	read_descr(&esds, &tag);
	if (tag == MP4DecConfigDescrTag) {
		esds++;    // object type id
		esds++;    // stream type
		esds += 3; // buffer size db
		esds += 4; // max bitrate
		esds += 4; // average bitrate

		len = read_descr(&esds, &tag);
		if (tag == MP4DecSpecificDescrTag)
			try {
				buffer.assign(esds, esds + len);
			} catch (...) {
				//leave buffer empty
			}
	}
}
/* extracted code ends here */

static void query_extra_data(ca_encoder *ca)
{
	UInt32 size = 0;

	OSStatus code;
	code = AudioConverterGetPropertyInfo(ca->converter,
			kAudioConverterCompressionMagicCookie,
			&size, NULL);
	if (code) {
		log_osstatus(LOG_ERROR, ca,
				"AudioConverterGetPropertyInfo(magic_cookie)",
				code);
		return;
	}

	if (!size) {
		CA_BLOG(LOG_WARNING, "Got 0 data size info for magic_cookie");
		return;
	}

	vector<uint8_t> extra_data;

	try {
		extra_data.resize(size);
	} catch (...) {
		CA_BLOG(LOG_WARNING, "Could not allocate extra data buffer");
		return;
	}

	code = AudioConverterGetProperty(ca->converter,
			kAudioConverterCompressionMagicCookie,
			&size, extra_data.data());
	if (code) {
		log_osstatus(LOG_ERROR, ca,
				"AudioConverterGetProperty(magic_cookie)",
				code);
		return;
	}

	if (!size) {
		CA_BLOG(LOG_WARNING, "Got 0 data size for magic_cookie");
		return;
	}

	read_esds_desc_ext(extra_data.data(), ca->extra_data, false);
}

static bool aac_extra_data(void *data, uint8_t **extra_data, size_t *size)
{
	ca_encoder *ca = static_cast<ca_encoder*>(data);

	if (!ca->extra_data.size())
		query_extra_data(ca);

	if (!ca->extra_data.size())
		return false;

	*extra_data = ca->extra_data.data();
	*size = ca->extra_data.size();
	return true;
}

static asbd_builder fill_common_asbd_fields(asbd_builder builder,
		bool in=false)
{
	UInt32 bytes_per_frame = 8;
	UInt32 channels = 2;
	UInt32 bits_per_channel = bytes_per_frame / chann


um => {
    return [...feeEstimateFactors, sum].reduce((sum, n) => sum + n);
  }, weight);
}

/**
 * Estimate the transaction fee for a specific tx using target fee
 * per kilobyte of the passed network and the transaction's weight
 * @param redeemScript The redeem script for the transaction
 * @param utxos The UTXOs used in the transaction
 * @param txWeight The transaction's weight in weight units
 * @param feeTokensPerVirtualByte Fee per byte in the transaction
 * @param unlock Claim secret (preimage) OR refund public key OR refund public key AND refund secret
 */
export function estimateFee(
  redeemScript: string,
  utxos: TxOutput[],
  txWeight: number,
  feeTokensPerVirtualByte: number,
  unlock?: string | [string, string],
) {
  // Guess at the final weight of the transaction for fee/vbyte calculation
  const anticipatedWeight = estimateWeightWithInputs(
    utxos,
    txWeight,
    Buffer.from(redeemScript, 'hex'),
    unlock,
  );

  const vRatio = 4; // A witness byte weighs one weight unit; compared to four non-witness weight units.
  return feeTokensPerVirtualByte * Math.ceil(anticipatedWeight / vRatio);
}
import { Injectable } from '@angular/core';

@Injectable()
export class Store {
  constructor() {}

  //写缓存localStorage
  setLocal(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }

    localStorage.setItem(key, value);
  }

  //读缓存localStorage
  getLocal<T>(key: string): T {
    let value: string = localStorage.getItem(key);
    if (value && value !== 'undefined' && value !== 'null') {
      return <T>JSON.parse(value);
    }
    return null;
  }

  //写缓存sessionStorage
  setSession(key: string, value: any) {
    if (value) {
      value = JSON.stringify(value);
    }

    sessionStorage.setItem(key, value);
  }

  //读缓存sessionStorage
  getSession<T>(key: string): T {
    let value: string = sessionStorage.getItem(key);
    if (value && value !== 'undefined' && value !== 'null') {
      return <T>JSON.parse(value);
    }
    return null;
  }
}
import {createAction} from '@ngrx/store';
import * as fromSecurity from './security.reducer';
import * as SecurityActions from './security.action';

describe('security/store/security.reducer.ts', () => {
  it('should return init state', () => {
    const newState = fromSecurity.reducer(undefined, createAction('noop'));
    expect(newState).toEqual(fromSecurity.initialState);
  });

  it('should load and logout', () => {
    let expectedState: fromSecurity.SecurityState = {
      enabled: false,
      authenticated: true,
      username: 'fakeuser',
      roles: ['role1', 'role2']
    };
    let newState = fromSecurity.reducer(
      undefined,
      SecurityActions.loaded({
        enabled: false,
        authenticated: true,
        username: 'fakeuser',
        roles: ['role1', 'role2']
      })
    );
    expect(newState).toEqual(expectedState);
    expectedState = {
      enabled: false,
      authenticated: false,
      username: undefined,
      roles: []
    };
    newState = fromSecurity.reducer(newState, SecurityActions.logout());
    expect(newState).toEqual(expectedState);
  });
});
import { unmarshall } from "@aws-sdk/util-dynamodb";
import { MASTERY_TABLE, TASK_SUBMISSIONS_TABLE } from "../environment";
import {
   Answer,
   QuestionAnswerItem,
   TaskProgressItem,
   TaskSubmissionResultItem
} from "./taskSubmissionInterface";
import * as questionService from


p/widgets/trip_detail_view.dart';
import 'package:client/business/trip/widgets/trip_overview_view.dart';
import 'package:client/business/trip/widgets/trip_settings_drawer.dart';
import 'package:client/common/material/app_bar_with_safe_area.dart';
import 'package:client/common/utils/date_util.dart';
import 'package:client/common/widgets/preference_button.dart';
import 'package:client/common/widgets/return_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class TripOverviewPage extends StatefulWidget {
  final String tripId;

  const TripOverviewPage({
    super.key,
    required this.tripId,
  });

  @override
  State<TripOverviewPage> createState() => _TripOverviewPageState();
}

class _TripOverviewPageState extends State<TripOverviewPage> {
  bool _isDetailView = true;
  bool _isShowEditTitle = false;

  @override
  void initState() {
    super.initState();
    // Initialize data
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final service = context.read<TripService>();
      service.fetchTripData(tripId: widget.tripId);
    });
  }

  void _showSettingsMenu(BuildContext context) {
    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: '',
      barrierColor: Colors.black.withOpacity(0.5),
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (context, animation, secondaryAnimation) {
        return Container();
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            parent: animation,
            curve: Curves.easeOutCubic,
          )),
          child: TripSettingsDrawer(
            isDetailView: _isDetailView,
            onViewModeChanged: (value) {
              setState(() {
                _isDetailView = value;
              });
            },
          ),
        );
      },
    );
  }

  Widget _buildHeader(TripService service) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 20.h),
          GestureDetector(
            onTap: () {
              setState(() {
                _isShowEditTitle = true;
              });
            },
            child: SizedBox(
              width: double.infinity,
              child: Text(
                service.trip!.title,
                style: TextStyle(
                  fontSize: 30.sp,
                  fontWeight: AppFontWeight.bold,
                  color: AppColor.primaryFont,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          SizedBox(height: 5.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '${DateUtil.formatDate(service.trip!.startTs)} | ${service.trip!.dailyTrips.length}天',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: AppFont


JSX attributes to apply to the custom\n// element's object properties instead of only HTML attributes.\n// https://github.com/facebook/react/issues/11347\n\nvar enableCustomElementPropertySupport = false; // Disables children for <textarea> elements\nvar warnAboutStringRefs = true; // -----------------------------------------------------------------------------\n// Debugging and DevTools\n// -----------------------------------------------------------------------------\n// Adds user timing marks for e.g. state updates, suspense, and work loop stuff,\n// for an experimental timeline tool.\n\nvar enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState\n\nvar enableProfilerTimer = true; // Record durations for commit and passive effects phases.\n\nvar enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an \"update\" and a \"cascading-update\".\n\nvar allNativeEvents = new Set();\n/**\n * Mapping from registration name to event name\n */\n\n\nvar registrationNameDependencies = {};\n/**\n * Mapping from lowercase registration names to the properly cased version,\n * used to warn in the case of missing event handlers. Available\n * only in true.\n * @type {Object}\n */\n\nvar possibleRegistrationNames =  {} ; // Trust the developer to only use possibleRegistrationNames in true\n\nfunction registerTwoPhaseEvent(registrationName, dependencies) {\n  registerDirectEvent(registrationName, dependencies);\n  registerDirectEvent(registrationName + 'Capture', dependencies);\n}\nfunction registerDirectEvent(registrationName, dependencies) {\n  {\n    if (registrationNameDependencies[registrationName]) {\n      error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);\n    }\n  }\n\n  registrationNameDependencies[registrationName] = dependencies;\n\n  {\n    var lowerCasedName = registrationName.toLowerCase();\n    possibleRegistrationNames[lowerCasedName] = registrationName;\n\n    if (registrationName === 'onDoubleClick') {\n      possibleRegistrationNames.ondblclick = registrationName;\n    }\n  }\n\n  for (var i = 0; i < dependencies.length; i++) {\n    allNativeEvents.add(dependencies[i]);\n  }\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n  {\n    // toStringTag is needed for namespaced types like Temporal.Instant\n    var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n    var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n    return type;\n  }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n  {\n    try {\n      testStringCoercion(value);\n      return false;\n    } catch (e) {\n      return true;\n    }\n  }\n}\n\nfunction testStringCoercion(value) {\n  // If you ended up here by following an exception call stack, here's what's\n  // happened: you supplied an object or symbol value to React (as a prop, key,\n  // DOM attribute, CSS pr


import sys
sys.stdin=open('input.txt','r')

n = int(input())
arr = [input() for _ in range(n)]

lst = sorted(arr, key=lambda x:(len(x),x))
for i in range(len(lst)):
    print(lst[i])


ufe0f',
  'arrow_right': '\u27a1\ufe0f',
  'arrow_right_hook': '\u21aa\ufe0f',
  'arrow_up': '\u2b06\ufe0f',
  'arrow_up_down': '\u2195\ufe0f',
  'arrow_up_small': '\ud83d\udd3c',
  'arrow_upper_left': '\u2196\ufe0f',
  'arrow_upper_right': '\u2197\ufe0f',
  'arrows_clockwise': '\ud83d\udd03',
  'arrows_counterclockwise': '\ud83d\udd04',
  'art': '\ud83c\udfa8',
  'articulated_lorry': '\ud83d\ude9b',
  'artificial_satellite': '\ud83d\udef0\ufe0f',
  'artist': '\ud83e\uddd1\u200d\ud83c\udfa8',
  'aruba': '\ud83c\udde6\ud83c\uddfc',
  'ascension_island': '\ud83c\udde6\ud83c\udde8',
  'asterisk': '*\ufe0f\u20e3',
  'astonished': '\ud83d\ude32',
  'astronaut': '\ud83e\uddd1\u200d\ud83d\ude80',
  'athletic_shoe': '\ud83d\udc5f',
  'atm': '\ud83c\udfe7',
  'atom_symbol': '\u269b\ufe0f',
  'australia': '\ud83c\udde6\ud83c\uddfa',
  'austria': '\ud83c\udde6\ud83c\uddf9',
  'auto_rickshaw': '\ud83d\udefa',
  'avocado': '\ud83e\udd51',
  'axe': '\ud83e\ude93',
  'azerbaijan': '\ud83c\udde6\ud83c\uddff',
  'b': '\ud83c\udd71\ufe0f',
  'baby': '\ud83d\udc76',
  'baby_bottle': '\ud83c\udf7c',
  'baby_chick': '\ud83d\udc24',
  'baby_symbol': '\ud83d\udebc',
  'back': '\ud83d\udd19',
  'bacon': '\ud83e\udd53',
  'badger': '\ud83e\udda1',
  'badminton': '\ud83c\udff8',
  'bagel': '\ud83e\udd6f',
  'baggage_claim': '\ud83d\udec4',
  'baguette_bread': '\ud83e\udd56',
  'bahamas': '\ud83c\udde7\ud83c\uddf8',
  'bahrain': '\ud83c\udde7\ud83c\udded',
  'balance_scale': '\u2696\ufe0f',
  'bald_man': '\ud83d\udc68\u200d\ud83e\uddb2',
  'bald_woman': '\ud83d\udc69\u200d\ud83e\uddb2',
  'ballet_shoes': '\ud83e\ude70',
  'balloon': '\ud83c\udf88',
  'ballot_box': '\ud83d\uddf3\ufe0f',
  'ballot_box_with_check': '\u2611\ufe0f',
  'bamboo': '\ud83c\udf8d',
  'banana': '\ud83c\udf4c',
  'bangbang': '\u203c\ufe0f',
  'bangladesh': '\ud83c\udde7\ud83c\udde9',
  'banjo': '


index} {
    left: percentage((@index / @grid-columns));
  }
}
.calc-grid-column(@index, @class, @type) when (@type = push) and (@index = 0) {
  .col-@{class}-push-0 {
    left: auto;
  }
}
.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index > 0) {
  .col-@{class}-pull-@{index} {
    right: percentage((@index / @grid-columns));
  }
}
.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index = 0) {
  .col-@{class}-pull-0 {
    right: auto;
  }
}
.calc-grid-column(@index, @class, @type) when (@type = offset) {
  .col-@{class}-offset-@{index} {
    margin-left: percentage((@index / @grid-columns));
  }
}

// Basic looping in LESS
.loop-grid-columns(@index, @class, @type) when (@index >= 0) {
  .calc-grid-column(@index, @class, @type);
  // next iteration
  .loop-grid-columns((@index - 1), @class, @type);
}

// Create grid for specific class
.make-grid(@class) {
  .float-grid-columns(@class);
  .loop-grid-columns(@grid-columns, @class, width);
  .loop-grid-columns(@grid-columns, @class, pull);
  .loop-grid-columns(@grid-columns, @class, push);
  .loop-grid-columns(@grid-columns, @class, offset);
}
/*!
 * jQuery UI CSS Framework 1.10.3
 * http://jqueryui.com
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Theming/API
 *
 * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thi


The draft will be published in "+z.y(z.Fm(z.B({lx:!0},a),b)));return(0,z.x)(a)};Pda=function(a,b){return(0,z.x)(z.y(z.cl({image:a.icon,strategy:"crop-fixed",height:a.size,width:a.size},0,b)))};
vha=function(a,b,c){a=a||{};b="";a=""+((null==a.favicon?0:a.favicon.imageId)||(null==a.favicon?0:a.favicon.id)?z.E(Pda({icon:a.favicon,size:128},c)):null==(null==a.favicon?null:a.favicon.imageId)&&null==(null==a.favicon?null:a.favicon.id)&&a.favicon?z.E(a.favicon):"");a=(0,z.L)(a);b+=a?'\x3clink rel\x3d"icon" href\x3d"'+z.D(z.E(a))+'" class\x3d"js-favicon"\x3e':'\x3clink rel\x3d"shortcut icon" href\x3d"'+z.D(z.E(c.layoutData.faviconUrl))+'" class\x3d"js-favicon is-default"\x3e';return(0,z.x)(b)};
wha=function(a,b){a=a||{};var c="";if(a.post)var d=""+a.post.title,d=z.C(d),e=a.post.homeCollection&&"APPROVED"==a.post.virtuals.statusForCollection,c=c+(""+d+(50>=(""+d).length?a.sequence?" – "+a.sequence.title+" – "+(""+b.productName):e?" – "+a.post.homeCollection.name+(a.post.homeCollection.domain?"":" – "+b.productName):a.post.creator?" – "+a.post.creator.name+" – "+(""+b.productName):"":""));else a=z.n("Story not found – {$productName}",{productName:""+b.productName}),c+=""+a;return z.A(c)};
xha=function(a,b){a=a||{};var c="";if(a.post)if(b=a.post.homeCollection&&"APPROVED"==a.post.virtuals.statusForCollection,null==a.post.content?0:a.post.content.metaDescription)c+=""+a.post.content.metaDescription;else{var d=""+z.On(a.post),d=z.C(d);if(150<(""+d).length)c+=""+d;else if(d=""+(a.post.subtitle?""+z.pl(a.post.subtitle):(null==a.post.content?0:a.post.content.subtitle)?""+z.pl(a.post.content.subtitle):""),d=z.C(d),140>=(""+d).length){var e=""+z.pl(a.post.title)+" "+(""+d),e=z.C(e);140<(""+
e).length?c+=""+e:(e=z.n("{$title} is published",{title:""+z.Lm(String(a.post.title))}),c+=d?""+d+" ":"",d=""+e,a.post.creator&&(e=z.n("by"),d+=" "+e+" "+(""+a.post.creator.name)),b&&(b=z.n("in"),d+=" "+b+" "+(""+(null==a.post.homeCollection?null:a.post.homeCollection.name))),d=z.C(d),c+=""+z.pl(d))}else c+=""+d}else a=z.n("We could not find the story you are looking for on {$productName}",{productName:""+z.pl(b.productName)}),c+=""+a;return z.A(c)};
Uk=function(a,b){var c=a.size;a=""+((null==a.faviconImage?0:a.favi


playName = "Setting the content of RefreshView removes previous platform view from visual tree")]
		public async Task ChangingRefreshViewContentRemovesPreviousContentsPlatformViewFromVisualTree()
		{
			SetupBuilder();

			var refreshView = new RefreshView();
			var initialContent = new Label();
			refreshView.Content = initialContent;

			await AttachAndRun(refreshView, async (handler) =>
			{
				var newContent = new Entry();
				Assert.NotNull(((initialContent as IView).Handler as IPlatformViewHandler).PlatformView.GetParent());
				refreshView.Content = newContent;
				Assert.Null(((initialContent as IView).Handler as IPlatformViewHandler).PlatformView.GetParent());
				await Task.Yield();
				Assert.NotNull(((newContent as IView).Handler as IPlatformViewHandler).PlatformView.GetParent());
			});
		}
	}
}


nixTimeMilliseconds();
            App.WindowManager.WindowSizesOrPositionsChanged();
        }

        private void Txt_blk_SoundClipId_PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
        {
            if (e.Property == TextBlock.TextProperty)
            {
                if (!string.IsNullOrEmpty((string?)e.NewValue) && e.NewValue != e.OldValue)
                {
                    App.WindowManager.OpenedEditSoundClipWindow(((EditSoundClipViewModel?)this.DataContext)?.Model.Id, this);
                }
            }
        }

        protected async void BrowseSoundClip(object? sender, RoutedEventArgs args)
        {
            try
            {
                string[]? url = await BrowseIO.OpenFileBrowser(GetWindow(), BrowseIO.FileBrowserType.AUDIO);
                ((EditSoundClipViewModel?)DataContext)?.SetClipAudioFilePath(url);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

        protected async void BrowseImage(object? sender, RoutedEventArgs args)
        {
            try
            {
                string[]? url = await BrowseIO.OpenFileBrowser(GetWindow(), BrowseIO.FileBrowserType.IMAGE);
                ((EditSoundClipViewModel?)DataContext)?.SetClipImageFilePath(url);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

        protected void DeleteSoundClip(object? sender, RoutedEventArgs args)
        {
            ((EditSoundClipViewModel?)this.DataContext)?.DeleteSoundClip();
            this.Close();
        }

        protected override void OnClosing(WindowClosingEventArgs e)
        {
            EffectiveViewportChanged -= EditSoundClip_EffectiveViewportChanged;
            App.WindowManager.ClosedEditSoundClipWindow(((EditSoundClipViewModel?)this.DataContext)?.Model.Id);
            ((EditSoundClipViewModel?)DataContext)?.Dispose();
            base.OnClosing(e);
        }

        Window GetWindow() => (Window?)this.VisualRoot ?? throw new NullReferenceException("Window should exist");
    }
}


 left );
		graphics.fillEllipseShape( right );
	}

    private static renderDebug( graphics: Phaser.GameObjects.Graphics,
                                eyesFrame: Phaser.Geom.Rectangle ) : void {

        graphics.fillStyle(0x00ff00, 0.4);
		graphics.fillRectShape( eyesFrame );
	}
}import { Injectable } from '@angular/core';
import * as moment from "moment";
//gotta look for an alternative to momentjs in future projects but works for this project

@Injectable()
export class AuthService {

    constructor() {}

    setLocalStorage(responseObj) {

        // Adds the expiration time defined on the JWT to the current moment
        const expiresAt = moment().add(Number.parseInt(responseObj.expiresIn), 'days');

        localStorage.setItem('id_token', responseObj.token);
        localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()) );
    }

    logout() {
        //removing it from the local storage is to logout and maybe login with another username
        localStorage.removeItem("id_token");
        localStorage.removeItem("expires_at");
    }

    public isLoggedIn() {
        //Is a "second" before? "year", "month" etc. could also be used instead
        //In a javascript class so "this" is used, if the moment() is returned
        //isLoggendin will return false, usage of the second parameter is important
        return moment().isBefore(this.getExpiration(), "second");
    }

    isLoggedOut() {
        return !this.isLoggedIn();
    }

    getExpiration() {
        const expiration = localStorage.getItem("expires_at");
        if (expiration) {
            const expiresAt = JSON.parse(expiration);
            return moment(expiresAt);
        } else {
            //gets "now"
            return moment();
        }
    }
}/* eslint-disable no-console */
import { Ignore } from './kafka-penguin/src/index';

const client = require('./clientConfig.ts');

const topic = 'test-topic';

// This allows the consumer to evaluate each message according to a condition
// The callback must return a boolean value
const callback = (message) => {
  try {
    JSON.parse(message.value);
  } catch (e) {
    return false;
  }
  return true;
};

// Set up the Ignore strategy
// with a configured KafkaJS client, a topic, and the evaluating callback
const exampleIgnoreConsumer = new Ignore(client, topic, callback);

// Initialize a consumer from the new instance of the Dead Letter Queue strategy
const consumerIgnore = exampleIgnoreConsumer.consumer({ groupId: 'testID' });

// Connecting the consumer to consume messages. bad messages
// If the callback evaluates a message as erroneous by returning false, the strategy
// enables the consumer to keep consuming good messages from the topic
consumerIgnore.connect()
  .then(consumerIgnore.subscribe())
  .then(() => consumerIgnore.run({
    eachMessage: ({ message }) => {
    //   if (message.value.length < 5) return true;
    //   return false;
    console.log("message value:", message.value.toString())
    },
  }))
  .catch((e) => console.log(`Error message from consumer: ${e}`));
import {
  buildConfigObject
} from '@okta/configuration-validation';

describe('buildConfigObject', () => {

  it('can be called with no arguments', () => {
    expect(buildConfigObject()).toEqual({});
  });

  it('pass-through: empty config', () => {
    const passedConfig = {};
    expect(buildConfigObject(passedConfig)).toEqual(passedConfig);
  });

  it('pass-through: leaves config object unchanged when all parameters are passed in preferred format', () =>


ic' is the physical
*screen that you see, 'back' the hidden back screen, and I use 'logic'
*as a pointer to the screen on which I draw.  Usually this is the same
*as 'back' (to update the hidden screen) but then I can set 'logic' to
*equal 'physic' when debugging, so my program writes to the visible
*screen.  Screen pointer codes 'physic_code' and so on have their
*mid-lower 8 bits shifted to the low 8 bits.  This is how the system
*takes its screen addresses.  The subroutine 'screen_swap' swaps the
*two screens over, leaving 'logic' pointing to the new back screen.
*You'll see how these are used later...

start
	move.l	sp,old_stack		|Store stack pointer.

	clr.l	-(sp)			|Toggle to
	move.w	#$20,-(sp)		|Supervisor Mode.
	trap	#1			|
	addq	#6,sp			|SUPER

*** TRANSFER INITIAL SYSTEM DATA TO STORAGE ***

	movem.l	$ffff8240.w,d0-d7	|Store palette.
	movem.l	d0-d7,colour_store

	move.w	#2,-(sp)		|PHYSBASE, get screen address.
	trap	#14			|
	addq.l	#2,sp			|PHYSBASE
	move.l	d0,screen_address_store	|Store screen address.

	move.w	#4,-(sp)		|Get screen resolution.
	trap	#14			|
	addq.l	#2,sp			|GETREZ
	move.w	d0,resolution_store	|Then store screen resolution.

	move.l	$70,v_blank_store	|Store 50Hz Interrupt Vector.

*Here I calculate the size of the program itself, leaving some room
*for requirements such as stack and heap.  This is taken largely from
*COMPUTE!'s TOS Guide...
	move.l	sp,a6			|Copy stack pointer.
	move.l	4(a6),a6		|Get basepage address.
	move.l	12(a6),d0		|Get length of code segment...
	add.l	20(a6),d0		|Add length of data segment...
	add.l	28(a6),d0		|Add length of storage segment...
	add.l	#$4000,d0		|Add size of stack and heap...
	add.l	#$100,d0		|Add size of base page.
*Now to set up the new stack and call MSHRINK, to return unused memory
*to the system....
	move.l	d0,d1			 |
	add.l	a6,d1			 |Add address of basepage to length,
	and.l	#-2,d1			 |then make even, to give
	move.l	d1,sp			 |new stack pointer.
	move.l	d0,-(sp)		|Push size of program memory.
	move.l	a6,-(sp)		|Push start address.
	clr.w	-(sp)			|Push dummy clear word.
	move.w	#$4a,-(sp)		|Shrink memory required.
	trap	#1			|
	add.w	#12,sp			|MSHRINK

*Now call MALLOC, to allocate some of that free memory back to the
*program.  (It's possible later to return the workspace to the system
*without losing the program itself, since the two are in separate
*memory blocks.)
	move.l	#WORKSPACE,-(sp)	|Allocate a memory block.
	move.w	#$48,-(sp)		|
	trap	#1			|
	addq	#6,sp			|MALLOC
	move.l	d0,m_block		|

	move.l	screen_address_store,d0	|Store screen address as
	move.l	d0,physic		|physic.
	lsr.w	#8,d0			|Calculate pointer of
	move.l	d0,physic_code		|physical screen.

	move.l	m_block,d0		|Get memory block address
	add.l	#255,d0			|and then
	clr.b	d0			|fit on a page boundary,
	move.l	d0,back			|to get back screen address.
	lsr.w	#8,d0			|Calculate back screen pointer.
	move.l	d0,back_code		|

	move.l	back,logic		|Define logical screen as
	move.l	back_code,logic_code	|back screen.

	move.w	#0,-(sp)		|For low resolution.


//  publish success not need to handle
    }

}
package tech.medivh.core.jfr

import jdk.jfr.consumer.RecordedEvent
import jdk.jfr.consumer.RecordingFile
import tech.medivh.core.statistic.TestCaseRecord
import tech.medivh.core.statistic.TestCaseRecordAccumulator
import java.io.File

/**
 *
 * jfr file length less than 64M, so we can load all data to memory
 *
 * @author gxz gongxuanzhangmelt@gmail.com
 **/
class MemoryClassifier : JfrClassifier {

    override fun classify(jfrFile: File): List<TestCaseRecord> {
        require(jfrFile.length() <= 48 * 1024 * 1024) { "jfr file length must less than 48M" }
        val accumulator = mutableMapOf<String, TestCaseRecordAccumulator>()

        RecordingFile(jfrFile.toPath()).use { recordingFile ->
            while (recordingFile.hasMoreEvents()) {
                val event: RecordedEvent = recordingFile.readEvent()
                if (event.eventType.name != MethodInvokeEvent::class.java.name) {
                    continue
                }
                val testCase = event.getString("testCase")
                val threadName = event.thread.javaName
                val node = FlameNode.fromMethodInvokeEvent(event)
                accumulator.computeIfAbsent(testCase) { TestCaseRecordAccumulator(it) }.accumulate(threadName, node)
            }
        }
        return accumulator.values.map { it.buildRecord() }.toList()
    }

    private val threadEventListMap = mutableMapOf<String, MutableList<FlameNode>>()

    fun append(threadName: String, flameNode: FlameNode) {
        threadEventListMap.computeIfAbsent(threadName) { mutableListOf() }.add(flameNode)
    }

}
package tech.medivh.plugin.gradle.kotlin

import com.alibaba.fastjson2.JSON
import tech.medivh.core.i18n
import tech.medivh.core.jfr.ExternalClassifier
import tech.medivh.core.jfr.JfrClassifier
import tech.medivh.core.jfr.MemoryClassifier
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

/**
 * @author gxz gongxuanzhangmelt@gmail.com
 **/
class MedivhReporter(private val medivhExtension: MedivhExtension) {

    fun report() {
        val dir = File(medivhExtension.properties.reportDir)
        val reportZip = dir.parentFile.parentFile.parentFile.resolve("medivh-report.zip")
        val reportDir = dir.resolve("report/")
        unzip(reportZip, reportDir)
        generateTraceData(reportDir)
        val indexHtml = reportDir.resolve("index.html")
        //  in windows, the path is like "C:\Users\xxx" but idea console can't recognize it is a file path
        println(i18n(medivhExtension.properties.language, "tip.seeReport", indexHtml.absolutePath.replace("\\", "/")))
    }

    private fun generateTraceData(dir: File) {
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val jfrFile = File("${medivhExtension.properties.reportDir}/medivh.jfr")
        val classifier: JfrClassifier = if (jfrFile.length() > 48 * 1024 * 1024) {
            ExternalClassifier()
        } else {
            MemoryClassifier()
        }
        val testCaseReportList = classifier.classify(jfrFile)
        val jsFile = dir.resolve("medivh.js")
        jsFile.writeText("const testCasesData = ")
        jsFile.appendText(JSON.toJSONString(testCaseReportList))
        jsFile.appendText(";")


Diff = Y - X;

    // Stores the minimum first term
    // and the corresponding common
    // difference of the resultant AP
    int first_term = INT_MAX, diff;

    // Iterate over all the common difference
    for (int i = 1; i * i <= maxDiff; i++) {

        // Check if X and Y is included
        // for current common difference
        if (maxDiff % i == 0) {

            // Store the possible
            // common difference
            int diff1 = i;
            int diff2 = maxDiff / diff1;

            // Number of terms from
            // X to Y with diff1
            // common difference
            int terms1 = diff2 + 1;

            // Number of terms from
            // X to Y with diff2
            // common difference
            int terms2 = diff1 + 1;

            // Find the corresponding first
            // terms with diff1 and diff2
            int first_term1
                = minFirstTerm(X, diff1, N - terms1);
            int first_term2
                = minFirstTerm(X, diff2, N - terms2);

            // Store the minimum first term
            // and the corresponding
            // common difference
            if (first_term1 < first_term) {
                first_term = first_term1;
                diff = diff1;
            }
            if (first_term2 < first_term) {
                first_term = first_term2;
                diff = diff2;
            }
        }
    }

    // Print the resultant AP
    for (int i = 0; i < N; i++) {
        cout << first_term << " ";
        first_term += diff;
    }
}

// Driver Code
int main()
{
    // Given length of AP
    // and the two terms
    int N = 5, X = 10, Y = 15;

    // Function Call
    printAP(N, X, Y);

    return 0;
}
```

## Java 语言(一种计算机语言，尤用于创建网站)

```
// Java program for the approach
import java.util.*;

class GFG{

// Function that finds the minimum
// positive first term including X
// with given common difference and
// the number of terms
static int minFirstTerm(int X, int diff, int N)
{

    // Stores the first term
    int first_term = Integer.MAX_VALUE;

    // Initialize the low and high
    int low = 0, high = N;

    // Perform binary search
    while (low <= high)
    {

        // Find the mid
        int mid = (low + high) / 2;

        // Check if first term is
        // greater than 0
        if (X - mid * diff > 0)
        {

            // Store the possible first term
            first_term = X - mid * diff;

            // Search between mid + 1 to high
            low = mid + 1;
        }
        else

            // Search between low to mid-1
            high = mid - 1;
    }

    // Return the minimum first term
    return first_term;
}

// Function that finds the Arithmetic
// Progression with minimum possible
// first term containing X and Y
static void printAP(int N, int X, int Y)
{

    // Considering X to be
    // smaller than Y always
    if (X > Y)
    {
        X = X + Y;
        Y = X - Y;
        X = X - Y;
    }

    // Stores the max common difference
    int maxDiff = Y - X;

    // Stores the minimum first term
    // and the c


.ReadJSON(b, &res); err != nil {
		return err
	}
	*o = res
	return nil
}

/*
AddAgentOKBodyNodeExporter NodeExporter runs on Generic or Container Node and exposes its metrics.
swagger:model AddAgentOKBodyNodeExporter
*/
type AddAgentOKBodyNodeExporter struct {
	// Unique randomly generated instance identifier.
	AgentID string `json:"agent_id,omitempty"`

	// The pmm-agent identifier which runs this instance.
	PMMAgentID string `json:"pmm_agent_id,omitempty"`

	// Desired Agent status: enabled (false) or disabled (true).
	Disabled bool `json:"disabled,omitempty"`

	// Custom user-assigned labels.
	CustomLabels map[string]string `json:"custom_labels,omitempty"`

	// True if exporter uses push metrics mode.
	PushMetricsEnabled bool `json:"push_metrics_enabled,omitempty"`

	// List of disabled collector names.
	DisabledCollectors []string `json:"disabled_collectors"`

	// AgentStatus represents actual Agent status.
	//
	//  - AGENT_STATUS_STARTING: Agent is starting.
	//  - AGENT_STATUS_INITIALIZATION_ERROR: Agent encountered error when starting.
	//  - AGENT_STATUS_RUNNING: Agent is running.
	//  - AGENT_STATUS_WAITING: Agent encountered error and will be restarted automatically soon.
	//  - AGENT_STATUS_STOPPING: Agent is stopping.
	//  - AGENT_STATUS_DONE: Agent has been stopped or disabled.
	//  - AGENT_STATUS_UNKNOWN: Agent is not connected, we don't know anything about it's state.
	// Enum: ["AGENT_STATUS_UNSPECIFIED","AGENT_STATUS_STARTING","AGENT_STATUS_INITIALIZATION_ERROR","AGENT_STATUS_RUNNING","AGENT_STATUS_WAITING","AGENT_STATUS_STOPPING","AGENT_STATUS_DONE","AGENT_STATUS_UNKNOWN"]
	Status *string `json:"status,omitempty"`

	// Listen port for scraping metrics.
	ListenPort int64 `json:"listen_port,omitempty"`

	// Path to exec process.
	ProcessExecPath string `json:"process_exec_path,omitempty"`

	// Log level for exporters
	//
	// - LOG_LEVEL_UNSPECIFIED: Auto
	// Enum: ["LOG_LEVEL_UNSPECIFIED","LOG_LEVEL_FATAL","LOG_LEVEL_ERROR","LOG_LEVEL_WARN","LOG_LEVEL_INFO","LOG_LEVEL_DEBUG"]
	LogLevel *string `json:"log_level,omitempty"`

	// Optionally expose the exporter process on all public interfaces
	ExposeExporter bool `json:"expose_exporter,omitempty"`

	// metrics resolutions
	MetricsResolutions *AddAgentOKBodyNodeExporterMetricsResolutions `json:"metrics_resolutions,omitempty"`
}

// Validate validates this add agent OK body node exporter
func (o *AddAgentOKBodyNodeExporter) Validate(formats strfmt.Registry) error {
	var res []error

	if err := o.validateStatus(formats); err != nil {
		res = append(res, err)
	}

	if err := o.validateLogLevel(formats); err != nil {
		res = append(res, err)
	}

	if err := o.validateMetricsResolutions(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

var addAgentOkBodyNodeExporterTypeStatusPropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["AGENT_STATUS_UNSPECIFIED","AGENT_STATUS_STARTING","AGENT_STATUS_INITIALIZATION_ERROR","AGENT_STATUS_RUNNING","AGENT_STATUS_WAITING","AGENT_STATUS_STOPPING","AGENT_STATUS_DONE","AGENT_STATUS_UNKNOWN"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {


            case G_IM_SIZ_4b: {
                u8* img_p = ((u8*)this->img_p) + ofs / 2;
                if ((block_x & 1) == 0) {
                    *img_p = (*img_p & 0x0F) | (texel << 4);
                } else {
                    *img_p = (*img_p & 0xF0) | (texel & 0xF);
                }
            }

            case G_IM_SIZ_8b: {
                ((u8*)this->img_p)[ofs] = texel;
            }

            case G_IM_SIZ_16b: {
                ((u16*)this->img_p)[ofs] = texel;
            }

            case G_IM_SIZ_32b: {
                ((u32*)this->img_p)[ofs] = texel;
            }
        }
    }

    /* Member variables */
    void* img_p;
    u16 width;
    u16 height;
    u8 blockX_size;
    u8 blockY_size;
    u8 n64_fmt;
    u8 n64_bpp;
};

#define EMU64_PRINTF_ENABLED_FLAG (1 << 0)
#define EMU64_PRINTF_FLAG (1 << 1)
#define EMU64_PRINTF1_FLAG (1 << 2)
#define EMU64_PRINTF2_FLAG (1 << 3)
#define EMU64_PRINTF3_FLAG (1 << 4)

class emu64_print {
  public:
    void Printf(const char* fmt, ...);
    // void Printf(const char* fmt, ...) {
    //     va_list list;

    //     if ((this->print_flags & EMU64_PRINTF_ENABLED_FLAG)) {
    //         va_start(list, fmt);
    //         // this->Vprintf(fmt, list);
    //         vprintf(fmt, list);
    //         va_end(list);
    //     }
    // }

    void Printf0(const char* fmt, ...);
    // void Printf0(const char* fmt, ...) {
    //     va_list list;

    //     va_start(list, fmt);
    //     // this->Vprintf(fmt, list);
    //     vprintf(fmt, list);
    //     va_end(list);
    // }

    void Printf1(const char* fmt, ...) {
        va_list list;

        if ((this->print_flags & EMU64_PRINTF1_FLAG)) {
            va_start(list, fmt);
            // this->Vprintf(fmt, list);
            vprintf(fmt, list);
            va_end(list);
        }
    }

    void Printf2(const char* fmt, ...) {
        va_list list;

        if ((this->print_flags & EMU64_PRINTF2_FLAG)) {
            va_start(list, fmt);
            // this->Vprintf(fmt, list);
            vprintf(fmt, list);
            va_end(list);
        }
    }

    void Printf3(const char* fmt, ...) {
        va_list list;

        if ((this->print_flags & EMU64_PRINTF3_FLAG)) {
            va_start(list, fmt);
            // this->Vprintf(fmt, list);
            vprintf(fmt, list);
            va_end(list);
        }
    }

  protected:
    u8 print_flags;

//   private:
    // void Vprintf(const char* fmt, std::__tag_va_List va_list) const; // this is only in e+??
};

#define EMU64_ASSERTLINE(cond, line)        \
    if (!(cond)) {                            \
        this->panic(#cond, __FILE__, line); \
    }

#define EMU64_ASSERT(cond) EMU64_PANICLINE(cond, __LINE__)

#define EMU64_PRINTF(msg, ...) this->Printf0(msg, __VA_ARGS__);

#ifdef EMU64_D


. Beats 作为日志搜集器](../ibm_articles_img/os-cn-elk-filebeat_images_image003.png)

这种架构解决了 Logstash 在各服务器节点上占用系统资源高的问题。相比 Logstash，Beats 所占系统的 CPU 和内存几乎可以忽略不计。另外，Beats 和 Logstash 之间支持 SSL/TLS 加密传输，客户端和服务器双向认证，保证了通信安全。

因此这种架构适合对数据安全性要求较高，同时各服务器性能比较敏感的场景。

### 引入消息队列机制的架构

到笔者整理本文时，Beats 还不支持输出到消息队列，所以在消息队列前后两端只能是 Logstash 实例。这种架构使用 Logstash 从各个数据源搜集数据，然后经消息队列输出插件输出到消息队列中。目前 Logstash 支持 Kafka、Redis、RabbitMQ 等常见消息队列。然后 Logstash 通过消息队列输入插件从队列中获取数据，分析过滤后经输出插件发送到 Elasticsearch，最后通过 Kibana 展示。详见图 4。

##### 图 4\. 引入消息队列机制的架构

![图 4. 引入消息队列机制的架构](../ibm_articles_img/os-cn-elk-filebeat_images_image004.png)

这种架构适合于日志规模比较庞大的情况。但由于 Logstash 日志解析节点和 Elasticsearch 的负荷比较重，可将他们配置为集群模式，以分担负荷。引入消息队列，均衡了网络传输，从而降低了网络闭塞，尤其是丢失数据的可能性，但依然存在 Logstash 占用系统资源过多的问题。

## 基于 Filebeat 架构的配置部署详解

前面提到 Filebeat 已经完全替代了 Logstash-Forwarder 成为新一代的日志采集器，同时鉴于它轻量、安全等特点，越来越多人开始使用它。这个章节将详细讲解如何部署基于 Filebeat 的 ELK 集中式日志解决方案，具体架构见图 5。

##### 图 5\. 基于 Filebeat 的 ELK 集群架构

![图 5. 基于 Filebeat 的 ELK 集群架构](../ibm_articles_img/os-cn-elk-filebeat_images_image005.png)

因为免费的 ELK 没有任何安全机制，所以这里使用了 Nginx 作反向代理，避免用户直接访问 Kibana 服务器。加上配置 Nginx 实现简单的用户认证，一定程度上提高安全性。另外，Nginx 本身具有负载均衡的作用，能够提高系统访问性能。

### 系统信息

#### 平台

笔者试验平台为 RHEL 6.x。注意，目前 ELK（包括 Beats）不支持 AIX。具体对平台的支持请查看 [这里](how_os) 。

#### JDK

JDK 是 IBM Java 8。ELK 需要 Oracle 1.7(或者是 OpenJDK 1.7) 及以上，如果是 IBM Java，则需要 8 及以上的版本。 [具体信息](show_jvm) 。

#### 浏览器

Kib


rr != nil && errors.As(err, &nvmlErr) && errors.Is(nvmlErr.NvmlErrorCode, nvml.ERROR_TIMEOUT)
}
// 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 2025-present Datadog, Inc.

//go:build linux && nvml

package safenvml

import (
	"errors"
	"maps"
	"testing"

	"github.com/NVIDIA/go-nvml/pkg/nvml"
	nvmlmock "github.com/NVIDIA/go-nvml/pkg/nvml/mock"
	"github.com/stretchr/testify/require"

	"github.com/DataDog/datadog-agent/pkg/gpu/testutil"
)

func TestNewDevice(t *testing.T) {
	// Create mock with all symbols available
	mockNvml := testutil.GetBasicNvmlMockWithOptions(
		testutil.WithSymbolsMock(allSymbols),
	)

	// Use WithMockNVML to set the mock
	WithMockNVML(t, mockNvml)

	// Test device creation
	mockDevice := testutil.GetDeviceMock(0)
	device, err := NewPhysicalDevice(mockDevice)

	// Verify results
	require.NoError(t, err)
	require.NotNil(t, device)
	require.Equal(t, testutil.GPUUUIDs[0], device.UUID)
	require.Equal(t, testutil.GPUCores[0], device.CoreCount)
	require.Equal(t, 0, device.Index)
	require.Equal(t, testutil.DefaultTotalMemory, device.Memory)
	require.Equal(t, uint32(75), device.SMVersion) // 7*10 + 5
}

func TestNewDeviceUUIDFailure(t *testing.T) {
	// Create mock with all symbols available
	mockNvml := testutil.GetBasicNvmlMockWithOptions(
		testutil.WithSymbolsMock(allSymbols),
	)

	// Use WithMockNVML to set the mock
	WithMockNVML(t, mockNvml)

	// Create a mock device that fails when getting UUID
	failingMockDevice := &nvmlmock.Device{
		GetUUIDFunc: func() (string, nvml.Return) {
			return "", nvml.ERROR_INVALID_ARGUMENT
		},
		GetCudaComputeCapabilityFunc: func() (int, int, nvml.Return) {
			return 7, 5, nvml.SUCCESS
		},
		GetNumGpuCoresFunc: func() (int, nvml.Return) {
			return testutil.DefaultGpuCores, nvml.SUCCESS
		},
		GetIndexFunc: func() (int, nvml.Return) {
			return 0, nvml.SUCCESS
		},
		GetMemoryInfoFunc: func() (nvml.Memory, nvml.Return) {
			return nvml.Memory{Total: testutil.DefaultTotalMemory}, nvml.SUCCESS
		},
	}

	// Test device creation with failing UUID
	device, err := NewPhysicalDevice(failingMockDevice)

	// Verify failure
	require.Error(t, err)
	require.Nil(t, device)

	// Check that it's the correct type of error using errors.As
	var nvmlErr *NvmlAPIError
	require.True(t, errors.As(err, &nvmlErr), "Expected error to be of type *NvmlAPIError")
	require.Equal(t, "GetUUID", nvmlErr.APIName)
	require.Equal(t, nvml.ERROR_INVALID_ARGUMENT, nvmlErr.NvmlErrorCode)
}

func TestDeviceWithMissingSymbol(t *testing.T) {
	// Create mock with MaxClockInfo symbol missing, not critical, should succeed
	symbols := maps.Clone(allSymbols)
	delete(symbols, toNativeName("GetMaxClockInfo"))

	mockNvml := testutil.GetBasicNvmlMockWithOptions(
		testutil.WithSymbolsMock


er: "Clear the caches" },
  {
    name: "update",
    placeholder: `Version: ${env.KIT_APP_VERSION}`,
  },
  {
    name: "install",
    alias: "i",
    placeholder: "Install an npm package",
  },
  {
    name: "uninstall",
    alias: "un",
    placeholder: "Uninstall an npm package",
  },
  {
    name: "add-kenv-to-profile",
    placeholder: "Add .kenv/bin to your path",
  },
  { name: "env", placeholder: "Modify .env" },
  { name: "issue", placeholder: "File an issue on github" },
  { name: "open-at-login", placeholder: "Open at login" },
  { name: "open-log", placeholder: "Open kit.log" },
  {
    name: "toggle-server",
    placeholder: "Start/stop the server",
  },
  { name: "quit", placeholder: "Quit Kit" },
]

let script = await arg("What do you want to do?", () =>
  cliScripts.map(({ name, placeholder, alias }) => {
    if (env.KIT_CONTEXT === "app") {
      return {
        name: chalk`{green.bold ${name}}${
          alias ? chalk` {yellow (${alias})}` : ""
        }`,
        description: placeholder,
        value: name,
      }
    }

    return {
      name: chalk`{green.bold ${name}}${
        alias ? chalk` {yellow (${alias})}` : ""
      }: ${placeholder}`,
      value: name,
    }
  })
)

let found = cliScripts.find(
  config => config.name == script || config.alias == script
)
if (found) {
  await cli(found.name)
}

export {}
import { Grid } from "./grid";

const gridSize = 100;

test("Check grid size", () => {
  const grid = new Grid(gridSize, false);
  expect(grid.numberOfCells()).toBe(gridSize * gridSize);
});

test("Check alive cells", () => {
  const grid = new Grid(gridSize, false);
  grid.addRandomCells(gridSize / 2);
  expect(grid.numberOfCellsAlive()).toBe(gridSize / 2);
});

test("Set and check alive cell", () => {
  const grid = new Grid(gridSize, false);

  grid.setCell(10, 10);
  expect(grid.hasCell(10, 10)).toBe(true);

  expect(grid.hasCell(20, 20)).toBe(false);
  grid.setCell(20, 20);
  expect(grid.hasCell(20, 20)).toBe(true);

  expect(grid.hasCell(0, 0)).toBe(false);
  expect(grid.hasCell(-10, -10)).toBe(false);
});

// https://www.conwaylife.com/wiki/Blinker
test("Create blinker and check if it really blinks", () => {
  const grid = new Grid(gridSize, false);

  // Check top of blinker.
  expect(grid.hasCell(1, 0)).toBe(false);

  grid.setCell(0, 1);
  grid.setCell(1, 1);
  grid.setCell(2, 1);

  grid.step();
  expect(grid.hasCell(1, 0)).toBe(true);
  grid.step();
  expect(grid.hasCell(1, 0)).toBe(false);
});
export class jXArray{
	array:any[]

	constructor(array){
		this.array = array
		return this
	}

	/**
		Intended for high performance by looping an array only once but performing multiple actions.
		Run multiple functions for each iteration of an array.

		Example: array.each(countTeacher, countChild) instead of two loops array.each(countTeacher) + array.each(countChild)
	*/
	each(method0, method1, method2, method3){
		if(!this.array)return this;
		for(var x=0; x < this.array.length; ++x){
			for(var a=0; a < arguments.length; ++a){
				arguments[a].


 error {
	return xxx_messageInfo_PlasmaCashEventMeta.Unmarshal(m, b)
}
func (m *PlasmaCashEventMeta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_PlasmaCashEventMeta.Marshal(b, m, deterministic)
}
func (dst *PlasmaCashEventMeta) XXX_Merge(src proto.Message) {
	xxx_messageInfo_PlasmaCashEventMeta.Merge(dst, src)
}
func (m *PlasmaCashEventMeta) XXX_Size() int {
	return xxx_messageInfo_PlasmaCashEventMeta.Size(m)
}
func (m *PlasmaCashEventMeta) XXX_DiscardUnknown() {
	xxx_messageInfo_PlasmaCashEventMeta.DiscardUnknown(m)
}

var xxx_messageInfo_PlasmaCashEventMeta proto.InternalMessageInfo

func (m *PlasmaCashEventMeta) GetBlockNumber() uint64 {
	if m != nil {
		return m.BlockNumber
	}
	return 0
}

func (m *PlasmaCashEventMeta) GetTxIndex() uint64 {
	if m != nil {
		return m.TxIndex
	}
	return 0
}

func (m *PlasmaCashEventMeta) GetLogIndex() uint64 {
	if m != nil {
		return m.LogIndex
	}
	return 0
}

type PlasmaDepositEvent struct {
	Slot         uint64         `protobuf:"varint,1,opt,name=slot,proto3" json:"slot,omitempty"`
	DepositBlock *types.BigUInt `protobuf:"bytes,2,opt,name=deposit_block,json=depositBlock" json:"deposit_block,omitempty"`
	// For ERC20 this is the number of coins deposited, for ERC721 this is a token ID.
	Denomination *types.BigUInt `protobuf:"bytes,3,opt,name=denomination" json:"denomination,omitempty"`
	// Entity that made the deposit
	From *types.Address `protobuf:"bytes,4,opt,name=from" json:"from,omitempty"`
	// Contract from which the coins originated (i.e. the currency of the coins)
	Contract             *types.Address       `protobuf:"bytes,5,opt,name=contract" json:"contract,omitempty"`
	Meta                 *PlasmaCashEventMeta `protobuf:"bytes,6,opt,name=meta" json:"meta,omitempty"`
	XXX_NoUnkeyedLiteral struct{}             `json:"-"`
	XXX_unrecognized     []byte               `json:"-"`
	XXX_sizecache        int32                `json:"-"`
}

func (m *PlasmaDepositEvent) Reset()         { *m = PlasmaDepositEvent{} }
func (m *PlasmaDepositEvent) String() string { return proto.CompactTextString(m) }
func (*PlasmaDepositEvent) ProtoMessage()    {}
func (*PlasmaDepositEvent) Descriptor() ([]byte, []int) {
	return fileDescriptor_plasma_cash_842bda1f571177cf, []int{34}
}
func (m *PlasmaDepositEvent) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_PlasmaDepositEvent.Unmarshal(m, b)
}
func (m *PlasmaDepositEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_PlasmaDepositEvent.Marshal(b, m, deterministic)
}
func (dst *PlasmaDepositEvent) XXX_Merge(src proto.Message) {
	xxx_messageInfo_PlasmaDepositEvent.Merge(dst, src)
}
func (m *PlasmaDepositEvent) XXX_Size() int {
	return xxx_messageInfo_PlasmaDepositEvent.Size(m)
}
func (m *PlasmaDepositEvent) XXX_DiscardUnknown() {
	xxx_messageInfo_PlasmaDepositEvent.DiscardUnknown(m)
}

var xxx_m