问:
What goes in the Exception field of a Throw Activity
Can anyone tell me how to use the Exception field of the Throw Activity?

I need specific examples.  I'm throwing an exception as I need to capture it in the calling code and then run some clean up code.

Thanks for any help

Richard

In reply to Chuck

I tried the following and the workflow cancels but the execution doesn't enter the catches.
Any idea why?

```<code>public class AbortException : System.Exception
{
}

class manager
{
    ...

    try
    {
        workflowApp.Run();
    }
    catch (AbortException ea)
    {

    }
    catch (Exception ex)
    {

    }

    ...
}
</code>```

with an Exception Property of: New AbortException

答:
The easiest is to create a class that extends exception and pass any values you want, like:

```<code>public class MyError : Exception
{
   public MyError() : base(string.Empty) {}
   public MyError(Exception e) : base(e.Message) {}
   public int MyCustomValue { get; set; }
}
</code>```

Then using it like, (passing the value of 5 to the catch handler)

```<code>throw new MyError(){ MyCustomValue = 5 };
</code>```

Then in your catch

```<code>try{}
catch(MyError ex)
{
    Console.Write(ex.MyCustomValue.ToString());
}
</code>```

Body:
Can anyone tell me how to use the Exception field of the Throw Activity?

I need specific examples.  I'm throwing an exception as I need to capture it in the calling code and then run some clean up code.

Thanks for any help

Richard

In reply to Chuck

I tried the following and the workflow cancels but the execution doesn't enter the catches.
Any idea why?

public class AbortException : System.Exception
{
}

class manager
{
    ...

    try
    {
        workflowApp.Run();
    }
    catch (AbortException ea)
    {

    }
    catch (Exception ex)
    {

    }

    ...
}

with an Exception Property of: New AbortException

Body:
The easiest is to create a class that extends exception and pass any values you want, like:

public class MyError : Exception
{
   public MyError() : base(string.Empty) {}
   public MyError(Exception e) : base(e.Message) {}
   public int MyCustomValue { get; set; }
}

Then using it like, (passing the value of 5 to the catch handler)

throw new MyError(){ MyCustomValue = 5 };

Then in your catch

try{}
catch(MyError ex)
{
    Console.Write(ex.MyCustomValue.ToString());
}


来源: stackexchange

问:
strapi + knex to execute complex Queries
How do  I get the knex object to execute custom or complex queries within my strapi service?

My Strapi version has the strapi-hook-knex and strapi-hook-bookshelf installed but when I run qb.raw it is an undefined object.

This is to run queries like this:

```<code>qb.select(knex.raw('.... ?? )', '...'))
</code>```

答:
With Strapi v4 use:

```<code>strapi.db.connection.raw
</code>```

instead of

```<code>strapi.connections.default.raw
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do  I get the knex object to execute custom or complex queries within my strapi service?

My Strapi version has the strapi-hook-knex and strapi-hook-bookshelf installed but when I run qb.raw it is an undefined object.

This is to run queries like this:

qb.select(knex.raw('.... ?? )', '...'))

Body:
With Strapi v4 use:

strapi.db.connection.raw

instead of

strapi.connections.default.raw


问:
Powershell - Find computers with a specific username logged in
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

```<code>Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }
</code>```

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

答:
Continuing from my comment. . .

Here's an quick and dirty approach you can take:

```<code>Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username
Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq $true -and SamAccountName -like $Prefix}

$check = Get-CimInstance -Query "SELECT Name,UserName from Win32_ComputerSystem WHERE UserName LIKE '%$userName%'" `
                -ComputerName $Computers.Name`
                -ErrorAction SilentlyContinue
if ($check) {
    # $check.UserName/Name may return an array same name users are found.
    Write-Output -InputObject ($check.UserName + " is logged into: " + $check.Name)
}
else {
    Write-Output -InputObject "Unable to find $userName."
}
</code>```

Seeing as you're not doing nothing with the systems that you're unable to ping, you can silence the output and only returning the results for the ones that are online. Best solution for you scenario and question, is to take advantage of the parallelization that Get-CIMInstance allows you to do when passing an array of computers to -ComputerName.

Write-Progress tends to be terribly slow and if you're looking for a fast solution, this will definitely slow you down.

Get-WMIObject is a deprecated cmdlet that has been superseded by Get-CIMInstance which offers the same functionality, with a safer remoting procedure.

Using -Query, we can use WQL to search at the time of query speeding up the process some more. The only downside to some admins is that it follows its own syntax.

One thing to note, if you can ping a machine, it doesn't mean you can connect to it.

Body:
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

Body:
Continuing from my comment. . .

Here's an quick and dirty approach you can take:

Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username
Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq $true -and SamAccountName -like $Prefix}

$check = Get-CimInstance -Query "SELECT Name,UserName from Win32_ComputerSystem WHERE UserName LIKE '%$userName%'" `
                -ComputerName $Computers.Name`
                -ErrorAction SilentlyContinue
if ($check) {
    # $check.UserName/Name may return an array same name users are found.
    Write-Output -InputObject ($check.UserName + " is logged into: " + $check.Name)
}
else {
    Write-Output -InputObject "Unable to find $userName."
}

Seeing as you're not doing nothing with the systems that you're unable to ping, you can silence the output and only returning the results for the ones that are online. Best solution for you scenario and question, is to take advantage of the parallelization that Get-CIMInstance allows you to do when passing an array of computers to -ComputerName.

Write-Progress tends to be terribly slow and if you're looking for a fast solution, this will definitely slow you down.

Get-WMIObject is a deprecated cmdlet that has been superseded by Get-CIMInstance which offers the same functionality, with a safer remoting procedure.

Using -Query, we can use WQL to search at the time of query speeding up the process some more. The only downside to some admins is that it follows its own syntax.

One thing to note, if you can ping a machine, it doesn't mean you can connect to it.


问:
Add new language to existing Xcode project localization
I'm working on an existing Xcode 3.2.2 Universal iPhone OS project which is already localized for 4 languages (EN, IT, DE and FR). We are now adding a new language (JA) into this project.

Each existing .lproj folder (en.lproj, it.lproj, de.lproj and fr.lproj) has almost 60 files - including PNGs, HTMLs and the Localizable.strings file. Each one of those files appear as localized groups inside Groups & Files in Xcode. They're spread all over the tree.

If I right-click one of those groups (say, Localizable.strings) inside Xcode, Get Info, click on "Add Localization" and type "ja" - as the Xcode docs suggest, nothing happens. From what I read in this newgroup, it's possibly because of the way those folders are named. If they were named like English.lproj and Italian.lproj, this was supposed to work.

So, for me to actually import a new language localized file into the existing group, I have to:

Right-click the localized group file.

Choose "Add Existing File".

Select the corresponding file inside the ja.lproj folder.

I'm about to get a new ja.lproj folder with those 60 localized files and would love to import them in the project in a way that doesn't involve searching for every single file in Groups & Trees and performing those steps... for every one of those 60 files.

Is that possible? Is there a right (or better) way to import a new language into this Xcode project?

答:
This is what I found works:

click add localization;

replace all the files in the new .lproj folder with localized files;

delete the localization, and choose "keeping files";

done.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Why can I click on a link outside of its text element?
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

```<code><div class="nav-list">
       <a class="home_A"href="Home.php">
          <img class="homeIcon" src="photos/icon.png">
       </a>
</div>
</code>```

CSS of the image

```<code>.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}
</code>```

CSS of the  link

```<code>.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}
</code>```

HTML of the  link

```<code><form method="POST" class="signinForm">
<ul>
    <li> <h1 class="signinH1">sign in</h1></li>
    <li> <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required></li>
    <li> <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required></li>
    <li> <input type="submit" value="Log in"class="signinbutton"></li>
    <li><a href="signUp.php">Sign up</a></li>
</ul>

</form>
</code>```

Thanks all.

答:
It might have to do with your CSS styles for  tags and/or  tags.

My guess is that something like the following might fix your issue

.homeIcon {
  display: inline-block;
}
```

Body:
I'm building a forum and I have a link that can be clicked outside of its text, how can I undo it?
I also have an image inside a tag that can be clicked outside of its image, I want to undo that too.
I have tried - position: relative; but it didn't work.

Here is the HTML code of the image.

CSS of the image

.homeIcon{
    width: 200px;
    display:block;
    margin:auto;
    margin: 0 auto;
}

CSS of the  link

.signinForm a{
margin: auto;
display:block;
text-align:center;
margin-top: 7px;
color: #006db6;
font-size: 20px;
}

HTML of the  link

<form method="POST" class="signinForm">

sign in

 <input type="text" placeholder="User name"name="username_login"class="username" value="<?php if(isset($_POST['username_login'])){echo $_POST['username_login'];}?>" required>

 <input type="password" placeholder="Password" name="password_login" class="password" value="<?php  if(isset($_POST['password_login'])){echo $_POST['password_login'];}?>" required>

 <input type="submit" value="Log in"class="signinbutton">

Sign up

</form>

Thanks all.

Body:
It might have to do with your CSS styles for <a> tags and/or <img> tags.

My guess is that something like the following might fix your issue

.homeIcon {
  display: inline-block;
}


问:
How do I reverse the sign in a django database query on matching rows?
I have a Django model that looks like this:

direction_choices = (
    ("up", "Up"),
    ("down", "Down"),
    ("left", "Left"),
    ("right", "Right"),
)

class Movement:
    direction = models.CharField(max_length=5, choices=direction_choices)
    distance = models.PositiveSmallIntegerField()
```
<p>Lets say the data in my database looks like this:</p>
```Movement(direction="up", 4)
Movement(direction="up", 6)
Movement(direction="down", 3)
Movement(direction="down", 1)
Movement(direction="left", 7)
Movement(direction="right", 4)
Movement(direction="left", 1)
Movement(direction="right", 8)
```
<p>I want to do a database query that will calculate the total distance moved in the Y axis.</p>
<p>In our example, it would be: <code>4+6-3-1 = 6</code></p>
<p>I can do something like:</p>
<pre class="lang-py prettyprint-override"><code>Movement.objects.all().filter(
    direction__in=("up", "down")
    ).aggregate(
        total=Sum('distance')
    )
</code>```

which gives me:

{'total': 16}
```

I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total.

I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this?

答:
I would do this using a group by to only sum within each direction, followed by doing the final subtraction in Python:

result = Movement.objects.values('direction').order_by('direction').annotate(total_distance=Sum('distance'))
# Transform to dict
result = {row['direction']: row['total_distance'] for row in result}
y_axis = result['up'] - result['down']
x_axis = result['right'] - result['left']
```

What's the advantage of this approach? It produces a more efficient query, which only needs to iterate over the data once, which is helpful if you have a lot of rows.

Body:
I have a Django model that looks like this:

direction_choices = (
    ("up", "Up"),
    ("down", "Down"),
    ("left", "Left"),
    ("right", "Right"),
)

class Movement:
    direction = models.CharField(max_length=5, choices=direction_choices)
    distance = models.PositiveSmallIntegerField()

Lets say the data in my database looks like this:

Movement(direction="up", 4)
Movement(direction="up", 6)
Movement(direction="down", 3)
Movement(direction="down", 1)
Movement(direction="left", 7)
Movement(direction="right", 4)
Movement(direction="left", 1)
Movement(direction="right", 8)

I want to do a database query that will calculate the total distance moved in the Y axis.

In our example, it would be: 4+6-3-1 = 6

I can do something like:

Movement.objects.all().filter(
    direction__in=("up", "down")
    ).aggregate(
        total=Sum('distance')
    )

which gives me:

{'total': 16}

I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total.

I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this?

Body:
I would do this using a group by to only sum within each direction, followed by doing the final subtraction in Python:

result = Movement.objects.values('direction').order_by('direction').annotate(total_distance=Sum('distance'))
# Transform to dict
result = {row['direction']: row['total_distance'] for row in result}
y_axis = result['up'] - result['down']
x_axis = result['right'] - result['left']

What's the advantage of this approach? It produces a more efficient query, which only needs to iterate over the data once, which is helpful if you have a lot of rows.


问:
How to make a string array?
How do I make a string array in python with length 100 for example. I don't use python much so I'm not really sure how. I want the array to be formatted in this way so I can assign a string to a value in a separate line.</p>
```<code>keyword = [100]
keyword[0] = "Blue Light Glasses"
keyword[1] = "Tech Fleece Joggers"
</code>```

答:
If you fix the lenght of the array, you can just create a list with a none value

```<code>keyword = [''] * 100   # list of 100 element
keyword[0] = 'Blue Light Glasses'
keyword[1] = "Tech Fleece Joggers"
</code>```

You can also create a empty list and add element in this list

```<code>keyword = list()
keyword.append('Blue Light Glasses')
keyword.append('Tech Fleece Joggers')
print(keyword)
</code>```

Output:

```<code>['Blue Light Glasses', 'Tech Fleece Joggers']
</code>```

OwnerDisplayName: anon

Title: How to make a string array?

Body:
How do I make a string array in python with length 100 for example. I don't use python much so I'm not really sure how. I want the array to be formatted in this way so I can assign a string to a value in a separate line.

keyword = [100]
keyword[0] = "Blue Light Glasses"
keyword[1] = "Tech Fleece Joggers"

Body:
If you fix the lenght of the array, you can just create a list with a none value

keyword = [''] * 100   # list of 100 element
keyword[0] = 'Blue Light Glasses'
keyword[1] = "Tech Fleece Joggers"

You can also create a empty list and add element in this list

keyword = list()
keyword.append('Blue Light Glasses')
keyword.append('Tech Fleece Joggers')
print(keyword)

Output:

['Blue Light Glasses', 'Tech Fleece Joggers']


问:
Toolbar in fragment appearing below action bar
I am trying to follow the Android docs on how to properly create a toolbar in a fragment. However, when I follow the example in the doc, by toolbar appears below the action bar rather than inside of it.

(Note that the "Done" button is not in the action bar).

Most examples I've found through searching stackoverflow seem to use setSupportActionBar, but I don't want to use this because the docs are clear that this shouldn't be used with a toolbar that only appears in one fragment.

Here is my code:

activity_main.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_container_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (savedInstanceState == null) {
            supportFragmentManager.commit {
                setReorderingAllowed(true)
                add<CityListFragment>(R.id.fragment_container_view)
            }
        }
    }
}
</code>```

city_list_fragment.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

CityListFragment.kt

```<code>class CityListFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.city_list_fragment, container, false)

        val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
        toolbar.inflateMenu(R.menu.menu_main)
        toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.done_btn -> {
                    true
                }
                else -> false
            }
        }

        return view
    }
}
</code>```

menu_main.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
    <item android:id="@+id/done_btn"
          android:title="Done"
          android:orderInCategory="100"
          app:showAsAction="ifRoom"/>
</menu>
</code>```

Am I doing something wrong? Or is this how android wants fragment-owned toolbars to look?

答:
There are some way to if you want to make custom toolbar in fragment respectively. Because you are showing your fragment over a activity so default toolbar will appear. You have to remove default toolbar from your activity. First way, go to theme and change style

```<code>         <style name="copy from your app"
    parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">

</code>```

another way - add this line in activity class oncreate method

```<code>    supportActionBar?.hide()
</code>```

another way -add this line in activity class oncreate method

```<code>  getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
</code>```

all ways should be in activity.

Body:
I am trying to follow the Android docs on how to properly create a toolbar in a fragment. However, when I follow the example in the doc, by toolbar appears below the action bar rather than inside of it.

(Note that the "Done" button is not in the action bar).

Most examples I've found through searching stackoverflow seem to use setSupportActionBar, but I don't want to use this because the docs are clear that this shouldn't be used with a toolbar that only appears in one fragment.

Here is my code:

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_container_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (savedInstanceState == null) {
            supportFragmentManager.commit {
                setReorderingAllowed(true)
                add<CityListFragment>(R.id.fragment_container_view)
            }
        }
    }
}

city_list_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

CityListFragment.kt

class CityListFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.city_list_fragment, container, false)

        val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
        toolbar.inflateMenu(R.menu.menu_main)
        toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.done_btn -> {
                    true
                }
                else -> false
            }
        }

        return view
    }
}

menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">
    <item android:id="@+id/done_btn"
          android:title="Done"
          android:orderInCategory="100"
          app:showAsAction="ifRoom"/>
</menu>

Am I doing something wrong? Or is this how android wants fragment-owned toolbars to look?

Body:
There are some way to if you want to make custom toolbar in fragment respectively. Because you are showing your fragment over a activity so default toolbar will appear. You have to remove default toolbar from your activity. First way, go to theme and change style

         <style name="copy from your app"
    parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">

another way - add this line in activity class oncreate method

    supportActionBar?.hide()

another way -add this line in activity class oncreate method

  getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

all ways should be in activity.


问:
Is class.getName() expensive?
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

```<code>public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}
</code>```

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

答:
Caching the class name will carry the overhead of another reference.  That shifts the cost of JVM opcodes (cpu complexity) for memory footprint.

These days CPUs are so fast that they basically wait on memory, so if you had to make a choice between opcodes and memory footprint, you are better off choosing to run more opcodes through the JVM.

At first this doesn't seem intuitive; but, consider the JVM and surrounding hardware.  Larger memory footprints mean fewer recently accessed items in cache, and the cost to re-fetch an item that falls out of cache is somewhere between 1,000 to 10,000 times the cost to run a single JVM opcode.  Couple this with the JVM's jit engine, and the CPU complexity for heavily accessed chunks of code gets optimized for free (in addition to everything else).

So, in general, I would trim your object by not caching the reference as it would allow more of them to be shoved into the level 1 cache.  However, like all real world performance tuning, you should test to see if the results match the hypothesis, and do your testing in such a manner that you don't get confused by all the other internal workings of the JVM.

Title: Is class.getName() expensive?

Body:
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?


问:
Why won't my python3 file import even though it is in the same directory?
I was attempting to import a python script that was in the same directory and it would not be recognized.</p>
```<code>import 1PythonScript

def do_stuff() -> None:
    pass

</code>```

答: Remove digits from the start of the filename.</p>

Body:
I was attempting to import a python script that was in the same directory and it would not be recognized.

import 1PythonScript

def do_stuff() -> None:
    pass


问:
I can't find the reason why the button is not moving to the right using kivy
I'm trying to design an app and for some reason, I can't find the reason the Button wont move to the right, does anyone have an idea why?</p>
```<code>#: import utils kivy.utils
BoxLayoutExample:

<BoxLayoutExample>:
    canvas:
        Color:
            rgba: 0.24, 0.29, 0.353,1
        Rectangle:
            size: self.width, self.height

        # TOP OF SCREEN
        # DropShadow
        Color:
            rgba: 0, 0, 0, .3
        Rectangle:
            pos: dp(0), self.top-72
            size: self.width, dp(70)

        # Black bar
        Color:
            rgba: .043, .047, .0627, 1
        Rectangle:
            pos: dp(0), self.top-70
            size: self.width, dp(70)

        # CENTER
        # DropShadow
        Color:
            rgba: 0, 0, 0, 0.5
        Rectangle:
            pos: self.center_x-self.center_x*0.86+2, self.center_y-182
            size: self.width*0.86, dp(300)
        Color:
            rgba: 0.125, 0.1568, 0.2, 1
        Rectangle:
            pos: self.center_x-self.center_x*0.86, self.center_y-180
            size: self.width*0.86, dp(300)

    Button:
        text: "1"
        size_hint: None, None
        size: "60dp", "130dp"
        pos_hint: {"right":1, "top": 1}
</code>```

答:
According to the BoxLayout documentation:

Position hints are partially working, depending on the orientation:

```<code>If the orientation is vertical: x, right and center_x will be used.

If the orientation is horizontal: y, top and center_y will be used.
</code>```

So, using vertical orientation will enable the right pos_hint. Try adding that to your BoxLayoutExample rule:

```<code><BoxLayoutExample>:
    orientation: 'vertical'
</code>```

Of course, then you cannot use the y, top or center_y pos_hints. If you need these also, then you should use a different base class (perhaps FloatLayout).

Body:
I'm trying to design an app and for some reason, I can't find the reason the Button wont move to the right, does anyone have an idea why?

#: import utils kivy.utils
BoxLayoutExample:

<BoxLayoutExample>:
    canvas:
        Color:
            rgba: 0.24, 0.29, 0.353,1
        Rectangle:
            size: self.width, self.height

        # TOP OF SCREEN
        # DropShadow
        Color:
            rgba: 0, 0, 0, .3
        Rectangle:
            pos: dp(0), self.top-72
            size: self.width, dp(70)

        # Black bar
        Color:
            rgba: .043, .047, .0627, 1
        Rectangle:
            pos: dp(0), self.top-70
            size: self.width, dp(70)

        # CENTER
        # DropShadow
        Color:
            rgba: 0, 0, 0, 0.5
        Rectangle:
            pos: self.center_x-self.center_x*0.86+2, self.center_y-182
            size: self.width*0.86, dp(300)
        Color:
            rgba: 0.125, 0.1568, 0.2, 1
        Rectangle:
            pos: self.center_x-self.center_x*0.86, self.center_y-180
            size: self.width*0.86, dp(300)

    Button:
        text: "1"
        size_hint: None, None
        size: "60dp", "130dp"
        pos_hint: {"right":1, "top": 1}

Body:
According to the BoxLayout documentation:

Position hints are partially working, depending on the orientation:

If the orientation is vertical: x, right and center_x will be used.

If the orientation is horizontal: y, top and center_y will be used.

So, using vertical orientation will enable the right pos_hint. Try adding that to your BoxLayoutExample rule:

<BoxLayoutExample>:
    orientation: 'vertical'

Of course, then you cannot use the y, top or center_y pos_hints. If you need these also, then you should use a different base class (perhaps FloatLayout).


问:
Trying to load content with useEffect and context
I am trying to show information of a state into a component. I am using the context to load information from different origin.

```<code> const router = useRouter()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [loadUser, setLoadUser] = useState({})

  const { state, dispatch } = useContext(Context)
  const { user } = state

  useEffect(() => {
    if (user == null) {
      router.push("/auth/login")
    }

    setLoadUser(user)
  }, [user])
</code>```

That code is inside a dashboard component. The idea is to get the user information into the state to show it on the dashboard. The problem is that the useEffect is executed at the same time that the content is rendered, therefore it does not have time to load the information, and the variables are null for me.

Here is an image of how the loadState variable behaves once inside the render.

I am using nextjs by the way.

I am passing the context with a provider to the App. And wrapped it.

```<code>// initial state
const initialState = {
  user: null
};

// Create context
const Context = createContext()

// root reducer
const reducer = (state, action) => {
  const { type, payload } = action;

  switch (type) {
    case "LOGIN":
      return { ...state, user: payload};

    case "LOGOUT":
      return { ...state, user: null };

      default:
      return state;
  }
}

// context provider
const Provider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const router = useRouter();

  useEffect(() => {
    dispatch({
      type: "LOGIN",
      payload: JSON.parse(window.localStorage.getItem("user"))
    })
  }, [])

  axios.interceptors.response.use(
    function (response) {
      return response
    },

    function (error) {
      let res = error.response;
      console.log(error)

      if (res.data.status === 401 && res.config && !res.config.__isRetryRequest) {
        return new Promise((resolve, reject) => {
          axios.get(`${process.env.NEXT_PUBLIC_API}/auth/logout`)
            .then(res => {
              dispatch({ type: "LOGOUT" })
              window.localStorage.removeItem("user")
              router.push('/auth/login')
            })
            .catch(error => {
              reject(error)
            })
        })
      }

      return Promise.reject(error);
    }
  )

  useEffect(() => {
    const getCsrfToken = async () => {
      const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API}/csrf-token`)
      axios.defaults.headers["X-CSRF-Token"] = data.csrfToken
    }

    getCsrfToken()
  }, [])

  return (
    <Context.Provider value={{ state, dispatch }}>
      {children}
    </Context.Provider>
  )
}

export { Context, Provider }
</code>```

答:
Add dependecy array. That shoud be quick fix.

```<code>  useEffect(() => {
    if (user == null) {
      router.push("/auth/login")
    }

    setLoadUser(user)
  }, [state]) // dependecy array looks at state changes
</code>```

You can read more about dependecy array on the official react documentation: https://reactjs.org/docs/hooks-effect.html

proper fix:

whenever you are using api calls in your app, those are asyncrhonus. You should use some loading state.

for example

```<code>const Context = () => {
   const [loading, setLoading] = useState(true)
   const [user, setUser] = useState(true)

   fetch('api/user').than(r=> setLoading(false);setUser(r.user))
// rest of the context code
}
</code>```

and in component itself:

```<code>  const  state = useContext(Context)

  useEffect(() => {
     state.loading ? null : setLoadUser(user)

  }, [state]) //
</code>```

Body:
I am trying to show information of a state into a component. I am using the context to load information from different origin.

 const router = useRouter()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [loadUser, setLoadUser] = useState({})

  const { state, dispatch } = useContext(Context)
  const { user } = state

  useEffect(() => {
    if (user == null) {
      router.push("/auth/login")
    }

    setLoadUser(user)
  }, [user])

That code is inside a dashboard component. The idea is to get the user information into the state to show it on the dashboard. The problem is that the useEffect is executed at the same time that the content is rendered, therefore it does not have time to load the information, and the variables are null for me.

Here is an image of how the loadState variable behaves once inside the render.

I am using nextjs by the way.

I am passing the context with a provider to the App. And wrapped it.

// initial state
const initialState = {
  user: null
};

// Create context
const Context = createContext()

// root reducer
const reducer = (state, action) => {
  const { type, payload } = action;

  switch (type) {
    case "LOGIN":
      return { ...state, user: payload};

    case "LOGOUT":
      return { ...state, user: null };

      default:
      return state;
  }
}

// context provider
const Provider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const router = useRouter();

  useEffect(() => {
    dispatch({
      type: "LOGIN",
      payload: JSON.parse(window.localStorage.getItem("user"))
    })
  }, [])

  axios.interceptors.response.use(
    function (response) {
      return response
    },

    function (error) {
      let res = error.response;
      console.log(error)

      if (res.data.status === 401 && res.config && !res.config.__isRetryRequest) {
        return new Promise((resolve, reject) => {
          axios.get(`${process.env.NEXT_PUBLIC_API}/auth/logout`)
            .then(res => {
              dispatch({ type: "LOGOUT" })
              window.localStorage.removeItem("user")
              router.push('/auth/login')
            })
            .catch(error => {
              reject(error)
            })
        })
      }

      return Promise.reject(error);
    }
  )

  useEffect(() => {
    const getCsrfToken = async () => {
      const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API}/csrf-token`)
      axios.defaults.headers["X-CSRF-Token"] = data.csrfToken
    }

    getCsrfToken()
  }, [])

  return (
    <Context.Provider value={{ state, dispatch }}>
      {children}
    </Context.Provider>
  )
}

export { Context, Provider }

Body:
Add dependecy array. That shoud be quick fix.

  useEffect(() => {
    if (user == null) {
      router.push("/auth/login")
    }

    setLoadUser(user)
  }, [state]) // dependecy array looks at state changes

You can read more about dependecy array on the official react documentation: https://reactjs.org/docs/hooks-effect.html

proper fix:

whenever you are using api calls in your app, those are asyncrhonus. You should use some loading state.

for example

const Context = () => {
   const [loading, setLoading] = useState(true)
   const [user, setUser] = useState(true)

   fetch('api/user').than(r=> setLoading(false);setUser(r.user))
// rest of the context code
}

and in component itself:

  const  state = useContext(Context)

  useEffect(() => {
     state.loading ? null : setLoadUser(user)

  }, [state]) //


问:
Structural pattern matching and infinity
I am computing the Lp distance functions for non-negative p's. For all but p = 0 and p = ∞ a built-in pow() function serves well.
Before I learned about a structural pattern matching, I had used a dictionary and exception handling:

```<code>from math import sqrt, inf
distance_function = {   0.0: lambda x, y: int(x != 0.0) + int(y != 0.0),
                        1.0: lambda x, y: abs(x) + abs(y), # Likely a tad faster than 'pow()'
                        inf: lambda x, y: max(abs(x), abs(y))}
def lp_distance(x, y, p):
    try:                return distance_function[p](x, y)
    except KeyError:    return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)
</code>```

Some people didn't want exceptions here. So I rewrote the snippet into the following one:

```<code>def lp_distance(x, y, p):
    match p:
        case 0.0:           return int(x != 0.0) + int(y != 0.0)
        case 1.0:           return abs(x) + abs(y)
        # The line below triggers "SyntaxError: name capture 'inf' makes remaining patterns unreachable"
        case inf:           return max(abs(x), abs(y))
        # But the following works:
        case p if p == inf: return max(abs(x), abs(y))
        case _:             return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)
</code>```

Why case inf: is not correct (Python v3.10.2)?

答:
In a case statement, a simple name is a pattern that captures (assigns) to that name. In contrast, a dotted name is a patterns that refers to the value of that name.

In simple terms NAME will always succeed and it will set NAME = <subject>.

In simple terms NAME1.NAME2 will succeed only if <subject> == NAME1.NAME2

Using just case inf: means that the value to match is unconditionally assigned to the name inf – it does not matter if the name was previously bound.

What you want instead is case math.inf:, which means to compare against this value.

import math

def lp_distance(x, y, p):
    match p:
        case 0.0:
            return int(x != 0.0) + int(y != 0.0)
        case 1.0:
            return abs(x) + abs(y)
        # compare against a value by using its dotted name
        case math.inf:
            return max(abs(x), abs(y))
        case _:
            return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)
```

Body:
I am computing the Lp distance functions for non-negative p's. For all but p = 0 and p = ∞ a built-in pow() function serves well.
Before I learned about a structural pattern matching, I had used a dictionary and exception handling:

from math import sqrt, inf
distance_function = {   0.0: lambda x, y: int(x != 0.0) + int(y != 0.0),
                        1.0: lambda x, y: abs(x) + abs(y), # Likely a tad faster than 'pow()'
                        inf: lambda x, y: max(abs(x), abs(y))}
def lp_distance(x, y, p):
    try:                return distance_function[p](x, y)
    except KeyError:    return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)

Some people didn't want exceptions here. So I rewrote the snippet into the following one:

def lp_distance(x, y, p):
    match p:
        case 0.0:           return int(x != 0.0) + int(y != 0.0)
        case 1.0:           return abs(x) + abs(y)
        # The line below triggers "SyntaxError: name capture 'inf' makes remaining patterns unreachable"
        case inf:           return max(abs(x), abs(y))
        # But the following works:
        case p if p == inf: return max(abs(x), abs(y))
        case _:             return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)

Why case inf: is not correct (Python v3.10.2)?


问:
Input in Prolog
I'm currently working on a recursive Prolog program to link routes together to create a basic GPS of the Birmingham area. At the moment I can get output as so:

Input

```<code>routeplan(selly_oak, aston, P).
</code>```

Output

```<code>P = [selly_oak, edgbaston, ... , aston]
</code>```

What I would like to do is have my program provide some sort of interface, so if I were to type in something along the lines of:

```<code>Route from selly_oak to aston
</code>```

It would provide me with:

```<code>Go from selly_oak to edgbaston
Go from edgbaston to ...
Finally, Go from ... to aston.
</code>```

Prolog is a powerful language so I assume this is easily possible, however many of the books I've taken out seem to skip over this part. As far as I am aware I have to use something along the lines of write() and read() although the details are unknown to me.

Could anyone here a Prolog novice out with some basic examples or links to further information?

EDIT: A lot of these answers seem very complicated, where the solution should only be around 5-10 lines of code. Reading in a value isn't a problem as I can do something along the lines of:

```<code>find:-
    write('Where are you? '),
    read(X),
    nl, write('Where do you want to go? '),
    read(Y),
    loopForRoute(X,Y).
</code>```

I'd prefer it if the output could be written out using write() so a new line (nl) can be used, so that it displays like the output above.

If this were my input, how would I then arrange the top routeplan() to work with these inputs? Also, if I were to add the Lines for these stations as an extra parameter how would this then be implemented? All links are defined at the beginning of the file like so:

```<code>rlinks(selly_oak, edgbaston, uob_line).
rlinks(edgbaston, bham_new_street, main_line).
</code>```

Therefore, with this information, it'd be good to be able to read the line as so.

```<code>Go from selly_oak to edgbaston using the uob_line
Go from edgbaston to ... using the ...
Finally, go from ... to aston using the astuni_line
</code>```

答:
For this sort of thing, I usually create shell predicates. So in your case...

```<code>guided:-
    print('Enter your start point'),nl,
    read(Start),
    print('Enter your destination'),nl,
    read(Dest),
    routeplan(Start, Dest, Route),
    print_route(Route).
</code>```

And print_route/1 could be something recursive like this:

```<code>print_route([]).

print_route([[A,B,Method]|Tail]):-
    print_route(Tail),
    print('Go from '), print(A),
    print(' to '), print(B),
    print(' by '), print(Method), nl.
</code>```

I've assumed that the 3rd variable of the routeplan/3 predicate is a list of lists. Also that it's built by adding to the tail. If it's not, it should be fairly easy to adapt. Ask in the comments.

OwnerDisplayName: EnderMB

Title: Input in Prolog

Body:
I'm currently working on a recursive Prolog program to link routes together to create a basic GPS of the Birmingham area. At the moment I can get output as so:

Input

routeplan(selly_oak, aston, P).

Output

P = [selly_oak, edgbaston, ... , aston]

What I would like to do is have my program provide some sort of interface, so if I were to type in something along the lines of:

Route from selly_oak to aston

It would provide me with:

Go from selly_oak to edgbaston
Go from edgbaston to ...
Finally, Go from ... to aston.

Prolog is a powerful language so I assume this is easily possible, however many of the books I've taken out seem to skip over this part. As far as I am aware I have to use something along the lines of write() and read() although the details are unknown to me.

Could anyone here a Prolog novice out with some basic examples or links to further information?

EDIT: A lot of these answers seem very complicated, where the solution should only be around 5-10 lines of code. Reading in a value isn't a problem as I can do something along the lines of:

find:-
    write('Where are you? '),
    read(X),
    nl, write('Where do you want to go? '),
    read(Y),
    loopForRoute(X,Y).

I'd prefer it if the output could be written out using write() so a new line (nl) can be used, so that it displays like the output above.

If this were my input, how would I then arrange the top routeplan() to work with these inputs? Also, if I were to add the Lines for these stations as an extra parameter how would this then be implemented? All links are defined at the beginning of the file like so:

rlinks(selly_oak, edgbaston, uob_line).
rlinks(edgbaston, bham_new_street, main_line).

Therefore, with this information, it'd be good to be able to read the line as so.

Go from selly_oak to edgbaston using the uob_line
Go from edgbaston to ... using the ...
Finally, go from ... to aston using the astuni_line

LastEditorDisplayName: EnderMB

Body:
For this sort of thing, I usually create shell predicates. So in your case...

guided:-
    print('Enter your start point'),nl,
    read(Start),
    print('Enter your destination'),nl,
    read(Dest),
    routeplan(Start, Dest, Route),
    print_route(Route).

And print_route/1 could be something recursive like this:

print_route([]).

print_route([[A,B,Method]|Tail]):-
    print_route(Tail),
    print('Go from '), print(A),
    print(' to '), print(B),
    print(' by '), print(Method), nl.

I've assumed that the 3rd variable of the routeplan/3 predicate is a list of lists. Also that it's built by adding to the tail. If it's not, it should be fairly easy to adapt. Ask in the comments.

OwnerDisplayName: Tom Wright

LastEditorDisplayName: Tom Wright


问:
What are the arguments against the use of the "<?="?

Possible Duplicate:

  Are PHP short tags acceptable to use?

The <?= is one of the very few elegant things about PHP, IMO. Yet, there are people that deliberately avoid it (in favor of the much longer <?php echo). Why would they do that?

答:
The problem is that not all servers support short tags

If you are developing an application for an controlled environment (for example, it will run only on your company server), then I don't see any problems with short tags

But, if it'll be a redistributable code, them you should open all tags explicitly <?php echo ?>


问:
Consistent memory use increase when using CallLog cursor in a periodic task
I'm developing an application that monitors customer's sales calls and uploads them to the server. I'm using following periodic method in a service to auto-upload calls that were not synced. It runs after every 0.5Hr delay.

After reducing the delay to 5s I noticed that the memory heap keeps on increasing every 5s. I quickly figured out that setting up callLogInfo is causing the memory issue which on long run leads to lags, memory leaks, slow phones.

GlobalScope.launch(Dispatchers.IO) {
    val projection = arrayOf(
        "_id",
        CallLog.Calls.NUMBER,
        CallLog.Calls.DATE,
        CallLog.Calls.DURATION,
        CallLog.Calls.TYPE,
        CallLog.Calls.CACHED_NAME,
        CallLog.Calls.PHONE_ACCOUNT_ID
    )
    val contentResolver = App.getContext().applicationContext.contentResolver
    val helper: DatabaseHelper = DatabaseHelper.getInstance(App.getContext())
    val callLogInfo = CallLogInfo()

    while (true) {
        Log.d("CallMonitorService", "Scanner loop")
        try {
            contentResolver.query(
                CallLog.Calls.CONTENT_URI,
                projection,
                null,
                null,
                CallLog.Calls.DEFAULT_SORT_ORDER
            )?.also { cursor ->
                cursor.moveToFirst()

                while (!cursor.isAfterLast) {
                    // Following 6 lines were the main cause of increasing memory heap
                    callLogInfo.name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME))
                    callLogInfo.number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER))
                    callLogInfo.callType = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE))
                    callLogInfo.date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE))
                    callLogInfo.duration = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION))
                    callLogInfo.simId = cursor.getStringOrNull(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID))

                    // If Call is not marked as "SYNCED" in Database, post the call for upload on a different handler
                    // It also marks the call as "SYNCED" after successful upload
                    // This is rarely called because most of the calls are synced from a BroadcastReceiver
                    if (helper.getStatus(callLogInfo.getUID()) != "SYNCED") {
                        UploadUtil().uploadCallLogAsync(App.getContext(), callLogInfo)
                    }
                    cursor.moveToNext()
                }
                cursor.close()
            }
        } catch (e: Exception) {
            Log.d("CallMonitorService","Exception in scanner loop: $e")
        }
        delay(5000) // (In ms) Actually it is 1800 * 1000 but for testing I use 5 * 1000
    }
}
```
<ul>
<li><code>callLogInfo</code> class</li>
</ul>
```class CallLogInfo {
    var name: String? = null
    var number: String? = null
    var callType: String? = null
    var date: Long = 0
    var duration: Long = 0
    var simId: String? = null

    fun getUID(): String {
        return "${this.number}_${this.callType}_${this.date}"
    }
}
```

Increasing memory heap

I know that for periodic tasks it is recommended to use either Handler + postDelayed or ScheduledExecutorService. I tried both the methods but faced the same issue so decided to post the original code.

Can anyone suggest a better and efficient approach to this or suggest some refactoring?

Thank you!!

答:
It seems that you call UploadUtil().uploadCallLogAsync for every single call log. Why don't upload them once in bulk? This will reduce a lot of data cost and battery cost.

Then you may use registerContentObserver(CallLog.Calls.CONTENT_URI) to watch the change of call logs, instead of uploading all the call logs everytime. (https://stackoverflow.com/a/4435473/2173056)

Body:
I'm developing an application that monitors customer's sales calls and uploads them to the server. I'm using following periodic method in a service to auto-upload calls that were not synced. It runs after every 0.5Hr delay.

After reducing the delay to 5s I noticed that the memory heap keeps on increasing every 5s. I quickly figured out that setting up callLogInfo is causing the memory issue which on long run leads to lags, memory leaks, slow phones.

GlobalScope.launch(Dispatchers.IO) {
    val projection = arrayOf(
        "_id",
        CallLog.Calls.NUMBER,
        CallLog.Calls.DATE,
        CallLog.Calls.DURATION,
        CallLog.Calls.TYPE,
        CallLog.Calls.CACHED_NAME,
        CallLog.Calls.PHONE_ACCOUNT_ID
    )
    val contentResolver = App.getContext().applicationContext.contentResolver
    val helper: DatabaseHelper = DatabaseHelper.getInstance(App.getContext())
    val callLogInfo = CallLogInfo()

    while (true) {
        Log.d("CallMonitorService", "Scanner loop")
        try {
            contentResolver.query(
                CallLog.Calls.CONTENT_URI,
                projection,
                null,
                null,
                CallLog.Calls.DEFAULT_SORT_ORDER
            )?.also { cursor ->
                cursor.moveToFirst()

                while (!cursor.isAfterLast) {
                    // Following 6 lines were the main cause of increasing memory heap
                    callLogInfo.name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME))
                    callLogInfo.number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER))
                    callLogInfo.callType = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE))
                    callLogInfo.date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE))
                    callLogInfo.duration = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION))
                    callLogInfo.simId = cursor.getStringOrNull(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID))

                    // If Call is not marked as "SYNCED" in Database, post the call for upload on a different handler
                    // It also marks the call as "SYNCED" after successful upload
                    // This is rarely called because most of the calls are synced from a BroadcastReceiver
                    if (helper.getStatus(callLogInfo.getUID()) != "SYNCED") {
                        UploadUtil().uploadCallLogAsync(App.getContext(), callLogInfo)
                    }
                    cursor.moveToNext()
                }
                cursor.close()
            }
        } catch (e: Exception) {
            Log.d("CallMonitorService","Exception in scanner loop: $e")
        }
        delay(5000) // (In ms) Actually it is 1800 * 1000 but for testing I use 5 * 1000
    }
}

callLogInfo class

class CallLogInfo {
    var name: String? = null
    var number: String? = null
    var callType: String? = null
    var date: Long = 0
    var duration: Long = 0
    var simId: String? = null

    fun getUID(): String {
        return "${this.number}_${this.callType}_${this.date}"
    }
}

Increasing memory heap

I know that for periodic tasks it is recommended to use either Handler + postDelayed or ScheduledExecutorService. I tried both the methods but faced the same issue so decided to post the original code.

Can anyone suggest a better and efficient approach to this or suggest some refactoring?

Thank you!!


问:
How can I cast a Long to an int in Java?
```<code>Long x;
int y = (int) x;
</code>```

Eclipse is marking this line with the error:

Can not cast Long to an int

答:
```<code>Long x1 = 123L;
long x2 = 123L;

int y1 = Math.toIntExact(x1);
int y2 = Math.toIntExact(x2);
</code>```

This conversion will work with primitive as well as with non-primitive types as well.

Body:
Long x;
int y = (int) x;

Eclipse is marking this line with the error:

Can not cast Long to an int

Body:
Long x1 = 123L;
long x2 = 123L;

int y1 = Math.toIntExact(x1);
int y2 = Math.toIntExact(x2);

This conversion will work with primitive as well as with non-primitive types as well.


问:
How can I create a destroy function to delete from database and if its saved change color of button
How can I create a destroy function to delete from the database, and if it is saved in the database, the color of the button changes to red, otherwise green. My form stores data correctly, but I can not destroy it.

Blade

```<code>@foreach (range(1, 3) as $item)
    <form method="post" action="/seats">
        @csrf
        <input type="hidden" name="user_id" value="{{Auth::user()->id}}"/>
        <input type="hidden" name="row_seats" value="4"/>
        <input type="hidden" name="seat_id" value="{{ $item }}"/>
        <button type="submit" style="width:60px; margin-left:10px;"
            class="btn btn-success">
            {{$item}}
        </button>
    </form>

    <form method="POST" action="/seats/{{ $seats->id }}">
        <button type="submit" style="margin-left:10px;" class="btn btn-danger">
            Unreserve {{$item}}
        </button>
    </form>
@endforeach
</code>```

Destroy function

```<code>public function destroy($id)
{
    $seats = Seats::find($id);
    $seats->delete();

    return redirect('/seats');
}
</code>```

Route

```<code>Route::post('/seats/{seats}',[App\Http\Controllers\SeatsController::class, 'destroy'])
    ->name('seats.destroy');
</code>```

答:
I think you are passing the wrong variable to the destroy route which is the seat id in the foreach loop. change this

action="/seats/{{ $seats->id }}"
to

action="{{ route('seats.destroy', $item) }}"

Body:
How can I create a destroy function to delete from the database, and if it is saved in the database, the color of the button changes to red, otherwise green. My form stores data correctly, but I can not destroy it.

Blade

@foreach (range(1, 3) as $item)
    <form method="post" action="/seats">
        @csrf
        <input type="hidden" name="user_id" value="{{Auth::user()->id}}"/>
        <input type="hidden" name="row_seats" value="4"/>
        <input type="hidden" name="seat_id" value="{{ $item }}"/>
        <button type="submit" style="width:60px; margin-left:10px;"
            class="btn btn-success">
            {{$item}}
        </button>
    </form>

    <form method="POST" action="/seats/{{ $seats->id }}">
        <button type="submit" style="margin-left:10px;" class="btn btn-danger">
            Unreserve {{$item}}
        </button>
    </form>
@endforeach

Destroy function

public function destroy($id)
{
    $seats = Seats::find($id);
    $seats->delete();

    return redirect('/seats');
}

Route

Route::post('/seats/{seats}',[App\Http\Controllers\SeatsController::class, 'destroy'])
    ->name('seats.destroy');


问:
the difference between WHERE... GROUP BY and GROUP BY....HAVING structure
I am quite new to SQL, and studying on coursera, here is a project on the final stage of the course. It asks find the distribution of star ratings of restaurants in a given city.
Here is my answer

```<code>SELECT
stars,
count(stars)
FROM business
group by stars
having city = 'Avon'
</code>```

basically i use the group by..having structure, group by cities first and then filter within the group.However it returned NO results.

The right answer is below

```<code>SELECT
stars,
count(stars)
FROM business
where city = 'Avon'
group by stars
</code>```

I understand the logic here, filter the city first and then group it by star.

My question is just simple, why my way is incorrect?

thanks in advance!

答:
HAVING works on the columns result set of the query above it. Your result set from SELECT stars, COUNT(stars) ... GROUP BY stars has no city column in its result set.

But WHERE works on the input table's columns.

Body:
I am quite new to SQL, and studying on coursera, here is a project on the final stage of the course. It asks find the distribution of star ratings of restaurants in a given city.
Here is my answer

SELECT
stars,
count(stars)
FROM business
group by stars
having city = 'Avon'

basically i use the group by..having structure, group by cities first and then filter within the group.However it returned NO results.

The right answer is below

SELECT
stars,
count(stars)
FROM business
where city = 'Avon'
group by stars

I understand the logic here, filter the city first and then group it by star.

My question is just simple, why my way is incorrect?

thanks in advance!


问:
Keep background audio from other apps alive, react-native-video IOS
long time listener first time caller.

I am so far unsuccessful in getting background music from something like Spotify to stay alive in my react-native app as soon as I navigate to a screen that is using react-native-video.  On Android no changes had to be made for that to work.  I am using react-native (non-expo) and am currently in testing on testflight.

If this is a duplicate let me know, but I am only finding many articles on how to make your app play in the background (my issue is the opposite), and I may not just know the term IOS uses for this type of control.  Important to note that one instance of this component DOES include audio, but the majority of videos presented have no audio.

I've tried:

updating AppDelgate.m with the instructions from react-native-video docs:

AppDelegate.m

```<code>    #import <AVFoundation/AVFoundation.h>  // import

     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      ...
      [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];  // allow
      ...
    }

</code>```

this had seemingly no effect

Using ignoreSilentSwitch="ignore" and obey

Obey successfully allows background audio to continue, but mutes the videos that do have audio.

Looking at the source, ignoreSilentSwitch=obey does the same thing as what I added to the AppDelegate.m file and is also negated if you use the isPaused prop.

Tried many of the other props involving audio hoping to get lucky.

Added Background Modes = "Audio, Airplay, and Picture in Picture" Capability on my app target in xcode.

Cried a little bit and questioned my life choices.

I implemented react-native-video using react-native-video-controls, but as I understand it's the same module with added features. Here is the implemenation:

```<code><VideoContainer>
    <VideoPlayer
      source={currentVideo}
      navigator={null}
      ref={videoRef}
      resizeMode={'cover'}
      controlTimeout={1500}
      paused={isPaused}
      repeat={true}
      muted={true}
      tapAnywhereToPause={true}
      disableBack={true}
      disableTimer={true}
      disableVolume={true}
      disableFullscreen={true}
      showOnStart={true}
      hideShutterView={true}
    />
 </VideoContainer>
</code>```

Any help, suggestion, feedback or rebuttal is greatly appreciated!

答:
I think there is a prop

```<code>mixWithOthers
</code>```

try setting it to 'mix'

Body:
long time listener first time caller.

I am so far unsuccessful in getting background music from something like Spotify to stay alive in my react-native app as soon as I navigate to a screen that is using react-native-video.  On Android no changes had to be made for that to work.  I am using react-native (non-expo) and am currently in testing on testflight.

If this is a duplicate let me know, but I am only finding many articles on how to make your app play in the background (my issue is the opposite), and I may not just know the term IOS uses for this type of control.  Important to note that one instance of this component DOES include audio, but the majority of videos presented have no audio.

I've tried:

updating AppDelgate.m with the instructions from react-native-video docs:

AppDelegate.m

    #import <AVFoundation/AVFoundation.h>  // import

     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      ...
      [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];  // allow
      ...
    }

this had seemingly no effect

Using ignoreSilentSwitch="ignore" and obey

Obey successfully allows background audio to continue, but mutes the videos that do have audio.

Looking at the source, ignoreSilentSwitch=obey does the same thing as what I added to the AppDelegate.m file and is also negated if you use the isPaused prop.

Tried many of the other props involving audio hoping to get lucky.

Added Background Modes = "Audio, Airplay, and Picture in Picture" Capability on my app target in xcode.

Cried a little bit and questioned my life choices.

I implemented react-native-video using react-native-video-controls, but as I understand it's the same module with added features. Here is the implemenation:

<VideoContainer>
    <VideoPlayer
      source={currentVideo}
      navigator={null}
      ref={videoRef}
      resizeMode={'cover'}
      controlTimeout={1500}
      paused={isPaused}
      repeat={true}
      muted={true}
      tapAnywhereToPause={true}
      disableBack={true}
      disableTimer={true}
      disableVolume={true}
      disableFullscreen={true}
      showOnStart={true}
      hideShutterView={true}
    />
 </VideoContainer>

Any help, suggestion, feedback or rebuttal is greatly appreciated!

Body:
I think there is a prop

mixWithOthers

try setting it to 'mix'


问:
Audio recorder question
looking for a free audio recorder so user will be able to record him self and the record will be uploaded to the server (by Rails).

Is there something I can use to achieve this?

答:
It is not so easy. There is no ready solution. You should setup your own media server, then pass to it sound (via Flash, I believe), record this sound on server and then store somewhere on server.

http://www.red5.org/

UPD

Similar question: How to record voice files using PHP, FLASH

Title: Audio recorder question


问:
Can't fix "Method in class cannot be applied"
I am trying to get the first 10 words from the dictionary list but when I compile the code, I keep getting:

SpellChecker.java:34: error: constructor SpellChecker in class SpellChecker cannot be applied to given types;
SpellChecker checker = new SpellChecker();
^
required: String[]
found:    no arguments
reason: actual and formal argument lists differ in length
I get the same thing for checker.print10(); How do I fix this?

```<code>import java.util.Arrays;

public class SpellChecker {
  private String[] dictionary = {"the","of","and","to","in","is","you","that","it","he","was","for","on","are",
                                 "as","with","his","they","I","at","be","this","have","from","or","one","had","by",
                                 "word","but","not","what","all","were","we","when","your","can","said","there","use",
                                 "an","each","which","she","do","how","their","if","will","up","other","about","out","many",
                                 "then","them","these","so","some","her","would","make","like","him","into","time","has","look",
                                 "two","more","write","go","see","number","no","way","could","people","my","than","first","water",
                                 "been","call","who","oil","its","now","find","long","down","day","did","get","come","made",
                                 "may","cat","dog","cats","dogs"};
   public SpellChecker(String[] newDictionary) {
   dictionary = newDictionary;
   }

   public static void print10(String[] d) {
      for(int i=0; i<10; i++) {
         System.out.println(d[i]);
      }
      System.out.println();
   }

   public boolean spellcheck(String w) {
      boolean found = false;
      for (int i=0; i< dictionary.length; i++) {
         if (w.equals(dictionary[i])) {
            found = true;
         }
      }
      return found;
   }

   public static void main(String[] args) {
      SpellChecker checker = new SpellChecker();
      checker.print10();

      String word = "catz";
      if (checker.spellcheck(word) == true) {
         System.out.println(word + " is spelled correctly!");
      }
      else {
         System.out.println(word + " is misspelled!");
      }
   }
}
</code>```

答:
I am not sure what you are trying to achieve, but if I set your code up like this:

```<code>public class MainClass {

public static void main(String[] args) {
    String[] dictionary = { "the", "of", "and", "to", "in", "is", "you", "that", "it", "he", "was", "for", "on",
            "are", "as", "with", "his", "they", "I", "at", "be", "this", "have", "from", "or", "one", "had", "by",
            "word", "but", "not", "what", "all", "were", "we", "when", "your", "can", "said", "there", "use", "an",
            "each", "which", "she", "do", "how", "their", "if", "will", "up", "other", "about", "out", "many", "then",
            "them", "these", "so", "some", "her", "would", "make", "like", "him", "into", "time", "has", "look", "two",
            "more", "write", "go", "see", "number", "no", "way", "could", "people", "my", "than", "first", "water",
            "been", "call", "who", "oil", "its", "now", "find", "long", "down", "day", "did", "get", "come", "made",
            "may", "cat", "dog", "cats", "dogs" };

    SpellChecker checker = new SpellChecker(dictionary);
    checker.print10();

    String word = "catz";
    if (checker.spellcheck(word) == true) {
        System.out.println(word + " is spelled correctly!");
    } else {
        System.out.println(word + " is misspelled!");
    }
}
}

public class SpellChecker {
private String[] dictionary;

public SpellChecker(String[] newDictionary) {
    dictionary = newDictionary;
}

public void print10() {
    String [] d = this.dictionary;
    for (int i = 0; i < 10; i++) {
        System.out.println(d[i]);
    }
    System.out.println();
}

public boolean spellcheck(String w) {
    boolean found = false;
    for (int i = 0; i < dictionary.length; i++) {
        if (w.equals(dictionary[i])) {
            found = true;
        }
    }
    return found;
}
}
</code>```

It works for me. And it seems to do what it should do.

Body:
I am trying to get the first 10 words from the dictionary list but when I compile the code, I keep getting:

SpellChecker.java:34: error: constructor SpellChecker in class SpellChecker cannot be applied to given types;
SpellChecker checker = new SpellChecker();
^
required: String[]
found:    no arguments
reason: actual and formal argument lists differ in length
I get the same thing for checker.print10(); How do I fix this?

import java.util.Arrays;

public class SpellChecker {
  private String[] dictionary = {"the","of","and","to","in","is","you","that","it","he","was","for","on","are",
                                 "as","with","his","they","I","at","be","this","have","from","or","one","had","by",
                                 "word","but","not","what","all","were","we","when","your","can","said","there","use",
                                 "an","each","which","she","do","how","their","if","will","up","other","about","out","many",
                                 "then","them","these","so","some","her","would","make","like","him","into","time","has","look",
                                 "two","more","write","go","see","number","no","way","could","people","my","than","first","water",
                                 "been","call","who","oil","its","now","find","long","down","day","did","get","come","made",
                                 "may","cat","dog","cats","dogs"};
   public SpellChecker(String[] newDictionary) {
   dictionary = newDictionary;
   }

   public static void print10(String[] d) {
      for(int i=0; i<10; i++) {
         System.out.println(d[i]);
      }
      System.out.println();
   }

   public boolean spellcheck(String w) {
      boolean found = false;
      for (int i=0; i< dictionary.length; i++) {
         if (w.equals(dictionary[i])) {
            found = true;
         }
      }
      return found;
   }

   public static void main(String[] args) {
      SpellChecker checker = new SpellChecker();
      checker.print10();

      String word = "catz";
      if (checker.spellcheck(word) == true) {
         System.out.println(word + " is spelled correctly!");
      }
      else {
         System.out.println(word + " is misspelled!");
      }
   }
}

Body:
I am not sure what you are trying to achieve, but if I set your code up like this:

public class MainClass {

public static void main(String[] args) {
    String[] dictionary = { "the", "of", "and", "to", "in", "is", "you", "that", "it", "he", "was", "for", "on",
            "are", "as", "with", "his", "they", "I", "at", "be", "this", "have", "from", "or", "one", "had", "by",
            "word", "but", "not", "what", "all", "were", "we", "when", "your", "can", "said", "there", "use", "an",
            "each", "which", "she", "do", "how", "their", "if", "will", "up", "other", "about", "out", "many", "then",
            "them", "these", "so", "some", "her", "would", "make", "like", "him", "into", "time", "has", "look", "two",
            "more", "write", "go", "see", "number", "no", "way", "could", "people", "my", "than", "first", "water",
            "been", "call", "who", "oil", "its", "now", "find", "long", "down", "day", "did", "get", "come", "made",
            "may", "cat", "dog", "cats", "dogs" };

    SpellChecker checker = new SpellChecker(dictionary);
    checker.print10();

    String word = "catz";
    if (checker.spellcheck(word) == true) {
        System.out.println(word + " is spelled correctly!");
    } else {
        System.out.println(word + " is misspelled!");
    }
}
}

public class SpellChecker {
private String[] dictionary;

public SpellChecker(String[] newDictionary) {
    dictionary = newDictionary;
}

public void print10() {
    String [] d = this.dictionary;
    for (int i = 0; i < 10; i++) {
        System.out.println(d[i]);
    }
    System.out.println();
}

public boolean spellcheck(String w) {
    boolean found = false;
    for (int i = 0; i < dictionary.length; i++) {
        if (w.equals(dictionary[i])) {
            found = true;
        }
    }
    return found;
}
}

It works for me. And it seems to do what it should do.


问:
CLLocationManager didFailWithError: what error stops location updates
The iOS CLLocationManager reports various errors in its didFailWithError method:
https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CoreLocationConstantsRef/Reference/reference.html#//apple_ref/c/econst/kCLErrorDenied

In the documentation it is not clear which of these error (except kCLErrorDenied and kCLErrorLocationUnknown) stop the location manager and location updates?

Regards,

答:
In my experience, these errors do not stop the location manager. You may however need to handle possible changes in the authorizations by using the function</p>
```<code>func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    // here you call the function where you manage the location authorizations at the launch of the app
}

</code>```

Body:
In my experience, these errors do not stop the location manager. You may however need to handle possible changes in the authorizations by using the function

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    // here you call the function where you manage the location authorizations at the launch of the app
}


问:
How to execute Nested loop in Django Template on single Queryset
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this

But I am unable to to this dynamically with for loop in Django template language. My Template code is

Latest Products

                            {% for product in recent_products %}

{{product.name}}

                                            {{product.price}} Tk

                            {% endfor %}

```
</div>
</div>
</p>
<p>here is my view function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>def index(request):
    products = Product.objects.all()
    categorys = ProductCategory.objects.all()

    today = timezone.now().date()
    last_day = today - timezone.timedelta(days=7)

    today = datetime.strftime(today, "%Y-%m-%d")
    last_day = datetime.strftime(last_day, "%Y-%m-%d")

    print(last_day)
    recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time")
    context = {
        'products': products,
        'categorys': categorys,
        'recent_products': recent_products
    }
    return render(request, 'index.html', context)</code>```

and my model class is:

class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True, null=True)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField(blank=True, null=True)
    ratings = models.FloatField(blank=True, null=True)
    number_of_ratings = models.IntegerField(blank=True, null=True)
    images = models.ImageField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    # user_review need to be added
    discount_rate = models.IntegerField(default=0)
    available_stock = models.IntegerField(default=0)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def discount(self):
        if self.discount_rate > 0:
            discounted_price = self.price - self.price * self.discount_rate / 100
            return discounted_price```

答:
If your view submit a queryset it will be static, if recent_products is a queryset of the three latest products then you can't change it this way.
I guess there are two solutions which you could implement:

If you don't want to show all products then the most easy way to do this is to make a queryset with a limit like 12 products, then you create a slider with 9 hidden products in it and you can show/hide the products on demand. This is still static, but maybe this will already work for you. The problem here is that you have to limit the queryset at some point. If you have a lot of products and you need to load a image for each one, this option will not work.

The other solution is truly dynamic, more efficient but also a bit more complicated. You could do ajax-requests for the product slider. So your view would not submit any products at all. You have to create another view which deals with ajax requests and submits 3 products, according to the page index. It would need some javascript do the requests and replacing the products and keeping track of the current page. The advantage of this is your page would load faster as it does not need to load all the images and product informations which may be never be seen and you could let the customer browse trough all of your products if they want to.

Body:
I want to render my query set data on template with a slider. Each slider will contain 3 product query like this

But I am unable to to this dynamically with for loop in Django template language. My Template code is

Latest Products

                            {% for product in recent_products %}

{{product.name}}

                                            {{product.price}} Tk

                            {% endfor %}

here is my view function:

def index(request):
    products = Product.objects.all()
    categorys = ProductCategory.objects.all()

    today = timezone.now().date()
    last_day = today - timezone.timedelta(days=7)

    today = datetime.strftime(today, "%Y-%m-%d")
    last_day = datetime.strftime(last_day, "%Y-%m-%d")

    print(last_day)
    recent_products = Product.objects.filter(added_time__range=[last_day, today]).order_by("-added_time")
    context = {
        'products': products,
        'categorys': categorys,
        'recent_products': recent_products
    }
    return render(request, 'index.html', context)

and my model class is:

class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True, null=True)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField(blank=True, null=True)
    ratings = models.FloatField(blank=True, null=True)
    number_of_ratings = models.IntegerField(blank=True, null=True)
    images = models.ImageField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    # user_review need to be added
    discount_rate = models.IntegerField(default=0)
    available_stock = models.IntegerField(default=0)
    added_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def discount(self):
        if self.discount_rate > 0:
            discounted_price = self.price - self.price * self.discount_rate / 100
            return discounted_price


问:
Iterate over a union
I have such enum/range:

period: 'UTD' | 'EOM' | 'ETM'

I want to iterate through all options in select:

```<code><select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
    >
        <ng-container *ngFor="let e of period">
            <option [value]="e" [selected]="e === period">
                {{ e }}
            </option>
        </ng-container>
    </select>
</code>```

I need to get HTML  with option per available enum in period range:

UTD
EOM
ETM

How is that possible please?

答:
Unions & string literals have no existence at runtime, therefor you can't iterate over them.

What you can do is : define your union like that

```<code>const Periods =  [ 'UTD' ,'EOM',  'ETM'] as const;
type Period = typeof Periods[number];
</code>```

And you will be able to iterate over Periods

Title: Iterate over a union

Body:
I have such enum/range:

period: 'UTD' | 'EOM' | 'ETM'

I want to iterate through all options in select:

<select
        class="custom-select"
        [value]="period"
        (change)="period=$event.target.value"
    >
        <ng-container *ngFor="let e of period">
            <option [value]="e" [selected]="e === period">
                {{ e }}
            </option>
        </ng-container>
    </select>

I need to get HTML  with option per available enum in period range:

UTD
EOM
ETM

How is that possible please?

Body:
Unions & string literals have no existence at runtime, therefor you can't iterate over them.

What you can do is : define your union like that

const Periods =  [ 'UTD' ,'EOM',  'ETM'] as const;
type Period = typeof Periods[number];

And you will be able to iterate over Periods


问:
How to get value from React Select Form
Sorry for just a basic question, But I'm a little stuck here to find any way to get values from React Select after making a selection.

This is a Simple Selection setup.

```<code>    const selectOptions = [
            { value: 'YES', label: 'Set to Active' },
            { value: 'NO', label: 'Set to Mute' }
       ]

    <Label className='form-label'>Select</Label>
         <Select
            isClearable={false}
            className='react-select'
            classNamePrefix='select'
            options={selectOptions}
            theme={selectThemeColors}
          />
</code>```

I want to get the value against user-selected choice and put it into userChoice content using useState.

```<code>const [userChoice, setUserChoice] = useState("")
</code>```

value can be YES or NO as defined in selectOptions. But how to pass this into userChoice.
I tried using onChange={(e) => setUserChoice(e.target.value)}  But this thing is not working.

Also tried onInputChange={handleInputChange} as suggested in previously asked threads on StackOverflow but not working here.

答:
The onChange callback handler gets called with the whole choice object instead of the event object. Therefore it should be like this.

```<code> <Select
      ...
      ...
      onChange={(choice) => setUserChoice(choice)}
 />
</code>```

If you only intested in YES / NO value, then use,

```<code>onChange={(choice) => setUserChoice(choice.value)}
</code>```

Title: How to get value from React Select Form

Body:
Sorry for just a basic question, But I'm a little stuck here to find any way to get values from React Select after making a selection.

This is a Simple Selection setup.

    const selectOptions = [
            { value: 'YES', label: 'Set to Active' },
            { value: 'NO', label: 'Set to Mute' }
       ]

    Select
         <Select
            isClearable={false}
            className='react-select'
            classNamePrefix='select'
            options={selectOptions}
            theme={selectThemeColors}
          />

I want to get the value against user-selected choice and put it into userChoice content using useState.

const [userChoice, setUserChoice] = useState("")

value can be YES or NO as defined in selectOptions. But how to pass this into userChoice.
I tried using onChange={(e) => setUserChoice(e.target.value)}  But this thing is not working.

Also tried onInputChange={handleInputChange} as suggested in previously asked threads on StackOverflow but not working here.

Body:
The onChange callback handler gets called with the whole choice object instead of the event object. Therefore it should be like this.

 <Select
      ...
      ...
      onChange={(choice) => setUserChoice(choice)}
 />

If you only intested in YES / NO value, then use,

onChange={(choice) => setUserChoice(choice.value)}


问:
btrfs: how to drain one disk in 'single' profile
Assume a multi-device btrfs with data profile single and metadata profile mirrored.
The first disk is almost full.
The second disk is large enough to hold all data of the whole filesystem.

The first disk needs replacement - is there a way to drain the data from the first disk, like e.g. some btrfs balance filter?

There is devid=1 to select data of the first disk only, but how to tell btrf balanceto shift all that data to the second disk?

答:
To remove a device and have its contents transferred to the remaining devices, you can use btrfs device remove ....

To replace a device you can use btrfs replace .... Afterwards you may need to btrfs filesystem resize ....


问:
How to focus on a component's child element from the parent?
I have the a component, with a template like this:

```<code><template>
<div class="referenceparent">
    <input
    v-model="searchterm"
    type="text"
    @input="Search"
    >
    <ul
    >
    <li
        v-for="(res, index) in searcheventresults"
        :key="index"
    >
        {{ res }}
    </li>
    </ul>
</div>
</template>
</code>```

I have a parent using this component like this:

```<code><div class="col-sm-1">
    <input
    id="el1"
    :ref="'DurnRef' + index"
    v-model="editedPrescription[index].durn"
    type="text"
    class="form-control Durn input-sm"
    placeholder="5"
    aria-label="Durn"
    @keyup.enter="DurnSelected(index)"
    >
</div>
<div class="col-sm-2">
    <autocomplete-input
    :ref="'DurnUnitRef' + index"
    placeholder="days"
    arialabel="DurationUnits"
    :searcheventresults="freqresults[index]"
    :defaultterm="editedPrescription[index].freq"
    @changed="(term) => {FreqSearch(term, index)}"
    @selected="(term) => {FreqSelected(term, index)}"
    />
</code>```

What I want to do, it, when I press Enter key on el1, I need to programmatically move focus to the input element in autocomplete-input. I tried adding a ref to autocomplete-input like above, hoping that the reference would propogate to the child input element. But when I called the ref with:

```<code>this.$refs[`DurnUnitRef${index}`].focus();
</code>```

But that does not work. When I checked that object, I found that it does not have a focus method. How can I achieve what I want, i.e focus on a particular element which is a child element of a component, programmatically from the parent in which the component is embedded?

答:
Is hard to get which problem you're experiencing without a working fiddle, but
I noticed two things that can be, or contribute to causing the behaviour.

You are asking to focus the ref attached to the component but your inner component with the input is wrapped inside a div. Doing so, the focus will be called on that div element, and that element does not have a tabindex property set, and divs are not focusable by default.

Another problem cause, is that you are not waiting for nextTick, though it could also be happening that the focus is being set before the DOM content is updated.

I put a fiddle here that explains both concepts. Let me know if this helped

var myApp = new Vue({
  el: '#app',
  data() {
     return {
        focus: false
     }
  },
  methods: {
    switchAndFocus() {
       this.$nextTick(function(){
        this.$refs.toFocus.focus();
        this.focus = true;
       });

    },
  },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<style>

.container {
  padding: 10px;

}
.testing {
     border: solid lightgray 1px;
}
.testing:focus {
     border: solid red 1px;
}
</style>
<div id="app" class="container">
  <div >
  <button @click="switchAndFocus">Click to focus</button>
  <h class="testing"  ref="toFocus" tabindex="1">Is {{!focus ? '' : 'focused'}}
  </div>
</div></code>```

Body:
I have the a component, with a template like this:

<template>

    <input
    v-model="searchterm"
    type="text"
    @input="Search"
    >

        {{ res }}

</template>

I have a parent using this component like this:

    <input
    id="el1"
    :ref="'DurnRef' + index"
    v-model="editedPrescription[index].durn"
    type="text"
    class="form-control Durn input-sm"
    placeholder="5"
    aria-label="Durn"
    @keyup.enter="DurnSelected(index)"
    >

    <autocomplete-input
    :ref="'DurnUnitRef' + index"
    placeholder="days"
    arialabel="DurationUnits"
    :searcheventresults="freqresults[index]"
    :defaultterm="editedPrescription[index].freq"
    @changed="(term) => {FreqSearch(term, index)}"
    @selected="(term) => {FreqSelected(term, index)}"
    />

What I want to do, it, when I press Enter key on el1, I need to programmatically move focus to the input element in autocomplete-input. I tried adding a ref to autocomplete-input like above, hoping that the reference would propogate to the child input element. But when I called the ref with:

this.$refs[`DurnUnitRef${index}`].focus();

But that does not work. When I checked that object, I found that it does not have a focus method. How can I achieve what I want, i.e focus on a particular element which is a child element of a component, programmatically from the parent in which the component is embedded?

Body:
Is hard to get which problem you're experiencing without a working fiddle, but
I noticed two things that can be, or contribute to causing the behaviour.

You are asking to focus the ref attached to the component but your inner component with the input is wrapped inside a div. Doing so, the focus will be called on that div element, and that element does not have a tabindex property set, and divs are not focusable by default.

Another problem cause, is that you are not waiting for nextTick, though it could also be happening that the focus is being set before the DOM content is updated.

I put a fiddle here that explains both concepts. Let me know if this helped

var myApp = new Vue({
  el: '#app',
  data() {
     return {
        focus: false
     }
  },
  methods: {
    switchAndFocus() {
       this.$nextTick(function(){
        this.$refs.toFocus.focus();
        this.focus = true;
       });

    },
  },
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<style>

.container {
  padding: 10px;

}
.testing {
     border: solid lightgray 1px;
}
.testing:focus {
     border: solid red 1px;
}
</style>
<div id="app" class="container">
  <div >
  <button @click="switchAndFocus">Click to focus</button>
  <h class="testing"  ref="toFocus" tabindex="1">Is {{!focus ? '' : 'focused'}}
  </div>
</div>


问:
How do I create an executable fat JAR with Gradle with implementation dependencies?
I've got a simple project in Gradle 4.6 and would like to make an executable JAR of it. I've tried shadow, gradle-fatjar-plugin, gradle-one-jar, spring-boot-gradle-plugin plugins but neither of them adds my dependencies declared as implementation (I don't have any compile ones). It works with compile e.g. for gradle-one-jar plugin but I would like to have implementation dependencies.

答:
previous answers are a little outdated nowadays, see here for something working with gradle-7.4:
How to create a fat JAR with Gradle Kotlin script?</p>
```<code>tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree) // OR .map { zipTree(it) }
    from(dependencies)
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
</code>```

Body:
previous answers are a little outdated nowadays, see here for something working with gradle-7.4:
How to create a fat JAR with Gradle Kotlin script?

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree) // OR .map { zipTree(it) }
    from(dependencies)
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}