问:
Why is this jQuery code takes too much time to execute?
I have a very simple jquery code that makes a button to fade in:

```<code>function showOne() {
console.log("SHOW");
$('.closebt').fadeIn('slow');
}
</code>```

this code is called by HTML:

```<code><a (click)="showOne()">SHOW</a>
</code>```

and this is the element:

```<code><div class="closebt">
  <button type="button">Click Me!1</button>
  <button type="button">Click Me!12</button>
</div>
</code>```

the console.log("SHOW"); is executed immediately as seen in Chrome console, but the $('.btn1').fadeIn('slow'); makes the button appear after 8-10 seconds, how can I make the buttons appear immediately?

Body:
I have a very simple jquery code that makes a button to fade in:

function showOne() {
console.log("SHOW");
$('.closebt').fadeIn('slow');
}

this code is called by HTML:

SHOW

and this is the element:

  <button type="button">Click Me!1</button>
  <button type="button">Click Me!12</button>

the console.log("SHOW"); is executed immediately as seen in Chrome console, but the $('.btn1').fadeIn('slow'); makes the button appear after 8-10 seconds, how can I make the buttons appear immediately?


来源: stackexchange

问:
Pytorch: Is there a better way to limit the number of classes in a Dataset (eg; CIFAR DS )
I tried to limit the number of classes in the CIFAR DS, I came up with this solution,
is there a better way?

!Note: this aint ChatGPT solution, because it couldn't give a propoer working solution for the problem at hand.

#Limit the number of classes in a DS
classes_to_keep = {0, 1, 2, 3, 4, 5, 6, 7} # set for fast existence check
# Create a new dataset that only keeps the desired classes
class SubsetCIFAR(torchvision.datasets.CIFAR10):
    def __init__(self, root, train=True, transform=None, download=True, indices=None):
        super().__init__(root, train=train, transform=transform, download=download)
        keepDeez = {indx:klass for indx, klass in enumerate(self.targets) if klass in indices}
        self.target = list(keepDeez.values())
        self.data = self.data[list(keepDeez.keys())]

trainset = SubsetCIFAR(root='./data', train=True, download=True, indices=classes_to_keep)
```

ContentLicense: CC BY-SA 4.0


问:
Autoencoder during training has loss about 0.003 and accuracy is also above 95 still yielding poor decoded image
I have implemented an auto encoder architecture to learn features of human face in pytorch with 5 encoding and  5 decoding layer .Model architecture is attached below.The image sizes that were passed to model were of varied sizes for eye its 128*128 similar different window size for different face component but still could not understand despite a low loss reconstructed image is very blurry attached is image for refernce.The model architecture was derived from paper of deep face drawing.
custom datatset that we prepared contain human face portrat with white background.attached is image with both black and white backgrounds.enter image description here[[enter image description here](https://i.stack.imgur.com/2NlgA.jpg)](https://i.stack.imgur.com/jET2F.png)

I tried this autoencoder but coud not get problem.Imge from decoder is not very well reconstructed.It would be really helpful if somebody can address this


问:
jOOQ timeout on parallel execution doesn't work
In short, I have the following queries:

```<code>fun find(request: Request): Result<Record> {
    val selectStep = dslContext
        .someFindLogic()
        .queryTimeout(QUERIES_TIMEOUT.toSeconds().toInt())

    return selectStep.fetch()
}

fun count(request: Request): Result<Record> {
    val selectStep = dslContext
        .someCountLogic()
        .queryTimeout(QUERIES_TIMEOUT.toSeconds().toInt())

    return selectStep.fetchCount()
}
</code>```

with the following "async" exection:

```<code>val data = CompletableFuture.supplyAsync { repository.find(request) }
val size = CompletableFuture.supplyAsync { repository.count(request) }

return SomeResponse(data.get(), size.get().toLong())
</code>```

the problem is that, for some unkown reason, the second count query haven't ever been restricted by query timeout, and following some bad situations, it's keep executing:

any ideas why it could happen?

Body:
In short, I have the following queries:

fun find(request: Request): Result<Record> {
    val selectStep = dslContext
        .someFindLogic()
        .queryTimeout(QUERIES_TIMEOUT.toSeconds().toInt())

    return selectStep.fetch()
}

fun count(request: Request): Result<Record> {
    val selectStep = dslContext
        .someCountLogic()
        .queryTimeout(QUERIES_TIMEOUT.toSeconds().toInt())

    return selectStep.fetchCount()
}

with the following "async" exection:

val data = CompletableFuture.supplyAsync { repository.find(request) }
val size = CompletableFuture.supplyAsync { repository.count(request) }

return SomeResponse(data.get(), size.get().toLong())

the problem is that, for some unkown reason, the second count query haven't ever been restricted by query timeout, and following some bad situations, it's keep executing:

any ideas why it could happen?


问:
Java Springboot (Maven) - .jar doesnt package right in Jenkins pipeline
Very complex issue here I cannot figure out...  For starters our corporate Jenkins instance has support for both Maven plugin style jobs and pipeline.  They have a heavy push on pipeline jobs, and I'm creating a pipeline for our Java Springboot (maven) job.

When this job is executed in the maven plugin style job - it runs fine and produces a jar that is runable and has been working for years.

Upon moving this job to a pipeline configuration scripted job - it will build but is about 24mb smaller than the maven plugin built job.  In doing a comparison using WinMerge tool - i find that there are several missing items from this packaged .jar (see screenshot).  If a full list of these is requested I can provide, but TLDNR - i've tried several different images for the jenkins agent... which is a dockerized container agent on the Jenkins instance.

WinMerge directory comparison of good vs. bad

I have tried images such as - openjdk1_8, maven:3.6.3-openjdk-8, and several other images - all with the same outcome of the same missing files.  This is beyond my experience level to figure out :/  so i'm at your guys mercy!  Thanks in advance - let me know if you'd need more info to what would be needed for troubleshooting.


问:
Project not reloading/rebuilding when using Spring Boot Devtools
I followed the steps to enable auto project rebuilding/reloading for IntelliJ:

In my build.gradle file, I have:

```<code>compileOnly 'org.springframework.boot:spring-boot-devtools'
</code>```

From what I can tell, this should be all that is needed.

I'm testing it with the following code:

```<code>@Controller
public class HomeController {
    @GetMapping("/")
    public String hello() {
        System.out.println("Huh, interesting... doesn't seem to be reloading at all??");
        return "home";
    }
}
</code>```

I'll change the text being printed out, save the file, and I won't see any activity in the 'run' tab in IntelliJ.

If I load '/' in my browser, I see the same text being printed out in the run tab (System.out.println), so it's not picking up any changes.

I've restarted IntelliJ, clicked the 'refresh' icon for gradle, still not reloading when a code change is saved.

I'm not sure if it matters, but I'm on a Mac with an M1 chip.

Edit: I've tried everything, having to click this button each time is going to drive me insane!!!

Body:
I followed the steps to enable auto project rebuilding/reloading for IntelliJ:

In my build.gradle file, I have:

compileOnly 'org.springframework.boot:spring-boot-devtools'

From what I can tell, this should be all that is needed.

I'm testing it with the following code:

@Controller
public class HomeController {
    @GetMapping("/")
    public String hello() {
        System.out.println("Huh, interesting... doesn't seem to be reloading at all??");
        return "home";
    }
}

I'll change the text being printed out, save the file, and I won't see any activity in the 'run' tab in IntelliJ.

If I load '/' in my browser, I see the same text being printed out in the run tab (System.out.println), so it's not picking up any changes.

I've restarted IntelliJ, clicked the 'refresh' icon for gradle, still not reloading when a code change is saved.

I'm not sure if it matters, but I'm on a Mac with an M1 chip.

Edit: I've tried everything, having to click this button each time is going to drive me insane!!!


问:
Newly added db tables on PostgreSQL are getting dropped and re-created during Strapi v4 startup when running on a blue-green deploy on AWS
We’re having a bizarre database issue using Strapi V4 (Node.js API framework)… Newly added PostgreSQL DB tables are getting dropped and re-created during startup ONLY when running on a blue-green deployment on AWS.

We’d appreciate help from anyone who has specific experience with this kind of situation using this framework or could lend us a senior/DevOps engineer for an hour or two to get a pair of fresh eyes on the problem.

We’re unable to reproduce this in local dev environments or cloud environments that use in-place deployment, so it’s been extremely troublesome trying to figure out the exact cause. (We can’t switch prod to in-place deploys because of uptime SLA with our clients.)


问:
Any idea why my carousel items are not showing up?
I am trying display a carousel of images on my page, but it is not displaying the images at all. when I console logged the image url, it is there, but no image at all.

also one more question, what would I use for the key here? I used the image url here as the key

```<code>import galleryStyles from "../styles/Gallery.module.css";
import Carousel from "react-bootstrap/Carousel";

const BigGallery = ({ images }) => {
  return (
    <>
      <div>hi </div>
      <Carousel interval={4000} className={galleryStyles.Carousel}>
        {images.map((image) => {
          console.log(image.url); // This logged the correct url
          <Carousel.Item key={image.url}>
            <img src={image.url} className={galleryStyles.image} />
          </Carousel.Item>;
        })}
      </Carousel>
    </>
  );
};

export default BigGallery;
</code>```

Body:
I am trying display a carousel of images on my page, but it is not displaying the images at all. when I console logged the image url, it is there, but no image at all.

also one more question, what would I use for the key here? I used the image url here as the key

import galleryStyles from "../styles/Gallery.module.css";
import Carousel from "react-bootstrap/Carousel";

const BigGallery = ({ images }) => {
  return (
    <>

hi

      <Carousel interval={4000} className={galleryStyles.Carousel}>
        {images.map((image) => {
          console.log(image.url); // This logged the correct url
          <Carousel.Item key={image.url}>

          </Carousel.Item>;
        })}
      </Carousel>
    </>
  );
};

export default BigGallery;


问:
Chrome Extensions - How to listen for updates on another tab and extract information from it to display in the extention?
I'm trying to make an extension that listens to updates on another tab (Whatsapp), retrieves the updated list of messages, and allows user to send messages from any tab using that extension.

Is there any specific API for accessing updated content in another tab and interacting with elements of that tab while you're in a 2nd tab?


问:
Django password reset PasswordResetConfirmView
View:

```<code>def f_forget_password(request):
    ctx = dict()
    if request.method == "POST":
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            to_email = password_reset_form.cleaned_data['email']
            to_email=to_email.lower()
            associated_users = User.objects.filter(Q(email=to_email))
            if associated_users.exists():
                if len(associated_users)!=1:
                    return HttpResponse('Email Is Invalid.')
                current_site = get_current_site(request)
                for user in associated_users:
                    mail_subject = "Password Reset Requested"
                    email_template_name = "password/password_reset_email.txt"
                    uid=urlsafe_base64_encode(force_bytes(user.pk))
                    c = {
                    "email":user.email,
                    'domain':current_site.domain,
                    'site_name': 'mysit',
                    "uid": uid,
                    "user": user,
                    'token': account_activation_token.make_token(user),
                    }
                    try:
                        message = loader.render_to_string(email_template_name, c)
                        email = EmailMessage(
                                    mail_subject, message, to=[to_email]
                        )
                        email.send()
                    except Exception as e:
                        return HttpResponse('Invalid header found.<br/>')
                    return redirect ("/password_reset/done/")
            else:
                return HttpResponse('Email not found.')
    template = loader.get_template('password/forget_password.html')
    response = HttpResponse(template.render(ctx, request),content_type='text/html')
    return response
</code>```

url:

```<code>path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'),
    path('reset/<uidb64>/<token>',
            auth_views.PasswordResetConfirmView.as_view(),
                 name='password_reset_confirm'),
    path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'),
</code>```

token.py:

```<code>class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()
</code>```

view PasswordResetConfirmView dont work and my password dont change.
when i clicked on passwordresetlink i have an Error:

Password reset unsuccessful

The password reset link was invalid, possibly because it has already
been used. Please request a new password reset.

Body:
View:

def f_forget_password(request):
    ctx = dict()
    if request.method == "POST":
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            to_email = password_reset_form.cleaned_data['email']
            to_email=to_email.lower()
            associated_users = User.objects.filter(Q(email=to_email))
            if associated_users.exists():
                if len(associated_users)!=1:
                    return HttpResponse('Email Is Invalid.')
                current_site = get_current_site(request)
                for user in associated_users:
                    mail_subject = "Password Reset Requested"
                    email_template_name = "password/password_reset_email.txt"
                    uid=urlsafe_base64_encode(force_bytes(user.pk))
                    c = {
                    "email":user.email,
                    'domain':current_site.domain,
                    'site_name': 'mysit',
                    "uid": uid,
                    "user": user,
                    'token': account_activation_token.make_token(user),
                    }
                    try:
                        message = loader.render_to_string(email_template_name, c)
                        email = EmailMessage(
                                    mail_subject, message, to=[to_email]
                        )
                        email.send()
                    except Exception as e:
                        return HttpResponse('Invalid header found.
')
                    return redirect ("/password_reset/done/")
            else:
                return HttpResponse('Email not found.')
    template = loader.get_template('password/forget_password.html')
    response = HttpResponse(template.render(ctx, request),content_type='text/html')
    return response

url:

path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'),
    path('reset/<uidb64>/<token>',
            auth_views.PasswordResetConfirmView.as_view(),
                 name='password_reset_confirm'),
    path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'),

token.py:

class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()

view PasswordResetConfirmView dont work and my password dont change.
when i clicked on passwordresetlink i have an Error:

Password reset unsuccessful

The password reset link was invalid, possibly because it has already
been used. Please request a new password reset.


问:
SqlAlchemy ORM __table__ using complex joins?
I've defined a model that represents the results of a SELECT statement that joins multiple tables together and performs calculations on the columns

```<code>from sqlalchemy import select

class ComplexModel(Base):
    __table__ = select([users_table.c.id, users_table.c.name, orders_table.c.total]).\
                 select_from(users_table.join(orders_table, users_table.c.id == orders_table.c.user_id))

</code>```

and can use it like:

```<code>session.query(ComplexModel).filter(ComplexModel.name == "John").first()
</code>```

How can I provide an interface that allows an IDE to detect the column names of a complex model is to define the columns as class-level attributes:

```<code>class ComplexModel:
    id = Column(Integer)
    name = Column(String)
    total = Column(Float)
</code>```

errors:

"Can't add additional column 'id' when specifying __table__"

I tried using a view:

same as above but:

```<code>__table__ = create_view(
        name="users-orders-view",
        selectable=select(...
</code>```

But still:
Can't add additional column 'id' when specifying __table__

Body:
I've defined a model that represents the results of a SELECT statement that joins multiple tables together and performs calculations on the columns

from sqlalchemy import select

class ComplexModel(Base):
    __table__ = select([users_table.c.id, users_table.c.name, orders_table.c.total]).\
                 select_from(users_table.join(orders_table, users_table.c.id == orders_table.c.user_id))

and can use it like:

session.query(ComplexModel).filter(ComplexModel.name == "John").first()

How can I provide an interface that allows an IDE to detect the column names of a complex model is to define the columns as class-level attributes:

class ComplexModel:
    id = Column(Integer)
    name = Column(String)
    total = Column(Float)

errors:

"Can't add additional column 'id' when specifying __table__"

I tried using a view:

same as above but:

__table__ = create_view(
        name="users-orders-view",
        selectable=select(...

But still:
Can't add additional column 'id' when specifying __table__


问:
Focus state in Jetpack's Compose Previews
I'm trying to generate previews for different states of my component, which is based on Material TextField. In order to do snapshot tests with Showkase and Paparazzi, I want to create a preview where my text field is focused, hence rendering the different outline in a different color. Is there a way I can achieve the desired result?

I tried different things such a using a focusRequester, but none work at while rendering preview. The only way I can get it to work is by starting the interactive preview, but that would not work with paparazzi.

```<code>@Preview
@Composable
internal fun TextFieldPreview(
    @PreviewParameter(TextFieldPreviewParameterProvider::class)
    parameter: TextFieldPreviewParameter
) {
    with(parameter) {
        val focusRequester = remember { FocusRequester() }

        MyTextField(
            value = "Text",
            onValueChange = {},
            isEnabled = isEnabled,
            isPrefilled = isPrefilled,
            isError = isError,
            errorMessage = isError.runIfTrue { "Error message" },
            modifier = Modifier.focusRequester(focusRequester)
        )

        LaunchedEffect(isFocused) {
            if (isFocused){
                focusRequester.requestFocus()
            }
        }
    }
}

internal data class TextFieldPreviewParameter(
    val isFocused: Boolean,
    val isEnabled: Boolean,
    val isPrefilled: Boolean,
    val isError: Boolean,
)
</code>```

Body:
I'm trying to generate previews for different states of my component, which is based on Material TextField. In order to do snapshot tests with Showkase and Paparazzi, I want to create a preview where my text field is focused, hence rendering the different outline in a different color. Is there a way I can achieve the desired result?

I tried different things such a using a focusRequester, but none work at while rendering preview. The only way I can get it to work is by starting the interactive preview, but that would not work with paparazzi.

@Preview
@Composable
internal fun TextFieldPreview(
    @PreviewParameter(TextFieldPreviewParameterProvider::class)
    parameter: TextFieldPreviewParameter
) {
    with(parameter) {
        val focusRequester = remember { FocusRequester() }

        MyTextField(
            value = "Text",
            onValueChange = {},
            isEnabled = isEnabled,
            isPrefilled = isPrefilled,
            isError = isError,
            errorMessage = isError.runIfTrue { "Error message" },
            modifier = Modifier.focusRequester(focusRequester)
        )

        LaunchedEffect(isFocused) {
            if (isFocused){
                focusRequester.requestFocus()
            }
        }
    }
}

internal data class TextFieldPreviewParameter(
    val isFocused: Boolean,
    val isEnabled: Boolean,
    val isPrefilled: Boolean,
    val isError: Boolean,
)


问:
In Javascript what does <ClassName[]> mean?
In this code below, what does Promise<LetterService[]> mean?

Is the LetterService[] saying create an array with LetterService objects inside it?

What are the <> indicating here?

```<code>export default interface LetterService {
    GetLetters(): Promise<LetterService[]> }
</code>```

Body:
In this code below, what does Promise<LetterService[]> mean?

Is the LetterService[] saying create an array with LetterService objects inside it?

What are the <> indicating here?

export default interface LetterService {
    GetLetters(): Promise<LetterService[]> }


问:
How to show Notifications from AlarmReceiver even when device has been restarted in jetpack compose
I have an application in Jetpack Compose that notifies scheduled alarms set by the user and it works well; however, when the device is restarted, the alarm does not sound. For example, if the user sets the alarm to go off in two minutes, this works; however, if the device is restarted before the alarm is triggered, the alarm will not sound.
I have this method to save an alarm:

```<code>@RequiresApi(Build.VERSION_CODES.M)
@Composable
fun AddPage(navController: NavController, vm: TaskViewModel = viewModel()) {
    val scope= rememberCoroutineScope()
    val calendar=Calendar.getInstance().apply {
        timeInMillis=System.currentTimeMillis()
    }

    val title = remember {
        mutableStateOf("")
    }
    val description = remember {
        mutableStateOf("")
    }
    val year= remember {
        mutableStateOf(calendar.get(Calendar.YEAR))
    }

    val month= remember {
        mutableStateOf(calendar.get(Calendar.MONTH)+1)
    }

    val day= remember {
        mutableStateOf(calendar.get(Calendar.DAY_OF_MONTH))
    }

    val hour= remember {
        mutableStateOf(calendar.get(Calendar.HOUR_OF_DAY))
    }

    val minutes= remember {
        mutableStateOf(calendar.get(Calendar.MINUTE))
    }
    val showPopup= remember {
        mutableStateOf(false)
    }
    val msg= remember {
        mutableStateOf("")
    }
    val icon= remember {
        mutableStateOf(Icons.Filled.Done)
    }

    if (showPopup.value){

        PopupMessagePage(msg.value,400.dp,500.dp,showPopup.value,{
                                                                                showPopup.value=false
        },
            icon.value)
    }
    val context = LocalContext.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Agregar Tarea",
            style = NoteTheme.typography.h1
        )

        RowOfThis(title, "Título", true)
        RowOfThis(description, "Descripción", false)
        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            DatePick(context = context, year = year, month = month, day = day)
        }
        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            TimePick(context = context, hours = hour, minutes = minutes)
        }

        Button(
            onClick = {
                if (title.value.isNullOrBlank() || description.value.isNullOrBlank()
                ) {
                    msg.value="Por favor ingrese todos los datos"
                    icon.value=Icons.Filled.Warning
                    showPopup.value=true
                    return@Button
                }
                scope.launch {

                    calendar.apply {
                        set(Calendar.YEAR,year.value)
                        set(Calendar.MONTH,(month.value-1))
                        set(Calendar.DAY_OF_MONTH,day.value)
                        set(Calendar.HOUR_OF_DAY,hour.value)
                        set(Calendar.MINUTE,minutes.value)
                    }

                    val shuff=(1..99999).shuffled().first()
                    vm.task.value.title = title.value
                    vm.task.value.description = description.value
                    vm.task.value.date = "${day.value}/${month.value}/${year.value}"
                    vm.task.value.time = calendar.timeInMillis
                    vm.task.value.dateCreated= getDateToday()
                    vm.task.value.shuff= shuff

                    vm.createTask(context, vm.task.value)
                    Log.e("tmepickerreceived","date and time  :${year.value}/${month.value}/${day.value} : ${hour.value}:${minutes.value}")

                    val alarmMgr= context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

                    val intent= Intent(context,AlarmReceiver::class.java)
                    intent.action="alarma"
                    intent.putExtra("ALARMA_ID_STRING","$shuff")
                    intent.putExtra("ALARMA_DESCRIPTION_STRING","${description.value}")
                    val pending=
                        PendingIntent.getBroadcast(context,shuff,intent, PendingIntent.FLAG_IMMUTABLE)

                    Log.e("time final","compare ${System.currentTimeMillis()}" +
                            " mytime: ${calendar.timeInMillis} " +
                            "hour: ${calendar.get(Calendar.HOUR_OF_DAY)} " +
                            "minute: ${calendar.get(Calendar.MINUTE)} " +
                            "year: ${calendar.get(Calendar.YEAR)} " +
                            "month: ${calendar.get(Calendar.MONTH)+1} " +
                            "day: ${calendar.get(Calendar.DAY_OF_MONTH)}")

                    alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,pending)
                    msg.value="Recordatorio activado"
                    icon.value=Icons.Filled.Done
                    showPopup.value=true
                    vm.resetTask()
                }

            },
            colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
        ) {
            Text(text = "Guardar", color = Color.White, style = NoteTheme.typography.subtitle)
        }
    }
}
</code>```

and i have this alarm receiver:

```<code>class AlarmReceiver: BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d("alarm","************************received")

        if (intent?.action == "alarma") {
            val number = intent?.getStringExtra("ALARMA_ID_STRING")
            val description=intent?.getStringExtra("ALARMA_DESCRIPTION_STRING")
            val mp= MediaPlayer.create(context,R.raw.alarma)
            mp.start()
            if (context != null) {
                if (number != null) {
                    val pendingResult: PendingResult = goAsync()
                    val asyncTask = Task(pendingResult,context,number.toInt())
                    asyncTask.execute()
                    showNotification(context,number.toInt(),"Recordatorio: ${number.toInt()}","$description")
                }
            }
        }
    }

    private class Task(
        private val pendingResult: PendingResult,
        private val context: Context,
        private val number:Int
    ) : AsyncTask<String, Int, String>() {

        override  fun doInBackground(vararg params: String?): String {
            if (context != null) {
                TaskDatabase.getDatabase(context).taskDao().deleteAfterAlarm(number)
            }
            return toString().also { log ->
                Log.d("BACKGROUND", log)
            }
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            // Must call finish() so the BroadcastReceiver can be recycled.
            pendingResult.finish()
        }
    }

    private  fun showNotification(context: Context,idN:Int,title:String,text:String){
        try{
            val manager=context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val id= UUID.randomUUID().toString()
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
                val channel= NotificationChannel(id,
                    UUID.randomUUID().toString(), NotificationManager.IMPORTANCE_HIGH)
                manager.createNotificationChannel(channel)
            }

            val fullScreenIntent = Intent(context, MainActivity::class.java)
            val fullScreenPendingIntent = PendingIntent.getActivity(context, 0,
                fullScreenIntent, PendingIntent.FLAG_IMMUTABLE)

            var builder= NotificationCompat.Builder(context,id)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setFullScreenIntent(fullScreenPendingIntent,true)

            manager.notify(idN,builder.build())

        }catch (exc:Exception){
            Toast.makeText(context,exc.toString(),Toast.LENGTH_LONG).show()
        }
    }
}
</code>```

that methods works fine but if device is restarted the alarm does not work  i have this in manifest too:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NotePadReminder"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.NotePadReminder">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <receiver android:name="com.mobile.notepadreminder.AlarmReceiver"
            android:enabled="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

Body:
I have an application in Jetpack Compose that notifies scheduled alarms set by the user and it works well; however, when the device is restarted, the alarm does not sound. For example, if the user sets the alarm to go off in two minutes, this works; however, if the device is restarted before the alarm is triggered, the alarm will not sound.
I have this method to save an alarm:

@RequiresApi(Build.VERSION_CODES.M)
@Composable
fun AddPage(navController: NavController, vm: TaskViewModel = viewModel()) {
    val scope= rememberCoroutineScope()
    val calendar=Calendar.getInstance().apply {
        timeInMillis=System.currentTimeMillis()
    }

    val title = remember {
        mutableStateOf("")
    }
    val description = remember {
        mutableStateOf("")
    }
    val year= remember {
        mutableStateOf(calendar.get(Calendar.YEAR))
    }

    val month= remember {
        mutableStateOf(calendar.get(Calendar.MONTH)+1)
    }

    val day= remember {
        mutableStateOf(calendar.get(Calendar.DAY_OF_MONTH))
    }

    val hour= remember {
        mutableStateOf(calendar.get(Calendar.HOUR_OF_DAY))
    }

    val minutes= remember {
        mutableStateOf(calendar.get(Calendar.MINUTE))
    }
    val showPopup= remember {
        mutableStateOf(false)
    }
    val msg= remember {
        mutableStateOf("")
    }
    val icon= remember {
        mutableStateOf(Icons.Filled.Done)
    }

    if (showPopup.value){

        PopupMessagePage(msg.value,400.dp,500.dp,showPopup.value,{
                                                                                showPopup.value=false
        },
            icon.value)
    }
    val context = LocalContext.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 30.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Agregar Tarea",
            style = NoteTheme.typography.h1
        )

        RowOfThis(title, "Título", true)
        RowOfThis(description, "Descripción", false)
        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            DatePick(context = context, year = year, month = month, day = day)
        }
        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            TimePick(context = context, hours = hour, minutes = minutes)
        }

        Button(
            onClick = {
                if (title.value.isNullOrBlank() || description.value.isNullOrBlank()
                ) {
                    msg.value="Por favor ingrese todos los datos"
                    icon.value=Icons.Filled.Warning
                    showPopup.value=true
                    return@Button
                }
                scope.launch {

                    calendar.apply {
                        set(Calendar.YEAR,year.value)
                        set(Calendar.MONTH,(month.value-1))
                        set(Calendar.DAY_OF_MONTH,day.value)
                        set(Calendar.HOUR_OF_DAY,hour.value)
                        set(Calendar.MINUTE,minutes.value)
                    }

                    val shuff=(1..99999).shuffled().first()
                    vm.task.value.title = title.value
                    vm.task.value.description = description.value
                    vm.task.value.date = "${day.value}/${month.value}/${year.value}"
                    vm.task.value.time = calendar.timeInMillis
                    vm.task.value.dateCreated= getDateToday()
                    vm.task.value.shuff= shuff

                    vm.createTask(context, vm.task.value)
                    Log.e("tmepickerreceived","date and time  :${year.value}/${month.value}/${day.value} : ${hour.value}:${minutes.value}")

                    val alarmMgr= context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

                    val intent= Intent(context,AlarmReceiver::class.java)
                    intent.action="alarma"
                    intent.putExtra("ALARMA_ID_STRING","$shuff")
                    intent.putExtra("ALARMA_DESCRIPTION_STRING","${description.value}")
                    val pending=
                        PendingIntent.getBroadcast(context,shuff,intent, PendingIntent.FLAG_IMMUTABLE)

                    Log.e("time final","compare ${System.currentTimeMillis()}" +
                            " mytime: ${calendar.timeInMillis} " +
                            "hour: ${calendar.get(Calendar.HOUR_OF_DAY)} " +
                            "minute: ${calendar.get(Calendar.MINUTE)} " +
                            "year: ${calendar.get(Calendar.YEAR)} " +
                            "month: ${calendar.get(Calendar.MONTH)+1} " +
                            "day: ${calendar.get(Calendar.DAY_OF_MONTH)}")

                    alarmMgr?.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,pending)
                    msg.value="Recordatorio activado"
                    icon.value=Icons.Filled.Done
                    showPopup.value=true
                    vm.resetTask()
                }

            },
            colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
        ) {
            Text(text = "Guardar", color = Color.White, style = NoteTheme.typography.subtitle)
        }
    }
}

and i have this alarm receiver:

class AlarmReceiver: BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d("alarm","************************received")

        if (intent?.action == "alarma") {
            val number = intent?.getStringExtra("ALARMA_ID_STRING")
            val description=intent?.getStringExtra("ALARMA_DESCRIPTION_STRING")
            val mp= MediaPlayer.create(context,R.raw.alarma)
            mp.start()
            if (context != null) {
                if (number != null) {
                    val pendingResult: PendingResult = goAsync()
                    val asyncTask = Task(pendingResult,context,number.toInt())
                    asyncTask.execute()
                    showNotification(context,number.toInt(),"Recordatorio: ${number.toInt()}","$description")
                }
            }
        }
    }

    private class Task(
        private val pendingResult: PendingResult,
        private val context: Context,
        private val number:Int
    ) : AsyncTask<String, Int, String>() {

        override  fun doInBackground(vararg params: String?): String {
            if (context != null) {
                TaskDatabase.getDatabase(context).taskDao().deleteAfterAlarm(number)
            }
            return toString().also { log ->
                Log.d("BACKGROUND", log)
            }
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            // Must call finish() so the BroadcastReceiver can be recycled.
            pendingResult.finish()
        }
    }

    private  fun showNotification(context: Context,idN:Int,title:String,text:String){
        try{
            val manager=context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val id= UUID.randomUUID().toString()
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
                val channel= NotificationChannel(id,
                    UUID.randomUUID().toString(), NotificationManager.IMPORTANCE_HIGH)
                manager.createNotificationChannel(channel)
            }

            val fullScreenIntent = Intent(context, MainActivity::class.java)
            val fullScreenPendingIntent = PendingIntent.getActivity(context, 0,
                fullScreenIntent, PendingIntent.FLAG_IMMUTABLE)

            var builder= NotificationCompat.Builder(context,id)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setFullScreenIntent(fullScreenPendingIntent,true)

            manager.notify(idN,builder.build())

        }catch (exc:Exception){
            Toast.makeText(context,exc.toString(),Toast.LENGTH_LONG).show()
        }
    }
}

that methods works fine but if device is restarted the alarm does not work  i have this in manifest too:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NotePadReminder"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.NotePadReminder">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <receiver android:name="com.mobile.notepadreminder.AlarmReceiver"
            android:enabled="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>


问:
React parent element not correctly updating combobox child component
So i'm building an app and since i'm using combobox multiple times i decided to create a reusable component as follow ( also is it necessary ? just curious )

```<code>import { useState, Fragment } from 'react'
import { Combobox } from '@headlessui/react'

function AppCombobox ({ data, selectedPerson, setSelectedPerson, value, displayValue}) {

return (
   <>
    <Combobox value={selectedPerson} onChange={setSelectedPerson}>
      <Combobox.Input
        as={Fragment}
        onChange={(event) => setQuery(event.target.value)}
        displayValue={(person) => person.name}
      >
        <input />
      </Combobox.Input>
      <Combobox.Options>
        {data.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {({ active, selected }) => (
            <>
                <span className={cn('block truncate', selected && 'font-semibold')}>{person.name}</span>
                {selected && (
                    <span className={cn('absolute inset-y-0 right-0 flex items-center pr-4', active ? 'text-white' : 'text-indigo-600')}>
                    <CheckIcon className="h-5 w-5" aria-hidden="true"/>
                 </span>
                )}
            </>
        )}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
   </>
);
</code>```

Parent Element

```<code>export default function Parent () {

   const [selectedPerson, setSelectedPerson] = useState(null)

   const people = [
      { id: 1, name: 'Durward Reynolds' },
      { id: 2, name: 'Kenton Towne' },
      { id: 3, name: 'Therese Wunsch' },
      { id: 4, name: 'Benedict Kessler'},
      { id: 5, name: 'Katelyn Rohan' },
   ]

    return (
       <AppCombobox value={selectedPerson} setSelectedPerson={setSelectedPerson} data={people}/>
    )

}
</code>```

The problem i'm facing is that When i have the state in the child element ( AppCombobox ) and i select an element, the selected element ui changes and has a checkbox next to it(see attached picture). but when i move the state to the parent element, The combobox checkIcon of the selected element doesn't get rendered. can you please help me out i've spend 2 hours trying to fix this bug

Body:
So i'm building an app and since i'm using combobox multiple times i decided to create a reusable component as follow ( also is it necessary ? just curious )

import { useState, Fragment } from 'react'
import { Combobox } from '@headlessui/react'

function AppCombobox ({ data, selectedPerson, setSelectedPerson, value, displayValue}) {

return (
   <>
    <Combobox value={selectedPerson} onChange={setSelectedPerson}>
      <Combobox.Input
        as={Fragment}
        onChange={(event) => setQuery(event.target.value)}
        displayValue={(person) => person.name}
      >
        <input />
      </Combobox.Input>
      <Combobox.Options>
        {data.map((person) => (
          <Combobox.Option key={person.id} value={person}>
            {({ active, selected }) => (
            <>
                {person.name}
                {selected && (

                    <CheckIcon className="h-5 w-5" aria-hidden="true"/>

                )}
            </>
        )}
          </Combobox.Option>
        ))}
      </Combobox.Options>
    </Combobox>
   </>
);

Parent Element

export default function Parent () {

   const [selectedPerson, setSelectedPerson] = useState(null)

   const people = [
      { id: 1, name: 'Durward Reynolds' },
      { id: 2, name: 'Kenton Towne' },
      { id: 3, name: 'Therese Wunsch' },
      { id: 4, name: 'Benedict Kessler'},
      { id: 5, name: 'Katelyn Rohan' },
   ]

    return (
       <AppCombobox value={selectedPerson} setSelectedPerson={setSelectedPerson} data={people}/>
    )

}

The problem i'm facing is that When i have the state in the child element ( AppCombobox ) and i select an element, the selected element ui changes and has a checkbox next to it(see attached picture). but when i move the state to the parent element, The combobox checkIcon of the selected element doesn't get rendered. can you please help me out i've spend 2 hours trying to fix this bug


问:
Digital Ocean SSH Returns 'shell request failed on channel 0'
I have been running a few continuous Python script fetching data from APIs and loading in MySQL, for last few days I notice that when I try to ssh it gives the error:

Digital Ocean SSH Returns 'shell request failed on channel 0'

I googled and the only solution I found was to restart the droplet which is horrible especially if running production code. I even was not able to view the console via the web interface of the digital ocean. My Droplet is in Singapore.

Let me add further that the server remains up, the apache is responding and I can view web pages I had created. Only SSH and SFTP stop working.

Can anyone help me?


问:
Datatable is not loading properly in Angular mat-tab
I am new to Angular, I have used Angular mat-tab-group for changing the table among tabs. But when I change the tabs the data and design of jQuery loads only on first tab, and when I change tab the only the table shows without any styles. What can I do?

Here is the HTML markup:

```<code><mat-tab-group>
    <mat-tab label="All Appointment">
        <ng-template matTabContent>
            <app-allappointment></app-allappointment>
        </ng-template>
    </mat-tab>

    <mat-tab label="Pending Appointment">
        <ng-template matTabContent>
        <app-pendingappointment></app-pendingappointment>
    </ng-template>
    </mat-tab>

    <mat-tab label="On Doctor's Review ">
        <ng-template matTabContent>
            <app-onreviewappointment></app-onreviewappointment>
        </ng-template>
    </mat-tab>

    <mat-tab label="Confimed Appointments">
        <ng-template matTabContent>
            <app-confirmedappointment></app-confirmedappointment>
        </ng-template>
    </mat-tab>
</mat-tab-group>
</code>```

Here is the problem

Body:
I am new to Angular, I have used Angular mat-tab-group for changing the table among tabs. But when I change the tabs the data and design of jQuery loads only on first tab, and when I change tab the only the table shows without any styles. What can I do?

Here is the HTML markup:

<mat-tab-group>
    <mat-tab label="All Appointment">
        <ng-template matTabContent>
            <app-allappointment></app-allappointment>
        </ng-template>
    </mat-tab>

    <mat-tab label="Pending Appointment">
        <ng-template matTabContent>
        <app-pendingappointment></app-pendingappointment>
    </ng-template>
    </mat-tab>

    <mat-tab label="On Doctor's Review ">
        <ng-template matTabContent>
            <app-onreviewappointment></app-onreviewappointment>
        </ng-template>
    </mat-tab>

    <mat-tab label="Confimed Appointments">
        <ng-template matTabContent>
            <app-confirmedappointment></app-confirmedappointment>
        </ng-template>
    </mat-tab>
</mat-tab-group>

Here is the problem


问:
How to download calendar events from external user in a non-interactive manner?
I created this method, which essentially does what I need:

```<code>    clientId := os.Getenv("CLIENT_ID")
    tenantId := "common"
    scopes := []string{"calendars.read", "calendars.readwrite"} // todo add offline_access
    credential, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
        ClientID: clientId,
        TenantID: tenantId,
        UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
            fmt.Println(message.Message)
            return nil
        },
    })
    if err != nil {
        log.Print(err)
        return
    }
    authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(credential, scopes)
    if err != nil {
        log.Print(err)
        return
    }
    adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
    if err != nil {
        log.Print(err)
        return
    }

    result, err := msgraphsdk.NewGraphServiceClient(adapter).Me().Calendar().Events().Get(context.Background(), nil)
    if err != nil {
        log.Print(err)
    }
    for _, event := range result.GetValue() {
        log.Print(*event.GetICalUId())
        log.Print(*event.GetSubject())
    }
</code>```

However, this one will print out https://microsoft.com/devicelogin and the code to authenticate interactively. I have the access token and refresh token from another resource. I would need to inject either access token or refresh token into something, to replace the logic that results in interactivity. I need that for a back-end service that handles calendar synchronization. What do I need to do? Do you have some pointers? I am using Golang and I am breaking my head for the last few days (nothing I tried worked). Please, help.

I went through all tutorials on Microsoft Graph for Go that I could find. I read tons of documentation. I suspect that publicClientApp, err := public.New("client_id", public.WithAuthority("https://login.microsoftonline.com/common")) and publicClientApp.AcquireTokenSilent(context.Background(), []string{"calendars.read", "calendars.readwrite"}, ...) could be the answer, but I cannot make it work. I have a working solution with curl, but I need to use Go SDK.

Body:
I created this method, which essentially does what I need:

    clientId := os.Getenv("CLIENT_ID")
    tenantId := "common"
    scopes := []string{"calendars.read", "calendars.readwrite"} // todo add offline_access
    credential, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
        ClientID: clientId,
        TenantID: tenantId,
        UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
            fmt.Println(message.Message)
            return nil
        },
    })
    if err != nil {
        log.Print(err)
        return
    }
    authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(credential, scopes)
    if err != nil {
        log.Print(err)
        return
    }
    adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
    if err != nil {
        log.Print(err)
        return
    }

    result, err := msgraphsdk.NewGraphServiceClient(adapter).Me().Calendar().Events().Get(context.Background(), nil)
    if err != nil {
        log.Print(err)
    }
    for _, event := range result.GetValue() {
        log.Print(*event.GetICalUId())
        log.Print(*event.GetSubject())
    }

However, this one will print out https://microsoft.com/devicelogin and the code to authenticate interactively. I have the access token and refresh token from another resource. I would need to inject either access token or refresh token into something, to replace the logic that results in interactivity. I need that for a back-end service that handles calendar synchronization. What do I need to do? Do you have some pointers? I am using Golang and I am breaking my head for the last few days (nothing I tried worked). Please, help.

I went through all tutorials on Microsoft Graph for Go that I could find. I read tons of documentation. I suspect that publicClientApp, err := public.New("client_id", public.WithAuthority("https://login.microsoftonline.com/common")) and publicClientApp.AcquireTokenSilent(context.Background(), []string{"calendars.read", "calendars.readwrite"}, ...) could be the answer, but I cannot make it work. I have a working solution with curl, but I need to use Go SDK.


问:
How to get total number of records to be synced in Flutter Amplify Datastore
Is there are good way to find out what the total number of records to be synced will be before the records are actually synced via the datastore? This is refering to at the start of time when I am going to sync the datastore with what's in the cloud (so the downstream sync). I'm wanting to create an actual progress indicator for the user (since it takes about a minute for ~1500 records to sync), and don't want to just put up a CircleProgressIndicator().

All I'm currently able to do is:

```<code>hubSubscription = Amplify.Hub.listen([HubChannel.DataStore], (msg) {
        if (msg.eventName == "ready") {
          getAllDevicesInDataStore().then((value) => stopListeningToHub());
        }
        if (kDebugMode) {
          if (msg.eventName == "modelSynced") {
            final syncedModelPayload = msg.payload as ModelSyncedEvent;
            print(
                'Model: ${syncedModelPayload.modelName}, Delta? ${syncedModelPayload.isDeltaSync}');
            print(
                '${syncedModelPayload.added}, ${syncedModelPayload.updated}, ${syncedModelPayload.deleted}');
          }
        }
      });
</code>```

I can implement a CircleProgressIndicator() while this is happening, but I want something more definitive.

Body:
Is there are good way to find out what the total number of records to be synced will be before the records are actually synced via the datastore? This is refering to at the start of time when I am going to sync the datastore with what's in the cloud (so the downstream sync). I'm wanting to create an actual progress indicator for the user (since it takes about a minute for ~1500 records to sync), and don't want to just put up a CircleProgressIndicator().

All I'm currently able to do is:

hubSubscription = Amplify.Hub.listen([HubChannel.DataStore], (msg) {
        if (msg.eventName == "ready") {
          getAllDevicesInDataStore().then((value) => stopListeningToHub());
        }
        if (kDebugMode) {
          if (msg.eventName == "modelSynced") {
            final syncedModelPayload = msg.payload as ModelSyncedEvent;
            print(
                'Model: ${syncedModelPayload.modelName}, Delta? ${syncedModelPayload.isDeltaSync}');
            print(
                '${syncedModelPayload.added}, ${syncedModelPayload.updated}, ${syncedModelPayload.deleted}');
          }
        }
      });

I can implement a CircleProgressIndicator() while this is happening, but I want something more definitive.


问:
Pandas unexpectedly casts type in heterogeneous dataframe
if I define a dataframe like this

```<code>import numpy as np
import pandas as pd
str1= ["woz", "baz", "fop", "jok"]
arr=np.array([2,3,4])
data = {"Goz":str1, "Jok": np.hstack((np.array([5,"fava"]), np.array ([1,2]) ) ) }
df = pd.DataFrame(data)

Goz Jok
0   woz 5
1   baz fava
2   fop 1
3   jok 2
</code>```

I am puzzled by the fact those nice floats in the second column, coming from a numpy array, are cast to string

```<code>type(df.loc[3]["Jok"])
out:: str
</code>```

Further, if I try to manually cast back to float64 for a subset of the dataframe, say

```<code>df.iloc[2:,1].astype("float64", copy=False)
</code>```

the type of the does not change. Besides I understand thecopy=False option, comes with extreme danger.

If on the other hand I define the dataframe using this

```<code>
data = {"Goz":str1, "Jok": np.array ([1,2,3,4])  }

</code>```

having hence the whole column to contain float64 uniformly, all seems to work.
Can somebody please clarify what is going on here?  How to handle type-heterogenous columns? Thanks a lot

Body:
if I define a dataframe like this

import numpy as np
import pandas as pd
str1= ["woz", "baz", "fop", "jok"]
arr=np.array([2,3,4])
data = {"Goz":str1, "Jok": np.hstack((np.array([5,"fava"]), np.array ([1,2]) ) ) }
df = pd.DataFrame(data)

Goz Jok
0   woz 5
1   baz fava
2   fop 1
3   jok 2

I am puzzled by the fact those nice floats in the second column, coming from a numpy array, are cast to string

type(df.loc[3]["Jok"])
out:: str

Further, if I try to manually cast back to float64 for a subset of the dataframe, say

df.iloc[2:,1].astype("float64", copy=False)

the type of the does not change. Besides I understand thecopy=False option, comes with extreme danger.

If on the other hand I define the dataframe using this

data = {"Goz":str1, "Jok": np.array ([1,2,3,4])  }

having hence the whole column to contain float64 uniformly, all seems to work.
Can somebody please clarify what is going on here?  How to handle type-heterogenous columns? Thanks a lot


问:
NextJS, Redux-tk Chrome Devtools Showing Incorrect Values on Breakpoint
Thanks for your attention.

i've set up a new application (next, react, redux-tk, gulp), and everything is working swimmingly in both local and hosted on the server. but i just cant seem to get the devtools working correctly. when i pause the debugger, values are all over the place and incorrect under the Sources tab -> hover over var/under Scope section. i think the sourcemaps are configured alright but im also not sure. here's the set-up which i've learned are supposed to connect things properly:

I have the redux-devtools-extension installed (is even necessary w/ rtk?)

Using the new rtk configureStore in store.js, which should enable devtools automatically from what i understand, but i've got a prod condition there:

```<code>
    export const store = configureStore({
        reducer: {
            // reducers removed for brevity
        },
        devTools: process.env.NODE_ENV !== 'prod'
    });

</code>```

my next.config.js has productionBrowserSourceMaps set to true:

```<code>
    module.exports = {
        env: {
            environment: env
        },
        productionBrowserSourceMaps: true,
        basePath: basePath
    };

</code>```

Chrome Devtools' sourcemaps setting is set to true.

My gulpfile.js has no related source maps/compiling config, just using it for sass processing.

Am i missing something? Babel perhaps? Not much experience there.

here's an example. when i pause here, selectedShip is definitely a ship object as i see it in the console and how it operates in the app (with name, shipCode, etc.), but in devtools its showing as the router object. not to mention there's two pcl-global-headers elements apparently being tracked. when there definitely isnt. this makes debugging basically impossible using sources lol. any ideas? am i missing something silly and small? please tell me im missing something silly and small

thanks again! hope you're having a great day!

Body:
Thanks for your attention.

i've set up a new application (next, react, redux-tk, gulp), and everything is working swimmingly in both local and hosted on the server. but i just cant seem to get the devtools working correctly. when i pause the debugger, values are all over the place and incorrect under the Sources tab -> hover over var/under Scope section. i think the sourcemaps are configured alright but im also not sure. here's the set-up which i've learned are supposed to connect things properly:

I have the redux-devtools-extension installed (is even necessary w/ rtk?)

Using the new rtk configureStore in store.js, which should enable devtools automatically from what i understand, but i've got a prod condition there:

    export const store = configureStore({
        reducer: {
            // reducers removed for brevity
        },
        devTools: process.env.NODE_ENV !== 'prod'
    });

my next.config.js has productionBrowserSourceMaps set to true:

    module.exports = {
        env: {
            environment: env
        },
        productionBrowserSourceMaps: true,
        basePath: basePath
    };

Chrome Devtools' sourcemaps setting is set to true.

My gulpfile.js has no related source maps/compiling config, just using it for sass processing.

Am i missing something? Babel perhaps? Not much experience there.

here's an example. when i pause here, selectedShip is definitely a ship object as i see it in the console and how it operates in the app (with name, shipCode, etc.), but in devtools its showing as the router object. not to mention there's two pcl-global-headers elements apparently being tracked. when there definitely isnt. this makes debugging basically impossible using sources lol. any ideas? am i missing something silly and small? please tell me im missing something silly and small

thanks again! hope you're having a great day!


问:
Why wont my Android app automatically run from Android Studio?
I am trying to run my app in debug mode on an Android device from Android Studio. I press the Debug 'app' button and it goes through the build process and then it says "Launch succeeded" in a bubble above the Debug tab, but the app doesn't start running. If I press the Debug button again though it does start and it says "App restart successful without requiring a re-install" in a bubble above the Run tab. Why won't it start the first time? I have "Launch" set to "Default Activity" under the Launch Options. Is there anything else I need to do? Thanks!</p>


问:
Is there an alternative to container queries to make an element change based on the proportions of its container, using plain CSS?
I need to be able to change the image within a header depending of the proportion of the available space, either to a landscape or portrait version of the logo, without container queries, or considering a progressive enhancement:

Use logo-horizontal.svg when the  container has a landscape proportion.

Use logo-vertical.svg when the  container has a portrait proportion.

There is not an object-fit answer for this question, it is a logo with two different versions.

Given a CSS grid and its following positions, like so:

 ------------------------
|    1fr - header        |
 ------------------------
|    6em - content       |
 ------------------------
|   48px - CallToAction  |
 ------------------------
```
<p>and the HTML</p>
<pre class="lang-html prettyprint-override"><code><header><img src="images/logo-horizontal.svg" /></header>

<div class="content"><p>Some text</p></div>

<div class="callToAction">Start here</div>
</code>```

Body:
I need to be able to change the image within a header depending of the proportion of the available space, either to a landscape or portrait version of the logo, without container queries, or considering a progressive enhancement:

Use logo-horizontal.svg when the  container has a landscape proportion.

Use logo-vertical.svg when the  container has a portrait proportion.

There is not an object-fit answer for this question, it is a logo with two different versions.

Given a CSS grid and its following positions, like so:

 ------------------------
|    1fr - header        |
 ------------------------
|    6em - content       |
 ------------------------
|   48px - CallToAction  |
 ------------------------

and the HTML

Some text

Start here


问:
Namespaced kubernetes operator for multiple namespaces
I am thinking about using cluster vs namespaced scope k8s operators.

In theory i have a lot of namespaces and i can deploy some kubernetes operator KO for each namespace. I suppose that in this case in each namespace KO subscribed for events in kubernets cluster for each namespace. Сould this be a performance problem for the cluster? Maybe for big number of namespaces is better idea to use cluster scope operator ? (It manage many instances for many namespaces but have only one subscription)


问:
Selection in Sectioned List in SwiftUI
If I have a list with multiple sections of heterogenous type (say like a sidebar in a macOS app), how do I keep track of the $selection? Here's a simplified example :

```<code>struct A: Hashable {
    let propA: Int
}

struct B: Hashable {
    let propB: Int
}

struct ContentView: View {
    let allAs = (1...10).map{A(propA: $0)}
    let allBs = (1...5).map{B(propB: $0)}
    @Binding var selectedA: A?
    @Binding var selectedB: B?

    var body: some View {
        List() {                                // What goes in selected: ?
            Section() {
                ForEach(allAs, id: \.propA) {
                    Text(String($0.propA))
                }
            } header: {
                Text("A Section")
            }

            Section() {
                ForEach(allBs, id: \.propB) {
                    Text(String($0.propB))
                }
            } header: {
                Text("B Section")
            }
        }
    }
}
</code>```

Is the only way around this to create a generic type or protocol to hold A and B?

Title: Selection in Sectioned List in SwiftUI

Body:
If I have a list with multiple sections of heterogenous type (say like a sidebar in a macOS app), how do I keep track of the $selection? Here's a simplified example :

struct A: Hashable {
    let propA: Int
}

struct B: Hashable {
    let propB: Int
}

struct ContentView: View {
    let allAs = (1...10).map{A(propA: $0)}
    let allBs = (1...5).map{B(propB: $0)}
    @Binding var selectedA: A?
    @Binding var selectedB: B?

    var body: some View {
        List() {                                // What goes in selected: ?
            Section() {
                ForEach(allAs, id: \.propA) {
                    Text(String($0.propA))
                }
            } header: {
                Text("A Section")
            }

            Section() {
                ForEach(allBs, id: \.propB) {
                    Text(String($0.propB))
                }
            } header: {
                Text("B Section")
            }
        }
    }
}

Is the only way around this to create a generic type or protocol to hold A and B?


问:
Is there a way to use an MS Access multiselect listbox control to filter records WITHOUT using VBA or iterating through the selected values?
I think the question speaks for itself, but I'll use a trivial example. Consider a table of salespeople as shown below:

Now consider a simple search/filter form with a list box where the user selects a region and it lists the salespeople in that region:

This is trivial. Assuming the list box is named lstRegionFilter, the query used to build the subform is simply:

```<code>select
    [tblSalespeople].[SalespersonName] as [Salesperson Name],
    [tblSalespeople].[Region] as [Region]
from
    tblSalespeople
where
    [tblSalespeople].[Region] = [forms]![frmSearchForm]![listRegionFilter];
</code>```

Now consider the list box is changed to a multiselection list box, so that the user can select multiple regions with the filter working accordingly, as follows:

While this can be done, every solution I've found involves a VBA procedure that iterates over the list box's selected items, constructs a comma-separated string, and feeds this string to the result query. This strikes me as being more work than ought to be necessary, and I figure I'm missing a simpler "built-in" solution, that ought to look something like this:

```<code>... where [tblSalespeople].[Region] in ([forms]![frmSearchForm]![listRegionFilter]);
</code>```

or perhaps

```<code>... where [tblSalespeople].[Region] in (select * from [forms]![frmSearchForm]![listRegionFilter]);
</code>```

The reason I figure there must be a simpler solution is because using a multi-selection list box to filter records would seem to be the most obvious purpose for the very existence of the multi-selection list box control in the first place. As such, it intuitively seems that there would need to be a built-in way of extracting the list box's selected values directly as a record-set-style object that would be natively understood by an Access query.

So, to make a long story short, my question is this:

Is there a simple built-in way to do this without writing code to iterate over the list box's selected items?

Body:
I think the question speaks for itself, but I'll use a trivial example. Consider a table of salespeople as shown below:

Now consider a simple search/filter form with a list box where the user selects a region and it lists the salespeople in that region:

This is trivial. Assuming the list box is named lstRegionFilter, the query used to build the subform is simply:

select
    [tblSalespeople].[SalespersonName] as [Salesperson Name],
    [tblSalespeople].[Region] as [Region]
from
    tblSalespeople
where
    [tblSalespeople].[Region] = [forms]![frmSearchForm]![listRegionFilter];

Now consider the list box is changed to a multiselection list box, so that the user can select multiple regions with the filter working accordingly, as follows:

While this can be done, every solution I've found involves a VBA procedure that iterates over the list box's selected items, constructs a comma-separated string, and feeds this string to the result query. This strikes me as being more work than ought to be necessary, and I figure I'm missing a simpler "built-in" solution, that ought to look something like this:

... where [tblSalespeople].[Region] in ([forms]![frmSearchForm]![listRegionFilter]);

or perhaps

... where [tblSalespeople].[Region] in (select * from [forms]![frmSearchForm]![listRegionFilter]);

The reason I figure there must be a simpler solution is because using a multi-selection list box to filter records would seem to be the most obvious purpose for the very existence of the multi-selection list box control in the first place. As such, it intuitively seems that there would need to be a built-in way of extracting the list box's selected values directly as a record-set-style object that would be natively understood by an Access query.

So, to make a long story short, my question is this:

Is there a simple built-in way to do this without writing code to iterate over the list box's selected items?


问:
How can I detect when the Flyout for a given DatePicker opens in WinUI 3?
I have a DatePicker on a Page and would like to know whenever the DatePickerFlyout associated with the DatePicker is opened. This would be straightforward if I had a reference to the relevant DatePickerFlyout (DatePickerFlyout has Opened and Opening events) , but I can't seem to find one.

Flyouts (Popups) appear in the Visual Tree under PopupRoot so I thought I might listen for changes in the PopupRoot branch. But walking up the tree stops at the RootScrollViewer, one level below PopupRoot, so I can't reference that branch.

VisualTreeHelper.GetOpenPopupsForXamlRoot() returns a list of open Popups (which includes Flyouts) but only if the Flyout in question is actually open.

Any idea how I can find and work with the actual DatePickerFlyout object?

Thank you in advance.


问:
PivotTable summing providing wrong values [Excel]
I have these columns in sheet1:

```<code>Value    Weights
-----------------
   XX         XX
   XX         XX
   XX         XX
   XX         XX
   XX         XX
...
</code>```

I then multiply the "Value" column by the "Weights" column to get a "Weighted_Values" column:

```<code>Value    Weights    Weighted_Values
------------------------------------
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
...
</code>```

I then sum the "Weighted_Values" column to get and record that summed value.

Now, what I am having trouble with, is repeating this process with a pivot table in Excel.

What I do is create my pivot table from the data in sheet1, and then proceed to create my "Weighted_Values" field via the "Insert Calculated Field" box, and then multiply the columns "Value" * "Weight" to create the new field "Weighted_Values". I then drag this newly created "Weighted_Values" field down to the "Values" box of the "PivotTable Fields" menu as "Sum of Weighted_Values". I see that "Values" is automatically populated in the "Rows" box, with the "Filters" and "Columns" boxes left empty. I then create my PivotTable, but see that the value for "Sum of Weighted_Values" is far larger than the summed value I reached in sheet1. Am I perhaps approaching my PivotTable workflow incorrectly? I was expecting the pivot table to show the exact same summed value I reached by just summing my "Weighted_Values" column in sheet1. Can someone please help me understand where I might have gone wrong in setting up my PivotTable? Thank you!

Here is an example of the mismatched summed values:

Sheet1:

PivotTable:

As you can see, the sums are way off. Where might I be going wrong with my pivot table?

Body:
I have these columns in sheet1:

Value    Weights
-----------------
   XX         XX
   XX         XX
   XX         XX
   XX         XX
   XX         XX
...

I then multiply the "Value" column by the "Weights" column to get a "Weighted_Values" column:

Value    Weights    Weighted_Values
------------------------------------
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
   XX         XX                 XX
...

I then sum the "Weighted_Values" column to get and record that summed value.

Now, what I am having trouble with, is repeating this process with a pivot table in Excel.

What I do is create my pivot table from the data in sheet1, and then proceed to create my "Weighted_Values" field via the "Insert Calculated Field" box, and then multiply the columns "Value" * "Weight" to create the new field "Weighted_Values". I then drag this newly created "Weighted_Values" field down to the "Values" box of the "PivotTable Fields" menu as "Sum of Weighted_Values". I see that "Values" is automatically populated in the "Rows" box, with the "Filters" and "Columns" boxes left empty. I then create my PivotTable, but see that the value for "Sum of Weighted_Values" is far larger than the summed value I reached in sheet1. Am I perhaps approaching my PivotTable workflow incorrectly? I was expecting the pivot table to show the exact same summed value I reached by just summing my "Weighted_Values" column in sheet1. Can someone please help me understand where I might have gone wrong in setting up my PivotTable? Thank you!

Here is an example of the mismatched summed values:

Sheet1:

PivotTable:

As you can see, the sums are way off. Where might I be going wrong with my pivot table?


问:
Intellij Run test using with Gradle success but Intellij IDEA test fail
I am using IntelliJ.

When i build and run with gradle, my all tests are success.

But if i change with IntelliJ IDEA, one test is fail.

The reason why one test fail, no constructor is not exist in response dto.

```<code>public class PathResponse {
    private List<StationResponse> stations;
    private int distance;

    public PathResponse(List<StationResponse> stations, int distance) {
        this.stations = stations;
        this.distance = distance;
    }

    protected PathResponse() {} // <- if put this, no error with InterlliJ IDEA also.
</code>```

Yes. i success the test with IntelliJ IDEA.

But i wonder why Gradle and IntelliJ IDEA test result is different.

Can someone tell me reason..???

Body:
I am using IntelliJ.

When i build and run with gradle, my all tests are success.

But if i change with IntelliJ IDEA, one test is fail.

The reason why one test fail, no constructor is not exist in response dto.

public class PathResponse {
    private List<StationResponse> stations;
    private int distance;

    public PathResponse(List<StationResponse> stations, int distance) {
        this.stations = stations;
        this.distance = distance;
    }

    protected PathResponse() {} // <- if put this, no error with InterlliJ IDEA also.

Yes. i success the test with IntelliJ IDEA.

But i wonder why Gradle and IntelliJ IDEA test result is different.

Can someone tell me reason..???


问:
How do I cast mongodb's _ids from string to ObjectId?
On the frontend I compile a collection of bookmark ids to be deleted as seen in the following function:

```<code>public deleteBookmarks = (siteId) => {
    const siteForBookmarkDelete = this.category?.sites.find(s1 => s1.site._id === siteId)

    const bookmarksForDelete = siteForBookmarkDelete.site.bookmarks
      .filter(bookmark => bookmark.checked === true)

    const bookmarkIds = [];

    for(let bm of bookmarksForDelete) {
      bookmarkIds.push(bm._id)
    }

    this.categoriesService.deleteBookmark(this.category?._id, siteId, bookmarkIds )

 }
</code>```

On the backend, I tried to delete the bookmarks with the condition:

```<code>...
{
       $pull: {
           bookmarks: {
               _id: {$in: bookmarkIds}
           }
       }
   })
</code>```

I get the error:

CastError: Cast to ObjectId failed for value "63bd8916abbd6f490b568121,63bd8918abbd6f490b56812a" (type string) at path "_id" because of "BSONTypeError"

at model.Query.exec

I interpret this to mean even though I put actual ObjectIds on the array, they were converted to strings so I modified my backend code to convert each _id on the array to ObjectId.

```<code>const mongoose = require('mongoose')
const { ObjectId} = mongoose.Schema.Types;

  exports.deleteBookmarks = async (req, res) => {
   const {categoryId, siteId, bookmarkIds} = req.params;

   const objectIds = [ObjectId];

   for(let bmId of bookmarkIds) {
      objectIds.push(ObjectId(bmId))
   }

   try {
       const site = await Sites.findOneAndUpdate({
          _id: siteId,
          categoryId
      },
   {
       $pull: {
           bookmarks: {
               _id: {$in: objectIds}
           }
       }
   })

    getAllCategories(req, res);
  } catch(error) {
      console.error(error);
      return res.status(500).send('Error adding bookmark.')
  }

  }
</code>```

Then I get this error:

\node_modules\mongoose\lib\schematype.js:43

this[schemaTypeSymbol] = true;
^

TypeError: Cannot set properties of undefined (setting 'Symbol(mongoose#schemaType)')

at SchemaType

I am thinking this ObjectId may be the wrong one to use but the documentation doesn't show what package it is getting its ObjectId from.

```<code>const { ObjectId} = mongoose.Schema.Types;
</code>```

Body:
On the frontend I compile a collection of bookmark ids to be deleted as seen in the following function:

public deleteBookmarks = (siteId) => {
    const siteForBookmarkDelete = this.category?.sites.find(s1 => s1.site._id === siteId)

    const bookmarksForDelete = siteForBookmarkDelete.site.bookmarks
      .filter(bookmark => bookmark.checked === true)

    const bookmarkIds = [];

    for(let bm of bookmarksForDelete) {
      bookmarkIds.push(bm._id)
    }

    this.categoriesService.deleteBookmark(this.category?._id, siteId, bookmarkIds )

 }

On the backend, I tried to delete the bookmarks with the condition:

...
{
       $pull: {
           bookmarks: {
               _id: {$in: bookmarkIds}
           }
       }
   })

I get the error:

CastError: Cast to ObjectId failed for value "63bd8916abbd6f490b568121,63bd8918abbd6f490b56812a" (type string) at path "_id" because of "BSONTypeError"

at model.Query.exec

I interpret this to mean even though I put actual ObjectIds on the array, they were converted to strings so I modified my backend code to convert each _id on the array to ObjectId.

const mongoose = require('mongoose')
const { ObjectId} = mongoose.Schema.Types;

  exports.deleteBookmarks = async (req, res) => {
   const {categoryId, siteId, bookmarkIds} = req.params;

   const objectIds = [ObjectId];

   for(let bmId of bookmarkIds) {
      objectIds.push(ObjectId(bmId))
   }

   try {
       const site = await Sites.findOneAndUpdate({
          _id: siteId,
          categoryId
      },
   {
       $pull: {
           bookmarks: {
               _id: {$in: objectIds}
           }
       }
   })

    getAllCategories(req, res);
  } catch(error) {
      console.error(error);
      return res.status(500).send('Error adding bookmark.')
  }

  }

Then I get this error:

\node_modules\mongoose\lib\schematype.js:43

this[schemaTypeSymbol] = true;
^

TypeError: Cannot set properties of undefined (setting 'Symbol(mongoose#schemaType)')

at SchemaType

I am thinking this ObjectId may be the wrong one to use but the documentation doesn't show what package it is getting its ObjectId from.

const { ObjectId} = mongoose.Schema.Types;


问:
Want to validate the width and height of each image in an multi-dimensional array
Hello I want to validate the width and height of each image that I upload as an array. Here is my code:

```<code>$photo_temp = array();
$photo_temp = $_FILES['photo']["tmp_name"];
$photo_temp = array_values(array_filter($photo_temp));
$other_temp = $_FILES['photo']["tmp_name"];

for($i=0;$i<count($photo);$i++)
{
 foreach ($other_temp as $single_file) {
 if(!empty($single_file)) {
 $photo_temp[$single_file] = getimagesize($single_file);
 $width2 = $photo_temp[$single_file][0];
 $height2 = $photo_temp[$single_file][1];
 }
}
print_r($photo_temp);
$my_ext1 = pathinfo( $photo[$i], PATHINFO_EXTENSION );
if( $my_ext1=='jpg' || $my_ext1=='png' || $my_ext1=='jpeg' || $my_ext1=='gif' ) {
$final_name1[$m] = $z.'.'.$my_ext1;
                    move_uploaded_file($photo_temp[$i],"../assets/uploads/product_photos/".$final_name1[$m]);
$m++;
$z++;
}else if ($width2 > "300" || $height2 > "200") {
$valid = 0;
$error_message .= 'Image dimension should be within 300X200<br>';
 }
}
</code>```

Here is the UI of how I'm aiming to do:
enter image description here

I want the error message to be sent if the image dimension is above 300 x 200 but the image kept on saving in the database even tho I had checked the error.

Body:
Hello I want to validate the width and height of each image that I upload as an array. Here is my code:

$photo_temp = array();
$photo_temp = $_FILES['photo']["tmp_name"];
$photo_temp = array_values(array_filter($photo_temp));
$other_temp = $_FILES['photo']["tmp_name"];

for($i=0;$i<count($photo);$i++)
{
 foreach ($other_temp as $single_file) {
 if(!empty($single_file)) {
 $photo_temp[$single_file] = getimagesize($single_file);
 $width2 = $photo_temp[$single_file][0];
 $height2 = $photo_temp[$single_file][1];
 }
}
print_r($photo_temp);
$my_ext1 = pathinfo( $photo[$i], PATHINFO_EXTENSION );
if( $my_ext1=='jpg' || $my_ext1=='png' || $my_ext1=='jpeg' || $my_ext1=='gif' ) {
$final_name1[$m] = $z.'.'.$my_ext1;
                    move_uploaded_file($photo_temp[$i],"../assets/uploads/product_photos/".$final_name1[$m]);
$m++;
$z++;
}else if ($width2 > "300" || $height2 > "200") {
$valid = 0;
$error_message .= 'Image dimension should be within 300X200
';
 }
}

Here is the UI of how I'm aiming to do:
enter image description here

I want the error message to be sent if the image dimension is above 300 x 200 but the image kept on saving in the database even tho I had checked the error.


问:
Is this a wrong way of finding the leap years?
I am a beginner, learning Python from "Python Programming MOOC 2022". They are asking me to write a code which asks for a year and then says whether it is a leap year or not. The problem is that when I write the code, the website says its wrong, as it has an infinite loop.

```<code># Write your solution here
y=int(input("Please type in a year:"))
if y%4==0:
    if y%100==0 :
        if y%400==0:
            print("That year is a leap year.")
        else:
            print("That year is not a leap year.")
    else:
        print("That year is a leap year.")
else:
    print("That year is not a leap year.")

</code>```

I cant really understand where the infinite loop is.
I'll be really thankful if you tell me what's wrong with this code so that I can fix it.

I ran this code on some online ides and it worked without any problem. I cant understand whether I am wrong or the website is facing some issues...

Body:
I am a beginner, learning Python from "Python Programming MOOC 2022". They are asking me to write a code which asks for a year and then says whether it is a leap year or not. The problem is that when I write the code, the website says its wrong, as it has an infinite loop.

# Write your solution here
y=int(input("Please type in a year:"))
if y%4==0:
    if y%100==0 :
        if y%400==0:
            print("That year is a leap year.")
        else:
            print("That year is not a leap year.")
    else:
        print("That year is a leap year.")
else:
    print("That year is not a leap year.")

I cant really understand where the infinite loop is.
I'll be really thankful if you tell me what's wrong with this code so that I can fix it.

I ran this code on some online ides and it worked without any problem. I cant understand whether I am wrong or the website is facing some issues...


问:
'QuerySet' object is not callable
I have this function that must get the class code, and then look for this class in the database, then fill in the participant field of this class with the user who is authenticated.

`def participar(request):
cc = nameUser(request)

```<code>if request.method == 'POST':
    busca = request.POST.get('busca')
    turma = Turma.objects.filter(codigo=busca)

    obj = turma(participantes=request.user)
    obj.save()

else:
    return render(request, 'turmas/participar.html', cc)

return render(request, 'turmas/participar.html', cc)`
</code>```

but when trying to add the following error occurs on the line turma(participantes=request.user)

'QuerySet' object is not callable

what was expected is that after searching for the desired class by its code, the authenticated user would be added to the participant field of that class

Title: 'QuerySet' object is not callable

Body:
I have this function that must get the class code, and then look for this class in the database, then fill in the participant field of this class with the user who is authenticated.

`def participar(request):
cc = nameUser(request)

if request.method == 'POST':
    busca = request.POST.get('busca')
    turma = Turma.objects.filter(codigo=busca)

    obj = turma(participantes=request.user)
    obj.save()

else:
    return render(request, 'turmas/participar.html', cc)

return render(request, 'turmas/participar.html', cc)`

but when trying to add the following error occurs on the line turma(participantes=request.user)

'QuerySet' object is not callable

what was expected is that after searching for the desired class by its code, the authenticated user would be added to the participant field of that class


问:
Validate the sum of three input fields in HTML
I am trying to to validate the sum of three input fields in HTML to be exactly 100. The Code I found on Stackoverflow for two input fields works only for two fields and not for my modification for three (below is my attempt of the modified code). The original code can be found at Validate sum of two input fields

I am most grateful for any help or advice! Here is my code

```<code><html>
<head>
<script>       src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
    <input type="text" class="input" id="value1">
    <input type="text" class="input" id="value2">
    <input type="text" class="input" id="value3">
    <button type="submit" name="submit" id="submit">check sum</button>
    <p id="resultMessage"></p>

    <script>
    $(document).ready(function() {
        // on button pressed
        $('#submit').on('click', function() {
            var val1 = $("#value1").val();
            var val2 = $("#value2").val();
            var val3 = $("#value3").val();

            // numeric validation
            if (!isNumeric(val1) || !isNumeric(val2) || !isNumeric(val3)) {
                $('#resultMessage').text('Some field does not contain a number');
                return;
            }

            // + operator converts input Strings to Number type
            var sum = +val1 + +val2 + +val3;

            if (sum > 100) {
                // if sum greather than 100
                $('#resultMessage').text('Sum is greather than 100 (' + sum + ')');
            } else if (sum < 100) {
                // some code if sum less than 100 ...
                $('#resultMessage').text('Sum is less than 100 (' + sum + ')');
            } else {
                // sum is 100
                $('#resultMessage').text('Sum equals 100');
            }
        });

        // function for numeric validation
        function isNumeric(n) {
            return !isNaN(parseFloat(n)) && isFinite(n);
        }
    });
    </script>
    </body>
    </html>
</code>```

My problem is that the modification does not work and I don't see why..

EDIT Per the comments, I have removed the extra parenthesis around !isNumeric(val2).
The problem still persists though. I see the three text boxes and a check sum button. However, whenever I enter any numbers and hit "check sum", nothing happens, no computation of any sum and no display of any sum.

I would be very grateful for any additional comments.

Body:
I am trying to to validate the sum of three input fields in HTML to be exactly 100. The Code I found on Stackoverflow for two input fields works only for two fields and not for my modification for three (below is my attempt of the modified code). The original code can be found at Validate sum of two input fields

I am most grateful for any help or advice! Here is my code

    <input type="text" class="input" id="value1">
    <input type="text" class="input" id="value2">
    <input type="text" class="input" id="value3">
    <button type="submit" name="submit" id="submit">check sum</button>

My problem is that the modification does not work and I don't see why..

EDIT Per the comments, I have removed the extra parenthesis around !isNumeric(val2).
The problem still persists though. I see the three text boxes and a check sum button. However, whenever I enter any numbers and hit "check sum", nothing happens, no computation of any sum and no display of any sum.

I would be very grateful for any additional comments.


问:
How can I filter two years ago from current date in PostgreSQL
I want to take records from database which "creationDate" is no older than 2 years and 2 months back from now(UTC).

How can I filter by date keeping in mind that the value in "creationDate" is integer?

Thanks


问:
Pick an object with a 6 DOF robot and a RGBD camera
I have a 6 DOF robotic arm (Nyrio NED 2). On the end effector, I have stuck a RGB-D camera (Luxonis DepthAI OAK-D) on the end effector.
What I want to do is to pick and drop a detected object.

So far, I've been able to:

Make the robot looks at the board

Capture the video and run a YOLO detection of the objects I'd like to pick

Get the spatial coordinates (X, Y, Z) of the object with the camera

The camera is upside down but I've managed to rotate the image and detections (see here). Z is forward and refers to the depth in meters. X is to the right.

The robot coordinates are in a different system: X is from left to right, Y is from back to front and Z is from bottom to top.

How can I convert the camera coordinates into the robot system ?

Would something like that do the job ?

```<code>def convert_to_robot_coordinates(object_pos_3d):
    # Rotation matrix to rotate the coordinates from the camera frame to the robot frame
    rotation_matrix = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])

    # Translation vector to translate the coordinates from the camera frame to the robot frame
    translation_vector = np.array([0.002, -0.045, -0.05])

    # Transform the coordinates using the rotation matrix
    object_pos_robot = np.matmul(rotation_matrix, object_pos_3d + translation_vector)

    return object_pos_robot
</code>```

The axis should be something like that:

Camera Coordinates system
Robot arm CS

X
Y

Y
Z

Z
X

Do you think this is correct ?

I've added a translation_vector as the camera is stuck to the end effector but a 4.5cm above and 5cm before the edge.

If yes, does that mean that if I do something like that, the robot should move and pick the object ?

```<code># Read detected position of the object from RGB-D camera
relative_pos = np.array([detection.spatialCoordinates.x, detection.spatialCoordinates.y, detection.spatialCoordinates.z])

# Convert to robot coordinates system
world_pos = convert_to_robot_coordinates(relative_pos)

# Shift position
x, y, z, roll, pitch, yaw = robot.arm.get_pose().to_list()
x += world_pos[0]
y += world_pos[1]
z += world_pos[2]

# Reach the coordinates and pick the object
robot.pick_place.pick_from_pose([x, y, z, roll, pitch, yaw])
</code>```

Body:
I have a 6 DOF robotic arm (Nyrio NED 2). On the end effector, I have stuck a RGB-D camera (Luxonis DepthAI OAK-D) on the end effector.
What I want to do is to pick and drop a detected object.

So far, I've been able to:

Make the robot looks at the board

Capture the video and run a YOLO detection of the objects I'd like to pick

Get the spatial coordinates (X, Y, Z) of the object with the camera

The camera is upside down but I've managed to rotate the image and detections (see here). Z is forward and refers to the depth in meters. X is to the right.

The robot coordinates are in a different system: X is from left to right, Y is from back to front and Z is from bottom to top.

How can I convert the camera coordinates into the robot system ?

Would something like that do the job ?

def convert_to_robot_coordinates(object_pos_3d):
    # Rotation matrix to rotate the coordinates from the camera frame to the robot frame
    rotation_matrix = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])

    # Translation vector to translate the coordinates from the camera frame to the robot frame
    translation_vector = np.array([0.002, -0.045, -0.05])

    # Transform the coordinates using the rotation matrix
    object_pos_robot = np.matmul(rotation_matrix, object_pos_3d + translation_vector)

    return object_pos_robot

The axis should be something like that:

Camera Coordinates system
Robot arm CS

X
Y

Y
Z

Z
X

Do you think this is correct ?

I've added a translation_vector as the camera is stuck to the end effector but a 4.5cm above and 5cm before the edge.

If yes, does that mean that if I do something like that, the robot should move and pick the object ?

# Read detected position of the object from RGB-D camera
relative_pos = np.array([detection.spatialCoordinates.x, detection.spatialCoordinates.y, detection.spatialCoordinates.z])

# Convert to robot coordinates system
world_pos = convert_to_robot_coordinates(relative_pos)

# Shift position
x, y, z, roll, pitch, yaw = robot.arm.get_pose().to_list()
x += world_pos[0]
y += world_pos[1]
z += world_pos[2]

# Reach the coordinates and pick the object
robot.pick_place.pick_from_pose([x, y, z, roll, pitch, yaw])