问:
Extract array of objects into array
I have a fetch function which returns a json file. The source file looks like this:

```<code>{
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}
</code>```

When the response from the fetch (after applying .json()) it is a array of multiple objectives, each with two strings:

```<code>0
title: "People Policies"
page: "people.html"

1
title: "Client Policies"
page: "client.html"
</code>```

where 0 and 1 are OBJECTS and title/page the strings.

Question: how can I extract the objects into a simple array (not objects) with multiple key pairs or is there another way to format the source file?

There are plenty of questions on here with similar questions but I just can't get any of them to work, including Object.entries(obj)

Thanks.

答:
From what I understood from your question is that your source data is an array of objects each having two string values. And after .json(), you're getting an indexed object like

```<code>{
 0: {
   // ....
   }
}

</code>```

In this case, you can try Object.values() like

```<code>
fetch(some_url).then(resp => resp.json()).then(resp => {
    // resp is your object
    let formattedArray = Object.values(resp);
    console.log(formattedArray)
})
</code>```

Title: Extract array of objects into array

Body:
I have a fetch function which returns a json file. The source file looks like this:

{
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}

When the response from the fetch (after applying .json()) it is a array of multiple objectives, each with two strings:

0
title: "People Policies"
page: "people.html"

1
title: "Client Policies"
page: "client.html"

where 0 and 1 are OBJECTS and title/page the strings.

Question: how can I extract the objects into a simple array (not objects) with multiple key pairs or is there another way to format the source file?

There are plenty of questions on here with similar questions but I just can't get any of them to work, including Object.entries(obj)

Thanks.

Body:
From what I understood from your question is that your source data is an array of objects each having two string values. And after .json(), you're getting an indexed object like

{
 0: {
   // ....
   }
}

In this case, you can try Object.values() like

fetch(some_url).then(resp => resp.json()).then(resp => {
    // resp is your object
    let formattedArray = Object.values(resp);
    console.log(formattedArray)
})


来源: stackexchange

问:
Formatting in Fortran 90/95
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

```<code>program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program
</code>```

The output is

```<code> Hello, World!
0Count = 123
</code>```

where I would have expected

```<code> Hello, World!

Count = 123
</code>```

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!

答:
This was used in the 70s and even 80s with line printers in FORTRAN 77 and earlier ... but when did you last see a line printer?   Any Fortran 90/95 book that teaches this feature should be thrown away.

This has already been answered on Stack Overflow: Are Fortran control characters (carriage control) still implemented in compilers?

ContentLicense: CC BY-SA 3.0

Title: Formatting in Fortran 90/95

Body:
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program

The output is

 Hello, World!
0Count = 123

where I would have expected

 Hello, World!

Count = 123

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!


问:
First Instance of "STD_OUTPUT_HANDLE" Identifier is Undefined
I am using Visual Studio 2019, and my code uses console outputs which change colors frequently. I am including Windows.h in my code, which is the header file that contains SetConsoleTextAttributes, whereas STD_OUTPUT_HANDLE should be initialized by using namespace std. My code in its entirety can be found here, but the following is the section with the error:

```<code>#include <iostream>
#include <cmath>
#include "HeadFile.h"
#include <windows.h>
#include <string.h>

using namespace std;

int Play(char(&spaces)[7][6], int(&color)[7][6], int player, int playerOneWins, int playerTwoWins, int ties)
{
    HANDLE hConsole;
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
.....
</code>```

The code runs fine, but inside of studio itself, I see the following error:

The error is coming from the first instance of STD_OUTPUT_HANDLE only (another case at the bottom of the picture has no errors). If I comment out the first one, the next instance errors:

How can I fix this issue? I've read in a few non-related posts that using namespace std can sometimes lead to problems. Is this the case?

答: Use Header file "Windows.h" instead of "windows.h".</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using Visual Studio 2019, and my code uses console outputs which change colors frequently. I am including Windows.h in my code, which is the header file that contains SetConsoleTextAttributes, whereas STD_OUTPUT_HANDLE should be initialized by using namespace std. My code in its entirety can be found here, but the following is the section with the error:

#include <iostream>
#include <cmath>
#include "HeadFile.h"
#include <windows.h>
#include <string.h>

using namespace std;

int Play(char(&spaces)[7][6], int(&color)[7][6], int player, int playerOneWins, int playerTwoWins, int ties)
{
    HANDLE hConsole;
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
.....

The code runs fine, but inside of studio itself, I see the following error:

The error is coming from the first instance of STD_OUTPUT_HANDLE only (another case at the bottom of the picture has no errors). If I comment out the first one, the next instance errors:

How can I fix this issue? I've read in a few non-related posts that using namespace std can sometimes lead to problems. Is this the case?


问:
Converting dataframe fraction to float
I would like to convert the string values in column b to float. Wondering how should I make it.</p>

```<code>A    B
1    16-1/4
2    3-1/4
3    21-1/4
4    8-1/4
</code>```

Title: Converting dataframe fraction to float

Body:
I would like to convert the string values in column b to float. Wondering how should I make it.

A    B
1    16-1/4
2    3-1/4
3    21-1/4
4    8-1/4

Body:
Use built-in Python function eval():

df.B = df.B.apply(eval)

Test:

In[1]: df

   A       B
0  1  16-1/4
1  2   3-1/4
2  3  21-1/4
3  4   8-1/4

In[2]: df.B = df.B.apply(eval)
In[3]: df

   A      B
0  1  15.75
1  2   2.75
2  3  20.75
3  4   7.75


问:
OpenGL Rotate Box
I most likely have this wrong, but in my camera class, I rotate and translate the whole scene around the camera so it looks like the camera is actually moving.  This works fine since all of the boxes in my game are axis aligned. I now want to rotate one of the boxes, but glRotate isn't working since I am using in the camera to rotate the scene.  Does anyone know any ways to rotate the whole scene and then rotate a part individually?</p>

答:
When you are drawing the object you want to rotate you can do a push matrix, rotate, draw, and a pop matrix.

```<code>void display() { // display callback function
   glPushMatrix();
   glRotate(...); // rotation
   myObject.draw(); // draw the objects you want to rotate
   glPopMatrix();
}
</code>```

Before you push matrix:

You may first need to change the matrix mode from projection to modelview or call glLoadIdentity();

Title: OpenGL Rotate Box

Body:
When you are drawing the object you want to rotate you can do a push matrix, rotate, draw, and a pop matrix.

void display() { // display callback function
   glPushMatrix();
   glRotate(...); // rotation
   myObject.draw(); // draw the objects you want to rotate
   glPopMatrix();
}

Before you push matrix:

You may first need to change the matrix mode from projection to modelview or call glLoadIdentity();


问:
Error: cannot open .git/FETCH_HEAD: Read-only file system
I installed git after setting up Ubuntu 18.04.
I run git fetch with my old project, I got Error: cannot open .git/FETCH_HEAD: Read-only file system. Before that, everything was ok
Thanks for any helps

答:
Error comes from my partition. I install dual-boot Window 10 and Ubuntu, turning on fast startup on Window 10 make partition can't unmount, and when I switch to Ubuntu, OS make partition mount read-only.

I try to run command

ntfsfix /dev/sda5

umount /dev/sda5

mount /dev/sda5

and it worked. Moreover, I turned of fast startup on Window 10


问:
an added value of array of request disappears in Laravel Controller
the user id is existed Before doing create. so it causes an error in the first one.
I made it the other way. the second one below works correctly.
I would like to know why the first one is wrong and it's gone.

```<code>//Error
    public function store(ContactRequest $request)
    {
        $request->user_id = $request->user()->id;
        Log::debug($request->user()->id);
        Log::debug($request);
        Contact::create($request->all());
    }
</code>```

//OK

```<code>    public function store(ContactRequest $request,Contact $contact)
    {

        $request->user_id = $request->user()->id;

        $contact->title = $request->title;
        $contact->body = $request->body;
        $contact->user_id = $request->user()->id;
        $contact->save();
    }
</code>```

```<code>the log of the first one is here.
What happened to the user_id!?
</code>```

```<code>[2020-05-30 15:59:10] local.DEBUG: 59
[2020-05-30 15:59:10] local.DEBUG: array (
  '_token' => 'gGWuxW6C2JRSCYDuCAC9HauynGclKQEQB7qUh6Rw',
  'title' => 'TITLE',
  'body' => 'MESSAGE',
  'action' => 'SEND',
)
</code>```

Contact is model class.
ContactRequest is here.

```<code>class ContactRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'title' => 'required|max:100',
            'body' => 'required|max:1000'
        ];
    }
    public function attributes() {
        return [
            'title' => 'title',
            'body' => 'CONTENTS'
        ];
    }
}
</code>```

答:
You will have to use $request->merge(['user_id'=>$request->user()->id]).
 Another tips is that you can simply use Auth::user()->id which also return the user id of current user.

Body:
the user id is existed Before doing create. so it causes an error in the first one.
I made it the other way. the second one below works correctly.
I would like to know why the first one is wrong and it's gone.

//Error
    public function store(ContactRequest $request)
    {
        $request->user_id = $request->user()->id;
        Log::debug($request->user()->id);
        Log::debug($request);
        Contact::create($request->all());
    }

//OK

    public function store(ContactRequest $request,Contact $contact)
    {

        $request->user_id = $request->user()->id;

        $contact->title = $request->title;
        $contact->body = $request->body;
        $contact->user_id = $request->user()->id;
        $contact->save();
    }

the log of the first one is here.
What happened to the user_id!?

[2020-05-30 15:59:10] local.DEBUG: 59
[2020-05-30 15:59:10] local.DEBUG: array (
  '_token' => 'gGWuxW6C2JRSCYDuCAC9HauynGclKQEQB7qUh6Rw',
  'title' => 'TITLE',
  'body' => 'MESSAGE',
  'action' => 'SEND',
)

Contact is model class.
ContactRequest is here.

class ContactRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'title' => 'required|max:100',
            'body' => 'required|max:1000'
        ];
    }
    public function attributes() {
        return [
            'title' => 'title',
            'body' => 'CONTENTS'
        ];
    }
}


答:
```<code>const data = {
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}

const pages = data.pages.map(obj => obj.pages)
const titles = data.pages.map(obj => obj.title)

</code>```

Not sure which one you wanted in an array so heres both.

Title: Extract array of objects into array

Body:
const data = {
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}

const pages = data.pages.map(obj => obj.pages)
const titles = data.pages.map(obj => obj.title)

Not sure which one you wanted in an array so heres both.


问:
viewPager and data binding android
I have a activity with a view pager and i implements MVVM.

I can't set view pager adapter.
I read all of the post in stack Over Flow but i have error.
which part of my code is wrong?
I posted all of the my codes.

This my xml codes

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:bind="http://schemas.android.com/tools">
<data>
    <variable
        name="main"
        type="ir.****.viewmodel.MainViewModel" />
</data>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"/>

<androidx.viewpager.widget.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    adapter="@{main}" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:itemTextColor="@android:color/transparent"
    app:menu="@menu/main_menu" />
</code>```

This is my viewModel codes

```<code>public class MainViewModel extends BaseObservable {
private  AppCompatActivity activity;

public MainViewModel(AppCompatActivity activity) {
    this.activity = activity;
}

@BindingAdapter("adapter")
public static void setViewPagerFragments(ViewPager pager , MainViewModel viewModel){
    pager.setAdapter(new MyFragmentAdapter(pager.getContext() , viewModel.activity.getSupportFragmentManager() ));
}
}
</code>```

This is my mainActivity Codes

```<code>public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    ActivityMainBinding mainBinding = DataBindingUtil.setContentView(this , R.layout.activity_main);
    MainViewModel viewModel = new MainViewModel(this);
    mainBinding.setMain(viewModel);
}
}
</code>```

This is my fragment adapter codes

```<code>public class MyFragmentAdapter extends FragmentPagerAdapter {
private static final int TRADE = 0;

private static final int[] TABS = new int[]{TRADE};

private Context mContext;

public MyFragmentAdapter(final Context context, final FragmentManager fm) {
    super(fm);
    mContext = context;
}

@Override
public Fragment getItem(int position) {
    switch (TABS[position]) {
        case TRADE:
            return TradeFragment.newInstance("first", "first");
    }
    return null;
}

@Override
public int getCount() {
    return TABS.length;
}

@Override
public CharSequence getPageTitle(int position) {
    switch (TABS[position]) {
        case TRADE:
            return mContext.getResources().getString(R.string.trade);
    }
    return null;
}
}
</code>```

and logcat message after crush

```<code>    java.lang.IllegalStateException: ViewPager with adapter ir.****.Adapter.MyFragmentAdapter@a0ef1f requires a view id
</code>```

答:
Try to add an id to your ViewPager in the layout:</p>

```<code><androidx.viewpager.widget.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    adapter="@{main}" />
</code>```

Title: viewPager and data binding android

Body:
I have a activity with a view pager and i implements MVVM.

I can't set view pager adapter.
I read all of the post in stack Over Flow but i have error.
which part of my code is wrong?
I posted all of the my codes.

This my xml codes

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:bind="http://schemas.android.com/tools">
<data>
    <variable
        name="main"
        type="ir.****.viewmodel.MainViewModel" />
</data>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"/>

<androidx.viewpager.widget.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    adapter="@{main}" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:itemTextColor="@android:color/transparent"
    app:menu="@menu/main_menu" />

This is my viewModel codes

public class MainViewModel extends BaseObservable {
private  AppCompatActivity activity;

public MainViewModel(AppCompatActivity activity) {
    this.activity = activity;
}

@BindingAdapter("adapter")
public static void setViewPagerFragments(ViewPager pager , MainViewModel viewModel){
    pager.setAdapter(new MyFragmentAdapter(pager.getContext() , viewModel.activity.getSupportFragmentManager() ));
}
}

This is my mainActivity Codes

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    ActivityMainBinding mainBinding = DataBindingUtil.setContentView(this , R.layout.activity_main);
    MainViewModel viewModel = new MainViewModel(this);
    mainBinding.setMain(viewModel);
}
}

This is my fragment adapter codes

public class MyFragmentAdapter extends FragmentPagerAdapter {
private static final int TRADE = 0;

private static final int[] TABS = new int[]{TRADE};

private Context mContext;

public MyFragmentAdapter(final Context context, final FragmentManager fm) {
    super(fm);
    mContext = context;
}

@Override
public Fragment getItem(int position) {
    switch (TABS[position]) {
        case TRADE:
            return TradeFragment.newInstance("first", "first");
    }
    return null;
}

@Override
public int getCount() {
    return TABS.length;
}

@Override
public CharSequence getPageTitle(int position) {
    switch (TABS[position]) {
        case TRADE:
            return mContext.getResources().getString(R.string.trade);
    }
    return null;
}
}

and logcat message after crush

    java.lang.IllegalStateException: ViewPager with adapter ir.****.Adapter.MyFragmentAdapter@a0ef1f requires a view id

Body:
Try to add an id to your ViewPager in the layout:

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    adapter="@{main}" />


问:
Adding Rounded rectangle css over text in Wordpress Navigation Menu
I am trying to update Default Navigation menu on Wordpress Astra Theme and trying to add rounded rectangle in one of the menu as shown the photo, what should I add in the additional CSS Panel? Just started learning CSS and Wordpress yesterday, Im a newbie.

https://i.stack.imgur.com/w2HKF.jpg

答:
Try this:

.round {
  border: 2px solid white;
  border-radius: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-sm bg-primary navbar-light">
  <ul class="navbar-nav">
    <li class="nav-item active">
      Active
    </li>
    <li class="nav-item">
      Link1
    </li>
    <li class="nav-item round">
      Link2
    </li>

  </ul>
</nav></code>```

Add a class to the li item of the navbar or may be the element class to which rectange css has to be applied (in this case we want to round Link2 so I have given a class to  its li element called round) and then give the border to it followed by setting its radius shown in code.

Body:
Try this:

.round {
  border: 2px solid white;
  border-radius: 10px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-sm bg-primary navbar-light">
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Active</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link1</a>
    </li>
    <li class="nav-item round">
      <a class="nav-link" href="#">Link2</a>
    </li>

  </ul>
</nav>

Add a class to the li item of the navbar or may be the element class to which rectange css has to be applied (in this case we want to round Link2 so I have given a class to  its li element called round) and then give the border to it followed by setting its radius shown in code.


问:
Download an image from Firebase Storage knowing the link
Hi then since new in android programming I would need a great help to solve this problem, then I am creating an image app, the images are uploaded by me on Firebase Storage and therefore I can access the link and tokens whenever I want, so when the user chooses an image he downloads the one he has chosen, now I have divided my app so I created as many fragments as there are images and the download button is contained in the fragment relating to the image now I show you how

```<code>import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

    public class fragment_1 extends Fragment {
    Button bntDwn_1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //here I would like to insert the function to download the image directly

            }
        });
    }
}
</code>```

now I show you the layout of the fragment

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment_1">

    <ImageView
        android:id="@+id/sfondo_1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:contentDescription="@string/sfondo_1"
        android:src="@drawable/forpaper_1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/dwn_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:text="@string/scarica"
        app:layout_constraintBottom_toBottomOf="@+id/sfondo_1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

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

now I show you MainActivity

```<code>import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private StorageReference mStorageRef;
    public Random mRandom;
    public TextView mCounterCrd;

    int StringCrd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Inizializzazione Archiviazione Cloud
        mStorageRef = FirebaseStorage.getInstance().getReference();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx =  fm.beginTransaction();
        fragment_1 fragmentview = new fragment_1();
        tx.replace(R.id.frame_place, fragmentview);
        tx.commit();
       }
    }
</code>```

now I would like to ask you a function to download the file already knowing the link and then manually inserting it for each image under the onClick function of each reference Button, I hope you can help me with many useful tips or necessary changes, thanks to all.

答:
guys I solved it like this:

```<code>import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class fragment_1 extends Fragment {

    private static final String DIRECTORY_DOWNLOADS = "CAMERA";
    Button bntDwn_1;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;
    StorageReference ref;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("fragment_1","Click su scarica fragment 1");
                download();
            }
        });
    }

    public void download(){
        storageReference= firebaseStorage.getInstance().getReference();
        ref = storageReference.child("fourapper_forpaper_1 (1).jpeg");
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();
                downloadFiles(getActivity(), "Sfondo", ".jpeg",DIRECTORY_DOWNLOADS,url);

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
    }

    private void downloadFiles(Context context, String fileName, String fileExtension, String destinationDirectory, String Url){
        DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(Url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName +fileExtension);
        downloadManager.enqueue(request);
    }
}
</code>```

everything works perfectly download the required file, only that it saves everything in downloads, while I would like to download the photos in a precise folder inside the photos of the device so as to be easily found, so how do I save the downloaded file inside a path specified by me and precisely within the image gallery? thank you all

Body:
Hi then since new in android programming I would need a great help to solve this problem, then I am creating an image app, the images are uploaded by me on Firebase Storage and therefore I can access the link and tokens whenever I want, so when the user chooses an image he downloads the one he has chosen, now I have divided my app so I created as many fragments as there are images and the download button is contained in the fragment relating to the image now I show you how

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

    public class fragment_1 extends Fragment {
    Button bntDwn_1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //here I would like to insert the function to download the image directly

            }
        });
    }
}

now I show you the layout of the fragment

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment_1">

    <ImageView
        android:id="@+id/sfondo_1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:contentDescription="@string/sfondo_1"
        android:src="@drawable/forpaper_1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/dwn_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:text="@string/scarica"
        app:layout_constraintBottom_toBottomOf="@+id/sfondo_1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

now I show you MainActivity

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private StorageReference mStorageRef;
    public Random mRandom;
    public TextView mCounterCrd;

    int StringCrd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Inizializzazione Archiviazione Cloud
        mStorageRef = FirebaseStorage.getInstance().getReference();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx =  fm.beginTransaction();
        fragment_1 fragmentview = new fragment_1();
        tx.replace(R.id.frame_place, fragmentview);
        tx.commit();
       }
    }

now I would like to ask you a function to download the file already knowing the link and then manually inserting it for each image under the onClick function of each reference Button, I hope you can help me with many useful tips or necessary changes, thanks to all.

Body:
guys I solved it like this:

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

public class fragment_1 extends Fragment {

    private static final String DIRECTORY_DOWNLOADS = "CAMERA";
    Button bntDwn_1;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;
    StorageReference ref;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        bntDwn_1 = (Button) getActivity().findViewById(R.id.dwn_1);
        bntDwn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("fragment_1","Click su scarica fragment 1");
                download();
            }
        });
    }

    public void download(){
        storageReference= firebaseStorage.getInstance().getReference();
        ref = storageReference.child("fourapper_forpaper_1 (1).jpeg");
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();
                downloadFiles(getActivity(), "Sfondo", ".jpeg",DIRECTORY_DOWNLOADS,url);

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
    }

    private void downloadFiles(Context context, String fileName, String fileExtension, String destinationDirectory, String Url){
        DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(Url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationDirectory, fileName +fileExtension);
        downloadManager.enqueue(request);
    }
}

everything works perfectly download the required file, only that it saves everything in downloads, while I would like to download the photos in a precise folder inside the photos of the device so as to be easily found, so how do I save the downloaded file inside a path specified by me and precisely within the image gallery? thank you all


问:
TableRow - Get number of columns
I have a dynamic TableRow in android, so I add and delete views from TableRow based on my actions.

I want to check if the table row is full or not, in another word I want to check for example if my table row have 10 views then I move to the second row.

I searched in the documentation, but I can't find a way to get the number of views in a TableRow.

Is there any way to solve this please?

答:
As mentioned in the comment by Mike:

TableRow is a ViewGroup, so getChildCount() will give you the number
  of direct children

The solution with kotlin is:

```<code>if (tableRow1.childCount < 10)
   // action
</code>```

Title: TableRow - Get number of columns

Body:
As mentioned in the comment by Mike:

TableRow is a ViewGroup, so getChildCount() will give you the number
  of direct children

The solution with kotlin is:

if (tableRow1.childCount < 10)
   // action


问:
What is the location of logs when Wso2 EI is run as a docker container
I pulled the latest WSO2 docker container from docker official website.
Then I ran the following command to run the container

```<code>docker run -it -p 8280:8280 -p 8243:8243 -p 9443:9443 --name integrator wso2/wso2ei-integrator
</code>```

Where can I find the wso2carbon.log?

答:
Found the answer in docker site itself.

```<code>https://hub.docker.com/r/wso2/wso2ei-integrator
</code>```

Can view the logs with docker logs integrator and can access the bash shell of container with  docker exec -it integrator bash

Body:
I pulled the latest WSO2 docker container from docker official website.
Then I ran the following command to run the container

docker run -it -p 8280:8280 -p 8243:8243 -p 9443:9443 --name integrator wso2/wso2ei-integrator

Where can I find the wso2carbon.log?

Body:
Found the answer in docker site itself.

https://hub.docker.com/r/wso2/wso2ei-integrator

Can view the logs with docker logs integrator and can access the bash shell of container with  docker exec -it integrator bash


问:
how to replace angular theme CSS stylesheet for whole app?
First I couldn't import css through index.html and I get MIME type error:
enter image description here
Refused to apply style from 'http://localhost:4200/css/pink-bluegrey.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

if i try to import it through angular.json then I can't insert ID tag id="themeAsset".

Reason why I want to add id is because i want to do this from https://material.angular.io/guide/theming

function changeTheme(themeName) {
  document.getElementById('themeAsset').href = /path/to/my/${themeName}.css;
}
so i could change style for whole app styles by click instead of adding classes to every component

答:
Working Stackblitz :- https://stackblitz.com/edit/angular-jrkmhn

I placed my css inside assets folder i.e. myStyles.css

CSS :-

```<code>.myDiv {
  background-color: black;
}
</code>```

index.html

```<code><link id="myLink">
<my-app>loading</my-app>
</code>```

app.component.html

```<code><div class="myDiv">Css Will Load</div>

<button style="margin-top: 2em" (click)="changeTheme('')">Change Theme</button>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

changeTheme(themeName) {
   var elem = document.getElementById('myLink');
   elem.setAttribute('href','./assets/myStyles.css');
   elem.setAttribute('rel','stylesheet');
   elem.setAttribute('type','text/css');
}
}
</code>```

Body:
Working Stackblitz :- https://stackblitz.com/edit/angular-jrkmhn

I placed my css inside assets folder i.e. myStyles.css

CSS :-

.myDiv {
  background-color: black;
}

index.html

<link id="myLink">
<my-app>loading</my-app>

app.component.html

<div class="myDiv">Css Will Load</div>

<button style="margin-top: 2em" (click)="changeTheme('')">Change Theme</button>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

changeTheme(themeName) {
   var elem = document.getElementById('myLink');
   elem.setAttribute('href','./assets/myStyles.css');
   elem.setAttribute('rel','stylesheet');
   elem.setAttribute('type','text/css');
}
}


问:
Display the word document from wwwroot folder instead of downloading: ASP.Net Core
I am trying to show the document located inside wwwroot folder in my .NET MVC Core application folder in an iframe.

Scenario:

I have a list of document on my Razor page: MyRazor.cshtml and there is a button for each list. When I click that button it takes me to the details of individual document using its Id.

When the page loads, the document gets downloaded instead of showing in iframe src.

Controller:

```<code>public ActionResult GetArticles(int id)
    {
        try
        {
            Articles getArticles = _articleRepository.GetArticles(id);
            return View(getArticles);
        }
        catch (Exception)
        {

            return NotFound();
        }
    }
</code>```

View:

```<code><div class="card">
    <iframe id="documentViewer" src="~/docs/@Html.DisplayFor(model => model.WordDocumentFile)" width="100%" height="700px;" frameborder="0"></iframe>
</div>
</code>```

which is undesirable. I just want the show that document inside my iframe.

What am I missing?

答:
Because doc files are not known by the web browsers, you need to transform them to HTML or PDF.

The best way is to store the PDF file in the corresponding folder, and then read the PDF file directly to display the content of the document, rather than download the file.

You can also refer to this:How do I render a Word document (.doc, .docx) in the browser using JavaScript?

Body:
I am trying to show the document located inside wwwroot folder in my .NET MVC Core application folder in an iframe.

Scenario:

I have a list of document on my Razor page: MyRazor.cshtml and there is a button for each list. When I click that button it takes me to the details of individual document using its Id.

When the page loads, the document gets downloaded instead of showing in iframe src.

Controller:

public ActionResult GetArticles(int id)
    {
        try
        {
            Articles getArticles = _articleRepository.GetArticles(id);
            return View(getArticles);
        }
        catch (Exception)
        {

            return NotFound();
        }
    }

View:

     model.WordDocumentFile)" width="100%" height="700px;" frameborder="0">

which is undesirable. I just want the show that document inside my iframe.

What am I missing?


问:
keras custom loss - ignore zero labels
I am trying to train a sequence tagging model (LSTM), where the sequence labels are either 1 (first class) , 2 (second class) or 0 (don't care).

I tried to write my own loss function that ignores the zeros:

```<code>import keras.backend as K
def my_loss(y_true, y_pred):
   """(sum([(t-p)**2 for t,p in zip(y_true, y_pred)])/n_nonzero)**0.5"""
   return K.sqrt(K.sum(K.square(y_pred*K.cast(y_true>0, "float32") - y_true), axis=-1) / K.sum(K.cast(y_true>0, "float32") ))
</code>```

Which essentially calculates mean squared error only on non-zeros.

However, I get loss=nan when training the model.

What I am doing wrong ?

What is the standard way to ignore certain labels in the training process ?

答:
It works for me by removing the argument of axis=-1:

K.sqrt(K.sum(K.square(y_pred*K.cast(y_true>0, "float32") - y_true), axis=-1) / K.sum(K.cast(y_true>0, "float32") ))

Subtracting y_true by y_pred when y_true is greater than 0. In particular, when y_true is equal to zero the term y_pred*K.cast(y_true>0, "float32") - y_true) is also equal to zero because it subtracts 0 by 0, as in case of y_true>0 the term K.cast(y_true>0, "float32") takes the value 1, otherwise it gets 0.

Title: keras custom loss - ignore zero labels

Body:
I am trying to train a sequence tagging model (LSTM), where the sequence labels are either 1 (first class) , 2 (second class) or 0 (don't care).

I tried to write my own loss function that ignores the zeros:

import keras.backend as K
def my_loss(y_true, y_pred):
   """(sum([(t-p)**2 for t,p in zip(y_true, y_pred)])/n_nonzero)**0.5"""
   return K.sqrt(K.sum(K.square(y_pred*K.cast(y_true>0, "float32") - y_true), axis=-1) / K.sum(K.cast(y_true>0, "float32") ))

Which essentially calculates mean squared error only on non-zeros.

However, I get loss=nan when training the model.

What I am doing wrong ?

What is the standard way to ignore certain labels in the training process ?


问:
Cannot set headers after they are sent to the client in a middleware
In a middleware function, I authenticate user and return when jwt token is invalid. This is the middleware function.

```<code>const authenticateUser = (req, res, next) => {
const token = req.header('x-auth');
if (!token) {
    res.json({ errMessage: 'Invalid token' });
}
try {
    const tokenData = verify(token, privateKey);
    req.user = { name: tokenData.name, email: tokenData.email, _id: tokenData._id }
    next();

} catch (error) {
    res.status(401);
     res.json({ errMessage: 'Invalid token', error });  //error here
     return
}}
</code>```

The error message:

```<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (..\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (..\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (..\node_modules\express\lib\response.js:267:15)
at authenticateUser (..\app\middlewares\authenticate.js:18:14)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)
at next (..\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (..\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)
at ..\node_modules\express\lib\router\index.js:281:22
at Function.process_params (..\node_modules\express\lib\router\index.js:335:12)
at next (..\node_modules\express\lib\router\index.js:275:10)
at Function.handle (..\node_modules\express\lib\router\index.js:174:3)
at router (..\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)
</code>```

答:
You are missing a return statement, if you are calling next you are probably going to some other middleware that is sending back json, or you are throwing an error after not being authorized, this should fix it.

const authenticateUser = (req, res, next) => {
const token = req.header('x-auth');
if (!token) {
    res.json({ errMessage: 'Invalid token' });
    return

}
try {
    const tokenData = verify(token, privateKey);
    req.user = { name: tokenData.name, email: tokenData.email, _id: tokenData._id }
    next();

} catch (error) {
    res.status(401);
     res.json({ errMessage: 'Invalid token', error });  //error here
     return
}}

```

Body:
In a middleware function, I authenticate user and return when jwt token is invalid. This is the middleware function.

const authenticateUser = (req, res, next) => {
const token = req.header('x-auth');
if (!token) {
    res.json({ errMessage: 'Invalid token' });
}
try {
    const tokenData = verify(token, privateKey);
    req.user = { name: tokenData.name, email: tokenData.email, _id: tokenData._id }
    next();

} catch (error) {
    res.status(401);
     res.json({ errMessage: 'Invalid token', error });  //error here
     return
}}

The error message:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (..\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (..\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (..\node_modules\express\lib\response.js:267:15)
at authenticateUser (..\app\middlewares\authenticate.js:18:14)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)
at next (..\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (..\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)
at ..\node_modules\express\lib\router\index.js:281:22
at Function.process_params (..\node_modules\express\lib\router\index.js:335:12)
at next (..\node_modules\express\lib\router\index.js:275:10)
at Function.handle (..\node_modules\express\lib\router\index.js:174:3)
at router (..\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (..\node_modules\express\lib\router\layer.js:95:5)


问:
Perl Regex: Need help on a way to split string into groups matching a pattern
I need to split this string to an array:

```<code>$string = "9583526578','9583636523','9673522574','9183556528','9983023378";
</code>```

Here's how I want my array to look like after splitting:

```<code>@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]
</code>```

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

答:
Tons of different ways.  Here's one:

```<code>$foo[0] = [];  # assuming you really meant an array of arrays of arrays as you showed
while ($string =~ m/([0-9]++)[^0-9]*+([0-9]++)?/g) {
    push @{ $foo[0] }, [ $1, $2 // () ];
}
</code>```

(Did you really mean an array containing just one reference to an array of arrayrefs?)

Body:
I need to split this string to an array:

$string = "9583526578','9583636523','9673522574','9183556528','9983023378";

Here's how I want my array to look like after splitting:

@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

Body:
Tons of different ways.  Here's one:

$foo[0] = [];  # assuming you really meant an array of arrays of arrays as you showed
while ($string =~ m/([0-9]++)[^0-9]*+([0-9]++)?/g) {
    push @{ $foo[0] }, [ $1, $2 // () ];
}

(Did you really mean an array containing just one reference to an array of arrayrefs?)


问:
iPhone4 - Call default browser with and redirect to a designated url
Like this question, I would like to write an app for iPhone4 to call default browser with and redirect to a designated url, could someone please suggest the code for this action?

答:
Use the -[UIApplication openURL:] method, which is accessed through the sharedApplication method of UIApplication.

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
</code>```

Body:
Use the -[UIApplication openURL:] method, which is accessed through the sharedApplication method of UIApplication.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];


问:
Pandas groupby and custom agg lambda function
I have a data frame and I want to aggregate a custom aggregation function.

Right now I have it like a predefined function, but I want to call it as a lambda function. Notice that the predefined function has a parameter that can be change.

from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
bunch = load_boston()

y = bunch.target
X = pd.DataFrame(bunch.data, columns=bunch.feature_names)

def percentile_func(y,PERCENTILE=50):
    return np.percentile(y,PERCENTILE)

X.groupby('CHAS')['CRIM'].agg([percentile_func,'sum', 'count'])
```

答:
You can use functools.partial here.

```<code>from functools import partial

f = partial(percentile_func,PERCENTILE=50) # you can change PERCENTILE value accordingly.

X.groupby('CHAS')['CRIM'].agg([f,'sum', 'count'])
</code>```

Body:
You can use functools.partial here.

from functools import partial

f = partial(percentile_func,PERCENTILE=50) # you can change PERCENTILE value accordingly.

X.groupby('CHAS')['CRIM'].agg([f,'sum', 'count'])


问:
Replacing Variables in String at Runtime
Currently I am using the following to evaluate variables that are placed in strings at runtime:

```<code>newVal = eval("`" + newVal + "`");
</code>```

So if I have the string:

```<code>"Hello from channel: ${erpVars["CommandChannel"]["name"]}"
</code>```

And erpVars["CommandChannel"]["name"] has value home, then the resulting string is:

```<code>Hello from channel: home
</code>```

There are other objects than just erpVars that could be holding matching values for the string, but this is just one example. It's also important to note that each string could have more than one variable that needs replacing.

I am trying to achieve the same thing without using eval(), as some of the variable values come from user input.

答:
Your case sounds super nasty (you should never ever use eval in JS! It poses a major security threat! also it looks weird that you want to replace this sort of a string) and perhaps if you told me more about where you get your inputs from and in what form, then maybe we could find together a much better solution for this. On that note, this is how I would solve your issue in its current form.

const newVal = 'Hello from channel: ${erpVars["CommandChannel"]["name"]}';

const strings = {
   erpVars: {
     CommandChannel: {
       name: "home"
     }
   }
};

const vars = newVal.match(/\$\{.+?\}/g);
let result = newVal;

vars.forEach(v => {
   let valuePath = '${erpVars["CommandChannel"]["name"]}'.match(/[\w\d]+/g).join('.');
   result = result.replace(v, _.get(strings, valuePath));
});

console.log(result);
```

Note that I'm skipping here the edge scenarios, like getting a null result from the newVal.match when there are no variables in the newVal, but that's easy to handle.
Also note that over here i'm using the lodash library in _.get() (https://lodash.com/docs/4.17.15#get). It's super popular for this kind of small tasks. Of course there are really a lot of other tools that allow you to extract a value based on a property path like erpVars.CommandChannel.name that is stored in the valuePath variable, including a crazy amount of instructions that tell you how to do it yourself.

Body:
Currently I am using the following to evaluate variables that are placed in strings at runtime:

newVal = eval("`" + newVal + "`");

So if I have the string:

"Hello from channel: ${erpVars["CommandChannel"]["name"]}"

And erpVars["CommandChannel"]["name"] has value home, then the resulting string is:

Hello from channel: home

There are other objects than just erpVars that could be holding matching values for the string, but this is just one example. It's also important to note that each string could have more than one variable that needs replacing.

I am trying to achieve the same thing without using eval(), as some of the variable values come from user input.

Body:
Your case sounds super nasty (you should never ever use eval in JS! It poses a major security threat! also it looks weird that you want to replace this sort of a string) and perhaps if you told me more about where you get your inputs from and in what form, then maybe we could find together a much better solution for this. On that note, this is how I would solve your issue in its current form.

const newVal = 'Hello from channel: ${erpVars["CommandChannel"]["name"]}';

const strings = {
   erpVars: {
     CommandChannel: {
       name: "home"
     }
   }
};

const vars = newVal.match(/\$\{.+?\}/g);
let result = newVal;

vars.forEach(v => {
   let valuePath = '${erpVars["CommandChannel"]["name"]}'.match(/[\w\d]+/g).join('.');
   result = result.replace(v, _.get(strings, valuePath));
});

console.log(result);

Note that I'm skipping here the edge scenarios, like getting a null result from the newVal.match when there are no variables in the newVal, but that's easy to handle.
Also note that over here i'm using the lodash library in _.get() (https://lodash.com/docs/4.17.15#get). It's super popular for this kind of small tasks. Of course there are really a lot of other tools that allow you to extract a value based on a property path like erpVars.CommandChannel.name that is stored in the valuePath variable, including a crazy amount of instructions that tell you how to do it yourself.


问:
Keyboard layout edge cropping up while running the app?

This is a layout i created using dp dimensions using a relative layout for keyboard, But when i try the keyboard on my phone, somehow, the right edge of my keyboard gets cropped as shown below, what could be the reason for this problem?

Here's my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimaryDark"
    android:id="@+id/Rel">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/texty"/>
    <TextView
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:layout_marginLeft="70dp"
        android:id="@+id/xcor"/>
    <TextView
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:layout_marginLeft="180dp"
        android:id="@+id/ycor"/>

    <Button
        android:layout_width="41dp"
        android:layout_height="@dimen/buttonh"
        android:layout_marginTop="@dimen/buttono1"
        android:background="@drawable/button"
        android:text="अ"
        android:id="@+id/अ"
        android:textSize="@dimen/text"/>
    <Button
        android:layout_width="41dp"
        android:layout_height="@dimen/buttonh"
        android:layout_marginTop="@dimen/buttono1"
        android:layout_marginLeft="41dp"
        android:background="@drawable/button"
        android:text="आ"
        android:id="@+id/आ"
        android:textSize="@dimen/text"/>
    ....

    Lots of Buttons

   .....
    <Button
        android:layout_width="41dp"
        android:layout_height="43dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="@dimen/buttono5"
        android:text="1"
        android:id="@+id/number"
        android:textSize="17dp"
        android:textColor="#FF494949"/>
    <Button
        android:layout_width="41dp"
        android:layout_height="43dp"
        android:layout_marginLeft="280dp"
        android:layout_marginTop="@dimen/buttono5"
        android:text="."
        android:id="@+id/dot"
        android:textSize="17dp"
        android:textColor="#FF494949"/>
    <ImageButton
        android:layout_width="60dp"
        android:layout_height="56dp"
        android:layout_marginLeft="330dp"
        android:layout_marginTop="192dp"
        android:src="@drawable/enterbutton"
        android:id="@+id/enter"
        android:textSize="17dp"/>

</RelativeLayout>
</code>```

As suggested in comments.

I tried changing width of my parent to some constant dp instead of match_parent but the result is same.

EDIT
I found out this bug only occurs on my phone which is an Oreo, Xiaomi Redmi note 5.

答:
your can use  layout_weight

```<code>   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>
</code>```

its responsive over display

Body:
This is a layout i created using dp dimensions using a relative layout for keyboard, But when i try the keyboard on my phone, somehow, the right edge of my keyboard gets cropped as shown below, what could be the reason for this problem?

Here's my xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimaryDark"
    android:id="@+id/Rel">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/texty"/>
    <TextView
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:layout_marginLeft="70dp"
        android:id="@+id/xcor"/>
    <TextView
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:layout_marginLeft="180dp"
        android:id="@+id/ycor"/>

    <Button
        android:layout_width="41dp"
        android:layout_height="@dimen/buttonh"
        android:layout_marginTop="@dimen/buttono1"
        android:background="@drawable/button"
        android:text="अ"
        android:id="@+id/अ"
        android:textSize="@dimen/text"/>
    <Button
        android:layout_width="41dp"
        android:layout_height="@dimen/buttonh"
        android:layout_marginTop="@dimen/buttono1"
        android:layout_marginLeft="41dp"
        android:background="@drawable/button"
        android:text="आ"
        android:id="@+id/आ"
        android:textSize="@dimen/text"/>
    ....

    Lots of Buttons

   .....
    <Button
        android:layout_width="41dp"
        android:layout_height="43dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="@dimen/buttono5"
        android:text="1"
        android:id="@+id/number"
        android:textSize="17dp"
        android:textColor="#FF494949"/>
    <Button
        android:layout_width="41dp"
        android:layout_height="43dp"
        android:layout_marginLeft="280dp"
        android:layout_marginTop="@dimen/buttono5"
        android:text="."
        android:id="@+id/dot"
        android:textSize="17dp"
        android:textColor="#FF494949"/>
    <ImageButton
        android:layout_width="60dp"
        android:layout_height="56dp"
        android:layout_marginLeft="330dp"
        android:layout_marginTop="192dp"
        android:src="@drawable/enterbutton"
        android:id="@+id/enter"
        android:textSize="17dp"/>

</RelativeLayout>

As suggested in comments.

I tried changing width of my parent to some constant dp instead of match_parent but the result is same.

EDIT
I found out this bug only occurs on my phone which is an Oreo, Xiaomi Redmi note 5.

Body:
your can use  layout_weight

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>

its responsive over display


答:
Route handler does not exit when the response is sent to client. So, you will need to wrap your code with proper if else like </p>

```<code>const authenticateUser = (req, res, next) => {
const token = req.header('x-auth');
if (!token) {
    res.json({ errMessage: 'Invalid token' });
}
else{
try {
    const tokenData = verify(token, privateKey);
    req.user = { name: tokenData.name, email: tokenData.email, _id: tokenData._id }
    next();

} catch (error) {
    res.status(401);
     res.json({ errMessage: 'Invalid token', error });  //error here
     return
}
}
}
</code>```

Title: Cannot set headers after they are sent to the client in a middleware

Body:
Route handler does not exit when the response is sent to client. So, you will need to wrap your code with proper if else like

const authenticateUser = (req, res, next) => {
const token = req.header('x-auth');
if (!token) {
    res.json({ errMessage: 'Invalid token' });
}
else{
try {
    const tokenData = verify(token, privateKey);
    req.user = { name: tokenData.name, email: tokenData.email, _id: tokenData._id }
    next();

} catch (error) {
    res.status(401);
     res.json({ errMessage: 'Invalid token', error });  //error here
     return
}
}
}


问:
populating map globally
I have declared the following   map globally and trying to populate globally.

```<code>   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));
</code>```

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong

2. why can't we initialize the map globally.

答:
Compiler is probably getting confused by the >> on line 1 (because it looks like a shift operator).  Try inserting a space in there:

```<code>typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList;
</code>```

[update]

See Vlad Lazarenko's comment for why this will not actually solve your problem.  Easiest fix is to wrap this contraption in an object, initialize it in the constructor, then declare one at global scope.  (But not if you can avoid it since globals are evil in the first place...)

Title: populating map globally

Body:
I have declared the following   map globally and trying to populate globally.

   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong

2. why can't we initialize the map globally.

Body:
Compiler is probably getting confused by the >> on line 1 (because it looks like a shift operator).  Try inserting a space in there:

typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList;

[update]

See Vlad Lazarenko's comment for why this will not actually solve your problem.  Easiest fix is to wrap this contraption in an object, initialize it in the constructor, then declare one at global scope.  (But not if you can avoid it since globals are evil in the first place...)


问:
Extract array of objects into array
I have a fetch function which returns a json file. The source file looks like this:

```<code>{
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}
</code>```

When the response from the fetch (after applying .json()) it is a array of multiple objectives, each with two strings:

```<code>0
title: "People Policies"
page: "people.html"

1
title: "Client Policies"
page: "client.html"
</code>```

where 0 and 1 are OBJECTS and title/page the strings.

Question: how can I extract the objects into a simple array (not objects) with multiple key pairs or is there another way to format the source file?

There are plenty of questions on here with similar questions but I just can't get any of them to work, including Object.entries(obj)

Thanks.

答:
const json = {
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]
}

const addObj = json.pages

for (el of json.pages) {
  console.log('key-value pairs:', Object.entries(el), '; keys:', Object.keys(el), '; values:', Object.values(el))
}```

Title: Extract array of objects into array

Body:
I have a fetch function which returns a json file. The source file looks like this:

{
    "pages":[
        {
            "page": "people.html",
            "title": "People"
        },
        {
            "page": "client.html",
            "title": "Client"
        }
    ]

}

When the response from the fetch (after applying .json()) it is a array of multiple objectives, each with two strings:

0
title: "People Policies"
page: "people.html"

1
title: "Client Policies"
page: "client.html"

where 0 and 1 are OBJECTS and title/page the strings.

Question: how can I extract the objects into a simple array (not objects) with multiple key pairs or is there another way to format the source file?

There are plenty of questions on here with similar questions but I just can't get any of them to work, including Object.entries(obj)

Thanks.


问:
Flutter firestore streambuilder with a future
I have a simple question. The reference to my firestore collection is dynamic. In this piece of code, getDocumentReference() gives me a reference to document after checking the user's email.
I use this document reference to get my snapshots.

```<code>Future<Stream<QuerySnapshot>> getHabits() async {
    DocumentReference document = await getDocumentReference();
    var snapshots =  document.collection('habits').snapshots();
    return snapshots;
}
</code>```

As you can see, I want to use this Future<Stream<QuerySnapshot>> for a streambuilder. How can I do that? I tried something like this. But it is not taking the future as input to stream

```<code>return StreamBuilder(
   stream: getHabits(),
);
</code>```

答:
You can wrap it in a FutureBuilder:

return FutureBuilder<Stream<QuerySnapshot>>(
   future: getHabits(),
   builder: (context, snapshot) {
      if (snapshot.hasData) {
          return StreamBuilder(stream: snapshot.data); // Success
      } else if (snapshot.hasError) {
          return Text('${snapshot.error}'); // Error
      } else {
          return CircularProgressIndicator(); // Loading
      }
   },

);
```

Body:
I have a simple question. The reference to my firestore collection is dynamic. In this piece of code, getDocumentReference() gives me a reference to document after checking the user's email.
I use this document reference to get my snapshots.

Future<Stream<QuerySnapshot>> getHabits() async {
    DocumentReference document = await getDocumentReference();
    var snapshots =  document.collection('habits').snapshots();
    return snapshots;
}

As you can see, I want to use this Future<Stream<QuerySnapshot>> for a streambuilder. How can I do that? I tried something like this. But it is not taking the future as input to stream

return StreamBuilder(
   stream: getHabits(),
);


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
Updated ans :

```<code>import sys
sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print(f"{sh} is not numeric")
    sys.exit(0)
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print(f"{sr} is not numeric")
    sys.exit(0)
</code>```

jupyter output

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
Updated ans :

import sys
sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print(f"{sh} is not numeric")
    sys.exit(0)
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print(f"{sr} is not numeric")
    sys.exit(0)

jupyter output


问:
flutter: top of image deleted in stack widget
I am trying to use stack in my widget tree:

```<code>  body: Center(
    child: SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),
          ),
          Positioned(
            top: -60,
            left: 0,
            right: 0,
            bottom: 0,
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);
</code>```

And this result is this:

Why top of setting icon has been deleted?

答:
I fixed the problem:

```<code> body: Center(
    child: SingleChildScrollView(
      child: Stack(
        // overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 80.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),

          ),
          FractionalTranslation(
            translation: Offset(0.0, 0.0),
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);
</code>```

and it is result:

I increases Top margin to top: 80.0 and replace Positioned with FractionalTranslation. Actually it works with Positioned too.

Body:
I am trying to use stack in my widget tree:

  body: Center(
    child: SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 20.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),
          ),
          Positioned(
            top: -60,
            left: 0,
            right: 0,
            bottom: 0,
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);

And this result is this:

Why top of setting icon has been deleted?

Body:
I fixed the problem:

 body: Center(
    child: SingleChildScrollView(
      child: Stack(
        // overflow: Overflow.visible,
        children: <Widget>[
          Container(
            // card view
            alignment: Alignment.center,
            height: 200,
            margin: EdgeInsets.only(
                top: 80.0, bottom: 50.0, left: 50.0, right: 50.0),
            decoration: BoxDecoration(
              color: color_transparent_black,
              borderRadius: BorderRadius.circular(14.0),
            ),

          ),
          FractionalTranslation(
            translation: Offset(0.0, 0.0),
            child: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: width * 0.3,
                height: height * 0.2,
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  child: Image.asset("assets/images/ic_setting.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
  ),
);

and it is result:

I increases Top margin to top: 80.0 and replace Positioned with FractionalTranslation. Actually it works with Positioned too.


问:
How to remove language in Abp.io template?
I need to hidd language select menu.
In sources Abp famework I saw code, what check count registrated languages. If lenguages more then one, language select menu item is visible.</p>

答:
in the web project, you can create the subfolder tree Themes/Basic/Components/ToolBar/LanguageSwitch and into create the file Default.cshtml

You can see che original content in
https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Components/Toolbar/LanguageSwitch/Default.cshtml

You go to comment all code if necessary.

Danilo


问:
Is there a way to overline text in android studio (java)
I am trying to display square roots in my java mobile aplication. I tried with HTML by typing the code below. It displays the square root symbol but there is no line over the variable (√100). Is there a way to overline the variable (x). Thanks for your help :)
TextView.settext(Html.fromHtml("&#x221A "+x));

答:
You can try StrikethroughSpan like this:</p>

```<code>textView.setText(x.toString(), TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) textView;
spannable.setSpan(new StrikethroughSpan(), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
</code>```

Body:
You can try StrikethroughSpan like this:

textView.setText(x.toString(), TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) textView;
spannable.setSpan(new StrikethroughSpan(), 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);


问:
How to sort a dataframe columns by the median of all its columns
How can I sort this datfarame by the median of its columns?

```<code>A    B    C

1    2    3
4    5    6
7    8    9
10   11   12
</code>```

So, the output would be

```<code>C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

</code>```

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

答:
Calculate median column-wise and order :

```<code>df[order(-sapply(df, median))]

#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10
</code>```

You can also use colMedians from matrixStats to get column-wise median.

```<code>df[order(-matrixStats::colMedians(as.matrix(df)))]
</code>```

data

```<code>df <- structure(list(A = c(1L, 4L, 7L, 10L), B = c(2L, 5L, 8L, 11L),
C = c(3L, 6L, 9L, 12L)), class = "data.frame", row.names = c(NA, -4L))
</code>```

Body:
How can I sort this datfarame by the median of its columns?

A    B    C

1    2    3
4    5    6
7    8    9
10   11   12

So, the output would be

C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

Body:
Calculate median column-wise and order :

df[order(-sapply(df, median))]

#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10

You can also use colMedians from matrixStats to get column-wise median.

df[order(-matrixStats::colMedians(as.matrix(df)))]

data

df <- structure(list(A = c(1L, 4L, 7L, 10L), B = c(2L, 5L, 8L, 11L),
C = c(3L, 6L, 9L, 12L)), class = "data.frame", row.names = c(NA, -4L))


问:
Failed installation of package "ncdf4" in R studio
I'm trying to install an R package called "ncdf4".
I've tried installing it in the "packages" section in the R-studio interface, but have also tried entering install.packages("ncdf4") into the console.

This is the output I get in both instances:

```<code>Installing package into ‘/home/user/R/x86_64-pc-linux-gnu-library/3.6’
(as ‘lib’ is unspecified)
trying URL 'https://cloud.r-project.org/src/contrib/ncdf4_1.17.tar.gz'
Content type 'application/x-gzip' length 124458 bytes (121 KB)
==================================================
downloaded 121 KB

* installing *source* package ‘ncdf4’ ...
** package ‘ncdf4’ successfully unpacked and MD5 sums checked
** using staged installation
configure.ac: starting
checking for nc-config... no
-----------------------------------------------------------------------------------
Error, nc-config not found or not executable.  This is a script that comes with the
netcdf library, version 4.1-beta2 or later, and must be present for configuration
to succeed.

If you installed the netcdf library (and nc-config) in a standard location, nc-config
should be found automatically.  Otherwise, you can specify the full path and name of
the nc-config script by passing the --with-nc-config=/full/path/nc-config argument
flag to the configure script.  For example:

./configure --with-nc-config=/sw/dist/netcdf4/bin/nc-config

Special note for R users:
-------------------------
To pass the configure flag to R, use something like this:

R CMD INSTALL --configure-args="--with-nc-config=/home/joe/bin/nc-config" ncdf4

where you should replace /home/joe/bin etc. with the location where you have
installed the nc-config script that came with the netcdf 4 distribution.
-----------------------------------------------------------------------------------
ERROR: configuration failed for package ‘ncdf4’
* removing ‘/home/user/R/x86_64-pc-linux-gnu-library/3.6/ncdf4’
Warning in install.packages :
  installation of package ‘ncdf4’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpXcbO2y/downloaded_packages’
</code>```

Is anybody able to decipher what went wrong from the code that I've provided?
Thanks.

答:
For Arch Linux users, you probably haven't installed netcdf. You can use pacman to install netcdf

```<code>sudo pacman -S netcdf
</code>```

Body:
I'm trying to install an R package called "ncdf4".
I've tried installing it in the "packages" section in the R-studio interface, but have also tried entering install.packages("ncdf4") into the console.

This is the output I get in both instances:

Installing package into ‘/home/user/R/x86_64-pc-linux-gnu-library/3.6’
(as ‘lib’ is unspecified)
trying URL 'https://cloud.r-project.org/src/contrib/ncdf4_1.17.tar.gz'
Content type 'application/x-gzip' length 124458 bytes (121 KB)
==================================================
downloaded 121 KB

* installing *source* package ‘ncdf4’ ...
** package ‘ncdf4’ successfully unpacked and MD5 sums checked
** using staged installation
configure.ac: starting
checking for nc-config... no
-----------------------------------------------------------------------------------
Error, nc-config not found or not executable.  This is a script that comes with the
netcdf library, version 4.1-beta2 or later, and must be present for configuration
to succeed.

If you installed the netcdf library (and nc-config) in a standard location, nc-config
should be found automatically.  Otherwise, you can specify the full path and name of
the nc-config script by passing the --with-nc-config=/full/path/nc-config argument
flag to the configure script.  For example:

./configure --with-nc-config=/sw/dist/netcdf4/bin/nc-config

Special note for R users:
-------------------------
To pass the configure flag to R, use something like this:

R CMD INSTALL --configure-args="--with-nc-config=/home/joe/bin/nc-config" ncdf4

where you should replace /home/joe/bin etc. with the location where you have
installed the nc-config script that came with the netcdf 4 distribution.
-----------------------------------------------------------------------------------
ERROR: configuration failed for package ‘ncdf4’
* removing ‘/home/user/R/x86_64-pc-linux-gnu-library/3.6/ncdf4’
Warning in install.packages :
  installation of package ‘ncdf4’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpXcbO2y/downloaded_packages’

Is anybody able to decipher what went wrong from the code that I've provided?
Thanks.

Body:
For Arch Linux users, you probably haven't installed netcdf. You can use pacman to install netcdf

sudo pacman -S netcdf


问:
Actually delete a git commit in such a way that it disappears from the log
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

```<code>git rebase -i fork1~1 fork1~3
</code>```

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

```<code>*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.
</code>```

答:
That is expected behavior.

Git is basically a simple directed graph where branches are auto-advanced names (aka refs) to commits, and thus a head node in some graph subtree. A reset is one method to change which commit a branch names.

Likewise, when a rebase is performed, changes that result in a different hash calculation result in a distinct commits. Parent hashes are also part of the calculation, which is why dropping a commit affects all descendants. The branch is then updated to point to the new commit tree’s head, while the original commits themselves are not actually removed from the set of all commits and can still be found via the reflog.

After a reset or rebase these outdated (including dropped) commits are “orphans” if and only if they cannot be referenced by any refs+. The commits can still be referenced by commit hash as they still exist on disk; however, if there are no direct refs to these commits, and they are not an ancestor of any refs, they are not expected to show up in the log command.

+Git refs (aka references) include ~branches~, ~tags~, and ~stash entries~.

If commits are not “orphaned”, and thus visible in the normal log, there is a branch or tag that needs to be updated. This also includes remote tracking branches and stash entries. Update and/or remove these refs as relevant. If the branch keeping these commits from being “orphaned” is already pushed and on a mainline .. well, let’s hope that is not the case.

Removing a commit from disk, after it has been made an orphan can be done via the prune command which can delete all orphans. Git normally does periodic GC housekeeping so this is not normally required.

If the commit has already been pushed, this process must be propagated to every repository that now has the change. If this involves force-pushing mainline branches it may be "very annoying" to other developers and/or infeasible, depending on how many other commits are descendants. This should only be done as last resort as commit (and any data therein) is already leaked and a potential dependency of other remote commits.

Body:
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

git rebase -i fork1~1 fork1~3

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.


问:
Laravel: if I neet to get data from other site should i make a route wirh get or post?
I am trying to implement payment by card in a laravel project. After i enter the card details the payment site must to redirect to my site with infos about payment.

For this i made a route like this

Route::post('/mobilpay/mobilpay/back', 'HomepageController@back');```
</div>
</div>
</p>

<p>I put also in VerifyCfsrTocken.php the code </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>protected $except = [
        'ipn/*',
        'mobilpay/*',

        //
    ];</code>```

After i enter the card details i get the error:

The GET method is not supported for this route. Supported methods: POST.```

Is a problem with my route? Should I make a route with get and not with post?

Thanks alot

答:
The issue is how you made the request at the frontend. You should either make a form post request or make an ajax post request.
Please do check your frontend</p>

Body:
I am trying to implement payment by card in a laravel project. After i enter the card details the payment site must to redirect to my site with infos about payment.

For this i made a route like this

Route::post('/mobilpay/mobilpay/back', 'HomepageController@back');

I put also in VerifyCfsrTocken.php the code

protected $except = [
        'ipn/*',
        'mobilpay/*',

        //
    ];

After i enter the card details i get the error:

The GET method is not supported for this route. Supported methods: POST.

Is a problem with my route? Should I make a route with get and not with post?

Thanks alot