问:
How do I get an "edit" button for a row in a list/for each loop? [SwiftUI]
I want to get an edit and add a button like the circled buttons shown in the image below. I need these buttons so that I can change the properties of the folders. How do I get this button to work when the default SwiftUI Edit button is clicked?

What I want:

(Before Edit button clicked)

(After Edit Button Clicked)

What I currently have:

(Before Edit button clicked)

(After Edit Button Clicked)

My code:

```<code>var body: some View {
        ZStack {
            List {
                ForEach(searchResults, id: \.self.id) { dir in
                    Section(dir.title) {
                        ForEach(dir.getChildFolders(), id: \.self.id) { folder in
                            NavigationLink(destination: DirectoryView(directory: folder)) {
                                Label(folder.title, systemImage: "folder")
                            }
                        }
                        .onDelete(perform: { offsets in
                            dir.items.remove(atOffsets: offsets)
                            updateView.update()
                        })
                        .onMove(perform: { source, destination in
                            dir.items.move(fromOffsets: source, toOffset: destination)
                            updateView.update()
                        })
                    }
                }

            }
</code>```

答:
You need to display the button yourself.

First, ensure you have some @State var tracking whether Edit mode is toggled:

@State var editing: Bool = false
```
<p>Then, in your <code>body</code>, show the circle button next to the <code>NavigationLink</code> if you are <code>editing</code>:</p>
<pre class="lang-swift prettyprint-override"><code>var body: some View {
    ZStack {
        List {
            ForEach(searchResults, id: \.self.id) { dir in
                Section(dir.title) {
                    ForEach(dir.getChildFolders(), id: \.self.id) { folder in
                        HStack {
                            NavigationLink(destination: DirectoryView(directory: folder)) {
                                Label(folder.title, systemImage: "folder")
                            }
                            if editing {
                                Spacer()
                                Button(action: {
                                    // Perform circle button action here
                                }) {
                                    Image(systemName: "ellipsis.circle")
                                }
                            }
                        }
                    }
                    .onDelete(perform: { offsets in
                        dir.items.remove(atOffsets: offsets)
                        updateView.update()
                    })
                    .onMove(perform: { source, destination in
                        dir.items.move(fromOffsets: source, toOffset: destination)
                        updateView.update()
                    })
                }
            }
        }
    }
}
</code>```

Body:
I want to get an edit and add a button like the circled buttons shown in the image below. I need these buttons so that I can change the properties of the folders. How do I get this button to work when the default SwiftUI Edit button is clicked?

What I want:

(Before Edit button clicked)

(After Edit Button Clicked)

What I currently have:

(Before Edit button clicked)

(After Edit Button Clicked)

My code:

var body: some View {
        ZStack {
            List {
                ForEach(searchResults, id: \.self.id) { dir in
                    Section(dir.title) {
                        ForEach(dir.getChildFolders(), id: \.self.id) { folder in
                            NavigationLink(destination: DirectoryView(directory: folder)) {
                                Label(folder.title, systemImage: "folder")
                            }
                        }
                        .onDelete(perform: { offsets in
                            dir.items.remove(atOffsets: offsets)
                            updateView.update()
                        })
                        .onMove(perform: { source, destination in
                            dir.items.move(fromOffsets: source, toOffset: destination)
                            updateView.update()
                        })
                    }
                }

            }

Body:
You need to display the button yourself.

First, ensure you have some @State var tracking whether Edit mode is toggled:

@State var editing: Bool = false

Then, in your body, show the circle button next to the NavigationLink if you are editing:

var body: some View {
    ZStack {
        List {
            ForEach(searchResults, id: \.self.id) { dir in
                Section(dir.title) {
                    ForEach(dir.getChildFolders(), id: \.self.id) { folder in
                        HStack {
                            NavigationLink(destination: DirectoryView(directory: folder)) {
                                Label(folder.title, systemImage: "folder")
                            }
                            if editing {
                                Spacer()
                                Button(action: {
                                    // Perform circle button action here
                                }) {
                                    Image(systemName: "ellipsis.circle")
                                }
                            }
                        }
                    }
                    .onDelete(perform: { offsets in
                        dir.items.remove(atOffsets: offsets)
                        updateView.update()
                    })
                    .onMove(perform: { source, destination in
                        dir.items.move(fromOffsets: source, toOffset: destination)
                        updateView.update()
                    })
                }
            }
        }
    }
}


来源: stackexchange

问:
How to display all array elements in one column of table
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

```
</div>
</div>
</p>
<p>This is how my arrays look like.</p>
``` $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);
```
<p>This is how I tried to display but it did not work as expected.</p>
```foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}
```

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

答:
You can use a multidimensional array and loop through it.</p>
```<code>$array = [
    1 => ['banana', 'orange', 'apple'],
    2 => ['ferrari', 'lamborghini', 'pagani'],
    3 => ['mars', 'moon', 'venus'],
];

<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
 <?php foreach($array as $key => $value) { ?>
    <tr>
        <?php foreach($value as $name) { ?>
        <td><?=$name?></td>
        <?php } ?>
    </tr>
<?php } ?>
</table>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

This is how my arrays look like.

 $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);

This is how I tried to display but it did not work as expected.

foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

Body:
You can use a multidimensional array and loop through it.

$array = [
    1 => ['banana', 'orange', 'apple'],
    2 => ['ferrari', 'lamborghini', 'pagani'],
    3 => ['mars', 'moon', 'venus'],
];

<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
 <?php foreach($array as $key => $value) { ?>
    <tr>
        <?php foreach($value as $name) { ?>
        <td><?=$name?></td>
        <?php } ?>
    </tr>
<?php } ?>
</table>


问:
Website (nginx) and nodejs REST API on the same server
I want to serve a gatsby.js static website using nginx and a nodejs REST API on the same server.

Currently I have the REST API running with a SSL certificate using Let's Encrypt. It is listening to port 80 and 443.

Now I want to serve the website but I found that the port 80 is already used by the nodejs server.

How can I handle this? Any idea on how to do it?

答:
I see 2 solutions to your problem,

You make your REST API listen on a different port than 80/443, so that your Gatsby application can use it. You should be able to do this in the configuration of your BACKEND application.

You create a sub-domain for your REST API using your DNS provider such as cms.mysite.com which will also use ports 80/443.

The domain name of the frontend application will be mysite.com.

You configure your Nginx server to serve both applications (BACKEND + FRONTEND) depending on which subdomain is making the request.
Here is an example of the Nginx default.conf configuration file:

```<code>upstream backend {
    server web:8000;
}

server {
    listen 80;
    server_name cms.mysite.com;

    location / {
        return 301 https://$host$request_uri;
    }

    ...
}

server {
    listen 443 ssl;
    server_name cms.mysite.com;

    ...
}

server {
    listen 80;
    server_name mysite.com;

    location / {
        return 301 https://$host$request_uri;
    }

    ...
}

server {
    listen 443 ssl;
    server_name mysite.com;

    ...

}
</code>```

This is my first answer to the community, I hope it will help you !

Body:
I see 2 solutions to your problem,

You make your REST API listen on a different port than 80/443, so that your Gatsby application can use it. You should be able to do this in the configuration of your BACKEND application.

You create a sub-domain for your REST API using your DNS provider such as cms.mysite.com which will also use ports 80/443.

The domain name of the frontend application will be mysite.com.

You configure your Nginx server to serve both applications (BACKEND + FRONTEND) depending on which subdomain is making the request.
Here is an example of the Nginx default.conf configuration file:

upstream backend {
    server web:8000;
}

server {
    listen 80;
    server_name cms.mysite.com;

    location / {
        return 301 https://$host$request_uri;
    }

    ...
}

server {
    listen 443 ssl;
    server_name cms.mysite.com;

    ...
}

server {
    listen 80;
    server_name mysite.com;

    location / {
        return 301 https://$host$request_uri;
    }

    ...
}

server {
    listen 443 ssl;
    server_name mysite.com;

    ...

}

This is my first answer to the community, I hope it will help you !


问:
Javascript split array
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

```<code>XXX MA Yo-Yo
</code>```

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

```<code>for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}
</code>```

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

答:
Try this</p>

```<code>for (var i = 0; i < arr.length; i++) {
    var w_temp = arr[i];

    // assuming w_temp contains an array where the second item
    // is the full name string
    var parts = w_temp[1].match(/^(.+?) (.+)$/);
    var cn_name = parts[1];
    var en_name = parts[2];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript split array

Body:
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

XXX MA Yo-Yo

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

Body:
Try this

for (var i = 0; i < arr.length; i++) {
    var w_temp = arr[i];

    // assuming w_temp contains an array where the second item
    // is the full name string
    var parts = w_temp[1].match(/^(.+?) (.+)$/);
    var cn_name = parts[1];
    var en_name = parts[2];
}


问:
Assertation Error, You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation
I'm learning drf. I created api using it for minimarket app. After creating some data, i tried to get all of them and i got AssertationError like "You passed a Serializer instance as data, but probably meant to pass serialized .data or .error. representation.
" :(    Who knows, what can i do?

views.py

```<code>@api_view(['GET'])
def view_items(request):

    # checking for the parameters from the URL
    items = Item.objects.all()

    # if there is something in items else raise error
    if items:
        return Response(ItemSerializer(items))
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)
</code>```

urls.py

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.ApiOverview, name='home'),
    path('create/', views.add_items, name='add-items'),
    path('all/', views.view_items, name='view_items'),
]
</code>```

serializers.py

```<code>from pyexpat import model
from django.db.models import fields
from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('category', 'subcategory', 'name', 'amount')
</code>```

答:
As the error says, you can not return a serializer in the response:

```return Response(<b><s>ItemSerializer(</s></b>items<b><s>)</s></b>)```

You can return the data of the serializer, so:

```<code>@api_view(['GET'])
def view_items(request):
    # checking for the parameters from the URL
    items = Item.objects.all()
    serializer = ItemSerializer(items<strong>, many=True</strong>)

    # if there is something in items else raise error
    if items:
        return Response(<strong>serializer.data</strong>)
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)</code>```

Body:
I'm learning drf. I created api using it for minimarket app. After creating some data, i tried to get all of them and i got AssertationError like "You passed a Serializer instance as data, but probably meant to pass serialized .data or .error. representation.
" :(    Who knows, what can i do?

views.py

@api_view(['GET'])
def view_items(request):

    # checking for the parameters from the URL
    items = Item.objects.all()

    # if there is something in items else raise error
    if items:
        return Response(ItemSerializer(items))
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.ApiOverview, name='home'),
    path('create/', views.add_items, name='add-items'),
    path('all/', views.view_items, name='view_items'),
]

serializers.py

from pyexpat import model
from django.db.models import fields
from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('category', 'subcategory', 'name', 'amount')

Body:
As the error says, you can not return a serializer in the response:

return Response(<s>ItemSerializer(</s>items<s>)</s>)

You can return the data of the serializer, so:

@api_view(['GET'])
def view_items(request):
    # checking for the parameters from the URL
    items = Item.objects.all()
    serializer = ItemSerializer(items, many=True)

    # if there is something in items else raise error
    if items:
        return Response(serializer.data)
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)


问:
Gitlab Rules: Manual step always shown even when rule met
We have a complex Gitlab pipeline, we've split the stages into different files and they are run based on the branch and source.

I'm trying to set up a schedule job to run that will just run one section of the pipeline, to do this I'm trying to use rules to ignore all other stages I don't want to run by doing something like this e.g.

```<code>    - if: $CI_PIPELINE_SOURCE == "schedule"
          when: never
</code>```

The problem is the stages also have a manual rule so even though I say skip if a schedule the pipeline still asks for a manual interaction:

```<code>  rules:
    - if: $CI_COMMIT_BRANCH == "master"
      when: never
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: never
    - when: manual
    - if: $CI_PIPELINE_SOURCE == "schedule"
      when: never
</code>```

Is there a way I can skip this stage when the source is a "schedule" but still have the manual step for the other scenarios?

答:
it is important to understand that rules are evaluated in the order you put them into the rules block.

this means your when:manual has precedence over your "Schedule" rule.

If you swap them like below, your schedule rule will be evaluated first, and you should not see a pipeline step see https://docs.gitlab.com/ee/ci/yaml/#rules

Rules are evaluated when the pipeline is created, and evaluated in order until the first match. When a match is found, the job is either included or excluded from the pipeline, depending on the configuration.

  rules:
    - if: $CI_COMMIT_BRANCH == "master"
      when: never
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: never
    - if: $CI_PIPELINE_SOURCE == "schedule"
      when: never
    - when: manual
```

Body:
We have a complex Gitlab pipeline, we've split the stages into different files and they are run based on the branch and source.

I'm trying to set up a schedule job to run that will just run one section of the pipeline, to do this I'm trying to use rules to ignore all other stages I don't want to run by doing something like this e.g.

    - if: $CI_PIPELINE_SOURCE == "schedule"
          when: never

The problem is the stages also have a manual rule so even though I say skip if a schedule the pipeline still asks for a manual interaction:

  rules:
    - if: $CI_COMMIT_BRANCH == "master"
      when: never
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: never
    - when: manual
    - if: $CI_PIPELINE_SOURCE == "schedule"
      when: never

Is there a way I can skip this stage when the source is a "schedule" but still have the manual step for the other scenarios?


问:
Multidimensional array of zeros in Ruby
To create a one-dimensional array, I can write:

```<code>arr = Array.new(10) { |z| 0 }
#=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

But I want to know how to initialize an array in more dimensions, e.g.:

```<code>#=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
</code>```

This is just an example. I am trying to understand the general case.

答:
I am trying to understand the general case.

```<code>Array.new(n) # where n is natural number 1..n

#=>[nil, nil, nil]
</code>```

This will create a 1-D Array i:e One dimension array.

Let extends further for a multi-dimensional array i:e Two dimension array .

In ruby, every method accepts a block.

```<code>Array.new(3) do
 Array.new(3)
 end
end
</code>```

Same can be written In online (macro style)  Array.new(3) { Array.new(3) }

```<code>[
 [nil, nil, nil],
 [nil, nil, nil],
 [nil, nil, nil]
]
</code>```

Further, it can extend to initialize each cell value.

Array.new(3) do
Array.new(3) do
0
end
end

```<code>[
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
]
</code>```

One line micro style Array.new(3) { Array.new(3) { 0 } }

Let extends further three-dimension array.

```<code>Array.new(2) do
  Array.new(3) do
    Array.new(4) do
      0
    end
  end
end
</code>```

OR

The same can be written as micro-style syntax

```<code>Array.new(2) { Array.new(3) { Array.new(4) } {0} }

[
  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
]
</code>```

Title: Multidimensional array of zeros in Ruby

Body:
To create a one-dimensional array, I can write:

arr = Array.new(10) { |z| 0 }
#=> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

But I want to know how to initialize an array in more dimensions, e.g.:

#=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

This is just an example. I am trying to understand the general case.

Body:
I am trying to understand the general case.

Array.new(n) # where n is natural number 1..n

#=>[nil, nil, nil]

This will create a 1-D Array i:e One dimension array.

Let extends further for a multi-dimensional array i:e Two dimension array .

In ruby, every method accepts a block.

Array.new(3) do
 Array.new(3)
 end
end

Same can be written In online (macro style)  Array.new(3) { Array.new(3) }

[
 [nil, nil, nil],
 [nil, nil, nil],
 [nil, nil, nil]
]

Further, it can extend to initialize each cell value.

Array.new(3) do
Array.new(3) do
0
end
end

[
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
]

One line micro style Array.new(3) { Array.new(3) { 0 } }

Let extends further three-dimension array.

Array.new(2) do
  Array.new(3) do
    Array.new(4) do
      0
    end
  end
end

OR

The same can be written as micro-style syntax

Array.new(2) { Array.new(3) { Array.new(4) } {0} }

[
  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
]


问:
Failure in installing python packages pip
OS: Ubuntu 18.04.5
python: python2.7.17
I created a python script in python 2.7.17

I have 20+ production servers all running at different versions of python2.7, say python 2.7.6, python 2.7.13

When I am installing the requirements.txt using virtualenv created with python2.7.13, everything is working fine.
However, when I install packages on servers with python2.7.6, I get an error:

```<code>Could not find a version that satisfies the requirement cachetools==3.1.1 (from -r requirements.txt (line 1)) (from versions: )
No matching distribution found for cachetools==3.1.1 (from -r requirements.txt (line 1))
</code>```

The problem is the version of packages in requirements.txt doesn't exist for python2.7.6 (python2.7.6 may have the package at a lower version)

How do I fix this version mismatch?

Is there any way to auto-detect the latest version of the package basis on the python version and then install it?

答:
It is mentioned in the pip docs here, that

Once pip has the set of requirements to satisfy, it chooses which version of each requirement to install using the simple rule that the latest version that satisfies the given constraints will be installed.

So, I suggest removing the package version specifier, for example replace pip install cachetools==3.1.1 with pip install cachetools.

Body:
OS: Ubuntu 18.04.5
python: python2.7.17
I created a python script in python 2.7.17

I have 20+ production servers all running at different versions of python2.7, say python 2.7.6, python 2.7.13

When I am installing the requirements.txt using virtualenv created with python2.7.13, everything is working fine.
However, when I install packages on servers with python2.7.6, I get an error:

Could not find a version that satisfies the requirement cachetools==3.1.1 (from -r requirements.txt (line 1)) (from versions: )
No matching distribution found for cachetools==3.1.1 (from -r requirements.txt (line 1))

The problem is the version of packages in requirements.txt doesn't exist for python2.7.6 (python2.7.6 may have the package at a lower version)

How do I fix this version mismatch?

Is there any way to auto-detect the latest version of the package basis on the python version and then install it?


问:
Get a flash object to be next to an input field
I am having trouble with getting two elements lined up properly.

Here is my HTML:

```<code><input class='pretty-border' id='shareinput' value='afdsdasfdasfadsff' />
<span>
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            width="14"
            height="14"
            id="clippy" >
        <param name="movie" value="/clippy.swf"/>
        <param name="allowScriptAccess" value="always" />
        <param name="quality" value="high" />
        <param name="scale" value="noscale" />
        <param NAME="FlashVars" value="id=clip_text">
        <param name="bgcolor" value="#FFFFFF">
        <embed src="/clippy.swf"
               width="14"
               height="14"
               name="clippy"
               quality="high"
               allowScriptAccess="always"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer"
               FlashVars="id=clip_text"
               bgcolor="#FFFFFF"
        />
    </object>
</span>
</code>```

And this is my CSS:

```<code>input.pretty-border {
  float:left;
  font-size:1em;
  width: 300px;
  padding: 5px 10px;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  border: 4px solid #c9deff;
}
</code>```

Unfortunately, there is a line break between the objects as can be seen in the attached picture. How can I get rid of it?

答:
try giving both elements the same class name then put the float:left for that class, not just the input element.</p>

```<code>.sameclass {
     float:left;
 }
</code>```

Body:
I am having trouble with getting two elements lined up properly.

Here is my HTML:

<input class='pretty-border' id='shareinput' value='afdsdasfdasfadsff' />

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
            width="14"
            height="14"
            id="clippy" >
        <param name="movie" value="/clippy.swf"/>
        <param name="allowScriptAccess" value="always" />
        <param name="quality" value="high" />
        <param name="scale" value="noscale" />
        <param NAME="FlashVars" value="id=clip_text">
        <param name="bgcolor" value="#FFFFFF">
        <embed src="/clippy.swf"
               width="14"
               height="14"
               name="clippy"
               quality="high"
               allowScriptAccess="always"
               type="application/x-shockwave-flash"
               pluginspage="http://www.macromedia.com/go/getflashplayer"
               FlashVars="id=clip_text"
               bgcolor="#FFFFFF"
        />
    </object>

And this is my CSS:

input.pretty-border {
  float:left;
  font-size:1em;
  width: 300px;
  padding: 5px 10px;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  border: 4px solid #c9deff;
}

Unfortunately, there is a line break between the objects as can be seen in the attached picture. How can I get rid of it?

Body:
try giving both elements the same class name then put the float:left for that class, not just the input element.

.sameclass {
     float:left;
 }


问:
Please do I interprete this ternary operator?
Please if this function was to be converted to a "normal" if else statement, how would it look like?

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

I want to add another condition, but I'm finding it hard to read or digest the current flow.

答:
If-y version

```<code>const iffyOrderArray =
  (arr: any[], key: string) => arr
    .sort((a, b) => {
      if (a[key] > b[key]) {
        return 1;
      } else {
        if (a[key] === b[key]) {
          if (a[key] > b[key]) {
            return 1;
          } else {
            return -1;
          }
        } else {
          return -1;
        }
      }
    });
</code>```

Original Version(Formatted)

```<code>const orderArr =
  (arr: any[], key: string) => arr
    .sort((a, b) =>
    ((a[key] > b[key])
      ? 1
      : (a[key] === b[key])
        ? ((a[key] > b[key])
          ? 1
          : -1)
        : -1));
</code>```

const orderArr = (arr, key) => arr
  .sort((a, b) => ((a[key] > b[key]) ?
    1 :
    (a[key] === b[key]) ?
    ((a[key] > b[key]) ?
      1 :
      -1) :
    -1));

const iffyOrderArray = (arr, key) => arr
  .sort((a, b) => {
    if (a[key] > b[key]) {
      return 1;
    } else {
      if (a[key] === b[key]) {
        if (a[key] > b[key]) {
          return 1;
        } else {
          return -1;
        }
      } else {
        return -1;
      }
    }
  });

const testArray = [{
  a: 42
}, {
  a: 21
}, {
  a: 23
}, {
  a: -45
}];

const testKey = "a";

console.log("Original", orderArr(testArray, testKey));

console.log("Revised", iffyOrderArray(testArray, testKey));```

On Stackoverflow, WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Body:
Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.

Body:
If-y version

const iffyOrderArray =
  (arr: any[], key: string) => arr
    .sort((a, b) => {
      if (a[key] > b[key]) {
        return 1;
      } else {
        if (a[key] === b[key]) {
          if (a[key] > b[key]) {
            return 1;
          } else {
            return -1;
          }
        } else {
          return -1;
        }
      }
    });

Original Version(Formatted)

const orderArr =
  (arr: any[], key: string) => arr
    .sort((a, b) =>
    ((a[key] > b[key])
      ? 1
      : (a[key] === b[key])
        ? ((a[key] > b[key])
          ? 1
          : -1)
        : -1));

const orderArr = (arr, key) => arr
  .sort((a, b) => ((a[key] > b[key]) ?
    1 :
    (a[key] === b[key]) ?
    ((a[key] > b[key]) ?
      1 :
      -1) :
    -1));

const iffyOrderArray = (arr, key) => arr
  .sort((a, b) => {
    if (a[key] > b[key]) {
      return 1;
    } else {
      if (a[key] === b[key]) {
        if (a[key] > b[key]) {
          return 1;
        } else {
          return -1;
        }
      } else {
        return -1;
      }
    }
  });

const testArray = [{
  a: 42
}, {
  a: 21
}, {
  a: 23
}, {
  a: -45
}];

const testKey = "a";

console.log("Original", orderArr(testArray, testKey));

console.log("Revised", iffyOrderArray(testArray, testKey));

On Stackoverflow, WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


问:
PowerApps Get Selected Item from Lookup to make a Button Visible at the Command line bar
I want a button from the command line bar to be visible or invisible depending on whether a record has been selected in the lookup field from the main form or not.
If no record has been selected, then the button should be displayed. Otherwise not.
For this problem, I want to use the Power Fx in PowerApps, but I haven't found a command yet, which shows me the content or something like that of the lookup field. Other field data types like text have worked without problems.
With Javascript, I already managed it without problems, but I would like to do it also in PowerFx if that should work.
Screenshot: https://i.stack.imgur.com/uqDJ6.png

The records come from the Table Company, where the attribute is Companyname.

Commands where I think they might work:

If([Selected Record];true;false);If(IsBlank([Selected Record]);true;false);If(IsBlankOrError([Selected Record]);true;false);If(IsEmpty([Selected Record]);true;false)

答:
I guess there are 2 scenarios:

The Lookup form control element is a Dropdown with a Selected output property. Then your approach would work like If(IsBlankOrError(DataCardValue1.Selected),true,false)

If your form control element is a ComboBox then you could use If(CountRows(DataCardValue1.SelectedItems)>0,true,false) or the above described IsBlankOrError.


问:
Crontab, every 6+1 hours (not every 7 hours)
If I set up my cron to be:

```<code>* */6 * * *
</code>```

Then my understanding is, that it will run at every day at every hour that is divisible by 6, so:

```<code>06:00
12:00
18:00
24:00
</code>```

Suppose I would like it to run it with a delay like 1 hour [pseudocode]:

```<code>* */6+1 * * *
</code>```

or

```<code>06:00 + 01:00 = 07:00
12:00 + 01:00 = 13:00
18:00 + 01:00 = 19:00
24:00 + 01:00 = 01:00
</code>```

How would I do that?

If I make it */7:

```<code>* */7 * * *
</code>```

It will run:

```<code>07:00
14:00
21:00
</code>```

which is not what I am looking for.

答:
There are a few different implementations of cron, so check the manual on your system by running man 5 crontab to confirm the format it supports.

Assuming you have the popular "Vixie cron", the format description includes the following:

Step values can be used in conjunction with ranges.  Following a range with /<number> specifies skips of the number's value through the range.  For example, 0-23/2 can be used in the hours field to specify command execution every other hour (the alternative in the V7 standard is 0,2,4,6,8,10,12,14,16,18,20,22).  Steps are also permitted after an asterisk, so if you want to say every two hours, just use */2.

And above that:

A field may be an asterisk (*), which always stands for first-last.

So, */6 is actually short-hand for 0-23/6 - start at 0, and continue in steps of 6 until we reach 23, giving 0,6,12,18. (Note that the hour field runs 0 to 23, not 1 to 24, as you've implied in the question.)

In this implementation, therefore, the sequence 1,7,13,19 can be written 1-23/6 (or 1-19/6).

With a large skip, writing out the list in full (1,7,13,19) is arguably more readable, and should work on all versions of cron, but that's up to you.

Body:
If I set up my cron to be:

* */6 * * *

Then my understanding is, that it will run at every day at every hour that is divisible by 6, so:

06:00
12:00
18:00
24:00

Suppose I would like it to run it with a delay like 1 hour [pseudocode]:

* */6+1 * * *

or

06:00 + 01:00 = 07:00
12:00 + 01:00 = 13:00
18:00 + 01:00 = 19:00
24:00 + 01:00 = 01:00

How would I do that?

If I make it */7:

* */7 * * *

It will run:

07:00
14:00
21:00

which is not what I am looking for.


问:
developing html5 canvas game: images or statements
I am porting an old dos game to html 5 canvas. It is a very basic game with animations of 2-3 frames. I have already extracted all the necessary frames which are very low-res and approximately 13*23 images. I can replicate the images by using canvas js statements or I can use the images I already have with drawImage().

The problem with using images is most modern browsers resize images by using interpolation techniques such as bicubic etc. This makes the images loose their dos-like low resolution appearances and they look awful since they have to be scaled as pixel arts.

The problem with using canvas js statements is that is very difficult to replicate all the images by hand but it solves the scaling problem.

What would be the ideal way to do it?

答: Draw them at their original width and height. They won't be anti-aliased if you draw them at integer-valued coordinates, i.e. (0, 0) rather than (0.5, 3.2).</p>


问:
How to set the limit for the dragging the div vise versa no more than minimum width which is 200
How can I set minimum width for not allowing drag left to no width in the following sample?

```<code>const App = () => {

    const [initialPos,   setInitialPos] = React.useState(null);
    const [initialSize, setInitialSize] = React.useState(null);

    const initial = (e) => {

        let resizable = document.getElementById('Resizable');

        setInitialPos(e.clientX);
        setInitialSize(resizable.offsetWidth);

    }

    const resize = (e) => {

        let resizable = document.getElementById('Resizable');

        resizable.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;

    }

    return(
        <div className = 'Block'>
            <div id = 'Resizable'/>
            <div id = 'Draggable'
                draggable   = 'true'
                onDragStart = {initial}
                onDrag      = {resize}
            />
        </div>
    );

}

ReactDOM.render(<App/>, document.getElementById('root'));
</code>```

https://codepen.io/erikmartinjordan/pen/dyMEXJb?editors=0110

答:
You can adjust your resize function to limit the width.

const resize = (e) => {
    let resizable = document.getElementById('Resizable');
    let newWidth = parseInt(initialSize) + parseInt(e.clientX - initialPos);
    if (newWidth < 200) {
    newWidth = 200;
    }
    resizable.style.width = `${newWidth}px`;
}
```

You can set 200 to be any maximum width. Just don't forget to change both 200 values, or even better make a variable for it!

Body:
How can I set minimum width for not allowing drag left to no width in the following sample?

const App = () => {

    const [initialPos,   setInitialPos] = React.useState(null);
    const [initialSize, setInitialSize] = React.useState(null);

    const initial = (e) => {

        let resizable = document.getElementById('Resizable');

        setInitialPos(e.clientX);
        setInitialSize(resizable.offsetWidth);

    }

    const resize = (e) => {

        let resizable = document.getElementById('Resizable');

        resizable.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;

    }

    return(

    );

}

ReactDOM.render(<App/>, document.getElementById('root'));

https://codepen.io/erikmartinjordan/pen/dyMEXJb?editors=0110

Body:
You can adjust your resize function to limit the width.

const resize = (e) => {
    let resizable = document.getElementById('Resizable');
    let newWidth = parseInt(initialSize) + parseInt(e.clientX - initialPos);
    if (newWidth < 200) {
    newWidth = 200;
    }
    resizable.style.width = `${newWidth}px`;
}

You can set 200 to be any maximum width. Just don't forget to change both 200 values, or even better make a variable for it!


问:
Error response from daemon: open \\.\pipe\docker_engine_linux: The system cannot find the file specified
While I am trying to start with docker on my windows 10 machine it is returning the following error.

ERROR: open \.\pipe\docker_engine_linux: The system cannot find the file specified.

I found when I logon to my computer, the hyper VM could not run docker virtual machine automatically though my docker desktop is running. Once I start docker virtual machine on hyper VM and restart docker once again, it works okay. But this is not a permanent solution. Could I get some help please?

答:
One way of solving this problem is doing the following step again every time you open your pc:

```<code># -------------------- enable the wsl for linux on windows ------------------- #
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

# ---------------------- enable virtual machine feature ---------------------- #
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

# ------------------------ set wsl as default version ------------------------ #
wsl --set-default-version 2
</code>```

and then start docker desktop icon
and docker engine will start without any porblem

Body:
One way of solving this problem is doing the following step again every time you open your pc:

# -------------------- enable the wsl for linux on windows ------------------- #
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

# ---------------------- enable virtual machine feature ---------------------- #
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

# ------------------------ set wsl as default version ------------------------ #
wsl --set-default-version 2

and then start docker desktop icon
and docker engine will start without any porblem


问:
How to configure WebStorm to work with nx lint instead of ESLint?
When working on nx projects with WebStorm (and probably with other JetBrains IDEs) I keep getting this error:

Error: Error while loading rule '@typescript-eslint/await-thenable': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.

I do have the parserOptions.project defined in the libs/mylibrary/.eslintrs.json:

{
  "extends": ["../../.eslintrc"],
  "parserOptions": {
    "project": "./tsconfig.*?.json",
    "tsconfigRootDir": "./libs/mylibrary"
  },
  ...
```

The error does not reproduce when I run ESLint manually, via npx eslint ./libs/mylibrary or via nx (nx lint mylibrary).

Any idea how to configure WebStorm to work well with nx lint?

答:
Can be a problem with wrong working folder the linter is run in. With Automatic configuration, the ESlint working folder is set to a folder where the nearest .eslintrc or eslintignore resides (as described in https://www.jetbrains.com/help/webstorm/eslint.html#ws_js_eslint_manual_configuration)
If the auto-detected working directory doesn't match your project configuration, you need to specify the working directory (directories) manually: in Settings | Languages & Frameworks | JavaScript | Code Quality Tools | ESLint, change configuration to Manual and specify the directory in which you run eslint --fix in terminal (project root folder?) as a working dir - this should solve the issue

Body:
When working on nx projects with WebStorm (and probably with other JetBrains IDEs) I keep getting this error:

Error: Error while loading rule '@typescript-eslint/await-thenable': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.

I do have the parserOptions.project defined in the libs/mylibrary/.eslintrs.json:

{
  "extends": ["../../.eslintrc"],
  "parserOptions": {
    "project": "./tsconfig.*?.json",
    "tsconfigRootDir": "./libs/mylibrary"
  },
  ...

The error does not reproduce when I run ESLint manually, via npx eslint ./libs/mylibrary or via nx (nx lint mylibrary).

Any idea how to configure WebStorm to work well with nx lint?


问:
VBA function works for debugger but fails to run in excel sheet
I'm new to VBA and I do not know what is happening here. I run a simple function like this:

```<code>    Function OnlyNumsRange(myRange As Range) As Range
       Dim cell As Range, newRange As Range

       Set newRange = myRange

       Dim rng As Range
       For Each rng In newRange
           rng.Value = rng.Value + 10
       Next

       Set OnlyNumsRange = newRange

    End Function
</code>```

Given a range, that code is supposed to return a new range with +10 on each cell.
This function works perfectly for VBA debugger, but when I try to run it on my excel sheet, it raises a #VALUE! error. Thank you in advance.

答: To return a value for the function, you assign the value to the function name, in this case, OnlyNumsRange.  You don't use Set in this case.</p>

Body:
I'm new to VBA and I do not know what is happening here. I run a simple function like this:

    Function OnlyNumsRange(myRange As Range) As Range
       Dim cell As Range, newRange As Range

       Set newRange = myRange

       Dim rng As Range
       For Each rng In newRange
           rng.Value = rng.Value + 10
       Next

       Set OnlyNumsRange = newRange

    End Function

Given a range, that code is supposed to return a new range with +10 on each cell.
This function works perfectly for VBA debugger, but when I try to run it on my excel sheet, it raises a #VALUE! error. Thank you in advance.


问:
How do I avoid CS0103 errors in Visual Studio when using Source Generators?
I've written a really simple source generator:

```<code>public void Execute(GeneratorExecutionContext context)
{
    var sourceBuilder = new StringBuilder(@"
        using System;
        namespace Injector.ConsoleApp;

        public partial class Program
        {
           static void HelloFrom(string name)
           {
               Console.WriteLine(""Hello from "" + name);
           }
        }
    ");

    context.AddSource("helloWorldGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
</code>```

It compiles, runs and behaves exactly as I'd hope and expect, but...

Visual Studio is unaware of the generated function and shows a CS0103 error. How can I get VS to not show an error for this?

答:
I figured it out! The solution was to change:

```<code>context.AddSource("helloWorldGenerator"...
</code>```

to

```<code>context.AddSource("Program"...
</code>```

Body:
I've written a really simple source generator:

public void Execute(GeneratorExecutionContext context)
{
    var sourceBuilder = new StringBuilder(@"
        using System;
        namespace Injector.ConsoleApp;

        public partial class Program
        {
           static void HelloFrom(string name)
           {
               Console.WriteLine(""Hello from "" + name);
           }
        }
    ");

    context.AddSource("helloWorldGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}

It compiles, runs and behaves exactly as I'd hope and expect, but...

Visual Studio is unaware of the generated function and shows a CS0103 error. How can I get VS to not show an error for this?

Body:
I figured it out! The solution was to change:

context.AddSource("helloWorldGenerator"...

to

context.AddSource("Program"...


问:
Give me error validator in undefinded but I used global key in Flutter, how to debug this error

Undefined named parameter error occurred when I used validator function in form text Field

I used the Global key and want to validate my form text field but when using the validator function compiler show the error validator is undefined. My code in a Flutter as follows:

```<code>import 'package:flutter/material.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreen();
}

class _LoginScreen extends State<LoginScreen> {
  //GlobalKey<FormState> formKey = GlobalKey();
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //child: Text('This is bakwas container'),
        appBar: AppBar(
          title: const Text('Login'),
        ),
        body: Form(
          key: _formKey,
          //validator:(){},
          child: Center(
            child: SizedBox(
              width: MediaQuery.of(context).size.width * .7,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const TextField(
                  // validator: (value) {
                    //   if (value == null || value.isEmpty) {
                    //     return 'Please enter some text';
                    //   }
                    //   return null;
                    // },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        labelText: 'Email', hintText: 'abc@example.com'),
                  ),
                  //const SizedBox(height: 10,)
                  const TextField(
                    obscureText: true,
                    keyboardType: TextInputType.visiblePassword,
                    decoration: InputDecoration(labelText: 'Password'),
                  ),
                  Container(
                      margin: const EdgeInsets.only(top: 10),
                      child: ElevatedButton(
                          onPressed: () {}, child: const Text('Press IT')))
                ],
              ),
            ),
          ),
        ));
  }
}
</code>```

答:
To use validator you need to replace TextFiled with TextFormField.

TextFormField(
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
  keyboardType: TextInputType.emailAddress,
  decoration: InputDecoration(
      labelText: 'Email', hintText: 'abc@example.com'),
),
```

Body:
Undefined named parameter error occurred when I used validator function in form text Field

I used the Global key and want to validate my form text field but when using the validator function compiler show the error validator is undefined. My code in a Flutter as follows:

import 'package:flutter/material.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreen();
}

class _LoginScreen extends State<LoginScreen> {
  //GlobalKey<FormState> formKey = GlobalKey();
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //child: Text('This is bakwas container'),
        appBar: AppBar(
          title: const Text('Login'),
        ),
        body: Form(
          key: _formKey,
          //validator:(){},
          child: Center(
            child: SizedBox(
              width: MediaQuery.of(context).size.width * .7,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const TextField(
                  // validator: (value) {
                    //   if (value == null || value.isEmpty) {
                    //     return 'Please enter some text';
                    //   }
                    //   return null;
                    // },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        labelText: 'Email', hintText: 'abc@example.com'),
                  ),
                  //const SizedBox(height: 10,)
                  const TextField(
                    obscureText: true,
                    keyboardType: TextInputType.visiblePassword,
                    decoration: InputDecoration(labelText: 'Password'),
                  ),
                  Container(
                      margin: const EdgeInsets.only(top: 10),
                      child: ElevatedButton(
                          onPressed: () {}, child: const Text('Press IT')))
                ],
              ),
            ),
          ),
        ));
  }
}


问:
How to prevent apify auto-sorting results?
Apify recently started to auto-sort results alphabetically. Its really annoying when we are uploading results directly to database.

Original column order given inside the code:

```<code>Result1
Result2
.
.
.
Result10
Result11
.
.
.
Result20
</code>```

After Apify sorts it alphabetically:

```<code>Result1
Result10
Result11
.
.
.
Result2
Result20
.
.
.
Result3
Result4
.
.
.
Result9
</code>```

Is there anyway we can prevent this and retain the original column order?

答:
This has always been like that for tabulated formats. You can add your own sorting if you add the fields parameter to the dataset items URL. Like this

https://api.apify.com/v2/datasets/DATASET_ID/items?clean=true&format=csv&fields=Result1,Result2

As the question was also about the Google Sheets actor, here is a solution for that:

The Google Sheets actor has a column order field

It also has a checkbox to retain the column order of the original sheet

Body:
Apify recently started to auto-sort results alphabetically. Its really annoying when we are uploading results directly to database.

Original column order given inside the code:

Result1
Result2
.
.
.
Result10
Result11
.
.
.
Result20

After Apify sorts it alphabetically:

Result1
Result10
Result11
.
.
.
Result2
Result20
.
.
.
Result3
Result4
.
.
.
Result9

Is there anyway we can prevent this and retain the original column order?


问:
Gradle's javadoc goal does not copy files from doc-files
I found that gradle's javadoc task does not copy files from doc-files subdirectories of package directories.

Is this possible to fix it?

答:
I tried first this approach:

```<code>javadoc {
  …
  doLast {
    copy {
      from "$projectDir/src/main/java"
      into "$project.docsDir/javadoc"
      include "**/doc-files/*"
    }
  }
}
</code>```

but I found that it does not work for Java modules (Jigsaw), because for them there is a folder with the module name underneath javadoc that holds the *.html files for the classes and where the doc-files need to end up, too.

So I came to this:

```<code>javadoc {
  …
  doLast {
    var moduleName = Tools.obtainModuleName( project.sourceSets.main )
    var targetDir = moduleName.map( "/%s"::formatted ).orElse( "" )
    copy {
      from "$projectDir/src/main/java"
      into "$project.docsDir/javadoc$targetDir"
      include "**/doc-files/*"
    }
  }
}
</code>```

Tools.obtainModuleName() is a function that gets the name of the Java module from the module-info.java file in the project:

public static final Optional<String> obtainModuleName( final SourceSet sourceSet )
{
    Optional<String> retValue = Optional.empty();

    final var directorySet = sourceSet.getAllJava();
    final var moduleDefinitionFile = directorySet.getFiles()
        .stream()
        .filter( File::exists )
        .filter( File::isFile )
        .filter( f -> f.getName().equals( MODULE_DEFINITION ) )
        .findFirst()
        .map( File::toPath );
    if( moduleDefinitionFile.isPresent() )
    {
        try( final var lines = lines( moduleDefinitionFile.get() ) )
        {
            final var contents = lines.collect( joining() );
            final var pattern = compile( ".*module\\s+(\\S+)\\s*\\{.*" );
            final var matcher = pattern.matcher( contents );
            if( matcher.matches() )
            {
                retValue = Optional.ofNullable( matcher.group( 1 ) );
            }
        }
        catch( final IOException e )
        {
            throw new Error( e );
        }
    }

    //---* Done *----------------------------------------------------------
    return retValue;
}   //  obtainModuleName()
```

Unfortunately, this is still not the solution …

The underlying problem is that Gradle's JavaDoc task works on the same SourceSet as the Java compiler task – and the latter does not accept anything else than *.java files.

Just copying the doc-files folders from the source to the JavaDoc folder as the last action of the JavaDoc task does only seem to work properly, because the JavaDoc tool itself (that one from $JDK_HOME/bin/javadoc) also processes other files than just *.java – at least it does something with *.html files: you can use the usual JavaDoc tags, like {@code …} or {@link …} or even custom tags in there.

Just adding the doc-files folders and their contents to the sourceSet will not help, too. In my case, it results in an error message about an illegal package name for the files in the doc-files folder because there are hyphens somewhere in a folder name (same path works fine for the Java sources …).

I am currently working on a solution to convince Gradle's JavaDoc task to work on the files in doc-files, too. Stay tuned …

Body:
I tried first this approach:

javadoc {
  …
  doLast {
    copy {
      from "$projectDir/src/main/java"
      into "$project.docsDir/javadoc"
      include "**/doc-files/*"
    }
  }
}

but I found that it does not work for Java modules (Jigsaw), because for them there is a folder with the module name underneath javadoc that holds the *.html files for the classes and where the doc-files need to end up, too.

So I came to this:

javadoc {
  …
  doLast {
    var moduleName = Tools.obtainModuleName( project.sourceSets.main )
    var targetDir = moduleName.map( "/%s"::formatted ).orElse( "" )
    copy {
      from "$projectDir/src/main/java"
      into "$project.docsDir/javadoc$targetDir"
      include "**/doc-files/*"
    }
  }
}

Tools.obtainModuleName() is a function that gets the name of the Java module from the module-info.java file in the project:

public static final Optional<String> obtainModuleName( final SourceSet sourceSet )
{
    Optional<String> retValue = Optional.empty();

    final var directorySet = sourceSet.getAllJava();
    final var moduleDefinitionFile = directorySet.getFiles()
        .stream()
        .filter( File::exists )
        .filter( File::isFile )
        .filter( f -> f.getName().equals( MODULE_DEFINITION ) )
        .findFirst()
        .map( File::toPath );
    if( moduleDefinitionFile.isPresent() )
    {
        try( final var lines = lines( moduleDefinitionFile.get() ) )
        {
            final var contents = lines.collect( joining() );
            final var pattern = compile( ".*module\\s+(\\S+)\\s*\\{.*" );
            final var matcher = pattern.matcher( contents );
            if( matcher.matches() )
            {
                retValue = Optional.ofNullable( matcher.group( 1 ) );
            }
        }
        catch( final IOException e )
        {
            throw new Error( e );
        }
    }

    //---* Done *----------------------------------------------------------
    return retValue;
}   //  obtainModuleName()

Unfortunately, this is still not the solution …

The underlying problem is that Gradle's JavaDoc task works on the same SourceSet as the Java compiler task – and the latter does not accept anything else than *.java files.

Just copying the doc-files folders from the source to the JavaDoc folder as the last action of the JavaDoc task does only seem to work properly, because the JavaDoc tool itself (that one from $JDK_HOME/bin/javadoc) also processes other files than just *.java – at least it does something with *.html files: you can use the usual JavaDoc tags, like {@code …} or {@link …} or even custom tags in there.

Just adding the doc-files folders and their contents to the sourceSet will not help, too. In my case, it results in an error message about an illegal package name for the files in the doc-files folder because there are hyphens somewhere in a folder name (same path works fine for the Java sources …).

I am currently working on a solution to convince Gradle's JavaDoc task to work on the files in doc-files, too. Stay tuned …


问:
How to use obj file at ARCore with new version of android studio
I'm using:

```<code>Android Studio Bumblebee | 2021.1.1
</code>```

now I want to render an obj file.
each obj file have three files:

obj file

mtl file

a jpg/png file

In previous versions of Android Studio I used to convert these 3 files into one file (sfb).

Install the Google Sceneform Tools plugin from plugins.

Create a sampleData folder in your project's app folder.

Copy your 3D model source asset file (three files)

Right-click the 3D model and select Import Sceneform Asset.

Change the path or name as per the requirements.

Click Finish to begin the import process.

You will find the .sfb file at the location that you mentioned in the fifth point.

then I used this file to render my 3d file (the my texture was inside of this sfb file.)
but this version not supported Google Sceneform Tools plugin.

答:
This plugin is outdated since 2020 I guess, same with the Library.
An up to date Library based on the old one can be found here https://github.com/SceneView/sceneform-android
The SFB-Support has been abandoned. The new kid on block is called glb/gltf. If you know Blender you can convert your OBJ-files to GLB-files https://docs.blender.org/manual/en/2.80/addons/io_scene_gltf2.html
If you have still questions feel free to join the SceneView Discord-Server https://discord.gg/UbNDDBTNqb</p>

Body:
I'm using:

Android Studio Bumblebee | 2021.1.1

now I want to render an obj file.
each obj file have three files:

obj file

mtl file

a jpg/png file

In previous versions of Android Studio I used to convert these 3 files into one file (sfb).

Install the Google Sceneform Tools plugin from plugins.

Create a sampleData folder in your project's app folder.

Copy your 3D model source asset file (three files)

Right-click the 3D model and select Import Sceneform Asset.

Change the path or name as per the requirements.

Click Finish to begin the import process.

You will find the .sfb file at the location that you mentioned in the fifth point.

then I used this file to render my 3d file (the my texture was inside of this sfb file.)
but this version not supported Google Sceneform Tools plugin.


问:
How to fix Python Numpy/Pandas installation?
I would like to install Python Pandas library (0.8.1) on Mac OS X 10.6.8. This library needs Numpy>=1.6.

I tried this

```<code>$ sudo easy_install pandas
Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge.net
Best match: pandas 0.8.1
Downloading http://pypi.python.org/packages/source/p/pandas/pandas-0.8.1.zip#md5=d2c5c5bea971cd760b0ae6f6850fcb74
Processing pandas-0.8.1.zip
Running pandas-0.8.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ckAMym/pandas-0.8.1/egg-dist-tmp-0mlL7t
error: Setup script exited with pandas requires NumPy >= 1.6 due to datetime64 dependency
</code>```

So I tried to install Numpy

```<code>$ sudo easy_install numpy
Searching for numpy
Best match: numpy 1.6.2
Adding numpy 1.6.2 to easy-install.pth file

Using /Library/Python/2.6/site-packages
Processing dependencies for numpy
Finished processing dependencies for numpy
</code>```

So I tried again

```<code>$ sudo easy_install pandas
</code>```

But the problem is still the same !

```<code>error: Setup script exited with pandas requires NumPy >= 1.6 due to datetime64 dependency
</code>```

I run Python

```<code>$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.__version__
'1.2.1'
</code>```

So Numpy 1.6 doesn't seems to be installed correctly !

I tried to install Numpy 1.6 with pip (instead of easy_install)...

```<code>$ sudo pip install numpy
Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.6/site-packages
Cleaning up...
</code>```

I added --upgrade flag

```<code>$ sudo pip install numpy --upgrade
Requirement already up-to-date: numpy in /Library/Python/2.6/site-packages
Cleaning up...

$ sudo pip install pandas
Downloading/unpacking pandas
  Downloading pandas-0.8.1.zip (1.9MB): 1.9MB downloaded
  Running setup.py egg_info for package pandas
    pandas requires NumPy >= 1.6 due to datetime64 dependency
    Complete output from command python setup.py egg_info:
    pandas requires NumPy >= 1.6 due to datetime64 dependency

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/pandas
Storing complete log in /Users/MyUsername/Library/Logs/pip.log
</code>```

I also tried to install binary version of Numpy http://sourceforge.net/projects/numpy/files/
numpy-1.6.2-py2.6-python.org-macosx10.3.dmg but it fails !!! (installer said me that numpy 1.6.2 can't be install on this disk. Numpy requires python.org Python 2.6 to install.

答:
What works really well for me was to install pandas in a virtual env like this:</p>
```<code>// create your virtualenv folder
python3 -m venv your-virtualenv-folder

// activate your virtualenv folder
source your-virtualenv-folder/bin/activate

// install pandas on your new virtualenv folder
python -m pip install pandas

// run your python file
python index.py
</code>```

Body:
I would like to install Python Pandas library (0.8.1) on Mac OS X 10.6.8. This library needs Numpy>=1.6.

I tried this

$ sudo easy_install pandas
Searching for pandas
Reading http://pypi.python.org/simple/pandas/
Reading http://pandas.pydata.org
Reading http://pandas.sourceforge.net
Best match: pandas 0.8.1
Downloading http://pypi.python.org/packages/source/p/pandas/pandas-0.8.1.zip#md5=d2c5c5bea971cd760b0ae6f6850fcb74
Processing pandas-0.8.1.zip
Running pandas-0.8.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ckAMym/pandas-0.8.1/egg-dist-tmp-0mlL7t
error: Setup script exited with pandas requires NumPy >= 1.6 due to datetime64 dependency

So I tried to install Numpy

$ sudo easy_install numpy
Searching for numpy
Best match: numpy 1.6.2
Adding numpy 1.6.2 to easy-install.pth file

Using /Library/Python/2.6/site-packages
Processing dependencies for numpy
Finished processing dependencies for numpy

So I tried again

$ sudo easy_install pandas

But the problem is still the same !

error: Setup script exited with pandas requires NumPy >= 1.6 due to datetime64 dependency

I run Python

$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.__version__
'1.2.1'

So Numpy 1.6 doesn't seems to be installed correctly !

I tried to install Numpy 1.6 with pip (instead of easy_install)...

$ sudo pip install numpy
Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Python/2.6/site-packages
Cleaning up...

I added --upgrade flag

$ sudo pip install numpy --upgrade
Requirement already up-to-date: numpy in /Library/Python/2.6/site-packages
Cleaning up...

$ sudo pip install pandas
Downloading/unpacking pandas
  Downloading pandas-0.8.1.zip (1.9MB): 1.9MB downloaded
  Running setup.py egg_info for package pandas
    pandas requires NumPy >= 1.6 due to datetime64 dependency
    Complete output from command python setup.py egg_info:
    pandas requires NumPy >= 1.6 due to datetime64 dependency

----------------------------------------
Command python setup.py egg_info failed with error code 1 in /tmp/pip-build/pandas
Storing complete log in /Users/MyUsername/Library/Logs/pip.log

I also tried to install binary version of Numpy http://sourceforge.net/projects/numpy/files/
numpy-1.6.2-py2.6-python.org-macosx10.3.dmg but it fails !!! (installer said me that numpy 1.6.2 can't be install on this disk. Numpy requires python.org Python 2.6 to install.

Body:
What works really well for me was to install pandas in a virtual env like this:

// create your virtualenv folder
python3 -m venv your-virtualenv-folder

// activate your virtualenv folder
source your-virtualenv-folder/bin/activate

// install pandas on your new virtualenv folder
python -m pip install pandas

// run your python file
python index.py


问:
Javascript split array
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

```<code>XXX MA Yo-Yo
</code>```

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

```<code>for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}
</code>```

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

答:
Because you invoke split method with limit = 1, then w_name has only 1 item.

In addition, yours input string has 2 whitespace, therefore, if you use split without limit parameter, w_name will contains 3 items ('XXX', 'CHAN', and 'Tai-Man').

I think you should use this:

```<code>var idx = str.indexOf(' ');
if (idx != -1) {
    var cn_name = str.substring(0, idx);
    var en_name = str.substring(idx + 1);
}
</code>```

Title: Javascript split array

Body:
I have a JavaScript array which contain the staff's Chinese and English names.

Example:

XXX MA Yo-Yo

Where XXX represents the Chinese name: 馬友友.

I want to split this into two parts by using the 1st space " " as an indicator.

for (i = 0; i < /* ... */)
{
    w_temp = arr[i];
    w_name = w_temp[1].split(' ', 1);

    /* ... */
}

w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.

How can I split it into two parts?

Body:
Because you invoke split method with limit = 1, then w_name has only 1 item.

In addition, yours input string has 2 whitespace, therefore, if you use split without limit parameter, w_name will contains 3 items ('XXX', 'CHAN', and 'Tai-Man').

I think you should use this:

var idx = str.indexOf(' ');
if (idx != -1) {
    var cn_name = str.substring(0, idx);
    var en_name = str.substring(idx + 1);
}


问:
Using `riscv64-unknown-elf-g++` to link rust static lib failed
I try to use riscv64-unknown-elf-g++ which is rv64imac architecture to compile C code with rust static lib.
The simple example is https://github.com/zzhengzhuo/base_bin .
When I use riscv64-unknown-elf-gcc, it works well. But when I use riscv64-unknown-elf-g++, it reports errors like this:

```<code>riscv64-unknown-elf-g++ -Ibase_lib -v -o build/base_bin main.c base_lib/target/riscv64imac-unknown-none-elf/release/libbase_lib.a
Using built-in specs.
COLLECT_GCC=riscv64-unknown-elf-g++
COLLECT_LTO_WRAPPER=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/lto-wrapper
Target: riscv64-unknown-elf
Configured with: /home/zhengzhuo/riscv-gnu-toolchain/riscv-gcc/configure --target=riscv64-unknown-elf --prefix=/opt/riscv --disable-shared --disable-threads --enable-languages=c,c++ --with-system-zlib --enable-tls --with-newlib --with-sysroot=/opt/riscv/riscv64-unknown-elf --with-native-system-header-dir=/include --disable-libmudflap --disable-libssp --disable-libquadmath --disable-libgomp --disable-nls --disable-tm-clone-registry --src=.././riscv-gcc --enable-multilib --with-abi=lp64 --with-arch=rv64imac --with-tune=rocket 'CFLAGS_FOR_TARGET=-Os   -mcmodel=medlow' 'CXXFLAGS_FOR_TARGET=-Os   -mcmodel=medlow'
Thread model: single
Supported LTO compression algorithms: zlib
gcc version 11.1.0 (GCC)
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin-'
 /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/cc1plus -quiet -v -I base_lib main.c -quiet -dumpdir build/base_bin- -dumpbase main.c -dumpbase-ext .c -mtune=rocket -march=rv64imac -mabi=lp64 -march=rv64imac -version -o /tmp/ccpwBEao.s
GNU C++17 (GCC) version 11.1.0 (riscv64-unknown-elf)
        compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/opt/riscv/riscv64-unknown-elf/usr/local/include"
ignoring duplicate directory "/opt/riscv/riscv64-unknown-elf/include"
#include "..." search starts here:
#include <...> search starts here:
 base_lib
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0/riscv64-unknown-elf
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0/backward
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/include
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/include-fixed
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include
End of search list.
GNU C++17 (GCC) version 11.1.0 (riscv64-unknown-elf)
        compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 70c8dfad8a0cf9a76df8ead2812f5775
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin-'
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/as -v -I base_lib --traditional-format -march=rv64imac -march=rv64imac -mabi=lp64 -o /tmp/cc4pRmao.o /tmp/ccpwBEao.s
GNU assembler version 2.37 (riscv64-unknown-elf) using BFD version (GNU Binutils) 2.37
COMPILER_PATH=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/libexec/gcc/riscv64-unknown-elf/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/lib/gcc/riscv64-unknown-elf/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/
LIBRARY_PATH=/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib/:/opt/riscv/riscv64-unknown-elf/lib/
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin.'
 /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/collect2 -plugin /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/liblto_plugin.so -plugin-opt=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/lto-wrapper -plugin-opt=-fresolution=/tmp/ccQyuKYm.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgloss -plugin-opt=-pass-through=-lgcc --sysroot=/opt/riscv/riscv64-unknown-elf -melf64lriscv -o build/base_bin /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib/crt0.o /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/crtbegin.o -L/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0 -L/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib -L/opt/riscv/riscv64-unknown-elf/lib /tmp/cc4pRmao.o base_lib/target/riscv64imac-unknown-none-elf/release/libbase_lib.a -lstdc++ -lm -lgcc --start-group -lc -lgloss --end-group -lgcc /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/crtend.o
/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/ld: /tmp/cc4pRmao.o: in function `.L0 ':
main.c:(.text+0xa): undefined reference to `echo(unsigned int)'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: build/base_bin] Error 1
</code>```

Thanks for any help.

答:
Adding extern "C" in the header file will work, more details see What is the effect of extern "C" in C++? .
related to https://github.com/riscv-collab/riscv-gnu-toolchain/issues/1021.
Thanks for everyone helped me.

Body:
I try to use riscv64-unknown-elf-g++ which is rv64imac architecture to compile C code with rust static lib.
The simple example is https://github.com/zzhengzhuo/base_bin .
When I use riscv64-unknown-elf-gcc, it works well. But when I use riscv64-unknown-elf-g++, it reports errors like this:

riscv64-unknown-elf-g++ -Ibase_lib -v -o build/base_bin main.c base_lib/target/riscv64imac-unknown-none-elf/release/libbase_lib.a
Using built-in specs.
COLLECT_GCC=riscv64-unknown-elf-g++
COLLECT_LTO_WRAPPER=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/lto-wrapper
Target: riscv64-unknown-elf
Configured with: /home/zhengzhuo/riscv-gnu-toolchain/riscv-gcc/configure --target=riscv64-unknown-elf --prefix=/opt/riscv --disable-shared --disable-threads --enable-languages=c,c++ --with-system-zlib --enable-tls --with-newlib --with-sysroot=/opt/riscv/riscv64-unknown-elf --with-native-system-header-dir=/include --disable-libmudflap --disable-libssp --disable-libquadmath --disable-libgomp --disable-nls --disable-tm-clone-registry --src=.././riscv-gcc --enable-multilib --with-abi=lp64 --with-arch=rv64imac --with-tune=rocket 'CFLAGS_FOR_TARGET=-Os   -mcmodel=medlow' 'CXXFLAGS_FOR_TARGET=-Os   -mcmodel=medlow'
Thread model: single
Supported LTO compression algorithms: zlib
gcc version 11.1.0 (GCC)
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin-'
 /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/cc1plus -quiet -v -I base_lib main.c -quiet -dumpdir build/base_bin- -dumpbase main.c -dumpbase-ext .c -mtune=rocket -march=rv64imac -mabi=lp64 -march=rv64imac -version -o /tmp/ccpwBEao.s
GNU C++17 (GCC) version 11.1.0 (riscv64-unknown-elf)
        compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/opt/riscv/riscv64-unknown-elf/usr/local/include"
ignoring duplicate directory "/opt/riscv/riscv64-unknown-elf/include"
#include "..." search starts here:
#include <...> search starts here:
 base_lib
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0/riscv64-unknown-elf
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include/c++/11.1.0/backward
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/include
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/include-fixed
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/include
End of search list.
GNU C++17 (GCC) version 11.1.0 (riscv64-unknown-elf)
        compiled by GNU C version 9.4.0, GMP version 6.2.0, MPFR version 4.0.2, MPC version 1.1.0, isl version none
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 70c8dfad8a0cf9a76df8ead2812f5775
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin-'
 /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/as -v -I base_lib --traditional-format -march=rv64imac -march=rv64imac -mabi=lp64 -o /tmp/cc4pRmao.o /tmp/ccpwBEao.s
GNU assembler version 2.37 (riscv64-unknown-elf) using BFD version (GNU Binutils) 2.37
COMPILER_PATH=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/libexec/gcc/riscv64-unknown-elf/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/lib/gcc/riscv64-unknown-elf/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/
LIBRARY_PATH=/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/:/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib/:/opt/riscv/riscv64-unknown-elf/lib/
COLLECT_GCC_OPTIONS='-I' 'base_lib' '-v' '-o' 'build/base_bin' '-mtune=rocket' '-march=rv64imac' '-mabi=lp64' '-march=rv64imac' '-dumpdir' 'build/base_bin.'
 /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/collect2 -plugin /opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/liblto_plugin.so -plugin-opt=/opt/riscv/libexec/gcc/riscv64-unknown-elf/11.1.0/lto-wrapper -plugin-opt=-fresolution=/tmp/ccQyuKYm.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgloss -plugin-opt=-pass-through=-lgcc --sysroot=/opt/riscv/riscv64-unknown-elf -melf64lriscv -o build/base_bin /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib/crt0.o /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/crtbegin.o -L/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0 -L/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/lib -L/opt/riscv/riscv64-unknown-elf/lib /tmp/cc4pRmao.o base_lib/target/riscv64imac-unknown-none-elf/release/libbase_lib.a -lstdc++ -lm -lgcc --start-group -lc -lgloss --end-group -lgcc /opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/crtend.o
/opt/riscv/lib/gcc/riscv64-unknown-elf/11.1.0/../../../../riscv64-unknown-elf/bin/ld: /tmp/cc4pRmao.o: in function `.L0 ':
main.c:(.text+0xa): undefined reference to `echo(unsigned int)'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: build/base_bin] Error 1

Thanks for any help.


问:
Solidity - how do i transfer from another contract to msg.sender
I would like to know how i set the origin from the transfer...

I have this contract (my actual contract is bigger than that, but that is the part that matters...):

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Testing{
    address payable public manager;

    constructor(){
         manager =payable(msg.sender);
    }

    function getMoneyFromManager(uint quantity) public payable{
        //someone different from manager should recieve money from manager
        //something like: msg.sender.transfer(quantity) => FROM MANAGER
    }

}
</code>```

But i don't know how to set the origin from the transfer. Any ideas?

答:
so you want to transfer ETH/BNB (native blockchain's crypto) fomr manager to user through the contract, but i'm sorry, you can't
is impossible take native crypto from an address and transfer it to another through smart contracts

but anyway there are 2 solutions:

keep native crypto inside the contract and not inside the manager wallet, so when you call that function, the contract will transfer native crypto from it self address(this) to the user

use wrapped token instead, with tokens you can do what you are trying to do. The wallet manager must approve within the token contract your actual contract to spend his token

then the contract will be like:

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

IMPORT "@openzeppelin/contracts/tokens/ERC20/IERC20.sol";

contract Testing{
    address public manager;
    IERC20 wETH;

    constructor(IERC20 _wETH){
         manager =msg.sender;
         wETH = _wETH;
    }

    function getMoneyFromManager(uint quantity) public payable{
        //msg.sender will receive money from manager
        wETH.transferFrom(manager, msg.sender, quantity)
    }

}
</code>```

NOTE:

Make getMoneyFromManager function onlyOwner, otherwise everyone will be able to get money

Body:
I would like to know how i set the origin from the transfer...

I have this contract (my actual contract is bigger than that, but that is the part that matters...):

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Testing{
    address payable public manager;

    constructor(){
         manager =payable(msg.sender);
    }

    function getMoneyFromManager(uint quantity) public payable{
        //someone different from manager should recieve money from manager
        //something like: msg.sender.transfer(quantity) => FROM MANAGER
    }

}

But i don't know how to set the origin from the transfer. Any ideas?

Body:
so you want to transfer ETH/BNB (native blockchain's crypto) fomr manager to user through the contract, but i'm sorry, you can't
is impossible take native crypto from an address and transfer it to another through smart contracts

but anyway there are 2 solutions:

keep native crypto inside the contract and not inside the manager wallet, so when you call that function, the contract will transfer native crypto from it self address(this) to the user

use wrapped token instead, with tokens you can do what you are trying to do. The wallet manager must approve within the token contract your actual contract to spend his token

then the contract will be like:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

IMPORT "@openzeppelin/contracts/tokens/ERC20/IERC20.sol";

contract Testing{
    address public manager;
    IERC20 wETH;

    constructor(IERC20 _wETH){
         manager =msg.sender;
         wETH = _wETH;
    }

    function getMoneyFromManager(uint quantity) public payable{
        //msg.sender will receive money from manager
        wETH.transferFrom(manager, msg.sender, quantity)
    }

}

NOTE:

Make getMoneyFromManager function onlyOwner, otherwise everyone will be able to get money


问:
Navigator Object in javascript. How to determine all properties

Possible Duplicate:

  How do I enumerate the properties of a javascript object?

Good day!

I want to determine all the properties of my navigator using javascript by doing this following code:

```<code><script type="text/javascript">
    for(var property in navigator){
        str="navigator."+ property;   //HAVING A PROBLEM HERE...
        document.write(property+ "  <em>"+
        str+"</em><br />");
    }
</script>
</code>```

But the concatenation of my str variable prints as it is. What i need is the actual value of the property.

eg. navigator.appCodeName should print mozilla instead of navigator.appCodeName itself.

Thank you in advance.

答:
You want to use navigator[property] to access the values assigned to the properties.

```<code>for(var property in navigator){
    var str = navigator[property]
    document.write(property+ "  <em>"+str+"</em><br />");
}
</code>```

You could also benefit from dropping document.write(), it's rarely the best way to modify the DOM.

Body:
Possible Duplicate:

  How do I enumerate the properties of a javascript object?

Good day!

I want to determine all the properties of my navigator using javascript by doing this following code:

But the concatenation of my str variable prints as it is. What i need is the actual value of the property.

eg. navigator.appCodeName should print mozilla instead of navigator.appCodeName itself.

Thank you in advance.

Body:
You want to use navigator[property] to access the values assigned to the properties.

for(var property in navigator){
    var str = navigator[property]
    document.write(property+ "&nbsp;&nbsp;<em>"+str+"</em><br />");
}

You could also benefit from dropping document.write(), it's rarely the best way to modify the DOM.


问:
Python - Data manipulation in a file
I'm at the stage where I've a txt file in the form:

```<code>text1;10;20;11
text2;3;4;5
text3;4;5;7
</code>```

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

```<code>text1;11
text2;5
text3;7
</code>```

Currently I have done:

```<code>    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()
</code>```

答:
you open the file get the data manipulation it and write the file back</p>
```<code>file_name ="/content/untitled"
list_res=[]
with open(file_name ,"r") as f:
  while True:
    line = f.readline()
    if not line:
      break
    list_t = line.split(";")
    list_res.append(f"{list_t[0]};{list_t[-1]}")
print(list_res)
with open(file_name ,"w") as f:
  f.write("".join(list_res))
</code>```

Title: Python - Data manipulation in a file

Body:
I'm at the stage where I've a txt file in the form:

text1;10;20;11
text2;3;4;5
text3;4;5;7

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

text1;11
text2;5
text3;7

Currently I have done:

    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()

Body:
you open the file get the data manipulation it and write the file back

file_name ="/content/untitled"
list_res=[]
with open(file_name ,"r") as f:
  while True:
    line = f.readline()
    if not line:
      break
    list_t = line.split(";")
    list_res.append(f"{list_t[0]};{list_t[-1]}")
print(list_res)
with open(file_name ,"w") as f:
  f.write("".join(list_res))


问:
Kubernetes NodePort not accesible from outside
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

```<code>primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'
</code>```

the service is visible:

```<code>NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s
</code>```

but I cant access it from outside, eg:

```<code>psql -h localhost -p 30000 -U myusername -d mydatabase
</code>```

but I think it is configured correctly, because when I execute port-forward postgres is available:

```<code>kubectl port-forward pod/postgres-nodeport-0 30000:5432
</code>```

答:
I found a solution:
You need to set the port to higher than 30000, e.g. 30001
but its strange, because earlier it worked with port 30000, and the documentation says that the port range is 30000-32767</p>

Body:
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'

the service is visible:

NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s

but I cant access it from outside, eg:

psql -h localhost -p 30000 -U myusername -d mydatabase

but I think it is configured correctly, because when I execute port-forward postgres is available:

kubectl port-forward pod/postgres-nodeport-0 30000:5432


问:
React-Native: Error type 3: Activity class does not exist
I'm aware there's a plethora of questions/answers regarding this issue.  However, I have spent the past few days trying a number of solutions I've found on SO and none have worked thus far.

My error:

```<code>BUILD SUCCESSFUL in 52s
372 actionable tasks: 352 executed, 20 up-to-date
info Running C:\Users\User\AppData\Local\Android\Sdk/platform-tools/adb -s emulator-5554 reverse tcp:8081 tcp:8081
info Starting the app on emulator-5554 (C:\Users\User\AppData\Local\Android\Sdk/platform-tools/adb -s emulator-5554 shell am start -n mypackage/mypackage.MainActivity)...
Starting: Intent { cmp=mypackage/.MainActivity }
Error type 3
Error: Activity class {mypackage/mypackage.MainActivity} does not exist.
</code>```

Here is a list of all the things I've attempted to do based on other SO posts:

Attempts

Running adb kill-server, adb start-server, then react-native run-android

Running adb reverse tcp:8081 tcp:8081, then react-native run-android (a senior dev I used to work with told me the issue might be related to this a long time ago, but I cannot get in touch with him)

Uninstalling the App from the Emulator, as well as my physical device

Build -> Clean Project

Files -> Invalidate Cache / Restart

Files -> Sync Project with Gradle Files

Build -> Rebuild Project

Deleted gradle cache files in /project/android/.gradle/5.1.1

AndroidManifest.xml -> <activity android:name=".MainActivity" to <activity android:name="packagename.MainActivity"

android/app/build.gradle to view buildTypes

```<code>debug {
  applicationIdSuffix ".debug"
}
stagingRelease {
  applicationIdSuffix ".staging"
}
release {

}
</code>```

Ran react-native run-android --variant=[debug] --appIdSuffix '[.debug]'

&&

Ran react-native run-android --variant=[stagingRelease] --appIdSuffix '[.staging]'

(these came with different errors)

Make sure android/app/build.gradle

```<code>defaultConfig {
        applicationId "WHATEVER_THIS_IS"
}
</code>```

needs to match android/app/src/main/java/com/app_name/MainActivity.java line one:

```<code>package WHATEVER_THIS_IS;
</code>```

needs to match android/app/src/main/java/com/app_name/MainApplication.java line one:

```<code>package WHATEVER_THIS_IS;
</code>```

needs to match android/app/src/main/AndroidManifest.xml line one:

```<code>package="WHATEVER_THIS_IS">
</code>```

Went to android/app/build.gradle and changed:

```<code>splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
    }
}
</code>```

to

```<code>splits {
    abi {
        reset()
        enable true
        universalApk true  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
    }
}
</code>```

Went to C:/Users/User/.gradle to delete the cache.  Was unable to delete everything, as I kept getting alerts that many of the files/folders inside are currently "open in another program" (untrue as far as I can tell)

Nothing worked.

Posts I followed for solutions

Error type 3 Error: Activity class {} does not exist

https://github.com/facebook/react-native/issues/8653

"react-native run-android" - BUILD is SUCCESSFUL but get error type 3 Error: Activity class MainActivity does not exist

Error type 3. Activity class {com.awesome_project/ com.awesome_project.MainActivity} does not exist in react native (Android device)

答:
For those who might experienced the same situation like the one I faced!

Explanation:

Note: I'm working on my app in eject mode

I have updated my react-native npm package to the latest version (By the time of writing this answer @0.67.2). And then when I was staring (running) my android app in the emulator using (npx react-native run-android), I have experienced this error:

Error type 3 - Error: Activity class {*.MainActivity} does not exist.

Solution which worked me:

In Android studio => Virtual device manager => I wiped user data (Please note the attached screenshot)

In Visual studio, in the root of your project, locate android folder. delete build folder inside app folder. (please note the attached screenshot)

run npx react-native run-android and you must be able to get your app running smoothly again.

Body:
I'm aware there's a plethora of questions/answers regarding this issue.  However, I have spent the past few days trying a number of solutions I've found on SO and none have worked thus far.

My error:

BUILD SUCCESSFUL in 52s
372 actionable tasks: 352 executed, 20 up-to-date
info Running C:\Users\User\AppData\Local\Android\Sdk/platform-tools/adb -s emulator-5554 reverse tcp:8081 tcp:8081
info Starting the app on emulator-5554 (C:\Users\User\AppData\Local\Android\Sdk/platform-tools/adb -s emulator-5554 shell am start -n mypackage/mypackage.MainActivity)...
Starting: Intent { cmp=mypackage/.MainActivity }
Error type 3
Error: Activity class {mypackage/mypackage.MainActivity} does not exist.

Here is a list of all the things I've attempted to do based on other SO posts:

Attempts

Running adb kill-server, adb start-server, then react-native run-android

Running adb reverse tcp:8081 tcp:8081, then react-native run-android (a senior dev I used to work with told me the issue might be related to this a long time ago, but I cannot get in touch with him)

Uninstalling the App from the Emulator, as well as my physical device

Build -> Clean Project

Files -> Invalidate Cache / Restart

Files -> Sync Project with Gradle Files

Build -> Rebuild Project

Deleted gradle cache files in /project/android/.gradle/5.1.1

AndroidManifest.xml -> <activity android:name=".MainActivity" to <activity android:name="packagename.MainActivity"

android/app/build.gradle to view buildTypes

debug {
  applicationIdSuffix ".debug"
}
stagingRelease {
  applicationIdSuffix ".staging"
}
release {

}

Ran react-native run-android --variant=[debug] --appIdSuffix '[.debug]'

&&

Ran react-native run-android --variant=[stagingRelease] --appIdSuffix '[.staging]'

(these came with different errors)

Make sure android/app/build.gradle

defaultConfig {
        applicationId "WHATEVER_THIS_IS"
}

needs to match android/app/src/main/java/com/app_name/MainActivity.java line one:

package WHATEVER_THIS_IS;

needs to match android/app/src/main/java/com/app_name/MainApplication.java line one:

package WHATEVER_THIS_IS;

needs to match android/app/src/main/AndroidManifest.xml line one:

package="WHATEVER_THIS_IS">

Went to android/app/build.gradle and changed:

splits {
    abi {
        reset()
        enable enableSeparateBuildPerCPUArchitecture
        universalApk false  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
    }
}

to

splits {
    abi {
        reset()
        enable true
        universalApk true  // If true, also generate a universal APK
        include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
    }
}

Went to C:/Users/User/.gradle to delete the cache.  Was unable to delete everything, as I kept getting alerts that many of the files/folders inside are currently "open in another program" (untrue as far as I can tell)

Nothing worked.

Posts I followed for solutions

Error type 3 Error: Activity class {} does not exist

https://github.com/facebook/react-native/issues/8653

"react-native run-android" - BUILD is SUCCESSFUL but get error type 3 Error: Activity class MainActivity does not exist

Error type 3. Activity class {com.awesome_project/ com.awesome_project.MainActivity} does not exist in react native (Android device)


问:
Debug-iphonesimulator/YogaKit/YogaKit.modulemap' not found
i'm created new project in react-native and i'm trying to build in xcode but it was coming fatal error

fatal error: module map file '/Users/gis00109/Library/Developer/Xcode/DerivedData/sam-capwmdorzbxfzphhezjlrwcbyxyp/Build/Products/Debug-iphonesimulator/YogaKit/YogaKit.modulemap' not found

答:
After trying every solution on the internet, this worked for me.

```<code>cd ios && pod install && cd ..
</code>```

then

```<code>npx react-native link
</code>```

or

```<code>yarn react-native link
</code>```

Body:
After trying every solution on the internet, this worked for me.

cd ios && pod install && cd ..

then

npx react-native link

or

yarn react-native link