问:
Unable to start the mysql server in ubuntu
After running the command
mysql -v in Ubuntu, I am getting the following error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

答:
By default, apt install MariaDB but not mySQL.

```<code>sudo apt install default-mysql-server
</code>```

If you would like to install real mySQL database by apt, follow these steps.

Firstly, we need to remove all preceding mysql installed on the host.

```<code>sudo apt-get --purge autoremove "^mysql.*"
</code>```

Dowload the stable package mysql-apt-config_0.8.15-1_all.deb from

```<code>sudo wget https://dev.mysql.com/get/mysql-apt-config_0.8.15-1_all.deb
</code>```

Install the downloaded release package:

```<code>sudo dpkg -i mysql-apt-config_0.8.15-1_all.deb
</code>```

Refresh your apt package cache to make the new software packages available

```<code>sudo apt update
</code>```

Install MySQL by executing:

```<code>sudo apt-get update
sudo apt-get install mysql-server mysql-client
</code>```
```<code>libmysqlclient-dev
</code>```

Check mysql status:

```<code>sudo service mysql status
</code>```

Body:
By default, apt install MariaDB but not mySQL.

sudo apt install default-mysql-server

If you would like to install real mySQL database by apt, follow these steps.

Firstly, we need to remove all preceding mysql installed on the host.

sudo apt-get --purge autoremove "^mysql.*"

Dowload the stable package mysql-apt-config_0.8.15-1_all.deb from

sudo wget https://dev.mysql.com/get/mysql-apt-config_0.8.15-1_all.deb

Install the downloaded release package:

sudo dpkg -i mysql-apt-config_0.8.15-1_all.deb

Refresh your apt package cache to make the new software packages available

sudo apt update

Install MySQL by executing:

sudo apt-get update
sudo apt-get install mysql-server mysql-client

libmysqlclient-dev

Check mysql status:

sudo service mysql status


来源: stackexchange

问:
How to enable AWS managed key (aws/s3) as a AWS KMS key in S3 encryption
How can i enable AWS managed key (aws/s3) as a AWS KMS key in S3 encryption using cloud formation?
I have the following code but i'm not sure if i should pass the key as an arn</p>
```<code>MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: aws:kms
              KMSMasterKeyID: !GetAtt ARN?
      VersioningConfiguration:
        Status: Enabled
</code>```

答:
You can use server-side encryption with S3-managed keys (SSE-S3) by modifying the Amazon S3 Bucket ServerSideEncryptionByDefault property to specify AES256 for SSEAlgorithm</p>
```<code>MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can i enable AWS managed key (aws/s3) as a AWS KMS key in S3 encryption using cloud formation?
I have the following code but i'm not sure if i should pass the key as an arn

MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: aws:kms
              KMSMasterKeyID: !GetAtt ARN?
      VersioningConfiguration:
        Status: Enabled

Body:
You can use server-side encryption with S3-managed keys (SSE-S3) by modifying the Amazon S3 Bucket ServerSideEncryptionByDefault property to specify AES256 for SSEAlgorithm

MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled


问:
How to read txt file in c# MVC
Hey guys i need to solve this problem and I am completely lost.

In root application create txt file, for example addresses.txt a in there will be dates in format: Name;Path;number_of_days;

2: In method Index load this .txt, where could be 10 rows with addresses. I need to load every row with string.Split separator will be semicolon(;)
This will be load to List object. Then it will go through the foreach and you will go through the individual addresses via File.Getfiles(), where the input parameter is the directory.
your files will be loaded, which you pass and if neither of them is younger than number_of_days, you note the error for this entry

答:
Use this</p>
```<code>var fileContents =
    System.IO.File.ReadAllText(HostingEnvironment.MapPath(@"~/App_Data/file.txt"));
</code>```

Title: How to read txt file in c# MVC

Body:
Use this

var fileContents =
    System.IO.File.ReadAllText(HostingEnvironment.MapPath(@"~/App_Data/file.txt"));


问:
Remove duplicate rows in Google Sheets - Remove rows nearest to the top
I have a Google sheet which is automatically updated with the contents of a gmail attachment each day.

I want to ensure that old duplicate rows are deleted. So the duplicate rows that are closer to the top of the sheet.

I am using the following script to delete duplicates, but unfortunately it deletes the newest rows closest to the bottom.

Any advice would be greatly appreciated.

Thank you

```<code>function removeDuplicates() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Sheet1");
  var vA=sh.getDataRange().getValues();
  var hA=vA[0];
  var hObj={};
  hA.forEach(function(e,i){hObj[e]=i;});//header title to index
  var uA=[];
  var d=0;
  for(var i=0;i<vA.length;i++) {
    if(uA.indexOf(vA[i][hObj['Test Name']])==-1) {
      uA.push(vA[i][hObj['Test Name']]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}
</code>```

答:
Try, assuming the data starts at row 1 (headers)</p>
```<code>function removeDuplicates2() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Sheet1");
  var vA=sh.getDataRange().getValues();
  var col = vA[0].indexOf('Test Name')
  var list = new Map()
  var rows = [];
  vA.reverse().forEach(function(e,i){
    if (list.get(e[col])){rows.push((vA.length-i))}else{list.set(e[col],(vA.length-i))}
  })
  rows.forEach(x => sh.deleteRow(x))
}
</code>```

Body:
I have a Google sheet which is automatically updated with the contents of a gmail attachment each day.

I want to ensure that old duplicate rows are deleted. So the duplicate rows that are closer to the top of the sheet.

I am using the following script to delete duplicates, but unfortunately it deletes the newest rows closest to the bottom.

Any advice would be greatly appreciated.

Thank you

function removeDuplicates() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Sheet1");
  var vA=sh.getDataRange().getValues();
  var hA=vA[0];
  var hObj={};
  hA.forEach(function(e,i){hObj[e]=i;});//header title to index
  var uA=[];
  var d=0;
  for(var i=0;i<vA.length;i++) {
    if(uA.indexOf(vA[i][hObj['Test Name']])==-1) {
      uA.push(vA[i][hObj['Test Name']]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}

Body:
Try, assuming the data starts at row 1 (headers)

function removeDuplicates2() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Sheet1");
  var vA=sh.getDataRange().getValues();
  var col = vA[0].indexOf('Test Name')
  var list = new Map()
  var rows = [];
  vA.reverse().forEach(function(e,i){
    if (list.get(e[col])){rows.push((vA.length-i))}else{list.set(e[col],(vA.length-i))}
  })
  rows.forEach(x => sh.deleteRow(x))
}


问:
Kotlin android app crashes because of coroutines
I'm developing my first app and learning as I go. The app communicates with a URL to fetch data, and sometimes to send data in a POST.
Since my last gradle update to 7.1.1, my app is crashing when I open 2 different activities where such a communication is happening.

Here's the error I'm getting:

```<code>E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.creoconcept.sifoa, PID: 7255
java.lang.IllegalStateException: No activity
    at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1366)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
    at androidx.fragment.app.FragmentManager.dispatchPause(FragmentManager.java:2802)
    at androidx.fragment.app.FragmentController.dispatchPause(FragmentController.java:295)
    at androidx.fragment.app.FragmentActivity.onPause(FragmentActivity.java:366)
    at com.creoconcept.sifoa.DisplayMyQrCode.onPause(DisplayMyQrCode.kt:63)
    at com.creoconcept.sifoa.DisplayMyQrCode$checkCodeScanned$1$run$1.invoke(DisplayMyQrCode.kt:37)
    at com.creoconcept.sifoa.DisplayMyQrCode$checkCodeScanned$1$run$1.invoke(DisplayMyQrCode.kt:26)
    at com.creoconcept.sifoa.Confs$communicateWithSifoaApi$1$1.invokeSuspend(Confs.kt:64)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
</code>```

I/Process: Sending signal. PID: 7255 SIG: 9

It looks like it has something to do with coroutines. I'm used to doing the same type of thing in jQuery, using ajax or $.get(), and don't quite understand this coroutines thing yet. I'm just trying to fetch some JSON from a URL, and it seems to be a much more complicated thing in Kotlin/Android than it is in jQuery.

Here's some of my code:

```<code>fun communicateWithSifoaApi(url:String, callback: (newRef: String) -> Unit){
    CoroutineScope(Dispatchers.Default).launch {
        withContext(Dispatchers.IO) {
            callback(URL(api_url + url).readText())
        }
    }
}
</code>```

Here's how I'm doing POSTs:

```<code>fun sendPostToApi(url:String, dataString:String, callback: (response: String) -> Unit){
    val mURL = URL(api_url + url)
    CoroutineScope(Dispatchers.Default).launch {
        withContext(Dispatchers.IO) {
            with(mURL.openConnection() as HttpURLConnection) {
                requestMethod = "POST"
                val wr = OutputStreamWriter(outputStream)
                wr.write(base64encoding.base64EncodeString(dataString))
                wr.flush()
                BufferedReader(InputStreamReader(inputStream)).use {
                    val response = StringBuffer()
                    var inputLine = it.readLine()
                    while (inputLine != null) {
                        response.append(inputLine)
                        inputLine = it.readLine()
                    }
                    callback(response.toString())
                }
            }
        }
    }
}
</code>```

I used to have GlobalScope.launch here, but after the update I started getting the "delicate API" message so I changed it to CoroutineScope(Dispatchers.Default).launch after some Googleing.
Before that I was using doAsync which seemed the most similar to jQuery's Ajax, but that was deprecated.

There's also an error now in FragmentManager.java, it now since the update says Cannot resolve symbol 'R' for androidx.fragment.R. I don't know if this has something to do with the problem.

I'd appreciate any help. Thanks.

fragment xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".GoToShoppingCartButton">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/goToShoppingCartButton"
        android:layout_width="70sp"
        android:layout_height="70sp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:backgroundTint="@color/buyButtonColor"
        android:clickable="true"
        android:contentDescription="@string/checkout"
        android:src="@drawable/cart"
        android:tint="@color/buyButtonTextColor"
        app:backgroundTint="@color/buyButtonColor"
        app:fabCustomSize="70sp"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</FrameLayout>
</code>```

Fragment .kt file:

```<code>package com.creoconcept.sifoa

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.floatingactionbutton.FloatingActionButton

class GoToShoppingCartButton : Fragment(R.layout.fragment_go_to_shopping_cart_button) {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_go_to_shopping_cart_button, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<FloatingActionButton>(R.id.goToShoppingCartButton).setOnClickListener {
            activity?.let {
                val intent = Intent(it, ShoppingCart::class.java).apply {}
                it.startActivity(intent)
            }
        }
    }

}
</code>```

code in a different activity, where the fragment is called:

```<code>private fun refreshGoToCartButton(){
    val buttonFragment =supportFragmentManager.findFragmentByTag("goToCartButton")
    if(buttonFragment != null) {
        val ft = supportFragmentManager.beginTransaction()
        if (shoppingCartArray.isNotEmpty()) {
            ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).show(buttonFragment).commit()
        } else {
            ft.hide(buttonFragment).commit()
        }
    } else if (shoppingCartArray.isNotEmpty()) {
        supportFragmentManager.commit {
            setReorderingAllowed(true)
            add<GoToShoppingCartButton>(R.id.browseImgsWrapper,"goToCartButton")
        }
    }
}
</code>```

Please note though that the crash happens even when i never even open the activity where this fragment is being used.

答:
ok so it seems to be fixed now. It apparently had nothing to do with the FragmentManager (that Cannot resolve symbol 'R' for androidx.fragment.R error seems to be an IDE error and I've chosen to ignore it..)

one of the lines in the crash report is:

```<code>at com.creoconcept.sifoa.DisplayMyQrCode.onPause(DisplayMyQrCode.kt:63)
</code>```

I was calling the onPause() function in a loop that was checking if the QR code had been scanned every 2 seconds. When it returns true the app is supposed to say "Code scanned" and then return to the main activity. I removed the onPause() call and replaced it with mainHandler.removeCallbacksAndMessages(null) and now it seems to not crash anymore.

Body:
I'm developing my first app and learning as I go. The app communicates with a URL to fetch data, and sometimes to send data in a POST.
Since my last gradle update to 7.1.1, my app is crashing when I open 2 different activities where such a communication is happening.

Here's the error I'm getting:

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.creoconcept.sifoa, PID: 7255
java.lang.IllegalStateException: No activity
    at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1366)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
    at androidx.fragment.app.FragmentManager.dispatchPause(FragmentManager.java:2802)
    at androidx.fragment.app.FragmentController.dispatchPause(FragmentController.java:295)
    at androidx.fragment.app.FragmentActivity.onPause(FragmentActivity.java:366)
    at com.creoconcept.sifoa.DisplayMyQrCode.onPause(DisplayMyQrCode.kt:63)
    at com.creoconcept.sifoa.DisplayMyQrCode$checkCodeScanned$1$run$1.invoke(DisplayMyQrCode.kt:37)
    at com.creoconcept.sifoa.DisplayMyQrCode$checkCodeScanned$1$run$1.invoke(DisplayMyQrCode.kt:26)
    at com.creoconcept.sifoa.Confs$communicateWithSifoaApi$1$1.invokeSuspend(Confs.kt:64)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

I/Process: Sending signal. PID: 7255 SIG: 9

It looks like it has something to do with coroutines. I'm used to doing the same type of thing in jQuery, using ajax or $.get(), and don't quite understand this coroutines thing yet. I'm just trying to fetch some JSON from a URL, and it seems to be a much more complicated thing in Kotlin/Android than it is in jQuery.

Here's some of my code:

fun communicateWithSifoaApi(url:String, callback: (newRef: String) -> Unit){
    CoroutineScope(Dispatchers.Default).launch {
        withContext(Dispatchers.IO) {
            callback(URL(api_url + url).readText())
        }
    }
}

Here's how I'm doing POSTs:

fun sendPostToApi(url:String, dataString:String, callback: (response: String) -> Unit){
    val mURL = URL(api_url + url)
    CoroutineScope(Dispatchers.Default).launch {
        withContext(Dispatchers.IO) {
            with(mURL.openConnection() as HttpURLConnection) {
                requestMethod = "POST"
                val wr = OutputStreamWriter(outputStream)
                wr.write(base64encoding.base64EncodeString(dataString))
                wr.flush()
                BufferedReader(InputStreamReader(inputStream)).use {
                    val response = StringBuffer()
                    var inputLine = it.readLine()
                    while (inputLine != null) {
                        response.append(inputLine)
                        inputLine = it.readLine()
                    }
                    callback(response.toString())
                }
            }
        }
    }
}

I used to have GlobalScope.launch here, but after the update I started getting the "delicate API" message so I changed it to CoroutineScope(Dispatchers.Default).launch after some Googleing.
Before that I was using doAsync which seemed the most similar to jQuery's Ajax, but that was deprecated.

There's also an error now in FragmentManager.java, it now since the update says Cannot resolve symbol 'R' for androidx.fragment.R. I don't know if this has something to do with the problem.

I'd appreciate any help. Thanks.

fragment xml:

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".GoToShoppingCartButton">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/goToShoppingCartButton"
        android:layout_width="70sp"
        android:layout_height="70sp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:backgroundTint="@color/buyButtonColor"
        android:clickable="true"
        android:contentDescription="@string/checkout"
        android:src="@drawable/cart"
        android:tint="@color/buyButtonTextColor"
        app:backgroundTint="@color/buyButtonColor"
        app:fabCustomSize="70sp"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</FrameLayout>

Fragment .kt file:

package com.creoconcept.sifoa

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.floatingactionbutton.FloatingActionButton

class GoToShoppingCartButton : Fragment(R.layout.fragment_go_to_shopping_cart_button) {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_go_to_shopping_cart_button, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<FloatingActionButton>(R.id.goToShoppingCartButton).setOnClickListener {
            activity?.let {
                val intent = Intent(it, ShoppingCart::class.java).apply {}
                it.startActivity(intent)
            }
        }
    }

}

code in a different activity, where the fragment is called:

private fun refreshGoToCartButton(){
    val buttonFragment =supportFragmentManager.findFragmentByTag("goToCartButton")
    if(buttonFragment != null) {
        val ft = supportFragmentManager.beginTransaction()
        if (shoppingCartArray.isNotEmpty()) {
            ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).show(buttonFragment).commit()
        } else {
            ft.hide(buttonFragment).commit()
        }
    } else if (shoppingCartArray.isNotEmpty()) {
        supportFragmentManager.commit {
            setReorderingAllowed(true)
            add<GoToShoppingCartButton>(R.id.browseImgsWrapper,"goToCartButton")
        }
    }
}

Please note though that the crash happens even when i never even open the activity where this fragment is being used.

Body:
ok so it seems to be fixed now. It apparently had nothing to do with the FragmentManager (that Cannot resolve symbol 'R' for androidx.fragment.R error seems to be an IDE error and I've chosen to ignore it..)

one of the lines in the crash report is:

at com.creoconcept.sifoa.DisplayMyQrCode.onPause(DisplayMyQrCode.kt:63)

I was calling the onPause() function in a loop that was checking if the QR code had been scanned every 2 seconds. When it returns true the app is supposed to say "Code scanned" and then return to the main activity. I removed the onPause() call and replaced it with mainHandler.removeCallbacksAndMessages(null) and now it seems to not crash anymore.


问:
How to set DynamicResource value in Setter object in code?
XAML example:

```<code>    <Style x:Key="MyStyle" TargetType="VisualElement">
        <Setter Property="BackgroundColor" Value="{DynamicResource PrimaryColor}" />
    </Style>
</code>```

How to do it in code?

```<code>    Style MyStyle = new Style(typeof(VisualElement))
    {
        Setters =
        {
            new Setter
            {
                Property = BackgroundColorProperty,
                Value = ???
              //Valye = new DynamicResourceExtension { Key = "PrimaryColor" } !!! not working
            }
        }
     }
</code>```

答:
Check Microsoft documentation :

```<code>public class DynamicStylesPageCS : ContentPage
{
    bool originalStyle = true;

    public DynamicStylesPageCS ()
    {
        ...
        var baseStyle = new Style (typeof(View)) {
            ...
        };
        var blueSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        var greenSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        ...
        var searchBar1 = new SearchBar { Placeholder = "These SearchBar controls" };
        searchBar1.SetDynamicResource (VisualElement.StyleProperty, "searchBarStyle");
        ...
        Resources = new ResourceDictionary ();
        Resources.Add ("blueSearchBarStyle", blueSearchBarStyle);
        Resources.Add ("greenSearchBarStyle", greenSearchBarStyle);
        Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];

        Content = new StackLayout {
            Children = { searchBar1, searchBar2, searchBar3, searchBar4,    button    }
        };
    }
    ...
}
</code>```

here

Body:
XAML example:

How to do it in code?

    Style MyStyle = new Style(typeof(VisualElement))
    {
        Setters =
        {
            new Setter
            {
                Property = BackgroundColorProperty,
                Value = ???
              //Valye = new DynamicResourceExtension { Key = "PrimaryColor" } !!! not working
            }
        }
     }

Body:
Check Microsoft documentation :

public class DynamicStylesPageCS : ContentPage
{
    bool originalStyle = true;

    public DynamicStylesPageCS ()
    {
        ...
        var baseStyle = new Style (typeof(View)) {
            ...
        };
        var blueSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        var greenSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        ...
        var searchBar1 = new SearchBar { Placeholder = "These SearchBar controls" };
        searchBar1.SetDynamicResource (VisualElement.StyleProperty, "searchBarStyle");
        ...
        Resources = new ResourceDictionary ();
        Resources.Add ("blueSearchBarStyle", blueSearchBarStyle);
        Resources.Add ("greenSearchBarStyle", greenSearchBarStyle);
        Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];

        Content = new StackLayout {
            Children = { searchBar1, searchBar2, searchBar3, searchBar4,    button    }
        };
    }
    ...
}

here


问:
Jackson writeValueAsString() throws JsonMappingException randomly
Getting random 'com.fasterxml.jackson.databind.JsonMappingException' during serialization of an object. The caused by exception is 'Caused by: java.lang.IndexOutOfBoundsException: Index: 3, Size: 2'

When re-running with same object again multiple times it passes properly without any exception.

```<code>    com.fasterxml.jackson.databind.JsonMappingException: Index: 3, Size: 2 (through reference chain: com.model.DefOperation["arguments"]->java.util.ArrayList[0]->com.model.DefOperation["arguments"]->java.util.ArrayList[0]->com.model.Def["input"]->com.model.DefInput["filter"]->com.model.DefInputExpression["DefInput"]->com.model.DefInput["filter"]->com.model.OperationExpression["operation"]->com.model.ProducerOperation["arguments"]->java.util.ArrayList[3])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:211)
    at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:210)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:105)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:119)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:119)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:35)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2718)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2210)
    at com.model.Executor.copyDatasetDefOperation(Executor.java:235)
Caused by: java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:659)
    at java.util.ArrayList.get(ArrayList.java:435)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:84)
    ... 44 more
</code>```

Have not used any custom serializer

```<code>    ObjectMapper mapper = new ObjectMapper();
    String op = mapper.writeValueAsString(operation);
</code>```

jackson-databind version is 2.4.5

Checked the similar issue: Jackson writeValueAsString() throws JsonMappingException periodically
But there are no date/timestamp attributes in our input object.

答:
I don't know if this will resolve your specific problem, but whether it may or may or may not it might simplify your serializing to Json issue. There is an open source library called MgntUtils that has a class JsonUtils with methods:

```<code>writeObjectToJsonString(java.lang.Object object)
</code>```

and

```<code>readObjectFromJsonString(java.lang.String jsonString, java.lang.Class<T> type)
</code>```

It uses jackson library under the hood anyway. So those are just a wrapper methods for simplifying use for standard and simple cases which usually is the majority of uses. Here is the JavaDoc for the JsonUtils class. The library could be found as Maven artifact and on Github (including source code and Javadoc). Also, it uses newer version of jackson - 2.12.3

Body:
Getting random 'com.fasterxml.jackson.databind.JsonMappingException' during serialization of an object. The caused by exception is 'Caused by: java.lang.IndexOutOfBoundsException: Index: 3, Size: 2'

When re-running with same object again multiple times it passes properly without any exception.

    com.fasterxml.jackson.databind.JsonMappingException: Index: 3, Size: 2 (through reference chain: com.model.DefOperation["arguments"]->java.util.ArrayList[0]->com.model.DefOperation["arguments"]->java.util.ArrayList[0]->com.model.Def["input"]->com.model.DefInput["filter"]->com.model.DefInputExpression["DefInput"]->com.model.DefInput["filter"]->com.model.OperationExpression["operation"]->com.model.ProducerOperation["arguments"]->java.util.ArrayList[3])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:211)
    at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:210)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:105)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:119)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:119)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:492)
    at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:35)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2718)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2210)
    at com.model.Executor.copyDatasetDefOperation(Executor.java:235)
Caused by: java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:659)
    at java.util.ArrayList.get(ArrayList.java:435)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:84)
    ... 44 more

Have not used any custom serializer

    ObjectMapper mapper = new ObjectMapper();
    String op = mapper.writeValueAsString(operation);

jackson-databind version is 2.4.5

Checked the similar issue: Jackson writeValueAsString() throws JsonMappingException periodically
But there are no date/timestamp attributes in our input object.

Body:
I don't know if this will resolve your specific problem, but whether it may or may or may not it might simplify your serializing to Json issue. There is an open source library called MgntUtils that has a class JsonUtils with methods:

writeObjectToJsonString(java.lang.Object object)

and

readObjectFromJsonString(java.lang.String jsonString, java.lang.Class<T> type)

It uses jackson library under the hood anyway. So those are just a wrapper methods for simplifying use for standard and simple cases which usually is the majority of uses. Here is the JavaDoc for the JsonUtils class. The library could be found as Maven artifact and on Github (including source code and Javadoc). Also, it uses newer version of jackson - 2.12.3


问:
What is the Module::Build equivalent to ExtUils::MakeMaker INST_SCRIPT?
I want to convert a project from use of ExtUtils::MakeMaker to Module::Build.
As the Makefile.PL is mostly default and Module::Build::Convert did not work for me (see below) I want to convert it manually but did not find the equivalent of INST_SCRIPT to place the executables in Perl's bin/ directory.

My WriteMakefile looks like this.

```<code>WriteMakefile(
    NAME                => 'Project',
    AUTHOR              => q{Mugen Kenichi <mugen.kenichi@uninets.eu>},
    VERSION_FROM        => 'lib/Project.pm',
    INST_SCRIPT         => 'script/',
    ($ExtUtils::MakeMaker::VERSION >= 6.3002
      ? ('LICENSE'=> 'perl')
      : ()),
    PL_FILES            => {},
    PREREQ_PM => {
        'JSON' => 0,
        'Log::Log4perl' => 0,
        'Proc::Daemon'  => 0,
        'Term::ANSIColor' => 0,
        'MooseX::Declare' => 0.34,
        'MooseX::Log::Log4perl' => 0,
        'Moose::Util::TypeConstraints' => 0,
        'MooseX::Templated::Role' => 0,
        'Template' => 0,
        # for testing
        'Test::More' => 0,
        'MooseX::Params::Validate' => 0,
        'File::Temp' => 0,
        'Sub::Exporter::ForMethods' => 0,
        'Data::Section' => 0,
    },
    dist                => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', },
    clean               => { FILES => 'Project-*' },
);
</code>```

I tried to use Module::Build::Convert but make2build throws errors i could not resolve:

```<code>Variable "$regex" will not stay shared at (re_eval 32) line 1.
Use of uninitialized value $lines[0] in pattern match (m//) at /home/mak/perl5/lib/perl5/Module/Build/Convert.pm line 1305, <DATA> line 1.
</code>```

perl version:

```<code>perl -v

This is perl 5, version 12, subversion 3 (v5.12.3) built for x86_64-linux
</code>```

答:
If that's what your Makefile.PL looks like, leave it like that. Don't switch to Module::Build, which appears to be an abandoneed build system. No one maintains Module::Build anymore, and until Leon Timmermans comes out with the next thing, unless there's some feature in Module::Build you absolutely must have, there's no reason to convert to it.

Having said that though, I create the list of script files and use it as the value for script_files. It's not as nice. See my Build.PL for Unicode::Tussle.

ContentLicense: CC BY-SA 3.0

Body:
I want to convert a project from use of ExtUtils::MakeMaker to Module::Build.
As the Makefile.PL is mostly default and Module::Build::Convert did not work for me (see below) I want to convert it manually but did not find the equivalent of INST_SCRIPT to place the executables in Perl's bin/ directory.

My WriteMakefile looks like this.

WriteMakefile(
    NAME                => 'Project',
    AUTHOR              => q{Mugen Kenichi <mugen.kenichi@uninets.eu>},
    VERSION_FROM        => 'lib/Project.pm',
    INST_SCRIPT         => 'script/',
    ($ExtUtils::MakeMaker::VERSION >= 6.3002
      ? ('LICENSE'=> 'perl')
      : ()),
    PL_FILES            => {},
    PREREQ_PM => {
        'JSON' => 0,
        'Log::Log4perl' => 0,
        'Proc::Daemon'  => 0,
        'Term::ANSIColor' => 0,
        'MooseX::Declare' => 0.34,
        'MooseX::Log::Log4perl' => 0,
        'Moose::Util::TypeConstraints' => 0,
        'MooseX::Templated::Role' => 0,
        'Template' => 0,
        # for testing
        'Test::More' => 0,
        'MooseX::Params::Validate' => 0,
        'File::Temp' => 0,
        'Sub::Exporter::ForMethods' => 0,
        'Data::Section' => 0,
    },
    dist                => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', },
    clean               => { FILES => 'Project-*' },
);

I tried to use Module::Build::Convert but make2build throws errors i could not resolve:

Variable "$regex" will not stay shared at (re_eval 32) line 1.
Use of uninitialized value $lines[0] in pattern match (m//) at /home/mak/perl5/lib/perl5/Module/Build/Convert.pm line 1305, <DATA> line 1.

perl version:

perl -v

This is perl 5, version 12, subversion 3 (v5.12.3) built for x86_64-linux


问:
Access Json object name
I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView.
Below is my viewsets and generics code:</p>
```<code>class TestList(viewsets.ViewSet):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

class TestList(generics.RetriveAPIView):
    queryset = Test.objects.all()
    serializer_class = TestSerializer
</code>```

答:
```<code>class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})
</code>```

change your urls.py like this.

```<code>path(r"url", TestList.as_view({"get": "list"}))
</code>```

Title: Access Json object name

Body:
I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView.
Below is my viewsets and generics code:

class TestList(viewsets.ViewSet):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

class TestList(generics.RetriveAPIView):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

Body:
class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

change your urls.py like this.

path(r"url", TestList.as_view({"get": "list"}))


问:
How to instantiate an Agent via code in Anylogic
I'm having an issue with Anylogic: I'm writing a function where I need to declare a new item of the type of an already existing Agent type.
If I declare it with the code:

MyAgent name = new MyAgent();

everything is ok but when I try to execute a function to change the value of an internal value,

name.func();

it gives me a NullPointerException, because the internal variable of the declared MyAgent seems not to exist.
What am I missing?
Thanks a lot in advance for your help

答:
When you have a population use the add_myAgents() method, but if you don't want to use a defined population you have to do this:

```<code>MyAgent m=new MyAgent();
m.createAndStart(anyAgent);
m.lognormal(0.1,0.1,5);
</code>```

createAndStart does the magic for you.

anyAgent can be actually any existing agent of your model (for example main), the population will still be created in the default population of your top-level agent, no matter what you put in there.

Body:
When you have a population use the add_myAgents() method, but if you don't want to use a defined population you have to do this:

MyAgent m=new MyAgent();
m.createAndStart(anyAgent);
m.lognormal(0.1,0.1,5);

createAndStart does the magic for you.

anyAgent can be actually any existing agent of your model (for example main), the population will still be created in the default population of your top-level agent, no matter what you put in there.


问:
react-native not updating MapView initialRegion with react-native-geolocation-service
I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?</p>
```<code>  const [location, setLocation] = useState({
    initialPosition: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    },
  });

  const getLocationPermissions = async () => {
    const granted = await request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      }),
      {
        title: 'DemoApp',
        message: 'App would like access to your location ',
      }
    );

    return granted === RESULTS.GRANTED;
  };

  useEffect(() => {
    //  check permission
    const isGranted = getLocationPermissions();

    if (isGranted) {
   // get location
      Geolocation.getCurrentPosition((info) => {
        let lat = info.coords.latitude;
        let long = info.coords.longitude;
   // update state with location,latitude: 52.62869394486038
   //longitude: -1.9794797216434805
        var initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
      });
    } else {
      console.log('error');
    }
  }, []);

  return (
    <View style={styles.container}>
      <MapView style={styles.map} initialRegion={location.initialPosition} />
    </View>
  );
</code>```

答:
I am guessing you are using react-native-maps MapView Component, it has a showsUserLocation boolean property.

```<code><MapView
style={styles.map}
showsUserLocation={true}
initialRegion={location.initialPosition}
/>
</code>```

Perhaps this would resolve it?

Body:
I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?

  const [location, setLocation] = useState({
    initialPosition: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    },
  });

  const getLocationPermissions = async () => {
    const granted = await request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      }),
      {
        title: 'DemoApp',
        message: 'App would like access to your location ',
      }
    );

    return granted === RESULTS.GRANTED;
  };

  useEffect(() => {
    //  check permission
    const isGranted = getLocationPermissions();

    if (isGranted) {
   // get location
      Geolocation.getCurrentPosition((info) => {
        let lat = info.coords.latitude;
        let long = info.coords.longitude;
   // update state with location,latitude: 52.62869394486038
   //longitude: -1.9794797216434805
        var initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
      });
    } else {
      console.log('error');
    }
  }, []);

  return (
    <View style={styles.container}>
      <MapView style={styles.map} initialRegion={location.initialPosition} />
    </View>
  );

Body:
I am guessing you are using react-native-maps MapView Component, it has a showsUserLocation boolean property.

<MapView
style={styles.map}
showsUserLocation={true}
initialRegion={location.initialPosition}
/>

Perhaps this would resolve it?


问:
Non English letters was not copied properly using BCP copy
I'm trying to copy csv to database table using bcp command. It's successfully copied, but the problem is non-English letters was migrated as some junk characters.

BCP query:

```<code>bcp "[table_name]" in "[file_path]" -F 1 -a 32768 -c -C RAW -t"|~|" -r "|\n|" -S "[server]" -U "[username]" -P "[password]" -d [database]
</code>```

after migration

This is the source

Another Scenario:

When I use -C 65001 instead of -C RAW above issue is fixed. But I've fixed another bug that is opened again. Please help me on the same.

Source: enter image description here
AfterMigration: enter image description here

答:
I've found the solution to my problem.
Previously I've used text and nvarchar data types in my destination tables.
using -C 65001 the non English letters migrated properly for nvarchar columns not for text datatype.
using -C RAW the non English letters migrated properly for text columns not for nvarchar datatype.

Body:
I'm trying to copy csv to database table using bcp command. It's successfully copied, but the problem is non-English letters was migrated as some junk characters.

BCP query:

bcp "[table_name]" in "[file_path]" -F 1 -a 32768 -c -C RAW -t"|~|" -r "|\n|" -S "[server]" -U "[username]" -P "[password]" -d [database]

after migration

This is the source

Another Scenario:

When I use -C 65001 instead of -C RAW above issue is fixed. But I've fixed another bug that is opened again. Please help me on the same.

Source: enter image description here
AfterMigration: enter image description here


问:
how to self signed a pdf with x509 certificat file in node JS framework
I need to self signed a pdf  with x509 certificat file in node JS framework  but i don't find any useful package in npm to install it</p>

答:
This similar question How to sign PDF with a x.509 signature/certificate has some answers suggesting to use openssl at the command line. This could be done with a microservice and an exec  type command using either node or python for example.

This type of feature is much better done as a microservice, as it allows you to swap out the functionality with another/better service at a later date. As long as you maintain the same API in the microservice, changes will be transparent to your main application


问:
Refresh access_token via refresh_token in Keycloak
I need to make the user keep login in the system if the user's access_token get expired and user want to keep login. How can I get newly updated access_token with the use of refresh_token on Keycloak?

I am using vertx-auth for the auth implementation with Keycloak on vert.x. Is it possible to refresh access_token with vertx-auth or Keycloak's REST API itself? Or what will be another implementation of this?

答:
Extending Yogendra Mishra's answer. Note that
client_id and client_secret can also be sent in Authorization header.

```<code>Authorization: Basic ${Base64(<client_id>:<client_secret>)}
</code>```

This works for both initial token call (without refresh token) and refresh token call to /openid-connect/token endpoint

Reference:
https://developer.okta.com/docs/reference/api/oidc/#client-secret

Body:
Extending Yogendra Mishra's answer. Note that
client_id and client_secret can also be sent in Authorization header.

Authorization: Basic ${Base64(<client_id>:<client_secret>)}

This works for both initial token call (without refresh token) and refresh token call to /openid-connect/token endpoint

Reference:
https://developer.okta.com/docs/reference/api/oidc/#client-secret


问:
Default start value for picker
I want to have blank value in my picker when I start the app(before I make selection).

Currently when I launch my app picker shows Value1 in the box. Here is my List that I bind with Picker:

private List<string> _PickerValueBind = new List<string>() {"Value1", "Value2"};

And the xaml:

```<code><Picker  ItemsSource="{Binding PickerValueBind}"  HorizontalOptions="FillAndExpand" IsEnabled="{Binding PickerEnabledBind}" SelectedIndex="{Binding PickerIndexBind}">
      <Picker.Behaviors>
           <prism:EventToCommandBehavior
                  EventName="SelectedIndexChanged"
                  Command="{Binding IndexChangedBind}" />
      </Picker.Behaviors>
</Picker>
</code>```

I tried using Picker.Title but it didn't work as desired. Also tried adding empty item as first item but in the end I don't want user to have option to pick empty value.

答: Set value of PickerIndexBind = -1 in viewmodel

Title: Default start value for picker

Body:
I want to have blank value in my picker when I start the app(before I make selection).

Currently when I launch my app picker shows Value1 in the box. Here is my List that I bind with Picker:

private List<string> _PickerValueBind = new List<string>() {"Value1", "Value2"};

And the xaml:

<Picker  ItemsSource="{Binding PickerValueBind}"  HorizontalOptions="FillAndExpand" IsEnabled="{Binding PickerEnabledBind}" SelectedIndex="{Binding PickerIndexBind}">
      <Picker.Behaviors>
           <prism:EventToCommandBehavior
                  EventName="SelectedIndexChanged"
                  Command="{Binding IndexChangedBind}" />
      </Picker.Behaviors>
</Picker>

I tried using Picker.Title but it didn't work as desired. Also tried adding empty item as first item but in the end I don't want user to have option to pick empty value.


问:
How to take a screen capture of a hidden/partially hidden window with Python
I'm trying to create a Python program that takes screen capture of a specific window that is hidden/partialy hidden by other windows. I've searched for code on the web but none of them seems to work with Windows 11 & Python 3.8+. What is the simplest way of doing this?

Like this if possile

答: If a window is hidden it doesn't get rendered, so there is nothing to take a screenshot of.</p>


问:
How to convert Model.updateOne() to Model.findOne() first then Model.set() then Model.save()
I have a mongodb People document like this:

```<code>[
 {
    _id: "1234567890",
    name: "El Wood",
    jobs: [
       {
          _id: "job1",
          title: "teacher"
       },
       {
          _id: "job2",
          title: "programmer"
       }

    ]
 },
 ...
]
</code>```

I want to update (update one) job1 title from teacher to lecturer.

Im using express and mongoose.

My first method is:

```<code>await People.updateOne({ "jobs._id": "job1" }, { $set: { "jobs.$.title": "lecturer" } });
</code>```

And code above is work.

My second method is findOne() first, than set(), than save():

```<code>const peopleToUpdate = await People.findOne({ "jobs._id": "job1" }) //
peopleToUpdate.set({ "jobs.$.title": "lecturer" })
peopleToUpdate.save()
</code>```

but the second method its doesn't work, the job1 title is not changing.

how to update the job1 title using second method way?

答:
That's happened because you're using asynchronous.
To able use the second method you need to use promises

```<code>const peopleToUpdate = await People.findOne({ 'jobs._id': 'job1' })
    .then(function (doc) {
        doc.title = 'lecturer';
        return doc.save();
    })
    .then(console.log)
    .catch(function (err) {
        handleError(err);
    });
</code>```

Please read these docs as your references

https://mongoosejs.com/docs/async-await.html#basic-use
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Body:
I have a mongodb People document like this:

[
 {
    _id: "1234567890",
    name: "El Wood",
    jobs: [
       {
          _id: "job1",
          title: "teacher"
       },
       {
          _id: "job2",
          title: "programmer"
       }

    ]
 },
 ...
]

I want to update (update one) job1 title from teacher to lecturer.

Im using express and mongoose.

My first method is:

await People.updateOne({ "jobs._id": "job1" }, { $set: { "jobs.$.title": "lecturer" } });

And code above is work.

My second method is findOne() first, than set(), than save():

const peopleToUpdate = await People.findOne({ "jobs._id": "job1" }) //
peopleToUpdate.set({ "jobs.$.title": "lecturer" })
peopleToUpdate.save()

but the second method its doesn't work, the job1 title is not changing.

how to update the job1 title using second method way?

Body:
That's happened because you're using asynchronous.
To able use the second method you need to use promises

const peopleToUpdate = await People.findOne({ 'jobs._id': 'job1' })
    .then(function (doc) {
        doc.title = 'lecturer';
        return doc.save();
    })
    .then(console.log)
    .catch(function (err) {
        handleError(err);
    });

Please read these docs as your references

https://mongoosejs.com/docs/async-await.html#basic-use
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


问:
How to remove multiple non-siblings elements from array by indexes within one pass?
Array.prototype.splice() allows to remove multiple elements from array but if and only if theese elements are siblings. But what if no?

Suppose, we need to remove 2th, 5th and 8th elements from array (cont from 0).

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (const [ index, element ] of targetArray.entries()) {

    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        // remove
    }

}
```
<p>Once we removed one element, the array will change and 5th element will not be 5th anymore.</p>
<p>Other approach is make elements empty first, and then remove empty elements:</p>
<pre class="lang-js prettyprint-override"><code>for (const i = 0; i < targetArray.length; i++)  {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(i)) {
        delete targetArray[i]
    }
}

for (const [ index, element ] of targetArray.entries()) {
    if (typeof element === "undefined") {
        targetArray.splice[index, 1]
    }
}
</code>```

But this methodology does not match with "one pass" requirement and also will delete the element which had
"undefined" value initially.

答:
sort indexesOfArrayElementWhichMustBeRemoved desc then loop and splice

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

indexesOfArrayElementWhichMustBeRemoved.sort((a,b)=>atargetArray.splice(v,1))

console.log(targetArray)```

Body:
Array.prototype.splice() allows to remove multiple elements from array but if and only if theese elements are siblings. But what if no?

Suppose, we need to remove 2th, 5th and 8th elements from array (cont from 0).

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

for (const [ index, element ] of targetArray.entries()) {

    if (indexesOfArrayElementWhichMustBeRemoved.includes(index)) {
        // remove
    }

}

Once we removed one element, the array will change and 5th element will not be 5th anymore.

Other approach is make elements empty first, and then remove empty elements:

for (const i = 0; i < targetArray.length; i++)  {
    if (indexesOfArrayElementWhichMustBeRemoved.includes(i)) {
        delete targetArray[i]
    }
}

for (const [ index, element ] of targetArray.entries()) {
    if (typeof element === "undefined") {
        targetArray.splice[index, 1]
    }
}

But this methodology does not match with "one pass" requirement and also will delete the element which had
"undefined" value initially.

Body:
sort indexesOfArrayElementWhichMustBeRemoved desc then loop and splice

const targetArray = [ "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india" ];
const indexesOfArrayElementWhichMustBeRemoved = [ 2, 5, 8 ];

indexesOfArrayElementWhichMustBeRemoved.sort((a,b)=>a<b).forEach((v)=>targetArray.splice(v,1))

console.log(targetArray)


问:
Re: Regex Question (Help)
I am new here. I just discovered this tool "Everything Search Engine". It allows the use of regex in the search. I posted in their forum for a bit help here http://forum.voidtools.com/viewtopic.php?f=5&t=1343. This section explains how regex can be used in the tool http://www.voidtools.com/faq.php#How_do_I_use_regex.

The question I am asking is:

What is the correct regex to use in the search to obtain the desired results describe below.

For example, I am searching for the word "dog" in the file name. And it returns a result "Pseudogout" which is a file name.

Notice the word "dog" is inside the word "Pseudogout".

How do I use the regex to eliminate such results?

I would appreciate some help here.

Thanks.

答:
Use anchors: ^dog$. The caret matches the beginning of a string, and the dollar sign, the end.

If you want to match the string "dog" inside another string, but not inside another word, you might be able to use something like ^dog$|^dog[^A-Za-z]|[^A-Za-z]dog[^A-Za-z]|[^A-Za-z]dog$ but that is obviously somewhat cumbersome to type and use.

(This subsumes some information from the comments below.)

Title: Re: Regex Question (Help)


问:
Maven docker cache dependencies
I'm trying to use docker to automate maven builds. The project I want to build takes nearly 20 minutes to download all the dependencies, so I tried to build a docker image that would cache these dependencies, but it doesn't seem to save it. My Dockerfile is

```<code>FROM maven:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD pom.xml /usr/src/app
RUN mvn dependency:go-offline
</code>```

The image builds, and it does download everything. However, the resulting image is the same size as the base maven:alpine image, so it doesn't seem to have cached the dependencies in the image. When I try to use the image to mvn compile it goes through the full 20 minutes of redownloading everything.

Is it possible to build a maven image that caches my dependencies so they don't have to download everytime I use the image to perform a build?

I'm running the following commands:

```<code>docker build -t my-maven .

docker run -it --rm --name my-maven-project -v "$PWD":/usr/src/mymaven -w /usr/src/mymaven my-maven mvn compile
</code>```

My understanding is that whatever RUN does during the docker build process becomes part of the resulting image.

答:
I had to deal with the same issue.

Unfortunately, as just said by another contributor, dependency:go-offline and the other goals, don't fully solve the problem: many dependencies are not downloaded.

I found a working solution as follow.

```<code># Cache dependencies

ADD settings.xml .
ADD pom.xml .

RUN mvn -B -s settings.xml -Ddocker.build.skip=true package test

# Build artifact

ADD src .
RUN mvn -B -s settings.xml -DskipTests package
</code>```

The trick is to do a full build without sources, which produces a full dependency scan.

In order to avoid errors on some plugins (for example: OpenAPI maven generator plugin or Spring Boot maven plugin) I had to skip its goals, but letting it to download all the dependencies by adding for each one a configuration settings like follow:

<configuration>
    <skip>${docker.build.skip}</skip>
</configuration>
```

Regards.

Title: Maven docker cache dependencies

Body:
I'm trying to use docker to automate maven builds. The project I want to build takes nearly 20 minutes to download all the dependencies, so I tried to build a docker image that would cache these dependencies, but it doesn't seem to save it. My Dockerfile is

FROM maven:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD pom.xml /usr/src/app
RUN mvn dependency:go-offline

The image builds, and it does download everything. However, the resulting image is the same size as the base maven:alpine image, so it doesn't seem to have cached the dependencies in the image. When I try to use the image to mvn compile it goes through the full 20 minutes of redownloading everything.

Is it possible to build a maven image that caches my dependencies so they don't have to download everytime I use the image to perform a build?

I'm running the following commands:

docker build -t my-maven .

docker run -it --rm --name my-maven-project -v "$PWD":/usr/src/mymaven -w /usr/src/mymaven my-maven mvn compile

My understanding is that whatever RUN does during the docker build process becomes part of the resulting image.

Body:
I had to deal with the same issue.

Unfortunately, as just said by another contributor, dependency:go-offline and the other goals, don't fully solve the problem: many dependencies are not downloaded.

I found a working solution as follow.

# Cache dependencies

ADD settings.xml .
ADD pom.xml .

RUN mvn -B -s settings.xml -Ddocker.build.skip=true package test

# Build artifact

ADD src .
RUN mvn -B -s settings.xml -DskipTests package

The trick is to do a full build without sources, which produces a full dependency scan.

In order to avoid errors on some plugins (for example: OpenAPI maven generator plugin or Spring Boot maven plugin) I had to skip its goals, but letting it to download all the dependencies by adding for each one a configuration settings like follow:

<configuration>
    <skip>${docker.build.skip}</skip>
</configuration>

Regards.


答:
So something like this?

```<code>for c in df.columns:
    if c != 'Date':
        df[c] = df[c]/df[c][0]
</code>```

This will iterate every column of the dataframe except for Date, and will divide it by the value of the corresponding column of the first row.

Title: I want normalize data by dividing every row by the price on the first row

Body:
I have a dataframe in pandas. I want to normalize my Close column by dividing every row by the price on the first row. This is my attempt:

import pandas as pd
import yfinance as yf

bova=yf.download('BOVA11.SA',
                 start='2014-01-01',
                 end='2021-12-31',
                 progress=False,
                 )
bova

output:

              Open          High     Low          Close     Adj Close   Volume
Date
2014-01-02  50.220001   50.270000   49.060001   49.080002   49.080002   1001210
2014-01-03  49.099998   49.470001   49.049999   49.259998   49.259998   1227270
2014-01-06  49.259998   49.990002   49.200001   49.840000   49.840000   702060
2014-01-07  49.549999   50.290001   49.230000   49.230000   49.230000   1304100
2014-01-08  49.540001   49.590000   49.209999   49.279999   49.279999   951950
... ... ... ... ... ... ...
2021-12-23  101.599998  101.599998  100.709999  100.849998  100.849998  5047637
2021-12-27  101.400002  101.800003  100.949997  101.599998  101.599998  5274352
2021-12-28  101.830002  101.830002  100.589996  101.059998  101.059998  7167734
2021-12-29  101.239998  101.349998  99.940002   100.250000  100.250000  7343838
2021-12-30  100.809998  101.449997  100.290001  100.800003  100.800003  3404622

Body:
So something like this?

for c in df.columns:
    if c != 'Date':
        df[c] = df[c]/df[c][0]

This will iterate every column of the dataframe except for Date, and will divide it by the value of the corresponding column of the first row.


问:
conversion EPSG3035 to EPSG3857 Mercator or 4326 LonLat
Working directly in JavaScript on a geojson file, I could not find any easy way to transform my coordinates from EPSG3035 to geographic (Lon,Lat). By easy I mean: not installing another software like QGIS or similar. I have tried proj4, and ol, but both failed.

I have no clue. [the OL solution is in "t.niese" answer below]

let coordinates = [4035675.373507705517113, 2862363.090465864632279]; // Luxembourg
console.log(coordinates);
// a "well-known text" WKT-OGC definition from https://epsg.io/3035
const WKT3035 = `PROJCS["ETRS89 / LAEA Europe",GEOGCS["ETRS89",DATUM["European_Terrestrial_Reference_System_1989",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6258"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4258"]],PROJECTION["Lambert_Azimuthal_Equal_Area"],PARAMETER["latitude_of_center",52],PARAMETER["longitude_of_center",10],PARAMETER["false_easting",4321000],PARAMETER["false_northing",3210000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","3035"]]`;
// trying OpenLayers
try {
  const fromLonLat = ol.proj.getTransform("EPSG:3035", "EPSG:4326");
  coordinates = fromLonLat(coordinates);
  console.log("using ol.proj", coordinates);
} catch (err) {
  console.error(err)
}
try {  // trying proj4
    coordinates = [4035675.373507705517113, 2862363.090465864632279];
    const srcProj = new proj4.Proj(WKT3035);
    proj4(srcProj).inverse(coordinates);
  console.log("using proj4", coordinates);
} catch (err) {
  console.error(err)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.8.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.5/proj4.js"></script></code>```

答:
The errors you get is because proj4 does not know the projection EPSG:3035

If you run console.log(proj4.defs('EPSG:3035')) you can see that it returns undefined.

console.log(proj4.defs('EPSG:3035'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.8.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.5/proj4.js"></script></code>```

If you only used proj4 you can just define the projection using:

```<code>proj4.defs("EPSG:3035", /* here goes the definition of that projection */);
</code>```

Using proj4.defs(name, definition) does not return anything, it defines the projection with that name so that it can be used with that name. After you defined the projection you can use proj4.defs(name) to get it.

If for OpenLayer you also need to register proj4 after that:

```<code>proj4.defs("EPSG:3035", /* here goes the definition of that projection */);
ol.proj.proj4.register(proj4);
</code>```

The definition for proj4 should be +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs (Source https://epsg.io/3035)

proj4.defs("EPSG:3035", '+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
ol.proj.proj4.register(proj4);

let coordinates = [4035675.373507705517113, 2862363.090465864632279]; // Luxembourg
console.log(coordinates);
try {
  // trying OpenLayers
  const fromLonLat = ol.proj.getTransform("EPSG:3035", "EPSG:4326");
  console.dir(fromLonLat(coordinates));
} catch (err) {
  console.error(err)
}

try {
  // trying proj4
  console.dir(proj4(proj4.defs('EPSG:3035'), proj4.defs('EPSG:4326'), coordinates));
} catch (err) {
  console.error(err)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.8.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.5/proj4.js"></script></code>```

Body:
The errors you get is because proj4 does not know the projection EPSG:3035

If you run console.log(proj4.defs('EPSG:3035')) you can see that it returns undefined.

console.log(proj4.defs('EPSG:3035'))

<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.8.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.5/proj4.js"></script>

If you only used proj4 you can just define the projection using:

proj4.defs("EPSG:3035", /* here goes the definition of that projection */);

Using proj4.defs(name, definition) does not return anything, it defines the projection with that name so that it can be used with that name. After you defined the projection you can use proj4.defs(name) to get it.

If for OpenLayer you also need to register proj4 after that:

proj4.defs("EPSG:3035", /* here goes the definition of that projection */);
ol.proj.proj4.register(proj4);

The definition for proj4 should be +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs (Source https://epsg.io/3035)

proj4.defs("EPSG:3035", '+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs');
ol.proj.proj4.register(proj4);

let coordinates = [4035675.373507705517113, 2862363.090465864632279]; // Luxembourg
console.log(coordinates);
try {
  // trying OpenLayers
  const fromLonLat = ol.proj.getTransform("EPSG:3035", "EPSG:4326");
  console.dir(fromLonLat(coordinates));
} catch (err) {
  console.error(err)
}

try {
  // trying proj4
  console.dir(proj4(proj4.defs('EPSG:3035'), proj4.defs('EPSG:4326'), coordinates));
} catch (err) {
  console.error(err)
}

<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.8.1/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.7.5/proj4.js"></script>


问:
libpng warning: cHRM: invalid chromaticities
I did not find anything useful on the docs and on the web to solve this warning. I am using the library in Python only to load few png images, nothing more than load and show them on teh screen. Everything works perfectly apart this annoying warning:

libpng warning: cHRM: invalid chromaticities

This is the offending code:

p.s. CARDICON_1 ... _6 are png images.

def drawIcon(shape, color, boxx, boxy):
    quarter = int(BOXSIZE * 0.25)
    half =    int(BOXSIZE * 0.5)
    half = half
    quarter = quarter
    half = 0
    quarter = 0

    left, top = leftTopCoordsOfBox(boxx, boxy) # get pixel coords from board coords
    # Draw the shapes
    # ALLSHAPES = (CANE, CAPRETTA, GALLINA, MAIALINO, RICCIO, TOPO)
    if shape == CARD1:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        cane = pygame.image.load(CARDICON_1)
        DISPLAYSURF.blit(cane, (left, top))
    elif shape == CARD2:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        capretta = pygame.image.load(CARDICON_2)
        DISPLAYSURF.blit(capretta, (left, top))
    elif shape == CARD3:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        gallina = pygame.image.load(CARDICON_3)
        DISPLAYSURF.blit(gallina, (left, top))
    elif shape == CARD4:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        maialino = pygame.image.load(CARDICON_4)
        DISPLAYSURF.blit(maialino, (left, top))
    elif shape == CARD5:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        riccio = pygame.image.load(CARDICON_5)
        DISPLAYSURF.blit(riccio, (left, top))
    elif shape == CARD6:
        pygame.draw.rect(DISPLAYSURF, color, pygame.Rect(left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half), 0, EDGERADIUS)
        topo = pygame.image.load(CARDICON_6)
        DISPLAYSURF.blit(topo, (left, top))
#--------------------------------------------------------------------------
```

答:
Summary of comments:...

You should be able to find issues/problems with corrupt/incorrect PNG files using:

```<code>pngcheck -v -v UNHAPPY.PNG
</code>```

You may be able to repair corrupt/incorrect PNG files with:

```<code>pngcrush -fix UNHAPPY.PNG
</code>```

You may be able to remove chunks of PNG files using:

```<code>pngcrush -rem CHUNKNAME UNHAPPY.PNG
</code>```

Body:
Summary of comments:...

You should be able to find issues/problems with corrupt/incorrect PNG files using:

pngcheck -v -v UNHAPPY.PNG

You may be able to repair corrupt/incorrect PNG files with:

pngcrush -fix UNHAPPY.PNG

You may be able to remove chunks of PNG files using:

pngcrush -rem CHUNKNAME UNHAPPY.PNG


问:
Dismiss a confirm / alert dialog from a javascript bookmarklet
I want to use a bookmarklet to fill up a form and click the submit button on a webpage (I have no control over the webpage content).
After the submit button is pressed, there is a popup confirmation box where I have to click OK . This last step breaks the automation. How do I automatically dismiss the popup from the bookmarklet (javascript) ?

答:
If your dialog is an alert dialog (usually, it has OK and Cancel buttons), you could override the confirm() method to always return true, which is what happens when you click OK:

```<code>window.confirm = function(){return true;};
</code>```

If your dialog is an alert dialog (usually, it has only an OK button), you need to override the alert() method to just return nothing (undefined):

```<code>window.alert = function(){};
</code>```

They must be set before the confirm() or alert() methods are called by the webpage.

Body:
If your dialog is an alert dialog (usually, it has OK and Cancel buttons), you could override the confirm() method to always return true, which is what happens when you click OK:

window.confirm = function(){return true;};

If your dialog is an alert dialog (usually, it has only an OK button), you need to override the alert() method to just return nothing (undefined):

window.alert = function(){};

They must be set before the confirm() or alert() methods are called by the webpage.


问:
How to call specific array values in v-for in Vuejs?
User.vue

<template>

      {{ item }}

</template>

```

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

答:
I guess you need to return an Array on that computed property. Use filter instead of find.</p>
```<code> computed: {
    user: function () {
      return this.lists.filter((item) => {
        if(item.cmd_id === this.$route.params.id) {
           return item
        }
      })
    }
 }
</code>```

Body:
User.vue

<template>

      {{ item }}

</template>

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

Body:
I guess you need to return an Array on that computed property. Use filter instead of find.

 computed: {
    user: function () {
      return this.lists.filter((item) => {
        if(item.cmd_id === this.$route.params.id) {
           return item
        }
      })
    }
 }


问:
LateInitializationError SharedPreferences
I am trying to make a singleton of sharedpreferences, but I get a failure of not initialized

(LateError (LateInitializationError: Field 'prefs' has not been initialized.)).

I don't know what could be wrong. I suppose that it could be for the late of SharedPreferences.dart, or it lacks somewhere to define the initialization?

Personaje_home.dart

```<code>class PersonajeHomePage extends StatefulWidget {
  const PersonajeHomePage({Key? key}) : super(key: key);

  @override
  State<PersonajeHomePage> createState() => _PersonajeHomePageState();
}

class _PersonajeHomePageState extends State<PersonajeHomePage> {
  @override
  Widget build(BuildContext context) {
    var estiloTexto = EstiloTextos();
    final proPersonaje = Provider.of<PersonajeProvider>(context);

    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Text(proPersonaje.leerLvLPersonaje.toString()),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

SharedPreferences.dart

```<code>class SharedPrefsPersonaje {
  static final SharedPrefsPersonaje _instancia = SharedPrefsPersonaje._internal();

  factory SharedPrefsPersonaje() {
    return _instancia;
  }
  SharedPrefsPersonaje._internal();

  late SharedPreferences prefs;
  initPrefs() async {
    prefs = await SharedPreferences.getInstance();
  }

  int get readExpPersonaje {
    return prefs.getInt("experiencia_personaje") ?? 0;
  }

  set saveExpPersonaje(int value) {
    prefs.setInt("experiencia_personaje", value);
  }

  int get readLvLPersonaje {
    return prefs.getInt("nivel_personaje") ?? 0;
  }

  set saveLvLPersonaje(int value) {
    prefs.setInt("nivel_personaje", value);
  }

  void eliminar() {
    prefs.clear();
  }
}
</code>```

main.dart

```<code>void main() {
  inicializamosCargaDatos();
  runApp(AppState());
}

class AppState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        //Cargamos datos del JSON, servidor
        ChangeNotifierProvider(
          create: (_) => PersonajeProvider(),
          lazy: false,
        ),
      ],
      child: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: "My APP",
      initialRoute: "/",
      getPages: [
        GetPage(
          name: "/",
          page: () => const PersonajeHomePage(),
        ),
      ],
    );
  }
}

Future<void> inicializamosCargaDatos() async {
  WidgetsFlutterBinding.ensureInitialized();

  final prefs = SharedPrefsPersonaje();
  await prefs.initPrefs();

}
</code>```

Provider_personajes.dart

```<code> class PersonajeProvider with ChangeNotifier {
  final prefs = SharedPrefsPersonaje();

  int xpPersonaje = 0;
  int lvlPersonaje = 0;

  get leerXPPersonaje {
    if (prefs.readExpPersonaje != 0) {
      return xpPersonaje = prefs.readExpPersonaje;
    }
    return xpPersonaje;
  }

  set guardarXPPersonaje(int xp) {
    xpPersonaje = xp + xpPersonaje;
    prefs.saveExpPersonaje = xpPersonaje;
    notifyListeners();
  }

  get leerLvLPersonaje {
    if (prefs.readLvLPersonaje != 0) {
      return lvlPersonaje = prefs.readLvLPersonaje;
    }
    return lvlPersonaje;
  }

  set guardarLvLPersonaje(int lvl) {
    lvlPersonaje = lvl + lvlPersonaje;
    prefs.saveLvLPersonaje = lvlPersonaje;
    notifyListeners();
  }

  void borrarDatos() {
    prefs.eliminar();
  }
}
</code>```

答:
You need to do something similar to what you do when using firebase:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await inicializamosCargaDeDatos();
  runApp(const MyApp());
}
```

This way, you're making sure that nothing in your app is executed before your instance is initialized.

Body:
I am trying to make a singleton of sharedpreferences, but I get a failure of not initialized

(LateError (LateInitializationError: Field 'prefs' has not been initialized.)).

I don't know what could be wrong. I suppose that it could be for the late of SharedPreferences.dart, or it lacks somewhere to define the initialization?

Personaje_home.dart

class PersonajeHomePage extends StatefulWidget {
  const PersonajeHomePage({Key? key}) : super(key: key);

  @override
  State<PersonajeHomePage> createState() => _PersonajeHomePageState();
}

class _PersonajeHomePageState extends State<PersonajeHomePage> {
  @override
  Widget build(BuildContext context) {
    var estiloTexto = EstiloTextos();
    final proPersonaje = Provider.of<PersonajeProvider>(context);

    return Scaffold(
      backgroundColor: Colors.grey.shade300,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Text(proPersonaje.leerLvLPersonaje.toString()),
            ],
          ),
        ),
      ),
    );
  }
}

SharedPreferences.dart

class SharedPrefsPersonaje {
  static final SharedPrefsPersonaje _instancia = SharedPrefsPersonaje._internal();

  factory SharedPrefsPersonaje() {
    return _instancia;
  }
  SharedPrefsPersonaje._internal();

  late SharedPreferences prefs;
  initPrefs() async {
    prefs = await SharedPreferences.getInstance();
  }

  int get readExpPersonaje {
    return prefs.getInt("experiencia_personaje") ?? 0;
  }

  set saveExpPersonaje(int value) {
    prefs.setInt("experiencia_personaje", value);
  }

  int get readLvLPersonaje {
    return prefs.getInt("nivel_personaje") ?? 0;
  }

  set saveLvLPersonaje(int value) {
    prefs.setInt("nivel_personaje", value);
  }

  void eliminar() {
    prefs.clear();
  }
}

main.dart

void main() {
  inicializamosCargaDatos();
  runApp(AppState());
}

class AppState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        //Cargamos datos del JSON, servidor
        ChangeNotifierProvider(
          create: (_) => PersonajeProvider(),
          lazy: false,
        ),
      ],
      child: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: "My APP",
      initialRoute: "/",
      getPages: [
        GetPage(
          name: "/",
          page: () => const PersonajeHomePage(),
        ),
      ],
    );
  }
}

Future<void> inicializamosCargaDatos() async {
  WidgetsFlutterBinding.ensureInitialized();

  final prefs = SharedPrefsPersonaje();
  await prefs.initPrefs();

}

Provider_personajes.dart

 class PersonajeProvider with ChangeNotifier {
  final prefs = SharedPrefsPersonaje();

  int xpPersonaje = 0;
  int lvlPersonaje = 0;

  get leerXPPersonaje {
    if (prefs.readExpPersonaje != 0) {
      return xpPersonaje = prefs.readExpPersonaje;
    }
    return xpPersonaje;
  }

  set guardarXPPersonaje(int xp) {
    xpPersonaje = xp + xpPersonaje;
    prefs.saveExpPersonaje = xpPersonaje;
    notifyListeners();
  }

  get leerLvLPersonaje {
    if (prefs.readLvLPersonaje != 0) {
      return lvlPersonaje = prefs.readLvLPersonaje;
    }
    return lvlPersonaje;
  }

  set guardarLvLPersonaje(int lvl) {
    lvlPersonaje = lvl + lvlPersonaje;
    prefs.saveLvLPersonaje = lvlPersonaje;
    notifyListeners();
  }

  void borrarDatos() {
    prefs.eliminar();
  }
}

Body:
You need to do something similar to what you do when using firebase:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await inicializamosCargaDeDatos();
  runApp(const MyApp());
}

This way, you're making sure that nothing in your app is executed before your instance is initialized.


问:
How do I create a Pipfile from an existing virtualenv?
I can't seem to find the exact answer here. Is it possible to work without requirements.txt at all?

With pip (or pipenv), if I have a virtual environment, I can generate requirements.txt easily.

But, what if I have a project where we're trying to move to using pipfiles entirely. How do I initialize the pipfile from the existing virtualenv? In such a way that I can get rid of requirements.txt

答:
This worked for me:

rm Pipfile

rm Pipfile.lock

source path/to/venv/bin/activate

pip freeze > requirements.txt

pipenv install -r requirements.txt

rm requirements.txt

Rule the world

-- In english:

Delete or rename Pipfile and Pipefile.lock

Activate the virtual env

Use pip freeze to create a requirements.txt file

Use pipenv to install from the requirement.txt file. This initializes the Pipefile as well

Delete the requirements.txt file

Grab a coffee

The generated Pipfile will be version locked, but easy to edit.


问:
SQLAlchemy: ProgrammingError but the printed SQL statement works?
I am trying to group and count the number of rows found in a table per month using SQLAlchemy.

The function is as follows:

def query_testing(
    session: scoped_session,
    from_date: datetime,
    to_date: datetime,
):
    qry = (
        session.query(
            func.count(U4.index).label("count"),
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            ).label("received"),
        )
        .filter(
            cast(U4.arrival, Date) >= from_date,
            cast(U4.arrival, Date) <= to_date,
        )
        .group_by(
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            ),
        )
        .order_by(
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            )
        )
    )
```
<p>Unfortnately, executing the query using <code>qry.all()</code> causes a ProgrammingError:</p>
```[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'u4erp.received' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
```
<p>When I <code>print(qry)</code> the statement and try to manually execute the generated SQL, the statement works (after manually changing <code>?</code> to the their intended values). The printed statement is as follows:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    count(u4erp.[index]) AS count,
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0) AS received
FROM
    u4erp
WHERE
    CAST(
        u4erp.received AS DATE
    ) >= '2020-01-01'
    AND CAST(
        u4erp.received AS DATE
    ) <= '2021-12-31'
GROUP BY
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0)
ORDER BY
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0)
</code>```

What causes the printed SQL statement to work, but raises a ProgrammingError when using SQLAlchemy? How do I fix it?

答:
I found a workaround for my specific usecase using text.

def query_testing(
    session: scoped_session,
    from_date: datetime,
    to_date: datetime,
):
    qry = (
        session.query(
            func.count(U4.index).label("count"),
            text(
                "DATEADD(MONTH, DATEDIFF(MONTH, 0, "
                "u4erp.received), 0) AS received"
            ),
        )
        .filter(
            cast(U4.arrival, Date) >= from_date,
            cast(U4.arrival, Date) <= to_date,
        )
        .group_by(
            text(
                "DATEADD(MONTH, DATEDIFF(MONTH, 0, "
                "u4erp.received), 0)"
            ),
        )
        .order_by(
            text(
                "DATEADD(MONTH, DATEDIFF(MONTH, 0, "
                "u4erp.received), 0)"
            ),
        )
    )
```

Body:
I am trying to group and count the number of rows found in a table per month using SQLAlchemy.

The function is as follows:

def query_testing(
    session: scoped_session,
    from_date: datetime,
    to_date: datetime,
):
    qry = (
        session.query(
            func.count(U4.index).label("count"),
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            ).label("received"),
        )
        .filter(
            cast(U4.arrival, Date) >= from_date,
            cast(U4.arrival, Date) <= to_date,
        )
        .group_by(
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            ),
        )
        .order_by(
            func.dateadd(
                text("month"),
                func.datediff(text("month"), 0, U4.arrival),
                0,
            )
        )
    )

Unfortnately, executing the query using qry.all() causes a ProgrammingError:

[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'u4erp.received' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

When I print(qry) the statement and try to manually execute the generated SQL, the statement works (after manually changing ? to the their intended values). The printed statement is as follows:

SELECT
    count(u4erp.[index]) AS count,
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0) AS received
FROM
    u4erp
WHERE
    CAST(
        u4erp.received AS DATE
    ) >= '2020-01-01'
    AND CAST(
        u4erp.received AS DATE
    ) <= '2021-12-31'
GROUP BY
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0)
ORDER BY
    dateadd(MONTH, datediff(MONTH, 0, u4erp.received), 0)

What causes the printed SQL statement to work, but raises a ProgrammingError when using SQLAlchemy? How do I fix it?