问:
I want to test ViewModel for my android app. The view model is regarding displaying posts in an app
The app is written in Kotlin and Compose. I am testing the app using Espresso(JUnit4). I have tested the activities but I'm facing issues regarding testing ViewModels. I have attached the code written for the activities and ViewModel. Please help me in testing the project.

The code for FeedScreenViewModel is given below:-

```<code>import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.amplitude.android.Amplitude
import com.kotlang.auth.login.UserProfileProto
import com.navachar.neptune.data.respository.FeedRepository
import com.navachar.neptune.data.db.entities.Post
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FeedScreenViewModel @Inject constructor(
    // TODO: Make this private
val amplitude: Amplitude,
private val feedRepository: FeedRepository,
): ViewModel()
{

companion object {
    private const val TAG = "FeedScreenViewModel"
}

val profile = feedRepository.getProfile().stateIn(
    scope = viewModelScope,
    started = SharingStarted.Eagerly,
    initialValue = UserProfileProto.getDefaultInstance()
)

val feedPagingFlow = feedRepository.feedPagingFlow()
    .cachedIn(viewModelScope)

/**
 * Adds or removes like from the given post
 *
 * @param post the post to update like for
 * @param isLiked the updated like state
 */
fun togglePostLike(post: Post, isLiked: Boolean) {
    viewModelScope.launch {
        feedRepository.setPostLike(post, isLiked)
    }
  }
}
</code>```

The code for FeedScreen is:-

```<code>import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import com.amplitude.android.Amplitude
import com.kotlang.auth.login.UserProfileProto
import com.navachar.neptune.R
import
com.navachar.neptune.presentation.screens.main.feed.actionscreens.post.PostActivity
import com.navachar.neptune.presentation.screens.main.feed.components.ErrorMessage
import com.navachar.neptune.presentation.screens.main.feed.components.PagingFooter
import com.navachar.neptune.presentation.screens.main.feed.components.Post
import com.navachar.neptune.presentation.screens.main.profile.ProfileActivity
import com.navachar.neptune.data.db.entities.Post
import com.navachar.neptune.data.db.entities.User
import com.navachar.neptune.data.db.entities.PostFull

const val TAG8="feed"

@Composable
fun FeedScreen(
modifier: Modifier = Modifier,
viewModel: FeedScreenViewModel = hiltViewModel()
) {

val context = LocalContext.current

val profile by viewModel.profile.collectAsState()
val pagingItems = viewModel.feedPagingFlow.collectAsLazyPagingItems()

FeedScreen(
    modifier = modifier,
    pagingItems = pagingItems,
    openCreatePostScreen = {
        context.startActivity(Intent(context, PostActivity::class.java))
    },
    toggleLike = viewModel::togglePostLike,
    openPostDetails = { post ->
        Intent(
            context,
            CommentActivity::class.java,
        ).apply {
            putExtra("activity", "MainActivity")
            putExtra("postId", post.id)

            context.startActivity(this)
        }
    },
    sharePost = {
        shareContent(
            it,
            profile,
            viewModel.amplitude,
            context,
        )
    },
    openProfile = { user ->
        context.startActivity(
            Intent(
                context,
                ProfileActivity::class.java
            ).apply {
                putExtra("UserId", user.id)
            }
        )
    },
    onRequestOpenUrl = { url ->
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
    }
 )
}

@Composable
private fun FeedScreen(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
openCreatePostScreen: () -> Unit,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
openPostDetails: (post: Post) -> Unit,
sharePost: (post: PostFull) -> Unit,
openProfile: (user: User) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {
Scaffold(
    modifier = modifier,
    content = {
        Feed(
            modifier = Modifier
                .fillMaxSize()
                .padding(it),
            pagingItems = pagingItems,
            toggleLike = toggleLike,
            openPostDetails = openPostDetails,
            sharePost = sharePost,
            openProfile = openProfile,
            onRequestOpenUrl = onRequestOpenUrl,
        )
    },

    bottomBar = {
        BottomBar(onClick = openCreatePostScreen)
    }
  )
}

@Composable
private fun Feed(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
openPostDetails: (post: Post) -> Unit,
sharePost: (post: PostFull) -> Unit,
openProfile: (user: User) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {

 when (val refreshState = pagingItems.loadState.refresh) {
    is LoadState.NotLoading -> {
        FeedLazyList(
            modifier = modifier.testTag(TAG8),
            pagingItems = pagingItems,
            openPostDetails = openPostDetails,
            openProfile = openProfile,
            sharePost = sharePost,
            toggleLike = toggleLike,
            onRequestOpenUrl = onRequestOpenUrl,
        )
    }

    is LoadState.Loading -> {
        Box(
            modifier = modifier,
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator()
        }
    }

    is LoadState.Error -> {
        ErrorMessage(
            modifier = modifier,
            error = refreshState.error,
            onRetry = pagingItems::retry,
        )
    }
  }
}

@Composable
private fun FeedLazyList(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
openPostDetails: (post: Post) -> Unit,
openProfile: (user: User) -> Unit,
sharePost: (post: PostFull) -> Unit,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {
  LazyColumn(
    modifier = modifier
) {
    items(pagingItems) { post ->
        if (post != null) {
            Post(
                post = post,
                openPostDetails = { openPostDetails(post.post) },
                openProfile = {
                    if (post.author != null) {
                        openProfile(post.author)
                    }
                },
                onSharePost = { sharePost(post) },
                onToggleLike = {
                    toggleLike(post.post, it)
                },
                onRequestOpenUrl = onRequestOpenUrl,
            )
        } else {
            // TODO: Show a shimmer placeholder for post
        }
    }

    item {
        PagingFooter(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            pagingItems = pagingItems
        )
    }
 }
}

@Composable
private fun BottomBar(
onClick: () -> Unit
) {
Row(
    Modifier
        .fillMaxWidth()
        .clickable(onClick = onClick)
        .padding(16.dp),
    verticalAlignment = Alignment.CenterVertically,
) {
    CompositionLocalProvider(
        LocalContentAlpha provides ContentAlpha.medium
    ) {
        Image(
            modifier = Modifier
                .size(24.dp)
                .clip(CircleShape),
            painter = painterResource(id = R.drawable.ic_account),
            contentDescription = "",
            contentScale = ContentScale.FillBounds
        )

        Spacer(modifier = Modifier.width(8.dp))

        Text(
            modifier = Modifier.fillMaxWidth(),
            text = stringResource(R.string.post_something),
            style = MaterialTheme.typography.body2,
            textAlign = TextAlign.Start,
        )
    }
 }
}

private fun shareContent(
post: PostFull,
profile: UserProfileProto,
amplitude: Amplitude,
context: Context
) {
 // TODO: Separate the amplitude logic from UI
val eventName = "CTA_Post_Share"
val eventTime = System.currentTimeMillis()
val userId = profile.loginId
val loadTime = ""
val postTag = post.post.tags.joinToString()
val postContentType = if (post.media.isEmpty()) "Text" else "Media"
val postId = post.post.id
amplitude.track(
    eventType = eventName,
    eventProperties = mapOf(
        Pair("Event_Time", eventTime),
        Pair("Screen_Load_Time", loadTime),
        Pair("User_ID", userId),
        Pair("Post_Tag", postTag),
        Pair("Post_Content_Type", postContentType),
        Pair("Post_ID", postId)
    )
)

// TODO: Localise the share content
val shareContent = "${post.author?.name} Posted at Urvar:\n\n" +
        "${post.post.body.take(200)}...\n\n" +
        "Read More: http://www.urvar.com/post/${post.post.id}"

val sendIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND

    putExtra(
        Intent.EXTRA_TEXT,
        shareContent
    )
    type = "text/plain"
}
 val shareIntent = Intent.createChooser(sendIntent, null)
 context.startActivity(shareIntent)
}
</code>```

Please help me test this viewmodel.

The code generated by Test for this View model is:-

```<code>class FeedScreenViewModelTest {

@Before
fun setUp() {
}

@After
fun tearDown() {
}

@Test
fun getProfile() {
}

@Test
fun getFeedPagingFlow() {
}

@Test
fun togglePostLike() {
}

  @Test
  fun getAmplitude() {
  }
}
</code>```

Please tell me what to write inside these functions.

Body:
The app is written in Kotlin and Compose. I am testing the app using Espresso(JUnit4). I have tested the activities but I'm facing issues regarding testing ViewModels. I have attached the code written for the activities and ViewModel. Please help me in testing the project.

The code for FeedScreenViewModel is given below:-

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.amplitude.android.Amplitude
import com.kotlang.auth.login.UserProfileProto
import com.navachar.neptune.data.respository.FeedRepository
import com.navachar.neptune.data.db.entities.Post
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FeedScreenViewModel @Inject constructor(
    // TODO: Make this private
val amplitude: Amplitude,
private val feedRepository: FeedRepository,
): ViewModel()
{

companion object {
    private const val TAG = "FeedScreenViewModel"
}

val profile = feedRepository.getProfile().stateIn(
    scope = viewModelScope,
    started = SharingStarted.Eagerly,
    initialValue = UserProfileProto.getDefaultInstance()
)

val feedPagingFlow = feedRepository.feedPagingFlow()
    .cachedIn(viewModelScope)

/**
 * Adds or removes like from the given post
 *
 * @param post the post to update like for
 * @param isLiked the updated like state
 */
fun togglePostLike(post: Post, isLiked: Boolean) {
    viewModelScope.launch {
        feedRepository.setPostLike(post, isLiked)
    }
  }
}

The code for FeedScreen is:-

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import com.amplitude.android.Amplitude
import com.kotlang.auth.login.UserProfileProto
import com.navachar.neptune.R
import
com.navachar.neptune.presentation.screens.main.feed.actionscreens.post.PostActivity
import com.navachar.neptune.presentation.screens.main.feed.components.ErrorMessage
import com.navachar.neptune.presentation.screens.main.feed.components.PagingFooter
import com.navachar.neptune.presentation.screens.main.feed.components.Post
import com.navachar.neptune.presentation.screens.main.profile.ProfileActivity
import com.navachar.neptune.data.db.entities.Post
import com.navachar.neptune.data.db.entities.User
import com.navachar.neptune.data.db.entities.PostFull

const val TAG8="feed"

@Composable
fun FeedScreen(
modifier: Modifier = Modifier,
viewModel: FeedScreenViewModel = hiltViewModel()
) {

val context = LocalContext.current

val profile by viewModel.profile.collectAsState()
val pagingItems = viewModel.feedPagingFlow.collectAsLazyPagingItems()

FeedScreen(
    modifier = modifier,
    pagingItems = pagingItems,
    openCreatePostScreen = {
        context.startActivity(Intent(context, PostActivity::class.java))
    },
    toggleLike = viewModel::togglePostLike,
    openPostDetails = { post ->
        Intent(
            context,
            CommentActivity::class.java,
        ).apply {
            putExtra("activity", "MainActivity")
            putExtra("postId", post.id)

            context.startActivity(this)
        }
    },
    sharePost = {
        shareContent(
            it,
            profile,
            viewModel.amplitude,
            context,
        )
    },
    openProfile = { user ->
        context.startActivity(
            Intent(
                context,
                ProfileActivity::class.java
            ).apply {
                putExtra("UserId", user.id)
            }
        )
    },
    onRequestOpenUrl = { url ->
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
    }
 )
}

@Composable
private fun FeedScreen(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
openCreatePostScreen: () -> Unit,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
openPostDetails: (post: Post) -> Unit,
sharePost: (post: PostFull) -> Unit,
openProfile: (user: User) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {
Scaffold(
    modifier = modifier,
    content = {
        Feed(
            modifier = Modifier
                .fillMaxSize()
                .padding(it),
            pagingItems = pagingItems,
            toggleLike = toggleLike,
            openPostDetails = openPostDetails,
            sharePost = sharePost,
            openProfile = openProfile,
            onRequestOpenUrl = onRequestOpenUrl,
        )
    },

    bottomBar = {
        BottomBar(onClick = openCreatePostScreen)
    }
  )
}

@Composable
private fun Feed(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
openPostDetails: (post: Post) -> Unit,
sharePost: (post: PostFull) -> Unit,
openProfile: (user: User) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {

 when (val refreshState = pagingItems.loadState.refresh) {
    is LoadState.NotLoading -> {
        FeedLazyList(
            modifier = modifier.testTag(TAG8),
            pagingItems = pagingItems,
            openPostDetails = openPostDetails,
            openProfile = openProfile,
            sharePost = sharePost,
            toggleLike = toggleLike,
            onRequestOpenUrl = onRequestOpenUrl,
        )
    }

    is LoadState.Loading -> {
        Box(
            modifier = modifier,
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator()
        }
    }

    is LoadState.Error -> {
        ErrorMessage(
            modifier = modifier,
            error = refreshState.error,
            onRetry = pagingItems::retry,
        )
    }
  }
}

@Composable
private fun FeedLazyList(
modifier: Modifier,
pagingItems: LazyPagingItems<PostFull>,
openPostDetails: (post: Post) -> Unit,
openProfile: (user: User) -> Unit,
sharePost: (post: PostFull) -> Unit,
toggleLike: (post: Post, isLiked: Boolean) -> Unit,
onRequestOpenUrl: (url: String) -> Unit,
) {
  LazyColumn(
    modifier = modifier
) {
    items(pagingItems) { post ->
        if (post != null) {
            Post(
                post = post,
                openPostDetails = { openPostDetails(post.post) },
                openProfile = {
                    if (post.author != null) {
                        openProfile(post.author)
                    }
                },
                onSharePost = { sharePost(post) },
                onToggleLike = {
                    toggleLike(post.post, it)
                },
                onRequestOpenUrl = onRequestOpenUrl,
            )
        } else {
            // TODO: Show a shimmer placeholder for post
        }
    }

    item {
        PagingFooter(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            pagingItems = pagingItems
        )
    }
 }
}

@Composable
private fun BottomBar(
onClick: () -> Unit
) {
Row(
    Modifier
        .fillMaxWidth()
        .clickable(onClick = onClick)
        .padding(16.dp),
    verticalAlignment = Alignment.CenterVertically,
) {
    CompositionLocalProvider(
        LocalContentAlpha provides ContentAlpha.medium
    ) {
        Image(
            modifier = Modifier
                .size(24.dp)
                .clip(CircleShape),
            painter = painterResource(id = R.drawable.ic_account),
            contentDescription = "",
            contentScale = ContentScale.FillBounds
        )

        Spacer(modifier = Modifier.width(8.dp))

        Text(
            modifier = Modifier.fillMaxWidth(),
            text = stringResource(R.string.post_something),
            style = MaterialTheme.typography.body2,
            textAlign = TextAlign.Start,
        )
    }
 }
}

private fun shareContent(
post: PostFull,
profile: UserProfileProto,
amplitude: Amplitude,
context: Context
) {
 // TODO: Separate the amplitude logic from UI
val eventName = "CTA_Post_Share"
val eventTime = System.currentTimeMillis()
val userId = profile.loginId
val loadTime = ""
val postTag = post.post.tags.joinToString()
val postContentType = if (post.media.isEmpty()) "Text" else "Media"
val postId = post.post.id
amplitude.track(
    eventType = eventName,
    eventProperties = mapOf(
        Pair("Event_Time", eventTime),
        Pair("Screen_Load_Time", loadTime),
        Pair("User_ID", userId),
        Pair("Post_Tag", postTag),
        Pair("Post_Content_Type", postContentType),
        Pair("Post_ID", postId)
    )
)

// TODO: Localise the share content
val shareContent = "${post.author?.name} Posted at Urvar:\n\n" +
        "${post.post.body.take(200)}...\n\n" +
        "Read More: http://www.urvar.com/post/${post.post.id}"

val sendIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND

    putExtra(
        Intent.EXTRA_TEXT,
        shareContent
    )
    type = "text/plain"
}
 val shareIntent = Intent.createChooser(sendIntent, null)
 context.startActivity(shareIntent)
}

Please help me test this viewmodel.

The code generated by Test for this View model is:-

class FeedScreenViewModelTest {

@Before
fun setUp() {
}

@After
fun tearDown() {
}

@Test
fun getProfile() {
}

@Test
fun getFeedPagingFlow() {
}

@Test
fun togglePostLike() {
}

  @Test
  fun getAmplitude() {
  }
}

Please tell me what to write inside these functions.


来源: stackexchange

问:
Add custom field to product variants WooCommerce and pass to API order
With this function I can add custom sku to simple product, then when order is Placed I see this custom sku in API order:

```<code>// Add Custom SKU Field

function my_add_custom_sku() {
    $args = array(
        'label' => __( 'ArticleID', 'woocommerce' ),
        'placeholder' => __( 'Enter Visma ArticleID Here', 'woocommerce' ),
        'id' => 'articleid',
        'desc_tip' => true,
        'description' => __( 'Visma ArticleID is for integration with Zapier.', 'woocommerce' ),
    );
    woocommerce_wp_text_input( $args );

}
add_action( 'woocommerce_product_options_sku', 'my_add_custom_sku' );

// Save
function my_save_custom_meta( $product ){
    if( isset($_POST['articleid']) ) {
        $product->update_meta_data( 'articleid', sanitize_text_field( $_POST['articleid'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'my_save_custom_meta', 10, 1 );

// Save as custom order item meta data and display on orders and email notifications
add_action( 'woocommerce_checkout_create_order_line_item', 'add_articleid_on_orders_and_emails', 10, 4 );
function add_articleid_on_orders_and_emails( $item, $cart_item_key, $values, $order ) {
    $articleid = $values['data']->get_meta('articleid'); // Get product "articleid"

    // For product variations when the "articleid" is not defined
    if ( empty($articleid) && $values['variation_id'] > 0 ) {
        $product    = wc_get_product( $values['product_id'] ); // Get the parent variable product
        $articleid = $product->get_meta( 'articleid' );  // Get parent product "articleid"
    }

    if ( ! empty($articleid) ) {
        $item->add_meta_data( 'articleid', $articleid ); // add it as custom order item meta data
    }
}

// Replace the label (slug) by a readable label name on orders and emails
add_filter( 'woocommerce_display_item_meta', 'filter_order_item_articleid_displayed_label', 100, 3 );
function filter_order_item_articleid_displayed_label( $html, $item, $args ) {
    // Not on admin
    if ( ! is_admin() && $item->get_meta('articleid') ) {
        $html = str_replace('articleid', __('ArticleID', 'woocommerce'), $html);
    }

    return $html;
}
</code>```

Now output API orders:

```<code>wp-json/wc/v3/orders
</code>```

Output:

```<code>"meta_data": [
                    {
                        "id": 90,
                        "key": "articleid",
                        "value": "testReplace",
                        "display_key": "articleid",
                        "display_value": "testReplace"
                    }
</code>```

How to also add custom sku for product varints and when order is placed then also display in orders API in meta_data ?

ContentLicense: CC BY-SA 4.0

Body:
With this function I can add custom sku to simple product, then when order is Placed I see this custom sku in API order:

// Add Custom SKU Field

function my_add_custom_sku() {
    $args = array(
        'label' => __( 'ArticleID', 'woocommerce' ),
        'placeholder' => __( 'Enter Visma ArticleID Here', 'woocommerce' ),
        'id' => 'articleid',
        'desc_tip' => true,
        'description' => __( 'Visma ArticleID is for integration with Zapier.', 'woocommerce' ),
    );
    woocommerce_wp_text_input( $args );

}
add_action( 'woocommerce_product_options_sku', 'my_add_custom_sku' );

// Save
function my_save_custom_meta( $product ){
    if( isset($_POST['articleid']) ) {
        $product->update_meta_data( 'articleid', sanitize_text_field( $_POST['articleid'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'my_save_custom_meta', 10, 1 );

// Save as custom order item meta data and display on orders and email notifications
add_action( 'woocommerce_checkout_create_order_line_item', 'add_articleid_on_orders_and_emails', 10, 4 );
function add_articleid_on_orders_and_emails( $item, $cart_item_key, $values, $order ) {
    $articleid = $values['data']->get_meta('articleid'); // Get product "articleid"

    // For product variations when the "articleid" is not defined
    if ( empty($articleid) && $values['variation_id'] > 0 ) {
        $product    = wc_get_product( $values['product_id'] ); // Get the parent variable product
        $articleid = $product->get_meta( 'articleid' );  // Get parent product "articleid"
    }

    if ( ! empty($articleid) ) {
        $item->add_meta_data( 'articleid', $articleid ); // add it as custom order item meta data
    }
}

// Replace the label (slug) by a readable label name on orders and emails
add_filter( 'woocommerce_display_item_meta', 'filter_order_item_articleid_displayed_label', 100, 3 );
function filter_order_item_articleid_displayed_label( $html, $item, $args ) {
    // Not on admin
    if ( ! is_admin() && $item->get_meta('articleid') ) {
        $html = str_replace('articleid', __('ArticleID', 'woocommerce'), $html);
    }

    return $html;
}

Now output API orders:

wp-json/wc/v3/orders

Output:

"meta_data": [
                    {
                        "id": 90,
                        "key": "articleid",
                        "value": "testReplace",
                        "display_key": "articleid",
                        "display_value": "testReplace"
                    }

How to also add custom sku for product varints and when order is placed then also display in orders API in meta_data ?


问:
Angular universal app loads very slow hosting on aws ec2
I have angular universal app hosting on aws ec2 which suddenly start loading very slow. Sometimes it loads fast but sometimes it takes almost 10 sec to make the connection to server then starts loading the app. These images are not more than 15kb and its taking 2-3 sec just to load them. For the js file its taking 5-6 secs sometimes it takes 11 secs to load main js file and the size is only 357kb.

Can anyonce please suggest what is issue is it angular app that is causing the issue or aws ec2 and how can I fix this


问:
How to cache attribute in jQuery? (tabIndex specifically)
I do not have any code yet. I would like to learn how can I do this.

So I have a modal. When I open it, I want to pass tabIndex: -1 to all elements behind that modal so users who use keyboard for navigating the site, only navigate elements in the modal.

I would like to know if it's possible to cache tabIndex in all body elements (even if it's not specified) so I don't have to reload the page upon closing the modal.

So my inital fix was to reload a page upon closing modal. This way all tabIndex attributes would be gone.

If I didn't set the page to be reloaded, then my all body elements would be unclikable.


问:
Adding rows and columns to a pandas DataFrame in multiple loops
I am trying to make a simple tool which can look for keywords (from multiple txt files) in multiple PDFs. In the end, I would like it to produce a report in the following form:

Name of the pdf document
Keyword document 1
Keyword document...
Keyword document x

PDF 1
1
546
77

PDF...
3
8
8

PDF x
324
23
34

Where the numbers represent the total number of occurrences of all keywords from the keyword document in that particular file.

This is where I got so far - the function can successfully locate, count, and relate summed keywords to the document:

import fitz
import glob

def keyword_finder():

    # access all PDFs from current directory
    for pdf_file in glob.glob('*.pdf'):
        # open files using PyMuPDF
        document = fitz.open(pdf_file)
        # count the number of pages in document
        document_pages = document.page_count

        # access all txt files (these contain the keywords)
        for text_file in glob.glob('*.txt'):
            # empty list to store the results
            occurrences_sdg = []
            # open keywords file
            inputs = open(text_file, 'r')
            # read txt file
            keywords_list = inputs.read()
            # split the words by an 'enter'
            keywords_list_separated = keywords_list.split('\n')

            for keyword in keywords_list_separated[1:-1]: # omit first and last entry
                occurrences_keyword = []
                # read in page by page
                for page in range(0, document_pages):
                    # load in text from i page
                    text_per_page = document.load_page(page)
                    # search for keywords on the page, and sum all occurrences
                    keyword_sum = len(text_per_page.search_for(keyword))
                    # add occurrences from each page to list per keyword
                    occurrences_keyword.append(keyword_sum)
                # sum all occurances of a keyword in the document
                occurrences_sdg.append(sum(occurrences_keyword))

            if sum(occurrences_sdg) > 0:
                print(f'{pdf_file} has {sum(occurrences_sdg)} keyword(s) from {text_file}\n')
```

I did try using pandas and I believe that still is the best choice. The number of loops makes it difficult for me to decide at which point the "skeleton" dataframe should be made, and when the results should be added. Final goal is to have this produced report saved as csv.

Body:
I am trying to make a simple tool which can look for keywords (from multiple txt files) in multiple PDFs. In the end, I would like it to produce a report in the following form:

Name of the pdf document
Keyword document 1
Keyword document...
Keyword document x

PDF 1
1
546
77

PDF...
3
8
8

PDF x
324
23
34

Where the numbers represent the total number of occurrences of all keywords from the keyword document in that particular file.

This is where I got so far - the function can successfully locate, count, and relate summed keywords to the document:

import fitz
import glob

def keyword_finder():

    # access all PDFs from current directory
    for pdf_file in glob.glob('*.pdf'):
        # open files using PyMuPDF
        document = fitz.open(pdf_file)
        # count the number of pages in document
        document_pages = document.page_count

        # access all txt files (these contain the keywords)
        for text_file in glob.glob('*.txt'):
            # empty list to store the results
            occurrences_sdg = []
            # open keywords file
            inputs = open(text_file, 'r')
            # read txt file
            keywords_list = inputs.read()
            # split the words by an 'enter'
            keywords_list_separated = keywords_list.split('\n')

            for keyword in keywords_list_separated[1:-1]: # omit first and last entry
                occurrences_keyword = []
                # read in page by page
                for page in range(0, document_pages):
                    # load in text from i page
                    text_per_page = document.load_page(page)
                    # search for keywords on the page, and sum all occurrences
                    keyword_sum = len(text_per_page.search_for(keyword))
                    # add occurrences from each page to list per keyword
                    occurrences_keyword.append(keyword_sum)
                # sum all occurances of a keyword in the document
                occurrences_sdg.append(sum(occurrences_keyword))

            if sum(occurrences_sdg) > 0:
                print(f'{pdf_file} has {sum(occurrences_sdg)} keyword(s) from {text_file}\n')

I did try using pandas and I believe that still is the best choice. The number of loops makes it difficult for me to decide at which point the "skeleton" dataframe should be made, and when the results should be added. Final goal is to have this produced report saved as csv.


问:
400 bad request in "POST" request in django react
I have react component in were Im posting data in djnago back end,
but it always gives me 400 bad request as response and in backend console too.

```<code>import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Button } from 'react-bootstrap'
import API_URL from './BackendDefaustUrls';
import {useNavigate, useParams} from "react-router-dom"

const AddProduct = () => {
    const [Image , setImage] = useState(null)
    const [Name , setName] = useState("")
    const [Price , setPrice] = useState("")
    const [Description , setDescription] = useState("")
    const [Category , setCategory] = useState("")
    const navigate = useNavigate()

    const {id} = useParams()

    const getProduct = async () => {
        await axios.get(API_URL+`api/${id}/`).then(response => {
            return response.data
        }).then(data => {
            setName(data.name)
            setImage(data.image)
            setPrice(data.price)
            setDescription(data.description)
            setCategory(data.category)
        })

    }

    useEffect(()=>{
        getProduct()
    },[])

    const AddProductInfo = async () =>{

        let formField = new FormData()
        formField.append('name',Name)
        formField.append('price',Price)
        formField.append('description',Description)
        formField.append('category',Category)

        if (Image != null) {
        formField.append('image',Image)
        }

        await axios({
        method: 'POST',
        url: API_URL + `api/`,
        data:formField
        }).then(response => {
        console.log(response.data);
        navigate("/")
        })

    }

    return (
        <div>
        <div className='container'>
            <div className="w-75 mx-auto shadow p-5">
                <h2 className="text-center mb-4">Add A Student</h2>

                <div className='form-group'>
                {/* image */}
                <label>Select Image To Upload</label>
                <input
                    type="file"
                    name="image"
                    className='form-control form-control-lg'
                    onChange={e=>setImage(e.target.files[0])}
                />
                </div>
                {/* !!!!!!!!!!!!!!!!!!!!!!! */}
                <div className='form-group'>
                <input
                    type="text"
                    name="name"
                    className='form-control form-control-lg'
                    placeholder="Enter Product Name"
                    value={Name}
                    onChange={e=>setName(e.target.value)}
                />
                </div>

                <div className='form-group'>
                <input
                    type="text"
                    name="price"
                    className='form-control form-control-lg'
                    placeholder="Price of Product"
                    value={Price}
                    onChange={e=>setPrice(e.target.value)}
                />
                </div>

                <div className='form-group'>
                <textarea
                    type="text"
                    name="description"
                    className='form-control form-control-lg'
                    placeholder="Description"
                    value={Description}
                    onChange={e=>setDescription(e.target.value)}
                />
                </div>

                <div className='form-group'>
                <input
                    type="text"
                    name="category"
                    className='form-control form-control-lg'
                    placeholder="Category"
                    value={Category}
                    onChange={e=>setCategory(e.target.value)}
                />
                </div>
                <Button className='btn btn-success' onClick={AddProductInfo}>Upload</Button>
            </div>
        </div>
        </div>
    )
}

export default AddProduct

</code>```

and my view.py is

```<code>from django.shortcuts import render
from .serializers import ProductsSerializer
from .models import Product
from rest_framework import viewsets
# Create your views here.

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductsSerializer

</code>```

and Im including a screenshot
enter image description here

if I just remove or commit getProduct() function and useEffect(), it posts fine but my main intention of this component is to update info with "PUT" but it was not working too. so I tried with "POST" and it gives me the same error.

I think if I can solve problem with "POST" THEN "PUT" request will be solved

and im sure the main problem is with getProduct().

Body:
I have react component in were Im posting data in djnago back end,
but it always gives me 400 bad request as response and in backend console too.

import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Button } from 'react-bootstrap'
import API_URL from './BackendDefaustUrls';
import {useNavigate, useParams} from "react-router-dom"

const AddProduct = () => {
    const [Image , setImage] = useState(null)
    const [Name , setName] = useState("")
    const [Price , setPrice] = useState("")
    const [Description , setDescription] = useState("")
    const [Category , setCategory] = useState("")
    const navigate = useNavigate()

    const {id} = useParams()

    const getProduct = async () => {
        await axios.get(API_URL+`api/${id}/`).then(response => {
            return response.data
        }).then(data => {
            setName(data.name)
            setImage(data.image)
            setPrice(data.price)
            setDescription(data.description)
            setCategory(data.category)
        })

    }

    useEffect(()=>{
        getProduct()
    },[])

    const AddProductInfo = async () =>{

        let formField = new FormData()
        formField.append('name',Name)
        formField.append('price',Price)
        formField.append('description',Description)
        formField.append('category',Category)

        if (Image != null) {
        formField.append('image',Image)
        }

        await axios({
        method: 'POST',
        url: API_URL + `api/`,
        data:formField
        }).then(response => {
        console.log(response.data);
        navigate("/")
        })

    }

    return (

Add A Student

                {/* image */}
                Select Image To Upload
                <input
                    type="file"
                    name="image"
                    className='form-control form-control-lg'
                    onChange={e=>setImage(e.target.files[0])}
                />

                {/* !!!!!!!!!!!!!!!!!!!!!!! */}

                <input
                    type="text"
                    name="name"
                    className='form-control form-control-lg'
                    placeholder="Enter Product Name"
                    value={Name}
                    onChange={e=>setName(e.target.value)}
                />

                <input
                    type="text"
                    name="price"
                    className='form-control form-control-lg'
                    placeholder="Price of Product"
                    value={Price}
                    onChange={e=>setPrice(e.target.value)}
                />

                <textarea
                    type="text"
                    name="description"
                    className='form-control form-control-lg'
                    placeholder="Description"
                    value={Description}
                    onChange={e=>setDescription(e.target.value)}
                />

                <input
                    type="text"
                    name="category"
                    className='form-control form-control-lg'
                    placeholder="Category"
                    value={Category}
                    onChange={e=>setCategory(e.target.value)}
                />

                <Button className='btn btn-success' onClick={AddProductInfo}>Upload</Button>

    )
}

export default AddProduct

and my view.py is

from django.shortcuts import render
from .serializers import ProductsSerializer
from .models import Product
from rest_framework import viewsets
# Create your views here.

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductsSerializer

and Im including a screenshot
enter image description here

if I just remove or commit getProduct() function and useEffect(), it posts fine but my main intention of this component is to update info with "PUT" but it was not working too. so I tried with "POST" and it gives me the same error.

I think if I can solve problem with "POST" THEN "PUT" request will be solved

and im sure the main problem is with getProduct().


问:
How to Solve RPCError 406 after input OTP on python for telegram bot
Anyone can help me to solved how to fix RPCError 406: UPDATE_APP_TO_LOGIN (caused by SignInRequest) after input OTP that I got from telegram?
RPCError406

```<code> def logi(self):
        app.processEvents()
        self.widget.setText(f'<p style=" text-align:center; font-size:20px; color:orange;"> Login <p>')
        with open('phone.txt' , 'r' , encoding='UTF-8')as f:
            phoness = f.read()
            phoness.strip()
            iss = phoness.replace(' ' , '')
            phones = iss.split()
            f.close()
            app.processEvents()
        if phones == []:
            app.processEvents()
            self.widget.setText(f'<p style=" text-align:center; font-size:20px; color:red;"> Please Put Your Number In phone.csv<p>')
        else:
            for phone in phones:
                app.processEvents()
                try:
                    phone1 = phone.strip()
                    client = TelegramClient(f'sessions/{phone1}' , 3177390 , 'e4292219105a11a30ed146956faef8c3')
                    client.start(phone)
                    client.disconnect()
                    app.processEvents()
                    self.widget.append(f"<p style=' text-align:center; font-size:13px; color:green;'>Signed in successfully as {phone}<p>")
                except KeyboardInterrupt:
                    self.widget.append(f" <p style=' text-align:center; font-size:13px; color:red;'> ---- Stoping ---- <p>")
                    client.disconnect()

                except PhoneNumberBannedError:
                    self.widget.append(f"<p style=' text-align:center; font-size:13px; color:red;'>is banned!<p>")
                    client.disconnect()
                    continue

                except Exception as e:
                    print(f"{e}")
                    self.widget.append(f"<p style=' text-align:center; font-size:13px; color:red;'>{e}<p>")

            self.widget.append(f"<p style=' text-align:center; font-size:20px; color:#2AFEB7;'> Done<p>")
</code>```

I used windows and python 3.10

I was try to update telethon but not work on me

Body:
Anyone can help me to solved how to fix RPCError 406: UPDATE_APP_TO_LOGIN (caused by SignInRequest) after input OTP that I got from telegram?
RPCError406

 def logi(self):
        app.processEvents()
        self.widget.setText(f'
 Login
')
        with open('phone.txt' , 'r' , encoding='UTF-8')as f:
            phoness = f.read()
            phoness.strip()
            iss = phoness.replace(' ' , '')
            phones = iss.split()
            f.close()
            app.processEvents()
        if phones == []:
            app.processEvents()
            self.widget.setText(f'
 Please Put Your Number In phone.csv
')
        else:
            for phone in phones:
                app.processEvents()
                try:
                    phone1 = phone.strip()
                    client = TelegramClient(f'sessions/{phone1}' , 3177390 , 'e4292219105a11a30ed146956faef8c3')
                    client.start(phone)
                    client.disconnect()
                    app.processEvents()
                    self.widget.append(f"
Signed in successfully as {phone}
")
                except KeyboardInterrupt:
                    self.widget.append(f"
 ---- Stoping ----
")
                    client.disconnect()

                except PhoneNumberBannedError:
                    self.widget.append(f"
is banned!
")
                    client.disconnect()
                    continue

                except Exception as e:
                    print(f"{e}")
                    self.widget.append(f"
{e}
")

            self.widget.append(f"
 Done
")

I used windows and python 3.10

I was try to update telethon but not work on me


问:
Error while uploading sketch to arduino using esp8266

Everyone is getting the same error but still couldnt find solution

Tried changing baud rate, usb cable is also good and i have all libraries.


问:
Why does FluentD in_forward plugin treat JSON object as an Array and log Incoming chunk is broken?
The code below is executed from a FluentD node in AWS. FluentD warns of Incoming chunk is broken here. The TLS connection is successful. I am using ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]. The payload (msg) is a well-formed JSON object. The payload appears as a JSON string in the FluentD log together with the ruby hash of the object (i.e. : is replaced with =>).

Why does the code below return true for msg.is_a?(Array)?

```<code>begin
    socket = TCPSocket.new(host, port)
    ssl_context = OpenSSL::SSL::SSLContext.new()

    rsa_cert = OpenSSL::X509::Certificate.new(ssl_cert_string)
    rsa_pkey = OpenSSL::PKey::RSA.new(ssl_key_string)
    ca_intermediate_cert = OpenSSL::X509::Certificate.new(ssl_ca_cert_string)

    ssl_context.add_certificate(rsa_cert, rsa_pkey, [ca_intermediate_cert])

    ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
    ssl_context.ssl_version = :TLSv1_2
    ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
    ssl_socket.sync_close = true
    ssl_socket.connect
    ssl_socket.puts(msg)
rescue Exception => e
    puts "FluentD exception :#{e.message}"
ensure
    ssl_socket&.close
    socket&.close
end
</code>```

The relevant portion of the fluent.conf is:

```<code><source>
  @type forward
  port {{port}}
  bind 0.0.0.0
  <parse>
    @type json
  </parse>
  <transport tls>
    version TLSv1_2
    cert_path {{tls_certificate}}
    private_key_path {{tls_private_key}}
    private_key_passphrase ""
  </transport>
  tag fluentd_ssl
</source>
</code>```

It is used like so:

```<code>foo = ProgressBar.new(N*M)
start_concurrent = Time.now
N.times.map do
  foo.increment!
  bar = ProgressBar.new(M)
  Thread.new do
    M.times do
      bar.increment!
      send_message(host, port, ssl_ca_cert_string, ssl_cert_string, ssl_key_string)
      sleep 0.1
    end
  end
end.each(&:join)
finish_concurrent = Time.now
duration = humanize(finish_concurrent - start_concurrent)
puts "Concurrent duration: #{duration}"
</code>```

I have tried using ssl_socket.syswrite(msg.to_s) and ssl_socket.write(msg.to_s) thinking that puts method had side-effects but both failed.

I don't know how-to / the best way-to apply the following monkey patch to FluentD (I am new to Ruby) so I can add the custom on_message warning to FluentD logs (I just assume that there is a way).

```<code>require 'fluent/plugin/in_forward'

module Skylight
  module Probes
    module Fluentd
      module ForwardInput
        def on_message(msg, chunk_size, conn)
          log.warn "on_message: #{msg}"
          super
        end
      end
    end
  end
end

Fluent::Plugin::ForwardInput.include Skylight::Probes::Fluentd::ForwardInput

</code>```

format mismatch between what was sent and what was expected

msgpack's unpacker receives broken msgpack stream from socket

How can I find out (Ruby or FluentD) why I am getting Incoming chunk is broken? Without overriding on_message.

The entire JSON object appears in the FluentD log so I don't think that it is chunk_size < msg size splitting the msg into an array but I know I'm missing something.

Body:
The code below is executed from a FluentD node in AWS. FluentD warns of Incoming chunk is broken here. The TLS connection is successful. I am using ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]. The payload (msg) is a well-formed JSON object. The payload appears as a JSON string in the FluentD log together with the ruby hash of the object (i.e. : is replaced with =>).

Why does the code below return true for msg.is_a?(Array)?

begin
    socket = TCPSocket.new(host, port)
    ssl_context = OpenSSL::SSL::SSLContext.new()

    rsa_cert = OpenSSL::X509::Certificate.new(ssl_cert_string)
    rsa_pkey = OpenSSL::PKey::RSA.new(ssl_key_string)
    ca_intermediate_cert = OpenSSL::X509::Certificate.new(ssl_ca_cert_string)

    ssl_context.add_certificate(rsa_cert, rsa_pkey, [ca_intermediate_cert])

    ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
    ssl_context.ssl_version = :TLSv1_2
    ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
    ssl_socket.sync_close = true
    ssl_socket.connect
    ssl_socket.puts(msg)
rescue Exception => e
    puts "FluentD exception :#{e.message}"
ensure
    ssl_socket&.close
    socket&.close
end

The relevant portion of the fluent.conf is:

<source>
  @type forward
  port {{port}}
  bind 0.0.0.0
  <parse>
    @type json
  </parse>
  <transport tls>
    version TLSv1_2
    cert_path {{tls_certificate}}
    private_key_path {{tls_private_key}}
    private_key_passphrase ""
  </transport>
  tag fluentd_ssl
</source>

It is used like so:

foo = ProgressBar.new(N*M)
start_concurrent = Time.now
N.times.map do
  foo.increment!
  bar = ProgressBar.new(M)
  Thread.new do
    M.times do
      bar.increment!
      send_message(host, port, ssl_ca_cert_string, ssl_cert_string, ssl_key_string)
      sleep 0.1
    end
  end
end.each(&:join)
finish_concurrent = Time.now
duration = humanize(finish_concurrent - start_concurrent)
puts "Concurrent duration: #{duration}"

I have tried using ssl_socket.syswrite(msg.to_s) and ssl_socket.write(msg.to_s) thinking that puts method had side-effects but both failed.

I don't know how-to / the best way-to apply the following monkey patch to FluentD (I am new to Ruby) so I can add the custom on_message warning to FluentD logs (I just assume that there is a way).

require 'fluent/plugin/in_forward'

module Skylight
  module Probes
    module Fluentd
      module ForwardInput
        def on_message(msg, chunk_size, conn)
          log.warn "on_message: #{msg}"
          super
        end
      end
    end
  end
end

Fluent::Plugin::ForwardInput.include Skylight::Probes::Fluentd::ForwardInput

format mismatch between what was sent and what was expected

msgpack's unpacker receives broken msgpack stream from socket

How can I find out (Ruby or FluentD) why I am getting Incoming chunk is broken? Without overriding on_message.

The entire JSON object appears in the FluentD log so I don't think that it is chunk_size < msg size splitting the msg into an array but I know I'm missing something.


问:
I want to be print my array list in dialog box how?
.I want to be print in my array list in dialog box means click on dictionary answer then print search result in dilog box

ignore this  .. //Lorem ipsum, in graphical and textual context, refers to filler text that is placed in a document or visual presentation. Lorem ipsum is derived from the Latin "dolorem ipsum" roughly translated as "pain itself."

Lorem ipsum presents the sample font and orientation of writing on web pages and other software applications where content is not the main concern of the developer.

Advertisement

```<code>import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'NPL Demo Dictionery',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: const MyHomePage(title:'SimulationX Dictionery'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> data = [
    'A (Nationality symbol for Australia)',
    'AA (Automobile Association)',
    'AAIB (Air Accidents Investigation Branch)',
    'ABC (Activity Based Costing)',
    'B (National Symbol for Belgium)',
    'B2B (Buisness to Business)',
    'B2C (Business To Customer)',
    'BA (British Airways)',
    'C&U (Construction & Use)',
    'CAA (Civil Aviation Authority)',
    'CAB (Citizen,s Advices Bureau)',
    'CAF (Currency Adjustment Factor)',
    'D (Nationality symbol for Germony)',
    'D/A (Deposit/Account)',
    'DAM (Drivers Action Movement)',
    'DC (Distribution Center)',
  ];
  Future searchData(String param) async {
    List<String> result =
        data.where((element) => element.contains(param)).toList();
    return result;

  }

  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text
        (
          style:GoogleFonts.workSans(textStyle: const TextStyle(fontSize: 25),fontWeight:FontWeight.w900),

        (widget.title),
      )),
      drawer: Drawer(
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.only(top: 60),
          children: [
            ListTile(
              leading: Icon(
                Icons.home,color: Color.fromARGB(255, 124, 3, 94),
              ),
              tileColor: Color.fromARGB(255, 221, 215, 221),
              title: const Text('Home',), hoverColor: Color.fromARGB(255, 81, 3, 92),textColor:Color.fromARGB(255, 0, 0, 0),
              onTap: () {
                Navigator.pop(context,MaterialPageRoute(builder: (context) => MyHomePage(title: '',)));
              },
            ),
            ListTile(
              leading: Icon(
                Icons.search,color: Colors.white,
              ),
              tileColor: Colors.purple,
              title: const Text('SearchWord'),hoverColor: Color.fromARGB(255, 204, 126, 204),textColor:Colors.white,
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(
                Icons.web,color: Color.fromARGB(255, 92, 1, 87),),
                tileColor: Color.fromARGB(255, 221, 215, 221),
              title: const Text('Xplore Simulation'),textColor: Color.fromARGB(255, 60, 6, 71),hoverColor: Color.fromARGB(255, 204, 126, 204),
                onTap: () async {
  const url = 'https://simulationsx.com/';
  if (await canLaunch(url)) {
   await launch(url);
  } else {
   throw 'Could not launch $url';
  }
  }),
              ListTile(
              leading: Icon(
                Icons.info_outline,color: Colors.white,

              ),
              tileColor: Colors.purple,textColor: Colors.white,hoverColor: Color.fromARGB(255, 204, 126, 204),
              title: const Text('Info'),
            onTap: () async {
  const url = 'https://simulationsx.com/contact/';
  if (await canLaunch(url)) {
   await launch(url);
  } else {
   throw 'Could not launch $url';
  }
  }
  ),
  ],
  ),
),
      body: Center(

      child: Column(

     mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
            Padding(padding: EdgeInsets.only(top: 20)),
            TypeAheadField<String>(
            textFieldConfiguration: TextFieldConfiguration(
           decoration: InputDecoration(
                                  ),
                          ),
              suggestionsCallback: (data) async {
              return await searchData(data);
              },
              itemBuilder: (context, suggestion) {
                return ListTile(

                  title: Text(suggestion),
                  onTap: () => {showDialog(context: context, builder: (data)=> AlertDialog (title:Text (),),
                ),},
                );
                  },

                   onSuggestionSelected: (suggestion) {
                   Navigator.of(context).pop(data);
             },
             ),

          ],
        ),
      ),
    );
  }
}

</code>```

Body:
.I want to be print in my array list in dialog box means click on dictionary answer then print search result in dilog box

ignore this  .. //Lorem ipsum, in graphical and textual context, refers to filler text that is placed in a document or visual presentation. Lorem ipsum is derived from the Latin "dolorem ipsum" roughly translated as "pain itself."

Lorem ipsum presents the sample font and orientation of writing on web pages and other software applications where content is not the main concern of the developer.

Advertisement

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'NPL Demo Dictionery',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: const MyHomePage(title:'SimulationX Dictionery'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> data = [
    'A (Nationality symbol for Australia)',
    'AA (Automobile Association)',
    'AAIB (Air Accidents Investigation Branch)',
    'ABC (Activity Based Costing)',
    'B (National Symbol for Belgium)',
    'B2B (Buisness to Business)',
    'B2C (Business To Customer)',
    'BA (British Airways)',
    'C&U (Construction & Use)',
    'CAA (Civil Aviation Authority)',
    'CAB (Citizen,s Advices Bureau)',
    'CAF (Currency Adjustment Factor)',
    'D (Nationality symbol for Germony)',
    'D/A (Deposit/Account)',
    'DAM (Drivers Action Movement)',
    'DC (Distribution Center)',
  ];
  Future searchData(String param) async {
    List<String> result =
        data.where((element) => element.contains(param)).toList();
    return result;

  }

  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text
        (
          style:GoogleFonts.workSans(textStyle: const TextStyle(fontSize: 25),fontWeight:FontWeight.w900),

        (widget.title),
      )),
      drawer: Drawer(
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.only(top: 60),
          children: [
            ListTile(
              leading: Icon(
                Icons.home,color: Color.fromARGB(255, 124, 3, 94),
              ),
              tileColor: Color.fromARGB(255, 221, 215, 221),
              title: const Text('Home',), hoverColor: Color.fromARGB(255, 81, 3, 92),textColor:Color.fromARGB(255, 0, 0, 0),
              onTap: () {
                Navigator.pop(context,MaterialPageRoute(builder: (context) => MyHomePage(title: '',)));
              },
            ),
            ListTile(
              leading: Icon(
                Icons.search,color: Colors.white,
              ),
              tileColor: Colors.purple,
              title: const Text('SearchWord'),hoverColor: Color.fromARGB(255, 204, 126, 204),textColor:Colors.white,
              onTap: () {
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(
                Icons.web,color: Color.fromARGB(255, 92, 1, 87),),
                tileColor: Color.fromARGB(255, 221, 215, 221),
              title: const Text('Xplore Simulation'),textColor: Color.fromARGB(255, 60, 6, 71),hoverColor: Color.fromARGB(255, 204, 126, 204),
                onTap: () async {
  const url = 'https://simulationsx.com/';
  if (await canLaunch(url)) {
   await launch(url);
  } else {
   throw 'Could not launch $url';
  }
  }),
              ListTile(
              leading: Icon(
                Icons.info_outline,color: Colors.white,

              ),
              tileColor: Colors.purple,textColor: Colors.white,hoverColor: Color.fromARGB(255, 204, 126, 204),
              title: const Text('Info'),
            onTap: () async {
  const url = 'https://simulationsx.com/contact/';
  if (await canLaunch(url)) {
   await launch(url);
  } else {
   throw 'Could not launch $url';
  }
  }
  ),
  ],
  ),
),
      body: Center(

      child: Column(

     mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
            Padding(padding: EdgeInsets.only(top: 20)),
            TypeAheadField<String>(
            textFieldConfiguration: TextFieldConfiguration(
           decoration: InputDecoration(
                                  ),
                          ),
              suggestionsCallback: (data) async {
              return await searchData(data);
              },
              itemBuilder: (context, suggestion) {
                return ListTile(

                  title: Text(suggestion),
                  onTap: () => {showDialog(context: context, builder: (data)=> AlertDialog (title:Text (),),
                ),},
                );
                  },

                   onSuggestionSelected: (suggestion) {
                   Navigator.of(context).pop(data);
             },
             ),

          ],
        ),
      ),
    );
  }
}


问:
can we have varying stack sizes which we can change also?
I have couple questions regarding the POSIX thread stack size and their safety issues:

A) Can we have varying stack sizes (for each thread set using: pthread_attr_getstacksize)?

B) When a thread dies (detached/exited), will the operating system reclaim its memory pages?

C) Could a thread keep writing into another threads stack segment if they happen to be adjacent to each other on the virtual memory mapping?


问:
Haproxy in docker cannot access device's localhost via "host.docker.internal"
I need to configure Haproxy for local testing.

The goal is to have 3 services

haproxy in docker container

listening http app on device's (macOS) localhost

a client app sending request through haproxy to the listening app (number 2.)

docker-compose.yml configuration for the proxy is

```<code>proxy_server:
  image: haproxy:2.7.0-alpine
  container_name: proxy_server
  user: root # I used this to install curl in the container
  ports:
    - '3128:80' # haproxy itself
    - '20005:20005' # configured proxy in haproxy.cfg
  restart: always
  volumes:
    - ./test/proxy_server/config:/usr/local/etc/haproxy # this maps the haproxy.cfg file into the container
  extra_hosts:
    - 'host.docker.internal:host-gateway' # allows the proxy to access device's localhost on linux
</code>```

haproxy.cfg is

```<code>defaults
  timeout client 5s
  timeout connect 5s
  timeout server 5s
  timeout http-request 5s

listen reverse-proxy
  bind *:20005
  mode http
  option httplog
  log stdout format raw local0 debug
</code>```

When the listening app (2.) listens on localhost:56454, I can connect into the haproxy container, install curl and connect to the listening app via host.docker.internal host.

```<code>/ # curl -v -I http://host.docker.internal:56454
*   Trying 192.168.65.2:56454...
* Connected to host.docker.internal (192.168.65.2) port 56454 (#0)
> HEAD / HTTP/1.1
> Host: host.docker.internal:56454
> User-Agent: curl/7.86.0
> Accept: */*
</code>```

This is correct.

The problem is that I am not able to send request through the proxy to the same URL (http://host.docker.internal:56454) because the proxy logs

```<code>172.22.0.1:56636 [10/Dec/2022:13:50:22.601] reverse-proxy reverse-proxy/<NOSRV> 0/-1/-1/-1/0 503 217 - - SC-- 1/1/0/0/0 0/0 "POST http://host.docker.internal:56454/confirmation HTTP/1.1"
</code>```

and the client gets following response:

```<code>HTTP Status 503: <html><body><h1>503 Service Unavailable</h1>\nNo server is available to handle this request.\n</body></html>
</code>```

Also, the request passes correctly when I use the following docker-compose.yml configuration with ubuntu/squid image instead of the haproxy one

```<code>proxy_server:
  image: ubuntu/squid
  container_name: proxy_server
  ports:
    - '3128:3128'
  restart: always
  extra_hosts:
    - 'host.docker.internal:host-gateway' # allows the proxy to access device's localhost on linux
</code>```

So, I guess the problem is that haproxy somehow does not see the service on http://host.docker.internal:56454 even though the service is accessible from the container.

I've also tried ubuntu and debian versions of the haproxy image and it still does not work correctly.

Any idea how to fix it?

Edit:

Investigating <NOSRV>... No clue how to fix it yet.

Body:
I need to configure Haproxy for local testing.

The goal is to have 3 services

haproxy in docker container

listening http app on device's (macOS) localhost

a client app sending request through haproxy to the listening app (number 2.)

docker-compose.yml configuration for the proxy is

proxy_server:
  image: haproxy:2.7.0-alpine
  container_name: proxy_server
  user: root # I used this to install curl in the container
  ports:
    - '3128:80' # haproxy itself
    - '20005:20005' # configured proxy in haproxy.cfg
  restart: always
  volumes:
    - ./test/proxy_server/config:/usr/local/etc/haproxy # this maps the haproxy.cfg file into the container
  extra_hosts:
    - 'host.docker.internal:host-gateway' # allows the proxy to access device's localhost on linux

haproxy.cfg is

defaults
  timeout client 5s
  timeout connect 5s
  timeout server 5s
  timeout http-request 5s

listen reverse-proxy
  bind *:20005
  mode http
  option httplog
  log stdout format raw local0 debug

When the listening app (2.) listens on localhost:56454, I can connect into the haproxy container, install curl and connect to the listening app via host.docker.internal host.

/ # curl -v -I http://host.docker.internal:56454
*   Trying 192.168.65.2:56454...
* Connected to host.docker.internal (192.168.65.2) port 56454 (#0)
> HEAD / HTTP/1.1
> Host: host.docker.internal:56454
> User-Agent: curl/7.86.0
> Accept: */*

This is correct.

The problem is that I am not able to send request through the proxy to the same URL (http://host.docker.internal:56454) because the proxy logs

172.22.0.1:56636 [10/Dec/2022:13:50:22.601] reverse-proxy reverse-proxy/<NOSRV> 0/-1/-1/-1/0 503 217 - - SC-- 1/1/0/0/0 0/0 "POST http://host.docker.internal:56454/confirmation HTTP/1.1"

and the client gets following response:

HTTP Status 503:
503 Service Unavailable
\nNo server is available to handle this request.\n

Also, the request passes correctly when I use the following docker-compose.yml configuration with ubuntu/squid image instead of the haproxy one

proxy_server:
  image: ubuntu/squid
  container_name: proxy_server
  ports:
    - '3128:3128'
  restart: always
  extra_hosts:
    - 'host.docker.internal:host-gateway' # allows the proxy to access device's localhost on linux

So, I guess the problem is that haproxy somehow does not see the service on http://host.docker.internal:56454 even though the service is accessible from the container.

I've also tried ubuntu and debian versions of the haproxy image and it still does not work correctly.

Any idea how to fix it?

Edit:

Investigating <NOSRV>... No clue how to fix it yet.


问:
Using chrome.action.setIcon() (Manifest V3) leads to TypeError: Cannot read properties of undefined (reading 'setIcon')
I am working on toggling the icon for a Google Chrome extension, using chrome.action.setIcon().

With Manifest V3.

My manifest.json contains the extension "action" property which sets the icons correctly:

  "action": {
    "default_icon": {
      "16": "/images/ext/icon16.png",
      "32": "/images/ext/icon32.png",
      "48": "/images/ext/icon48.png",
      "128": "/images/ext/icon128.png"
    },
  }
```
<p>When running the code to change the extension icon, in the service worker ("<code>background.js</code>"):</p>
<pre class="lang-js prettyprint-override"><code>FUNCTION-WITH-ICON-TOGGLING(){
 chrome.action.setIcon({
            path: {
              '16': '/images/on/icon16.png',
              '32': '/images/on/icon32.png',
              '48': '/images/on/icon48.png',
              '128': '/images/on/icon128.png'
            }
          });
}
</code>```

In a function run when the extension is pressed:

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: FUNCTION-WITH-ICON-TOGGLING }});
```
<p>I am greeted with a fun error:</p>
<pre class="lang-js prettyprint-override"><code> Error handling response: TypeError: Cannot read properties of undefined (reading 'setIcon')
</code>```

I have tried changing syntax to even the original working icons, and the single icon path,
With the same error.
eg.

chrome.action.setIcon({
            path: "/images/on/icon16.png"
          });
```

I have searched extensively and not found this error reported. If anybody can point me in the right direction, I would really appreciate the help!

The full work in progress implementation can be found here:
background.js

Testing in Chrome Version 108.0.5359.96 (latest to date).

Body:
I am working on toggling the icon for a Google Chrome extension, using chrome.action.setIcon().

With Manifest V3.

My manifest.json contains the extension "action" property which sets the icons correctly:

  "action": {
    "default_icon": {
      "16": "/images/ext/icon16.png",
      "32": "/images/ext/icon32.png",
      "48": "/images/ext/icon48.png",
      "128": "/images/ext/icon128.png"
    },
  }

When running the code to change the extension icon, in the service worker ("background.js"):

FUNCTION-WITH-ICON-TOGGLING(){
 chrome.action.setIcon({
            path: {
              '16': '/images/on/icon16.png',
              '32': '/images/on/icon32.png',
              '48': '/images/on/icon48.png',
              '128': '/images/on/icon128.png'
            }
          });
}

In a function run when the extension is pressed:

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: FUNCTION-WITH-ICON-TOGGLING }});

I am greeted with a fun error:

 Error handling response: TypeError: Cannot read properties of undefined (reading 'setIcon')

I have tried changing syntax to even the original working icons, and the single icon path,
With the same error.
eg.

chrome.action.setIcon({
            path: "/images/on/icon16.png"
          });

I have searched extensively and not found this error reported. If anybody can point me in the right direction, I would really appreciate the help!

The full work in progress implementation can be found here:
background.js

Testing in Chrome Version 108.0.5359.96 (latest to date).


问:
Python: Send an email at a specific time via SMTP
I'm using python and smtplib module to send an email via SMTP server.

I create the header of the email like this, I'm using EmailMessage()

```<code>msg = EmailMessage()
msg["From"] = fromAddress
msg["To"] = toAddress
msg["Subject"] = "Hello"
msg["Delivery-Date"]
</code>```

Is it possible to send an email via an SMTP server (Outlook) by specifying date and time of receipt of the email in the header of the message. With Delivery-Date, it doesn't work.

Body:
I'm using python and smtplib module to send an email via SMTP server.

I create the header of the email like this, I'm using EmailMessage()

msg = EmailMessage()
msg["From"] = fromAddress
msg["To"] = toAddress
msg["Subject"] = "Hello"
msg["Delivery-Date"]

Is it possible to send an email via an SMTP server (Outlook) by specifying date and time of receipt of the email in the header of the message. With Delivery-Date, it doesn't work.


问:
How to solve this quadratic optimization problem
My problem is described in this picture(It's like a Pyramid structure):

The objective function is below:

In this problem, D is known, A is the object that I want to get. It is a layered structure, each block in the upper layer is divided into four sub-blocks in the layer below. And the value of the upper layer node is equal to the sum of the four child nodes of the lower layer. In above example, I used only 2 layers.

What I want to do is simulate the distribution of D with A, so in the objective function is the ratio of two adjacent squares in each row in A compared to the value in D. I do this comparison on each layer and sum them. Then it is all of my objective function. But in the finest layer, the value in A has a constrain A<=1, the value in A can be a number between 0 and 1. I have tried to solve it using Quadratic programming in python library CVXPY. However, it seems the speed is slow.

So I want to solve it in another way, because this is a convex optimization problem, which can guarantee the global optimal solution. What I think is whether it is possible to use the method of derivation. There are two unknown variables in each item, that is, the two items with A in the formula. Partial derivatives are obtained for them, and the restriction of A<=1 is added, then solve using gradient descent method. Is this mathematically feasible, because I don't know much about optimization, and if it is possible, how should I do it? If not possible, what other methods can I use?


问:
Secure passwords in Spring Boot apps for Production using Jasypt?
As far as I see, there are some approaches for keeping passwords in Spring Boot apps e.g. Jasypt. I read some documentation for Jasypt, but could not understand some points. Could you clarify me on these points?

1- I want to secure passwords especially in application.properties.yml, docker-compose.yml files. I don't want to use Cloud services and for this situation, is Jasypt the best option for me? Or would you suggest a more proper approach for this purpose?

2- I am wondering how to use the app after I secure using Jasypt in PRODUCTION environment on Docker container. For example, the customer create app and database containers on Docker using the provided jar file and necessary commands. In that case, should I provide them the same commands modified for Jasypt with the necessary key used in Jasypt command? I am confused with this scenario.


问:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null')
So I am trying to post a message to another site. But I am getting error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').

index.html

```
<p>l.html's script
(it has nothing else. no iframes or something like that. only this script in <script> tag)</p>
<pre class="lang-js prettyprint-override"><code>        window.addEventListener("message", (event) => {
            if (event.origin !== "index.html") {
                console.log(event.data);
            }
          }, false);
</code>```

What did I do wrong?

Body:
So I am trying to post a message to another site. But I am getting error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').

index.html

l.html's script
(it has nothing else. no iframes or something like that. only this script in


问:
How to solve this error "java.lang.UnsatisfiedLinkError: 'void java.util.zip.Deflater.reset(long)' "?
I am trying to generate a signed apk for flutter project in android studio. But build is failing to due following error:

```<code>Build Output:
> Task :flutter_inappwebview:minifyReleaseWithR8 FAILED
AGPBI: {"kind":"error","text":"java.lang.UnsatisfiedLinkError: 'void java.util.zip.Deflater.reset(long)'","sources":[{}],"tool":"R8"}
java.lang.UnsatisfiedLinkError: 'void java.util.zip.Deflater.reset(long)'
</code>```

Can someone please tell how to solve the following error:

java.lang.UnsatisfiedLinkError: 'void
java.util.zip.Deflater.reset(long)'

Body:
I am trying to generate a signed apk for flutter project in android studio. But build is failing to due following error:

Build Output:
> Task :flutter_inappwebview:minifyReleaseWithR8 FAILED
AGPBI: {"kind":"error","text":"java.lang.UnsatisfiedLinkError: 'void java.util.zip.Deflater.reset(long)'","sources":[{}],"tool":"R8"}
java.lang.UnsatisfiedLinkError: 'void java.util.zip.Deflater.reset(long)'

Can someone please tell how to solve the following error:

java.lang.UnsatisfiedLinkError: 'void
java.util.zip.Deflater.reset(long)'


问:
Nginx Docker Angular: falied while connecting to upstream
I'm trying to run Second Frontend project on Angular. I see in the error that the path is missing:
My error:

nginx | 2022/12/10 13:36:33 [error] 104#104: *323 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: mysite.com, request: "GET /profile/home HTTP/2.0", **upstream: "http://XXX.XXX.XXX.XXX:4201/home"**, host: "mysite.com"

It's supposed to be upstream: "http://XXX.XXX.XXX.XXX:4201/PROFILE/home"
But for some reason it's not.

My nginx.conf

```<code>location /profile {
        proxy_pass http://servertwo:4201/profile;
        proxy_intercept_errors on;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "no-referrer-when-downgrade" always;
        add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
}
</code>```

My Docker

```<code>FROM node:18.8.0-alpine AS servertwo-build

WORKDIR /usr/src/servertwo

COPY . .

RUN npm ci && npm run build

FROM nginx:stable-alpine

COPY nginx/default.conf /etc/nginx/conf.d/default.conf

COPY --from=servertwo-build  /usr/src/servertwo/dist/servertwo /var/www/html

EXPOSE 4201

</code>```

In My angular.json :

```<code>"baseHref": "/profile/"
</code>```

How can I fix this?

Body:
I'm trying to run Second Frontend project on Angular. I see in the error that the path is missing:
My error:

nginx | 2022/12/10 13:36:33 [error] 104#104: *323 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: mysite.com, request: "GET /profile/home HTTP/2.0", **upstream: "http://XXX.XXX.XXX.XXX:4201/home"**, host: "mysite.com"

It's supposed to be upstream: "http://XXX.XXX.XXX.XXX:4201/PROFILE/home"
But for some reason it's not.

My nginx.conf

location /profile {
        proxy_pass http://servertwo:4201/profile;
        proxy_intercept_errors on;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "no-referrer-when-downgrade" always;
        add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
}

My Docker

FROM node:18.8.0-alpine AS servertwo-build

WORKDIR /usr/src/servertwo

COPY . .

RUN npm ci && npm run build

FROM nginx:stable-alpine

COPY nginx/default.conf /etc/nginx/conf.d/default.conf

COPY --from=servertwo-build  /usr/src/servertwo/dist/servertwo /var/www/html

EXPOSE 4201

In My angular.json :

"baseHref": "/profile/"

How can I fix this?


问:
Matplotlib figsize incorrect on screen
I would like to obtain a 10x10 cm matplotlib-figure. The following code opens a figure that is 12.2 cm on one screen and 7.0 cm on another screen (PDF in Acrobat Reader: 13.5 / 7.8 cm).

Obviously some screen-scaling issue, but how to fix it? If it was only the PDF displaying incorrectly I wouldn't care, but I want to see the matplotlib figure correctly on my screens. Both windows screen scalings are at 100%.

```<code>import matplotlib.pyplot as plt
cm = 1/2.54
fig = plt.figure(figsize = (10 * cm, 10 * cm))
plt.show()
fig.savefig("test.pdf")
</code>```

Title: Matplotlib figsize incorrect on screen

Body:
I would like to obtain a 10x10 cm matplotlib-figure. The following code opens a figure that is 12.2 cm on one screen and 7.0 cm on another screen (PDF in Acrobat Reader: 13.5 / 7.8 cm).

Obviously some screen-scaling issue, but how to fix it? If it was only the PDF displaying incorrectly I wouldn't care, but I want to see the matplotlib figure correctly on my screens. Both windows screen scalings are at 100%.

import matplotlib.pyplot as plt
cm = 1/2.54
fig = plt.figure(figsize = (10 * cm, 10 * cm))
plt.show()
fig.savefig("test.pdf")


问:
Laravel search on multiple tables using this scenario
I want to search on "Table: employees > name" or "Table: jobs > company" of assigned jobs. What should I add to perform this? Is this a correct and optimized code to perform the task? This is my code:

SearchController

```<code>public function search_assigned_jobs($search=null)
{
  $result = AssignJob::with('jobs', 'employees')->whereHas('employees', function ($query) use ($search){
    $query->where('name', 'like', '%'.$search.'%');
      })->orWhereHas('jobs', function ($query) use ($search){
        $query->where('company', 'like', '%'.$search.'%');
      })->get();

    return $this->success($result);
}
</code>```

API Route

```<code>Route::get('admin/search-assigned-jobs/{search?}', [SearchController::class, 'search_assigned_jobs']);
</code>```

Tables
https://imgur.com/I40fDAB

Models
https://imgur.com/mtYgCUD

Body:
I want to search on "Table: employees > name" or "Table: jobs > company" of assigned jobs. What should I add to perform this? Is this a correct and optimized code to perform the task? This is my code:

SearchController

public function search_assigned_jobs($search=null)
{
  $result = AssignJob::with('jobs', 'employees')->whereHas('employees', function ($query) use ($search){
    $query->where('name', 'like', '%'.$search.'%');
      })->orWhereHas('jobs', function ($query) use ($search){
        $query->where('company', 'like', '%'.$search.'%');
      })->get();

    return $this->success($result);
}

API Route

Route::get('admin/search-assigned-jobs/{search?}', [SearchController::class, 'search_assigned_jobs']);

Tables
https://imgur.com/I40fDAB

Models
https://imgur.com/mtYgCUD


问:
#include <iostream> error in visual studio code
Not sure why because it worked fine before but I get an error when trying to include  in Visual Studio Code

I did add the include path to the properties.json file as in the picture but it's still not working
did i include the wrong path or is there any other solution?

```<code>{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\MinGW",
                "C:\\MinGW\\include",
                "C:\\MinGW\bin",
                "C:\\MinGW\\lib"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:/MinGW/bin/gcc.exe",
            "cStandard": "c11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "windows-gcc-x86"
        }
    ],
    "version": 4
}
</code>```

Body:
Not sure why because it worked fine before but I get an error when trying to include  in Visual Studio Code

I did add the include path to the properties.json file as in the picture but it's still not working
did i include the wrong path or is there any other solution?

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\MinGW",
                "C:\\MinGW\\include",
                "C:\\MinGW\bin",
                "C:\\MinGW\\lib"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:/MinGW/bin/gcc.exe",
            "cStandard": "c11",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "windows-gcc-x86"
        }
    ],
    "version": 4
}


问:
I'm trying to set up a new SharePoint production server and getting an error creating an Open XML 2.5 document
I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.

Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)

This is what the code looks like in the function that is failing.

```<code>''' \<summary\>
'''
''' \</summary\>
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
   Try
      Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
      Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
      MainPart.Document = New Document()
      Dim DocBody As New Body()
      Return wpd
   Catch ex As Exception
      WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
      Return Nothing
   End Try
End Function
</code>```

Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.

ERROR: Source: OpenXML Routine: WPDCreateFromStream User:

Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.

StackTrace:    at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)

Source: WindowsBase

Data: System.Collections.ListDictionaryInternal

InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer

ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)

TargetSite: Void EasyTraceEvent(Keyword, Event)

I know this is not an issue with the code as the same code works in development. I assume it has to do with  permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.

I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.

If anyone has run into this and can point me to a solution, I would appreciate it.

The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.

I am creating a new document, that is why it is coded using WordProcessingDocument.Create

Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.

The more I think about it, it just feels like a permission issue.

Body:
I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.

Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)

This is what the code looks like in the function that is failing.

''' \
'''
''' \
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
   Try
      Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
      Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
      MainPart.Document = New Document()
      Dim DocBody As New Body()
      Return wpd
   Catch ex As Exception
      WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
      Return Nothing
   End Try
End Function

Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.

ERROR: Source: OpenXML Routine: WPDCreateFromStream User:

Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.

StackTrace:    at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)

Source: WindowsBase

Data: System.Collections.ListDictionaryInternal

InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer

ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)

TargetSite: Void EasyTraceEvent(Keyword, Event)

I know this is not an issue with the code as the same code works in development. I assume it has to do with  permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.

I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.

If anyone has run into this and can point me to a solution, I would appreciate it.

The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.

I am creating a new document, that is why it is coded using WordProcessingDocument.Create

Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.

The more I think about it, it just feels like a permission issue.