问:
ZeroDivisionError: float division by zero when i try show video durations in directory
Idea: Get duration of all videos in a directory.

Problem: I want to output the duration of all videos in a directory but i get an error and this is my code:

This is original code https://pastebin.com/xnpfwE55

```<code>from colorama import init
from colorama import Fore
import datetime
import glob
import cv2
init()

w = input(str(Fore.GREEN+"Type path to dir: ")) # path of directory
b = print(str(glob.glob(w+"*"))) # Adds a directory and reads files from there
print(b)
# create video capture object
data = cv2.VideoCapture(str(b))

# count the number of frames
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = int(data.get(cv2.CAP_PROP_FPS))

# calculate dusration of the video
seconds = int(frames / fps)
video_time = str(datetime.timedelta(seconds=seconds))
print("duration in seconds:", seconds)
print("video time:", video_time)
</code>```

What should I do?

Output:

```<code>[gooder@GOD ffmpeg]$ python untitled2.py
Type path to dir: /home/gooder/Desktop/ffmpeg/videos/
['/home/gooder/Desktop/ffmpeg/videos/ou1t.mp4', '/home/gooder/Desktop/ffmpeg/videos/out.mp4', '/home/gooder/Desktop/ffmpeg/videos/Halloween.Kills.2021.DUB.HDRip.x264.mkv']
None
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (1127) open OpenCV | GStreamer warning: Error opening bin: no element "None"
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created
[ERROR:0@2.770] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap.cpp (164) open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.5.5) /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): None in function 'icvExtractPattern'

Traceback (most recent call last):
  File "/home/gooder/Desktop/ffmpeg/untitled2.py", line 19, in <module>
    seconds = int(frames / fps)
ZeroDivisionError: float division by zero
</code>```

答:
There seems to be some confused code in this line:

b = print(str(glob.glob(w+"*"))) # Adds a directory and reads files from there
```
<p>You glob the contents of the directory you entered in the variable <code>w</code>, convert that list to a string, <code>print</code> that string to standard output and then assign <code>None</code> to <code>b</code>, because <code>print</code> writes its arguments to standard output (or some other stream) and doesn't return anything.</p>
<p>It has already been pointed out in the comments that calling <code>print</code> in this way won't do what you want here. The first step would therefore be to get rid of it:</p>
<pre class="lang-py prettyprint-override"><code>b = str(glob.glob(w+"*")) # Adds a directory and reads files from there
print(b)
</code>```

However that's not enough, because b won't be a filename, it will be the result of converting a list of filenames to a string. Attempting to open a file whose name is the value of b will still fail.

glob.glob returns a list, with each item in the list being a file that matched the pattern given. You need to loop through this list and then run the rest of your code once for each item in the list:

for b in glob.glob(w+"*"): # Adds a directory and reads files from there
    print(b)

    # create video capture object
    data = cv2.VideoCapture(b)

    # remaining lines also indented, but omitted here for brevity
```
<p>Each time through the loop, <code>b</code> should be the name of one of the files in the directory you entered.</p>
<p>Finally, in case <code>cv2</code> can't read the FPS for a video file for whatever reason, I would recommend not attempting to calculate the duration of the video.  Replace the code at the bottom of your loop with something like the following:</p>
<pre class="lang-py prettyprint-override"><code>    if fps == 0:
        print("Could not read an FPS value, unable to calculate duration of video")
    else:
        # calculate duration as normal...
</code>```

Body:
Idea: Get duration of all videos in a directory.

Problem: I want to output the duration of all videos in a directory but i get an error and this is my code:

This is original code https://pastebin.com/xnpfwE55

from colorama import init
from colorama import Fore
import datetime
import glob
import cv2
init()

w = input(str(Fore.GREEN+"Type path to dir: ")) # path of directory
b = print(str(glob.glob(w+"*"))) # Adds a directory and reads files from there
print(b)
# create video capture object
data = cv2.VideoCapture(str(b))

# count the number of frames
frames = data.get(cv2.CAP_PROP_FRAME_COUNT)
fps = int(data.get(cv2.CAP_PROP_FPS))

# calculate dusration of the video
seconds = int(frames / fps)
video_time = str(datetime.timedelta(seconds=seconds))
print("duration in seconds:", seconds)
print("video time:", video_time)

What should I do?

Output:

[gooder@GOD ffmpeg]$ python untitled2.py
Type path to dir: /home/gooder/Desktop/ffmpeg/videos/
['/home/gooder/Desktop/ffmpeg/videos/ou1t.mp4', '/home/gooder/Desktop/ffmpeg/videos/out.mp4', '/home/gooder/Desktop/ffmpeg/videos/Halloween.Kills.2021.DUB.HDRip.x264.mkv']
None
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (1127) open OpenCV | GStreamer warning: Error opening bin: no element "None"
[ WARN:0@1.851] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_gstreamer.cpp (862) isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created
[ERROR:0@2.770] global /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap.cpp (164) open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.5.5) /build/opencv/src/opencv-4.5.5/modules/videoio/src/cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): None in function 'icvExtractPattern'

Traceback (most recent call last):
  File "/home/gooder/Desktop/ffmpeg/untitled2.py", line 19, in <module>
    seconds = int(frames / fps)
ZeroDivisionError: float division by zero

Body:
There seems to be some confused code in this line:

b = print(str(glob.glob(w+"*"))) # Adds a directory and reads files from there

You glob the contents of the directory you entered in the variable w, convert that list to a string, print that string to standard output and then assign None to b, because print writes its arguments to standard output (or some other stream) and doesn't return anything.

It has already been pointed out in the comments that calling print in this way won't do what you want here. The first step would therefore be to get rid of it:

b = str(glob.glob(w+"*")) # Adds a directory and reads files from there
print(b)

However that's not enough, because b won't be a filename, it will be the result of converting a list of filenames to a string. Attempting to open a file whose name is the value of b will still fail.

glob.glob returns a list, with each item in the list being a file that matched the pattern given. You need to loop through this list and then run the rest of your code once for each item in the list:

for b in glob.glob(w+"*"): # Adds a directory and reads files from there
    print(b)

    # create video capture object
    data = cv2.VideoCapture(b)

    # remaining lines also indented, but omitted here for brevity

Each time through the loop, b should be the name of one of the files in the directory you entered.

Finally, in case cv2 can't read the FPS for a video file for whatever reason, I would recommend not attempting to calculate the duration of the video.  Replace the code at the bottom of your loop with something like the following:

    if fps == 0:
        print("Could not read an FPS value, unable to calculate duration of video")
    else:
        # calculate duration as normal...


来源: stackexchange

问:
Java multilevel menu structure
I'm building a web application in Java (Tapestry 5).
I want to create a multilevel menu where I can show the root elements for example at the top of my page and the children of the selected on the left.

To implement this I was thinking to use a tree structure like this:

```<code>public class SiteMap {

private List<MenuItem> root;

public class MenuItem {

    private String pageFileName;
    private String pageNavigationName;

    private List<MenuItem> children;
    private MenuItem parent;

    public MenuItem(String pageFileName, String pageNavigationName, MenuItem parent) {
        this.pageFileName = pageFileName;
        this.pageNavigationName = pageNavigationName;
        this.parent = parent;
    }

    public String getPageFileName() {
        return pageFileName;
    }

    public String getPageNavigationName() {
        return pageNavigationName;
    }

    public List<MenuItem> getChildren() {
        return children;
    }

    public MenuItem getParent() {
        return this.parent;
    }
}
}
</code>```

Now what if I want to build a menu based on the children of 1 parent item (only have the pageFileName - String) somewhere in the tree. Ill have to traverse recursively through the tree to find this parent item based on the pageFileName (String) , which seems not a good way.

Is this (using a tree structure) the right way to implement this? Or is there a better option?
Any thoughts and hints are appreciated!

Thanks in advance!

Nathan

答:
```<code>MenuItem root = null;
MenuItem curr = myMenuItem;
while(curr.getParent() != null) {
    curr = curr.getParent();
}
root = curr;
</code>```

There's nothing wrong with doing it that way, that code will run very fast, especailly since you aren't going to have millions of menu entries.

ContentLicense: CC BY-SA 3.0

Title: Java multilevel menu structure

Body:
I'm building a web application in Java (Tapestry 5).
I want to create a multilevel menu where I can show the root elements for example at the top of my page and the children of the selected on the left.

To implement this I was thinking to use a tree structure like this:

public class SiteMap {

private List<MenuItem> root;

public class MenuItem {

    private String pageFileName;
    private String pageNavigationName;

    private List<MenuItem> children;
    private MenuItem parent;

    public MenuItem(String pageFileName, String pageNavigationName, MenuItem parent) {
        this.pageFileName = pageFileName;
        this.pageNavigationName = pageNavigationName;
        this.parent = parent;
    }

    public String getPageFileName() {
        return pageFileName;
    }

    public String getPageNavigationName() {
        return pageNavigationName;
    }

    public List<MenuItem> getChildren() {
        return children;
    }

    public MenuItem getParent() {
        return this.parent;
    }
}
}

Now what if I want to build a menu based on the children of 1 parent item (only have the pageFileName - String) somewhere in the tree. Ill have to traverse recursively through the tree to find this parent item based on the pageFileName (String) , which seems not a good way.

Is this (using a tree structure) the right way to implement this? Or is there a better option?
Any thoughts and hints are appreciated!

Thanks in advance!

Nathan

Body:
MenuItem root = null;
MenuItem curr = myMenuItem;
while(curr.getParent() != null) {
    curr = curr.getParent();
}
root = curr;

There's nothing wrong with doing it that way, that code will run very fast, especailly since you aren't going to have millions of menu entries.


问:
LU Factorization for MATLAB
How do you write MATLAB code for LU factorization when U is the unit matrix instead of L. The upper triangular matrix will have the diagonal of 1s instead of the lower triangular matrix.</p>

答:
You are looking for  Crout's Method for LU decomposition.

The Wikipedia article has the following code

```<code>function [L, U] = LUdecompCrout(A)

        [R, C] = size(A);
        for i = 1:R
            L(i, 1) = A(i, 1);
            U(i, i) = 1;
        end
        for j = 2:R
            U(1, j) = A(1, j) / L(1, 1);
        end
        for i = 2:R
            for j = 2:i
                L(i, j) = A(i, j) - L(i, 1:j - 1) * U(1:j - 1, j);
            end

            for j = i + 1:R
                U(i, j) = (A(i, j) - L(i, 1:i - 1) * U(1:i - 1, j)) / L(i,i);

            end
        end
   end
</code>```

ContentLicense: CC BY-SA 4.0

Title: LU Factorization for MATLAB

Body:
You are looking for  Crout's Method for LU decomposition.

The Wikipedia article has the following code

function [L, U] = LUdecompCrout(A)

        [R, C] = size(A);
        for i = 1:R
            L(i, 1) = A(i, 1);
            U(i, i) = 1;
        end
        for j = 2:R
            U(1, j) = A(1, j) / L(1, 1);
        end
        for i = 2:R
            for j = 2:i
                L(i, j) = A(i, j) - L(i, 1:j - 1) * U(1:j - 1, j);
            end

            for j = i + 1:R
                U(i, j) = (A(i, j) - L(i, 1:i - 1) * U(1:i - 1, j)) / L(i,i);

            end
        end
   end


问:
How to join adjacent elements in a list with a string in between?
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

and the output needs to be:

```<code>1-2
3-4
5-6
7-8
</code>```

Now I have gotten as far as this, but have no idea what to do next:

```<code>a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))
</code>```

And this only gives me this as result:

```<code>[(1, 2), (3, 4), (5, 6), (7, 8)]
</code>```

I feel like I am close and just missing one tiny step.

Body:
I am starting on my Python journey and am doing some exercises to get the hang of it all. One question is really giving me troubles as I do not understand how to complete it.

Given a list with an even number of integers, join adjacent elements using '-' and print each pair.
So it will be that this is given:

a = [1, 2, 3, 4, 5, 6, 7, 8]

and the output needs to be:

1-2
3-4
5-6
7-8

Now I have gotten as far as this, but have no idea what to do next:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a1 = a[::2]
a2 = a[1::2]

duos = zip(a1, a2)
print(list(duos))

And this only gives me this as result:

[(1, 2), (3, 4), (5, 6), (7, 8)]

I feel like I am close and just missing one tiny step.

Body:
Build a lazy iterator:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> it = iter(a)
>>> print([f"{x}-{y}" for x,y in zip(it,it)])
['1-2', '3-4', '5-6', '7-8']


问:
CentOS Stream 8 - DNF Broken - Unable to Run Update/Upgrade
I thought I successfully upgraded from CentOS8 to Centos Stream 8, however I was never able to get dnf distro-sync to work.  Now DNF appears to be broken and dnf upgrade throws unsatisfied dependencies for libsmartcols.so.1 in relation to DNF itself.

dnf distro-sync:
When running the sync, the following appears:

```<code>Error:
 Problem: The operation would result in removing the following protected packages: setup
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)
</code>```

I tried every possible combination of --skip-broken, --nobest --allowerasing, etc. to resolve.  Tried using the vault versions, no difference.  All of the old CentOS repos were removed, so the only repos in the /etc/yum.repos.d/ folder are -Stream-.  I do not have any EPEL repos installed at this time.

cat /etc/centos-release => CentOS Stream release 8

The server survives reboots and seems to work correctly for everything else.

When running dnf -y upgrade -v, the following results:

```<code>dnf -y upgrade -v
Loaded plugins: builddep, changelog, config-manager, copr, debug, debuginfo-install, download, generate_completion_cache, groups-manager, needs-restarting, playground, repoclosure, repodiff, repograph, repomanage, reposync
DNF version: 4.7.0
cachedir: /var/cache/dnf
User-Agent: constructed: 'libdnf (CentOS Stream 8; generic; Linux.x86_64)'
repo: using cache for: appstream
appstream: using metadata from Tue 08 Feb 2022 07:27:22 PM EST.
repo: using cache for: baseos
baseos: using metadata from Tue 08 Feb 2022 07:26:22 PM EST.
repo: using cache for: extras
extras: using metadata from Tue 08 Feb 2022 04:08:34 PM EST.
Last metadata expiration check: 0:26:35 ago on Thu 10 Feb 2022 12:44:57 PM EST.
--> Starting dependency resolution
---> Package dnf-plugins-core.noarch 4.0.21-8.el8 will be upgraded
---> Package dnf-plugins-core.noarch 4.0.21-10.el8 will be an upgrade
---> Package libdnf.x86_64 0.63.0-5.el8 will be upgraded
---> Package libdnf.x86_64 0.63.0-7.el8 will be an upgrade
---> Package python3-dnf-plugins-core.noarch 4.0.21-8.el8 will be upgraded
---> Package python3-dnf-plugins-core.noarch 4.0.21-10.el8 will be an upgrade
---> Package python3-hawkey.x86_64 0.63.0-5.el8 will be upgraded
---> Package python3-hawkey.x86_64 0.63.0-7.el8 will be an upgrade
---> Package python3-libdnf.x86_64 0.63.0-5.el8 will be upgraded
---> Package python3-libdnf.x86_64 0.63.0-7.el8 will be an upgrade
--> Finished dependency resolution
Dependencies resolved.
==============================================================================================================================================================================================================
 Package                                                      Architecture                               Version                                             Repository                                  Size
==============================================================================================================================================================================================================
Upgrading:
 dnf-plugins-core                                             noarch                                     4.0.21-10.el8                                       baseos                                      71 k
 libdnf                                                       x86_64                                     0.63.0-7.el8                                        baseos                                     701 k
 python3-dnf-plugins-core                                     noarch                                     4.0.21-10.el8                                       baseos                                     230 k
 python3-hawkey                                               x86_64                                     0.63.0-7.el8                                        baseos                                     116 k
 python3-libdnf                                               x86_64                                     0.63.0-7.el8                                        baseos                                     778 k

Transaction Summary
==============================================================================================================================================================================================================
Upgrade  5 Packages

Total size: 1.9 M
Downloading Packages:
[SKIPPED] dnf-plugins-core-4.0.21-10.el8.noarch.rpm: Already downloaded
[SKIPPED] libdnf-0.63.0-7.el8.x86_64.rpm: Already downloaded
[SKIPPED] python3-dnf-plugins-core-4.0.21-10.el8.noarch.rpm: Already downloaded
[SKIPPED] python3-hawkey-0.63.0-7.el8.x86_64.rpm: Already downloaded
[SKIPPED] python3-libdnf-0.63.0-7.el8.x86_64.rpm: Already downloaded
Using rpmkeys executable at /usr/bin/rpmkeys to verify signatures
Running transaction check
Error: transaction check vs depsolve:
libsmartcols.so.1()(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.25)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.28)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.29)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.30)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1()(64bit) is needed by python3-hawkey-0.63.0-7.el8.x86_64
libsmartcols.so.1()(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.25)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.27)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.28)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.29)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.30)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
To diagnose the problem, try running: 'rpm -Va --nofiles --nodigest'.
You probably have corrupted RPMDB, running 'rpm --rebuilddb' might fix the issue.
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
</code>```

I have tried cleaning the packages (dnf clean all), removing the cache files, individually trying to update/upgrade each package, etc..  I'm out of ideas.

Any suggestions?

答:
Afer a couple more hours of trying, I was able to resolve it by performing the following:

Copy a CentOS-Base.repo file from another server

Edit the repo file to reflect the vault.centos.org location, turn off gpgcheck

dnf clean all

dnf install libsmartcols-2.32.1-28.el8

Ran dnf -y upgrade again and it worked.  Go figure.

Hopefully, this will help someone else with the same or similar issue.

Body:
I thought I successfully upgraded from CentOS8 to Centos Stream 8, however I was never able to get dnf distro-sync to work.  Now DNF appears to be broken and dnf upgrade throws unsatisfied dependencies for libsmartcols.so.1 in relation to DNF itself.

dnf distro-sync:
When running the sync, the following appears:

Error:
 Problem: The operation would result in removing the following protected packages: setup
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)

I tried every possible combination of --skip-broken, --nobest --allowerasing, etc. to resolve.  Tried using the vault versions, no difference.  All of the old CentOS repos were removed, so the only repos in the /etc/yum.repos.d/ folder are -Stream-.  I do not have any EPEL repos installed at this time.

cat /etc/centos-release => CentOS Stream release 8

The server survives reboots and seems to work correctly for everything else.

When running dnf -y upgrade -v, the following results:

dnf -y upgrade -v
Loaded plugins: builddep, changelog, config-manager, copr, debug, debuginfo-install, download, generate_completion_cache, groups-manager, needs-restarting, playground, repoclosure, repodiff, repograph, repomanage, reposync
DNF version: 4.7.0
cachedir: /var/cache/dnf
User-Agent: constructed: 'libdnf (CentOS Stream 8; generic; Linux.x86_64)'
repo: using cache for: appstream
appstream: using metadata from Tue 08 Feb 2022 07:27:22 PM EST.
repo: using cache for: baseos
baseos: using metadata from Tue 08 Feb 2022 07:26:22 PM EST.
repo: using cache for: extras
extras: using metadata from Tue 08 Feb 2022 04:08:34 PM EST.
Last metadata expiration check: 0:26:35 ago on Thu 10 Feb 2022 12:44:57 PM EST.
--> Starting dependency resolution
---> Package dnf-plugins-core.noarch 4.0.21-8.el8 will be upgraded
---> Package dnf-plugins-core.noarch 4.0.21-10.el8 will be an upgrade
---> Package libdnf.x86_64 0.63.0-5.el8 will be upgraded
---> Package libdnf.x86_64 0.63.0-7.el8 will be an upgrade
---> Package python3-dnf-plugins-core.noarch 4.0.21-8.el8 will be upgraded
---> Package python3-dnf-plugins-core.noarch 4.0.21-10.el8 will be an upgrade
---> Package python3-hawkey.x86_64 0.63.0-5.el8 will be upgraded
---> Package python3-hawkey.x86_64 0.63.0-7.el8 will be an upgrade
---> Package python3-libdnf.x86_64 0.63.0-5.el8 will be upgraded
---> Package python3-libdnf.x86_64 0.63.0-7.el8 will be an upgrade
--> Finished dependency resolution
Dependencies resolved.
==============================================================================================================================================================================================================
 Package                                                      Architecture                               Version                                             Repository                                  Size
==============================================================================================================================================================================================================
Upgrading:
 dnf-plugins-core                                             noarch                                     4.0.21-10.el8                                       baseos                                      71 k
 libdnf                                                       x86_64                                     0.63.0-7.el8                                        baseos                                     701 k
 python3-dnf-plugins-core                                     noarch                                     4.0.21-10.el8                                       baseos                                     230 k
 python3-hawkey                                               x86_64                                     0.63.0-7.el8                                        baseos                                     116 k
 python3-libdnf                                               x86_64                                     0.63.0-7.el8                                        baseos                                     778 k

Transaction Summary
==============================================================================================================================================================================================================
Upgrade  5 Packages

Total size: 1.9 M
Downloading Packages:
[SKIPPED] dnf-plugins-core-4.0.21-10.el8.noarch.rpm: Already downloaded
[SKIPPED] libdnf-0.63.0-7.el8.x86_64.rpm: Already downloaded
[SKIPPED] python3-dnf-plugins-core-4.0.21-10.el8.noarch.rpm: Already downloaded
[SKIPPED] python3-hawkey-0.63.0-7.el8.x86_64.rpm: Already downloaded
[SKIPPED] python3-libdnf-0.63.0-7.el8.x86_64.rpm: Already downloaded
Using rpmkeys executable at /usr/bin/rpmkeys to verify signatures
Running transaction check
Error: transaction check vs depsolve:
libsmartcols.so.1()(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.25)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.28)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.29)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.30)(64bit) is needed by libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1()(64bit) is needed by python3-hawkey-0.63.0-7.el8.x86_64
libsmartcols.so.1()(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.25)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.27)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.28)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.29)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
libsmartcols.so.1(SMARTCOLS_2.30)(64bit) is needed by python3-libdnf-0.63.0-7.el8.x86_64
To diagnose the problem, try running: 'rpm -Va --nofiles --nodigest'.
You probably have corrupted RPMDB, running 'rpm --rebuilddb' might fix the issue.
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.

I have tried cleaning the packages (dnf clean all), removing the cache files, individually trying to update/upgrade each package, etc..  I'm out of ideas.

Any suggestions?


问:
How to run Animated.Spring in external component call
I'm trying to call Animated.Spring from a parent component and the function isn't running. How do you fix this issue?

It works within the component but not when called from outside. I'm using alerts to show that the function code does run but it skips the Animated call for some reason.

Here is my code:

```<code>import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'

export default class App extends Component {
  handlerSimpleCall = () => {
    //Calling a function of other class (without arguments)
    new Alerts().handleAnimation();
  };

  render() {
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          flex: 1,
          backgroundColor: '#F5FCFF',
        }}>
        <Alerts />
        <View style={{ margin: 10 }}>
          <Button
            title="Function Without Argument"
            onPress={this.handlerSimpleCall}
            color="#606070"
          />
        </View>
      </View>
    );
  }
}

class Alerts extends Component {
  constructor(props) {
    super(props);
    this.animatedValue = new Animated.Value(1)
  }

  handleAnimation = () => {
    this.animatedValue.setValue(0)
    alert("ASD")
    Animated.spring(this.animatedValue, {
      toValue: 1,
      useNativeDriver: true,
      friction: 1
    }).start()
  }
  render() {
    return (
      <View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
        <Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
        <View style={{ width: 100, marginTop: 20 }}>
          <Button onPress={this.handleAnimation} title='Press Me' />
        </View>
      </View>
    )
  }
}
</code>```

答:
You should use a ref to refer to your component, rather than creating a new Alerts().

I was able to make it work like this:

```<code>import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'

export default class App extends Component {
    constructor(props) {
    super(props);
    this.alertRef = React.createRef();
  }

  render() {
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          flex: 1,
          backgroundColor: '#F5FCFF',
        }}>
        <Alerts
          ref={this.alertRef}
        />
        <View style={{ margin: 10 }}>
          <Button

            title="Function Without Argument"
            onPress={() => this.alertRef.current.handleAnimation()}
            color="#606070"
          />
        </View>
      </View>
    );
  }
}

class Alerts extends Component {
  constructor(props) {
    super(props);
    this.animatedValue = new Animated.Value(1)
  }

  handleAnimation = () => {
    this.animatedValue.setValue(0)
    alert("ASD")
    Animated.spring(this.animatedValue, {
      toValue: 1,
      useNativeDriver: true,
      friction: 1
    }).start()
  }
  render() {
    return (
      <View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
        <Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
        <View style={{ width: 100, marginTop: 20 }}>
          <Button onPress={this.handleAnimation} title='Press Me' />
        </View>
      </View>
    )
  }
}
</code>```

Body:
I'm trying to call Animated.Spring from a parent component and the function isn't running. How do you fix this issue?

It works within the component but not when called from outside. I'm using alerts to show that the function code does run but it skips the Animated call for some reason.

Here is my code:

import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'

export default class App extends Component {
  handlerSimpleCall = () => {
    //Calling a function of other class (without arguments)
    new Alerts().handleAnimation();
  };

  render() {
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          flex: 1,
          backgroundColor: '#F5FCFF',
        }}>
        <Alerts />
        <View style={{ margin: 10 }}>
          <Button
            title="Function Without Argument"
            onPress={this.handlerSimpleCall}
            color="#606070"
          />
        </View>
      </View>
    );
  }
}

class Alerts extends Component {
  constructor(props) {
    super(props);
    this.animatedValue = new Animated.Value(1)
  }

  handleAnimation = () => {
    this.animatedValue.setValue(0)
    alert("ASD")
    Animated.spring(this.animatedValue, {
      toValue: 1,
      useNativeDriver: true,
      friction: 1
    }).start()
  }
  render() {
    return (
      <View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
        <Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
        <View style={{ width: 100, marginTop: 20 }}>
          <Button onPress={this.handleAnimation} title='Press Me' />
        </View>
      </View>
    )
  }
}

Body:
You should use a ref to refer to your component, rather than creating a new Alerts().

I was able to make it work like this:

import React, { Component } from 'react'
import { View, Animated, Button, Easing } from 'react-native'

export default class App extends Component {
    constructor(props) {
    super(props);
    this.alertRef = React.createRef();
  }

  render() {
    return (
      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          flex: 1,
          backgroundColor: '#F5FCFF',
        }}>
        <Alerts
          ref={this.alertRef}
        />
        <View style={{ margin: 10 }}>
          <Button

            title="Function Without Argument"
            onPress={() => this.alertRef.current.handleAnimation()}
            color="#606070"
          />
        </View>
      </View>
    );
  }
}

class Alerts extends Component {
  constructor(props) {
    super(props);
    this.animatedValue = new Animated.Value(1)
  }

  handleAnimation = () => {
    this.animatedValue.setValue(0)
    alert("ASD")
    Animated.spring(this.animatedValue, {
      toValue: 1,
      useNativeDriver: true,
      friction: 1
    }).start()
  }
  render() {
    return (
      <View style={{ height: '100%', width: '100%', justifyContent: "center", alignItems: "center" }}>
        <Animated.View style={{ height: 150, width: 150, backgroundColor: 'red', transform: [{ scale: this.animatedValue }] }} />
        <View style={{ width: 100, marginTop: 20 }}>
          <Button onPress={this.handleAnimation} title='Press Me' />
        </View>
      </View>
    )
  }
}


问:
Can't put extras for an intent in notification
I'm creating a notification from a Service that has an intent with an extra integer. For some reason, this isn't as easy as it seems. This is what I'm doing:

```<code>Notification notification = new Notification(R.drawable.notification_icon, "Title", 0);
Intent relaunchIntent = new Intent(this, SomeClass.class);
relaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
relaunchIntent.putExtra("load", getId());
notification.setLatestEventInfo(this, "Title", "Tap here to open", PendingIntent.getActivity(this, 0, relaunchIntent, 0);
notificationManager.notify(1234, notification);
</code>```

And then from SomeClass, it reads like this...

```<code>if(getIntent().getExtras() != null)
    load(getIntent().getExtras().getInt("load", -1));
</code>```

What's weird is that I get inconsistent results when I read the value from the getInt() method. Sometimes I get values of things I set in a previous notifications. For example, I get a value of 3 when I had set that extra to be 4. I know this is very confusing and strange, which is why I'm wondering if anyone has experienced anything like this and what you may have done to fix it. Thanks!

答:
You should try using PendingIntent.FLAG_UPDATE_CURRENT when you call PendingIntent.getActivity. From the documentation:

This can be used if you are creating intents where only the extras
  change, and don't care that any entities that received your previous
  PendingIntent will be able to launch it with your new extras even if
  they are not explicitly given to it.

I ran into this issue myself, and found the answer from a comment on this answer.

Body:
I'm creating a notification from a Service that has an intent with an extra integer. For some reason, this isn't as easy as it seems. This is what I'm doing:

Notification notification = new Notification(R.drawable.notification_icon, "Title", 0);
Intent relaunchIntent = new Intent(this, SomeClass.class);
relaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
relaunchIntent.putExtra("load", getId());
notification.setLatestEventInfo(this, "Title", "Tap here to open", PendingIntent.getActivity(this, 0, relaunchIntent, 0);
notificationManager.notify(1234, notification);

And then from SomeClass, it reads like this...

if(getIntent().getExtras() != null)
    load(getIntent().getExtras().getInt("load", -1));

What's weird is that I get inconsistent results when I read the value from the getInt() method. Sometimes I get values of things I set in a previous notifications. For example, I get a value of 3 when I had set that extra to be 4. I know this is very confusing and strange, which is why I'm wondering if anyone has experienced anything like this and what you may have done to fix it. Thanks!


答:
Completing your work:

```<code>for x, y in duos:
    print(f'{x}-{y}')
</code>```

(Note you need to do this instead of your print(list(duos)), otherwise that consumes the zip iterator and there's nothing left.)

Title: How to join adjacent elements in a list with a string in between?

Body:
Completing your work:

for x, y in duos:
    print(f'{x}-{y}')

(Note you need to do this instead of your print(list(duos)), otherwise that consumes the zip iterator and there's nothing left.)


问:
Authentication Handler not blocking requests
I have added authentication to my API with the possibility to authenticate with two different authentication schemes.
Based on the format of the Auth header I forward the authentication request to the appropriate Authentication handler using a ForwardDefaultSelector.

```<code> services.AddAuthentication(opt =>
                    {
                        opt.DefaultScheme = "ForwardScheme";
                        opt.DefaultChallengeScheme = "ForwardScheme";
                    })
                    .AddPolicyScheme("ForwardScheme", "ForwardScheme", options =>
                        options.ForwardDefaultSelector = context =>
                            context.Request.IsSchemeA()
                                ? "SchemeA"
                                : "SchemeB")
                    .AddSchemeA()
                    .AddSchemeB();
</code>```

Adding Schemes:

```<code>public static AuthenticationBuilder AddSchemeA(this AuthenticationBuilder builder)
        {
            builder.AddScheme<AuthenticationSchemeOptions, SchemeAHandler>(
                "SchemeA", null);
            return builder;
        }
</code>```

The forwarding seems to be working fine, I can see the request coming to the right auth handler based on the header value.

The problem is even when the auth fails, the API call is not blocked and I still get a 200 response back.

In the AuthHandler I am just returning this:

```<code> return AuthenticateResult.Fail("Authentication Failed");
</code>```

Any idea what I am missing here?
Thanks.

答:
@EnricoMassone thanks for pointing me in the right direction.

I was missing [Authorize] attribute on my controller methods.

you can set the attribute individually on each method or you could do something like this, and it would enable authorization on all methods for all of your controllers

Body:
I have added authentication to my API with the possibility to authenticate with two different authentication schemes.
Based on the format of the Auth header I forward the authentication request to the appropriate Authentication handler using a ForwardDefaultSelector.

 services.AddAuthentication(opt =>
                    {
                        opt.DefaultScheme = "ForwardScheme";
                        opt.DefaultChallengeScheme = "ForwardScheme";
                    })
                    .AddPolicyScheme("ForwardScheme", "ForwardScheme", options =>
                        options.ForwardDefaultSelector = context =>
                            context.Request.IsSchemeA()
                                ? "SchemeA"
                                : "SchemeB")
                    .AddSchemeA()
                    .AddSchemeB();

Adding Schemes:

public static AuthenticationBuilder AddSchemeA(this AuthenticationBuilder builder)
        {
            builder.AddScheme<AuthenticationSchemeOptions, SchemeAHandler>(
                "SchemeA", null);
            return builder;
        }

The forwarding seems to be working fine, I can see the request coming to the right auth handler based on the header value.

The problem is even when the auth fails, the API call is not blocked and I still get a 200 response back.

In the AuthHandler I am just returning this:

 return AuthenticateResult.Fail("Authentication Failed");

Any idea what I am missing here?
Thanks.


问:
Inconsistent print with value from for statement (python)
So I’ve created a very basic program that rolls a dice a given number of times, and then displays who wins the game.
I’ve tried to print the results as they go along with the roll #.

The problem I’m having is the output seems weirdly, an indecipherably (at least to my eyes) inconsistent (ie: sometimes it will show the roll #, sometimes it won’t.

Besides how much cleaner I could make this code, what am I doing that’s producing inconsistent roll # printing?

Code as follows:

```<code>import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    ones = 0
    twos = 0
    threes = 0
    fours = 0
    fives = 0
    sixes = 0
    tries = 1

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        if ran_num == 1:
            print(f"Roll {tries}: One for the ones")
            ones += 1
        elif ran_num == 2:
            print("Roll {tries}: Two Two look at my shoe")
            twos += 1
        elif ran_num == 3:
            print("Roll {tries}: THREE!! I'm free'")
            threes += 1
        elif ran_num == 4:
            print("Roll {tries}: F0ar equals m0ar")
            fours += 1
        elif ran_num == 5:
            print("Roll {tries}: Five five don't step in a bee hive'")
            fives += 1
        elif ran_num == 6:
            print("Roll {tries}: Super Sixes - Yeharrrr!")
            sixes += 1
    rolls += 1
    tries += 1
    print(f"Final scores are: \n1: {ones}\n2: {twos}\n3: {threes}\n4: {fours}\n5: {fives}\n6: {sixes}")

HighRolla()’’’
</code>```

答:
To answer your question: You forgot the f at the start of the strings in the print statements for 2 through 6. Therefore, it prints the actual text {tries} instead of the value.

In addition, I'd recommend:

Using a dictionary instead of all of those ifs.

Note that you didn't initialize rolls before using it, and you also set tries to 1 instead of 0. There is also no use for rolls.

Using a defaultdict for counting the results, instead of initializing a separate variable for each number. defaultdict returns a new dictionary-like object, where the first argument provides the initial value for the default_factory.

Method names in python should also be lowercase and seperated by _.

Implementing those steps would make your code much shorter and more pythonic.

Putting it all together:

```<code>import random
from collections import defaultdict

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def high_rolla():
    num_rolls = int(input("How many guesses?"))
    random_results = defaultdict(int)
    tries = 0
    random_to_print = {1: "One for the ones",
                       2: "Two Two look at my shoe",
                       3: "THREE!! I'm free'",
                       4: "F0ar equals m0ar",
                       5: "Five five don't step in a bee hive'",
                       6: "Super Sixes - Yeharrrr!"}
    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        tries += 1
        print(f"Roll {tries}: " + random_to_print[ran_num])
        random_results[ran_num] += 1
    print("Final scores are: ")
    for key, value in random_results.items():
        print(str(key) + " : " + str(value))

high_rolla()
</code>```

Output:

```<code>Let's play a little game!
who is the most popular number on a die?
Lets find out!
How many guesses?3
Roll 1: Two Two look at my shoe
Roll 2: Two Two look at my shoe
Roll 3: One for the ones
Final scores are:
2 : 2
1 : 1
</code>```

Body:
So I’ve created a very basic program that rolls a dice a given number of times, and then displays who wins the game.
I’ve tried to print the results as they go along with the roll #.

The problem I’m having is the output seems weirdly, an indecipherably (at least to my eyes) inconsistent (ie: sometimes it will show the roll #, sometimes it won’t.

Besides how much cleaner I could make this code, what am I doing that’s producing inconsistent roll # printing?

Code as follows:

import random

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def HighRolla():
    ones = 0
    twos = 0
    threes = 0
    fours = 0
    fives = 0
    sixes = 0
    tries = 1

    num_rolls = int(input("How many guesses?"))

    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        if ran_num == 1:
            print(f"Roll {tries}: One for the ones")
            ones += 1
        elif ran_num == 2:
            print("Roll {tries}: Two Two look at my shoe")
            twos += 1
        elif ran_num == 3:
            print("Roll {tries}: THREE!! I'm free'")
            threes += 1
        elif ran_num == 4:
            print("Roll {tries}: F0ar equals m0ar")
            fours += 1
        elif ran_num == 5:
            print("Roll {tries}: Five five don't step in a bee hive'")
            fives += 1
        elif ran_num == 6:
            print("Roll {tries}: Super Sixes - Yeharrrr!")
            sixes += 1
    rolls += 1
    tries += 1
    print(f"Final scores are: \n1: {ones}\n2: {twos}\n3: {threes}\n4: {fours}\n5: {fives}\n6: {sixes}")

HighRolla()’’’

Body:
To answer your question: You forgot the f at the start of the strings in the print statements for 2 through 6. Therefore, it prints the actual text {tries} instead of the value.

In addition, I'd recommend:

Using a dictionary instead of all of those ifs.

Note that you didn't initialize rolls before using it, and you also set tries to 1 instead of 0. There is also no use for rolls.

Using a defaultdict for counting the results, instead of initializing a separate variable for each number. defaultdict returns a new dictionary-like object, where the first argument provides the initial value for the default_factory.

Method names in python should also be lowercase and seperated by _.

Implementing those steps would make your code much shorter and more pythonic.

Putting it all together:

import random
from collections import defaultdict

print("Let's play a little game!")
print("who is the most popular number on a die?")
print("Lets find out!")

def high_rolla():
    num_rolls = int(input("How many guesses?"))
    random_results = defaultdict(int)
    tries = 0
    random_to_print = {1: "One for the ones",
                       2: "Two Two look at my shoe",
                       3: "THREE!! I'm free'",
                       4: "F0ar equals m0ar",
                       5: "Five five don't step in a bee hive'",
                       6: "Super Sixes - Yeharrrr!"}
    for roll in range(num_rolls):
        ran_num = random.randint(1, 6)
        tries += 1
        print(f"Roll {tries}: " + random_to_print[ran_num])
        random_results[ran_num] += 1
    print("Final scores are: ")
    for key, value in random_results.items():
        print(str(key) + " : " + str(value))

high_rolla()

Output:

Let's play a little game!
who is the most popular number on a die?
Lets find out!
How many guesses?3
Roll 1: Two Two look at my shoe
Roll 2: Two Two look at my shoe
Roll 3: One for the ones
Final scores are:
2 : 2
1 : 1


问:
C signal: segmentation fault (core dumped)
I am learning C, and I am facing this error.
Why I cannot pass a pointer to the funcion as change(&p_x); and only change(&x); works? Thanks

```<code>#include <stdio.h>

void change(int *p_xa) // GET ERROR HERE signal: segmentation fault (core dumped)
{
    *p_xa = 999;
}

int main()
{
    int x = 1;
    int * p_x = &x;

    *p_x = 2;

    change(&p_x); // cannot do this

    printf("x is: %d \n", *p_x);

    return 0;
}
</code>```

答: Since you're taking a pointer as a parameter, you must also pass it when you call the function(you are passing the pointer of the pointer)</p>

Body:
I am learning C, and I am facing this error.
Why I cannot pass a pointer to the funcion as change(&p_x); and only change(&x); works? Thanks

#include <stdio.h>

void change(int *p_xa) // GET ERROR HERE signal: segmentation fault (core dumped)
{
    *p_xa = 999;
}

int main()
{
    int x = 1;
    int * p_x = &x;

    *p_x = 2;

    change(&p_x); // cannot do this

    printf("x is: %d \n", *p_x);

    return 0;
}


问:
WPF binding window title to a checkbox state
I have a checkbox which looks something like this (have removed many things to make it short) -

<CheckBox IsChecked="{Binding functionABC, Mode=TwoWay}">

</CheckBox>
```

Now, I have to map the window title of app to 2 different values depending on checked or unchecked. I could have done it normally, but there is a trigger set already for both states, and I don't know how to work around it.

答:
Use a Style with a DataTrigger

<Window
  ...>

  <Window.Style>

    </Style>
  </Window.Style>
  ...
</Window>
```
<hr />
<h1>Update</h1>
<p>As thatguy suggested this style can be simplified by</p>
<pre class="lang-xml prettyprint-override"><code><!-- !!! remove the Title property from the Window declaration !!! -->

<Window
  ...>

  <Window.Style>
    <Style TargetType="Window">
      <Setter Property="Title" Value="False Title" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding functionABC}" Value="True">
          <Setter Property="Title" Value="True Title" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Window.Style>
  ...
</Window>
</code>```

sample project on github

Body:
I have a checkbox which looks something like this (have removed many things to make it short) -

<CheckBox IsChecked="{Binding functionABC, Mode=TwoWay}">

</CheckBox>

Now, I have to map the window title of app to 2 different values depending on checked or unchecked. I could have done it normally, but there is a trigger set already for both states, and I don't know how to work around it.

Body:
Use a Style with a DataTrigger

<!-- !!! remove the Title property from the Window declaration !!! -->

<Window
  ...>

  <Window.Style>
    <Style TargetType="Window">
      <Style.Triggers>
        <DataTrigger Binding="{Binding functionABC}" Value="True">
          <Setter Property="Title" Value="True Title" />
        </DataTrigger>
        <DataTrigger Binding="{Binding functionABC}" Value="False">
          <Setter Property="Title" Value="False Title" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Window.Style>
  ...
</Window>

Update

As thatguy suggested this style can be simplified by

<!-- !!! remove the Title property from the Window declaration !!! -->

<Window
  ...>

  <Window.Style>
    <Style TargetType="Window">
      <Setter Property="Title" Value="False Title" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding functionABC}" Value="True">
          <Setter Property="Title" Value="True Title" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Window.Style>
  ...
</Window>

sample project on github


问:
for loop with pandas shows error when dealing with large data in jupyter
I am using Jupyter notebook on Windows.

I am trying to populate data for all the stocks of the S&P 500. I created a pandas dataframe and am populating for each stock: ticker, price and market capitalization.

Here is the code:

```<code>my_columns = ['Ticker', 'Stock Price', 'Market Capitalization']
final_dataframe = pd.DataFrame(columns = my_columns)
for stock in stocks['Ticker'][:5]:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(api_url).json()
    final_dataframe = final_dataframe.append(
        pd.Series(
        [
            stock,
            data['latestPrice'],
            data['marketCap'],
        ],
        index = my_columns),
    ignore_index = True
    )
</code>```

This will show the first 5 stocks when I view final_dataframe.

However, if I want to see for ALL stocks by removing the "[:5]" (in line 3 of the code), I get error.

I tested this again to see first 50 stocks "[:50]", it worked fine.

I tested it on the first 500 stocks "[:500]", I get error.

So I am thinking maybe it has something to do with the size of data?

Optional info: I am following a course where the lecturer simply removed [:5] from the code to see all stock data and was successful as well. In my case that's not true.

Here is the error:

```<code>---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [45], in <module>
      3 for stock in stocks['Ticker']:
      4     api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
----> 5     data = requests.get(api_url).json()
      6     final_dataframe = final_dataframe.append(
      7         pd.Series(
      8         [
   (...)
     14     ignore_index = True
     15     )

File F:\Projects\algorithmic-trading-python\venv\lib\site-packages\requests\models.py:888, in Response.json(self, **kwargs)
    886 if encoding is not None:
    887     try:
--> 888         return complexjson.loads(
    889             self.content.decode(encoding), **kwargs
    890         )
    891     except UnicodeDecodeError:
    892         # Wrong UTF codec detected; usually because it's not UTF-8
    893         # but some other 8-bit codec.  This is an RFC violation,
    894         # and the server didn't bother to tell us what codec *was*
    895         # used.
    896         pass

File ~\AppData\Local\Programs\Python\Python38\lib\json\__init__.py:357, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352     del kw['encoding']
    354 if (cls is None and object_hook is None and
    355         parse_int is None and parse_float is None and
    356         parse_constant is None and object_pairs_hook is None and not kw):
--> 357     return _default_decoder.decode(s)
    358 if cls is None:
    359     cls = JSONDecoder

File ~\AppData\Local\Programs\Python\Python38\lib\json\decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    335
    336     """
--> 337     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338     end = _w(s, end).end()
    339     if end != len(s):

File ~\AppData\Local\Programs\Python\Python38\lib\json\decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
    353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
--> 355     raise JSONDecodeError("Expecting value", s, err.value) from None
    356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

</code>```

What can I try next?

答:
requests.get(api_url) is not fetching anything for a token somewhere between 50th and 500th row. You could put in an if condition to check if it's not None first before calling the json method:

```<code>my_columns = ['Ticker', 'Stock Price', 'Market Capitalization']
lst = []
for stock in stocks['Ticker']:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    r = requests.get(api_url)
    # proceed only if r is not None
    if r:
        data = r.json()
        lst.append([stock, data['latestPrice'], data['marketCap']])
final_dataframe = pd.DataFrame(lst, columns=my_columns)
</code>```

Body:
I am using Jupyter notebook on Windows.

I am trying to populate data for all the stocks of the S&P 500. I created a pandas dataframe and am populating for each stock: ticker, price and market capitalization.

Here is the code:

my_columns = ['Ticker', 'Stock Price', 'Market Capitalization']
final_dataframe = pd.DataFrame(columns = my_columns)
for stock in stocks['Ticker'][:5]:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(api_url).json()
    final_dataframe = final_dataframe.append(
        pd.Series(
        [
            stock,
            data['latestPrice'],
            data['marketCap'],
        ],
        index = my_columns),
    ignore_index = True
    )

This will show the first 5 stocks when I view final_dataframe.

However, if I want to see for ALL stocks by removing the "[:5]" (in line 3 of the code), I get error.

I tested this again to see first 50 stocks "[:50]", it worked fine.

I tested it on the first 500 stocks "[:500]", I get error.

So I am thinking maybe it has something to do with the size of data?

Optional info: I am following a course where the lecturer simply removed [:5] from the code to see all stock data and was successful as well. In my case that's not true.

Here is the error:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [45], in <module>
      3 for stock in stocks['Ticker']:
      4     api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
----> 5     data = requests.get(api_url).json()
      6     final_dataframe = final_dataframe.append(
      7         pd.Series(
      8         [
   (...)
     14     ignore_index = True
     15     )

File F:\Projects\algorithmic-trading-python\venv\lib\site-packages\requests\models.py:888, in Response.json(self, **kwargs)
    886 if encoding is not None:
    887     try:
--> 888         return complexjson.loads(
    889             self.content.decode(encoding), **kwargs
    890         )
    891     except UnicodeDecodeError:
    892         # Wrong UTF codec detected; usually because it's not UTF-8
    893         # but some other 8-bit codec.  This is an RFC violation,
    894         # and the server didn't bother to tell us what codec *was*
    895         # used.
    896         pass

File ~\AppData\Local\Programs\Python\Python38\lib\json\__init__.py:357, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352     del kw['encoding']
    354 if (cls is None and object_hook is None and
    355         parse_int is None and parse_float is None and
    356         parse_constant is None and object_pairs_hook is None and not kw):
--> 357     return _default_decoder.decode(s)
    358 if cls is None:
    359     cls = JSONDecoder

File ~\AppData\Local\Programs\Python\Python38\lib\json\decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    335
    336     """
--> 337     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338     end = _w(s, end).end()
    339     if end != len(s):

File ~\AppData\Local\Programs\Python\Python38\lib\json\decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
    353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
--> 355     raise JSONDecodeError("Expecting value", s, err.value) from None
    356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What can I try next?

Body:
requests.get(api_url) is not fetching anything for a token somewhere between 50th and 500th row. You could put in an if condition to check if it's not None first before calling the json method:

my_columns = ['Ticker', 'Stock Price', 'Market Capitalization']
lst = []
for stock in stocks['Ticker']:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token={IEX_CLOUD_API_TOKEN}'
    r = requests.get(api_url)
    # proceed only if r is not None
    if r:
        data = r.json()
        lst.append([stock, data['latestPrice'], data['marketCap']])
final_dataframe = pd.DataFrame(lst, columns=my_columns)


问:
NodeJs Error: Port already in use:3000 using socket.io and express
I'm making a node.js application that uses socket.io and express.

The code looks like this-

```<code>const express=require('express');
const app=express();
const http=require('http').Server(app);
app.use(express.static('public'));

const io=require('socket.io')(http,{
  cors:{origin:'*'}
});

http.listen(3000,()=>{
  console.log('listening to port 3000');
});

//when connection made
io.on('connection',(socket)=>{
  console.log('connection made!');
});
</code>```

Here,public is a folder container all the html files for the website.

Now,when I run it locally on my pc,it works fine
But when I deployed it on the glitch.com servers,i get this error:

```<code>Error: listen EADDREINUSE: address already in use :::3000
</code>```

As far as i know,3000 is the only available port in glitch and I cannot use another port.

Also,the questions on stack overflow related to this topic doesn't help me since most of the answers are related to killing the running tasks themselves and I don't have permission to do so on the server.

答:
According to this question on glitch.com's forums you might have two services listening to the same port, but that doesn't seem to be the case.

You should also be able to change the default listening port by setting the PORT environment variable in your .env file if you have one. Trying a different port should solve the problem

EDIT:
Apparently the problem could be the initial configuration of the server, you can try setting everything up like this:

```<code>const app = require('express')();
const server = require('http').createServer(app); <--
const io = require('socket.io')(server);
io.on('connection', () => { /* your code */ });

server.listen(process.env.PORT, () => {/* your code */});
</code>```

(Got this from socket.io github page)

If this doesn't work either you should try asking on glitch.com's support forums, one of their technicians will help you better troubleshoot your problem, they have all the necessary tools

Body:
I'm making a node.js application that uses socket.io and express.

The code looks like this-

const express=require('express');
const app=express();
const http=require('http').Server(app);
app.use(express.static('public'));

const io=require('socket.io')(http,{
  cors:{origin:'*'}
});

http.listen(3000,()=>{
  console.log('listening to port 3000');
});

//when connection made
io.on('connection',(socket)=>{
  console.log('connection made!');
});

Here,public is a folder container all the html files for the website.

Now,when I run it locally on my pc,it works fine
But when I deployed it on the glitch.com servers,i get this error:

Error: listen EADDREINUSE: address already in use :::3000

As far as i know,3000 is the only available port in glitch and I cannot use another port.

Also,the questions on stack overflow related to this topic doesn't help me since most of the answers are related to killing the running tasks themselves and I don't have permission to do so on the server.

Body:
According to this question on glitch.com's forums you might have two services listening to the same port, but that doesn't seem to be the case.

You should also be able to change the default listening port by setting the PORT environment variable in your .env file if you have one. Trying a different port should solve the problem

EDIT:
Apparently the problem could be the initial configuration of the server, you can try setting everything up like this:

const app = require('express')();
const server = require('http').createServer(app); <--
const io = require('socket.io')(server);
io.on('connection', () => { /* your code */ });

server.listen(process.env.PORT, () => {/* your code */});

(Got this from socket.io github page)

If this doesn't work either you should try asking on glitch.com's support forums, one of their technicians will help you better troubleshoot your problem, they have all the necessary tools


问:
Add Button with Image and Text in ToolbarItem SwiftUI
I want button exactly as in Reminders app in iOS
Below code note working, I also tried using label and system image name.

```<code>        .toolbar {
            ToolbarItem(placement: .bottomBar) {
                Button(action: {}, label: {
                    HStack {
                        Image(systemName: "plus.circle.fill")
                        Text("New Reminder")
                    }
                })

            }
        }
</code>```

答:
Create a custom label style

```<code>struct VerticalLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        VStack {
            configuration.icon.font(.headline)
            configuration.title.font(.footnote)
        }
    }
}
</code>```

Then you can you use the custom style for your label

```<code>Button(action: {}, label: {
   Label("Home", systemImage: "house")
      .labelStyle(VerticalLabelStyle())
})
</code>```

Body:
I want button exactly as in Reminders app in iOS
Below code note working, I also tried using label and system image name.

        .toolbar {
            ToolbarItem(placement: .bottomBar) {
                Button(action: {}, label: {
                    HStack {
                        Image(systemName: "plus.circle.fill")
                        Text("New Reminder")
                    }
                })

            }
        }

Body:
Create a custom label style

struct VerticalLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        VStack {
            configuration.icon.font(.headline)
            configuration.title.font(.footnote)
        }
    }
}

Then you can you use the custom style for your label

Button(action: {}, label: {
   Label("Home", systemImage: "house")
      .labelStyle(VerticalLabelStyle())
})


问:
Not able to insert a string to a position in a dataframe
I'm trying to iterate over two data frames with different lenghts in order to look for some data in a string. If the data is found, I should be able to add info to a specific position in a data frame. Here is the code.

In the df data frame, I created an empty column, which is going to receive the data in the future.

I also have the df_userstory data frame. And here is where I'm looking for the data. So, I created the code below.

Both df['Issue key'][i] and df_userstory['parent_of'][i] contains strings.

```<code>df['parent'] = ""

for i in df_userstory.index:
    if df['Issue key'][i] in df_userstory['parent_of'][i]:
        item = df_userstory['Issue key'][i]
        df['parent'].iloc[i] = item

df
</code>```

For some reason, when I run this code the df['parent'] remains empty. I've tried different approaches, but everything failed.

I've tried to do the following in order to check what was happening:

```<code>df['parent'] = ""

for i in df_userstory.index:
    if df['Issue key'][i] in df_userstory['parent_of'][i]:
        print('True')
</code>```

Nothing was printed out.

I appreciate your help here.

Cheers

答:
Iterating over each index will lose all the performance benefits of using Pandas dataframe.
You should use dataframe merge.

```<code># select the two columns you need from df_userstory
df_us = df_userstory.loc[:, ['parent_of', 'Issue key']]

# rename to parent, that will be merged with df dataframe
df_us.rename(columns={'Issue key': 'parent'}, inplace=True).drop_duplicates()

# merge
df = df.merge(df_us, left_on='Issue key', right_on='parent_of', how='left')
</code>```

Ref: Pandas merge

Body:
I'm trying to iterate over two data frames with different lenghts in order to look for some data in a string. If the data is found, I should be able to add info to a specific position in a data frame. Here is the code.

In the df data frame, I created an empty column, which is going to receive the data in the future.

I also have the df_userstory data frame. And here is where I'm looking for the data. So, I created the code below.

Both df['Issue key'][i] and df_userstory['parent_of'][i] contains strings.

df['parent'] = ""

for i in df_userstory.index:
    if df['Issue key'][i] in df_userstory['parent_of'][i]:
        item = df_userstory['Issue key'][i]
        df['parent'].iloc[i] = item

df

For some reason, when I run this code the df['parent'] remains empty. I've tried different approaches, but everything failed.

I've tried to do the following in order to check what was happening:

df['parent'] = ""

for i in df_userstory.index:
    if df['Issue key'][i] in df_userstory['parent_of'][i]:
        print('True')

Nothing was printed out.

I appreciate your help here.

Cheers

Body:
Iterating over each index will lose all the performance benefits of using Pandas dataframe.
You should use dataframe merge.

# select the two columns you need from df_userstory
df_us = df_userstory.loc[:, ['parent_of', 'Issue key']]

# rename to parent, that will be merged with df dataframe
df_us.rename(columns={'Issue key': 'parent'}, inplace=True).drop_duplicates()

# merge
df = df.merge(df_us, left_on='Issue key', right_on='parent_of', how='left')

Ref: Pandas merge


问:
Dynamically add matTooltip in text for specific keywords
I am working in a personal Angular project (using Angular Material) and I can't find a solution for this problem.

For example, I have a long text like this :

When you take the Dodge action, you focus entirely on avoiding
attacks. Until the start of your next turn, any Attack roll made
against you has disadvantage if you can see the attacker, and you make
Dexterity Saving Throws with advantage. You lose this benefit if you
are Incapacitated (as explained in Conditions ) or if your speed drops
to 0.

I have some keywords, here disadvantage, advantage incapacitated. I would like to make the font bold and add a tooltip to add a small explanation for each keyword.

I have no problem making the font bold with a pipe, but I can't find a solution for adding a tooltip for the keywords. Using innerHTML does not work, here is my current solution :

```<code><div innerHTML="description | transformKeyWord"></div>
</code>```

And my pipe :

```<code>transform(value: string, ...args: unknown[]): unknown {
    let result = value
      result = result.replace('advantage', '<span matTooltip="Advantage description">advantage</span>')
      result = result.replace('incapacitated', '<b [matTooltip]="Incapacitated description">incapacitated</b>')
    return result;
  }
</code>```

I don't think this is the good solution using a pipe with innerHTML, that is why I am asking for help.

答:
TLDR: https://stackblitz.com/edit/angular-ivy-86uxvs?file=src/app/app.component.html

The way I see it, each keyword is an object with a word and a tooltip. So I'll define the schema for that.

export type keyword = {
  word: string;
  tooltip: string;
};
```
<p>I'll define the keywords in an object for easy lookup:</p>
<pre class="lang-js prettyprint-override"><code>  keywords: { [key: string]: keyword } = {
    disadvantage: {
      word: 'disadvantage',
      tooltip: 'advantage description',
    },
    incapacitated: {
      word: 'incapacitated',
      tooltip: 'incapacitated description',
    },
  };
</code>```

I think the best way is to split the string into an array of strings and keywords, so we can print them to the html in order. Here's a function that does that - I put all this in a service because it seems fitting.

  toDynamicText(text: string): (string | keyword)[] {
    const res: (string | keyword)[] = [];
    const tokens = text.split(' ');
    let i = 0;
    for (const token of tokens) {
      let keyword = this.keywords[token.toLowerCase()]; //undefined if word is not a keyword
      if (keyword) {
        i = res.push(keyword);
      } else {
        if (!res[i]) res[i] = token;
        else res[i] += ' ' + token;
      }
    }
    return res;
  }
```
<p>output array looks like this:</p>
<pre class="lang-json prettyprint-override"><code>[
  "When you take the Dodge action, you focus entirely on avoiding attacks. Until the start of your next turn, any Attack roll made against you has",
  {
    "word": "disadvantage",
    "tooltip": "advantage description"
  },
  "if you can see the attacker, and you make Dexterity Saving Throws with advantage. You lose this benefit if you are",
  {
    "word": "incapacitated",
    "tooltip": "incapacitated description"
  },
  "(as explained in Conditions ) or if your speed drops to 0. "
]
</code>```

and here's an example of how to use it:

  text =
    'When you take the Dodge action, you focus entirely on avoiding attacks. ' +
    'Until the start of your next turn, any Attack roll made against you has disadvantage if you can see the attacker, ' +
    'and you make Dexterity Saving Throws with advantage. ' +
    'You lose this benefit if you are Incapacitated (as explained in Conditions ) or if your speed drops to 0. ';

  dynamicText: (string | keyword)[] = [];

  constructor(private dynamicTextService: DynamicTextService) {}
  ngOnInit(): void {
    this.dynamicText = this.dynamicTextService.toDynamicText(this.text);
  }

  isString(token: any) {
    return typeof token === 'string';
  }

  //Typescript compiler wants a typecast, so we have two helper functions
  getTooltip(token: string | keyword) {
    return (token as keyword).tooltip;
  }

  getWord(token: string | keyword) {
    return (token as keyword).word;
  }
```
<pre class="lang-html prettyprint-override"><code><p>
  <ng-container *ngFor="let token of dynamicText">
    <ng-container *ngIf="isString(token)">{{ token }}</ng-container>
    <ng-container *ngIf="!isString(token)"
      ><b [matTooltip]="getTooltip(token)" style="cursor: pointer">
        {{ getWord(token) }}
      </b></ng-container
    >
  </ng-container>
</p>
</code>```

You could make it more robust by ensuring that the tooltip and word properties exist before trying to return them.

I would make this a component with text as an input variable.

Body:
I am working in a personal Angular project (using Angular Material) and I can't find a solution for this problem.

For example, I have a long text like this :

When you take the Dodge action, you focus entirely on avoiding
attacks. Until the start of your next turn, any Attack roll made
against you has disadvantage if you can see the attacker, and you make
Dexterity Saving Throws with advantage. You lose this benefit if you
are Incapacitated (as explained in Conditions ) or if your speed drops
to 0.

I have some keywords, here disadvantage, advantage incapacitated. I would like to make the font bold and add a tooltip to add a small explanation for each keyword.

I have no problem making the font bold with a pipe, but I can't find a solution for adding a tooltip for the keywords. Using innerHTML does not work, here is my current solution :

And my pipe :

transform(value: string, ...args: unknown[]): unknown {
    let result = value
      result = result.replace('advantage', 'advantage')
      result = result.replace('incapacitated', 'incapacitated')
    return result;
  }

I don't think this is the good solution using a pipe with innerHTML, that is why I am asking for help.

Body:
TLDR: https://stackblitz.com/edit/angular-ivy-86uxvs?file=src/app/app.component.html

The way I see it, each keyword is an object with a word and a tooltip. So I'll define the schema for that.

export type keyword = {
  word: string;
  tooltip: string;
};

I'll define the keywords in an object for easy lookup:

  keywords: { [key: string]: keyword } = {
    disadvantage: {
      word: 'disadvantage',
      tooltip: 'advantage description',
    },
    incapacitated: {
      word: 'incapacitated',
      tooltip: 'incapacitated description',
    },
  };

I think the best way is to split the string into an array of strings and keywords, so we can print them to the html in order. Here's a function that does that - I put all this in a service because it seems fitting.

  toDynamicText(text: string): (string | keyword)[] {
    const res: (string | keyword)[] = [];
    const tokens = text.split(' ');
    let i = 0;
    for (const token of tokens) {
      let keyword = this.keywords[token.toLowerCase()]; //undefined if word is not a keyword
      if (keyword) {
        i = res.push(keyword);
      } else {
        if (!res[i]) res[i] = token;
        else res[i] += ' ' + token;
      }
    }
    return res;
  }

output array looks like this:

[
  "When you take the Dodge action, you focus entirely on avoiding attacks. Until the start of your next turn, any Attack roll made against you has",
  {
    "word": "disadvantage",
    "tooltip": "advantage description"
  },
  "if you can see the attacker, and you make Dexterity Saving Throws with advantage. You lose this benefit if you are",
  {
    "word": "incapacitated",
    "tooltip": "incapacitated description"
  },
  "(as explained in Conditions ) or if your speed drops to 0. "
]

and here's an example of how to use it:

  text =
    'When you take the Dodge action, you focus entirely on avoiding attacks. ' +
    'Until the start of your next turn, any Attack roll made against you has disadvantage if you can see the attacker, ' +
    'and you make Dexterity Saving Throws with advantage. ' +
    'You lose this benefit if you are Incapacitated (as explained in Conditions ) or if your speed drops to 0. ';

  dynamicText: (string | keyword)[] = [];

  constructor(private dynamicTextService: DynamicTextService) {}
  ngOnInit(): void {
    this.dynamicText = this.dynamicTextService.toDynamicText(this.text);
  }

  isString(token: any) {
    return typeof token === 'string';
  }

  //Typescript compiler wants a typecast, so we have two helper functions
  getTooltip(token: string | keyword) {
    return (token as keyword).tooltip;
  }

  getWord(token: string | keyword) {
    return (token as keyword).word;
  }

<p>
  <ng-container *ngFor="let token of dynamicText">
    <ng-container *ngIf="isString(token)">{{ token }}</ng-container>
    <ng-container *ngIf="!isString(token)"
      ><b [matTooltip]="getTooltip(token)" style="cursor: pointer">
        {{ getWord(token) }}
      </b></ng-container
    >
  </ng-container>
</p>

You could make it more robust by ensuring that the tooltip and word properties exist before trying to return them.

I would make this a component with text as an input variable.


问:
Aws Glue Crawler is not updating the table after 1st crawl
I am adding a new file in parquet format which is created by a Glue Databrew in my S3 folder. The new file has the same schema as the previous file. But when I am running the Crawler for the 2nd time it is neither updating the table nor creating a new one in the data catalog. Also when I am crawling both the files together, both of them are getting added.

Log File is giving the following information:

INFO : Created partitions with values [[New file name]] for table

BENCHMARK : Finished writing to Catalog

I have tried with and without "Create a single schema for each S3 path". But the crawler is not updating the table with the new file. Sooner I will add new files on a daily basis to do my analysis. Any solution?

答:
The best way to approach this issue in my opinion is to use AWS DataBrew output to Data Catalog directly. Data Catalog can be updated either by the crawler or by DataBrew directly but the recommended practice is that you employ any one of those mechanisms not both.

Can you try running the job with output as your data catalog and let Databrew manage your catalog? It should update your catalog table with right data/files.


问:
Alternative JSF implementation with JBoss 71
I am trying to use icefaces 1.7.1 in a war application deployed on JBoss 7.0.0.Final

Deployment is failing with an error "Could not compile stylesheet" in icefaces-comp.jar/META-INF/faces-config.xml.  I assume this is because JBoss 7 is expecting me to use the JSF implementation that comes with JBoss 7.

I can not change or upgrade the JSF implementation.

JBoss 6 allowed legacy applications to add the following to web.xml so that the JSF implementation bundled with JBoss is ignored:

```<code><context-param>
   <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name>
   <param-value>true</param-value>
</context-param>
</code>```

This does not seem to work with JBoss 7.

Does anybody know how to use an alternative JSF implementation with JBoss 7?

Thanks.

答: JBoss 7.0.1.Final has been released and fixes this issue, i.e. the org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL context param now works in JBoss 7.0.1.Final.</p>

Body:
I am trying to use icefaces 1.7.1 in a war application deployed on JBoss 7.0.0.Final

Deployment is failing with an error "Could not compile stylesheet" in icefaces-comp.jar/META-INF/faces-config.xml.  I assume this is because JBoss 7 is expecting me to use the JSF implementation that comes with JBoss 7.

I can not change or upgrade the JSF implementation.

JBoss 6 allowed legacy applications to add the following to web.xml so that the JSF implementation bundled with JBoss is ignored:

<context-param>
   <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name>
   <param-value>true</param-value>
</context-param>

This does not seem to work with JBoss 7.

Does anybody know how to use an alternative JSF implementation with JBoss 7?

Thanks.


问:
A typical bracket balanced problem in ocaml
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

```<code>false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"
</code>```
```<code>let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;
</code>```

But I got the following results:

```<code>is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false
</code>```

答:
Presented as an alternative, this is a good opportunity to gain experience with folds. They work well in any situation where you are iterating over something one element at a time and need to evaluate that element in conjunction with an initial state to generate a new value.

The state we'll keep track of is the nesting level. It'll start out as 0. Each iteration, if it's less than 0, the nesting is obviously unbalanced. No further elements from the string will balance the parens, so we'll simply propagate this value to the end of the fold, resulting in a false return.

Otherwise we'll increment or decrement the levels as we encounter open and close parens. Or take no action for non-paren characters.

```<code>let balanced str =
  let f level ch =
    if level < 0 then
      level
    else
      match ch with
      | '(' -> level + 1
      | ')' -> level - 1
      | _   -> level
  in
  String.fold_left f 0 str = 0
</code>```

# balanced ")(";;
- : bool = false
# balanced "(a)b)";;
- : bool = false
# balanced "fo";;
- : bool = true
# balanced "a(b(c)d)e";;
- : bool = true
```
<p>Consider how this operates on <code>"(a)b)"</code>:</p>
```balanced "(a)b)"
String.fold_left f 0 "(a)b)"
String.fold_left f 1 "a)b)"
String.fold_left f 1 ")b)"
String.fold_left f 0 "b)"
String.fold_left f 0 ")"
String.fold_left f -1 ""
-1
-1 = 0
false
```
<p>If we look at <code>"a(b(c)d)e"</code>:</p>
```balanced "a(b(c)d)e"
String.fold_left f 0 "a(b(c)d)e"
String.fold_left f 0 "(b(c)d)e"
String.fold_left f 1 "b(c)d)e"
String.fold_left f 1 "(c)d)e"
String.fold_left f 2 "c)d)e"
String.fold_left f 2 ")d)e"
String.fold_left f 1 "d)e"
String.fold_left f 1 ")e"
String.fold_left f 0 "e"
String.fold_left f 0 ""
0
0 = 0
true
```
<p>The propagation of the negative level value can be seen if we test <code>"())hello()"</code>:</p>
```balanced "())hello()"
String.fold_left f 0 "())hello()"
String.fold_left f 1 "))hello()"
String.fold_left f 0 ")hello()"
String.fold_left f -1 "hello()"
String.fold_left f -1 "ello()"
String.fold_left f -1 "llo()"
String.fold_left f -1 "lo()"
String.fold_left f -1 "o()"
String.fold_left f -1 "()"
String.fold_left f -1 ")"
String.fold_left f -1 ""
-1
-1 = 0
false
```
<p>One note about this approach: it does not <em>short circuit</em>. A string that starts with <code>)</code> will clearly result in <code>false</code> but the entire string will need to be iterated over.</p>
<p>One way around this would be to have our locally scoped <code>f</code> function raise an exception on <code>level</code> being negative, and then to handle this exception by returning <code>false</code>.</p>
```exception Unbalanced_parens

let balanced str =
  let f level ch =
    if level < 0 then
      raise Unbalanced_parens
    else
      match ch with
      | '(' -> level + 1
      | ')' -> level - 1
      | _   -> level
  in
  match String.fold_left f 0 str with
  | 0 -> true
  | _ | exception Unbalanced_parens -> false
```
<p>Now, if we test <code>"())hello()"</code>:</p>
```balanced "())hello()"
String.fold_left f 0 "())hello()"
String.fold_left f 1 "))hello()"
String.fold_left f 0 ")hello()"
String.fold_left f -1 "hello()"
raise Unbalanced_parens
false
```

Body:
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"

let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;

But I got the following results:

is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false

Body:
Presented as an alternative, this is a good opportunity to gain experience with folds. They work well in any situation where you are iterating over something one element at a time and need to evaluate that element in conjunction with an initial state to generate a new value.

The state we'll keep track of is the nesting level. It'll start out as 0. Each iteration, if it's less than 0, the nesting is obviously unbalanced. No further elements from the string will balance the parens, so we'll simply propagate this value to the end of the fold, resulting in a false return.

Otherwise we'll increment or decrement the levels as we encounter open and close parens. Or take no action for non-paren characters.

let balanced str =
  let f level ch =
    if level < 0 then
      level
    else
      match ch with
      | '(' -> level + 1
      | ')' -> level - 1
      | _   -> level
  in
  String.fold_left f 0 str = 0

# balanced ")(";;
- : bool = false
# balanced "(a)b)";;
- : bool = false
# balanced "fo";;
- : bool = true
# balanced "a(b(c)d)e";;
- : bool = true

Consider how this operates on "(a)b)":

balanced "(a)b)"
String.fold_left f 0 "(a)b)"
String.fold_left f 1 "a)b)"
String.fold_left f 1 ")b)"
String.fold_left f 0 "b)"
String.fold_left f 0 ")"
String.fold_left f -1 ""
-1
-1 = 0
false

If we look at "a(b(c)d)e":

balanced "a(b(c)d)e"
String.fold_left f 0 "a(b(c)d)e"
String.fold_left f 0 "(b(c)d)e"
String.fold_left f 1 "b(c)d)e"
String.fold_left f 1 "(c)d)e"
String.fold_left f 2 "c)d)e"
String.fold_left f 2 ")d)e"
String.fold_left f 1 "d)e"
String.fold_left f 1 ")e"
String.fold_left f 0 "e"
String.fold_left f 0 ""
0
0 = 0
true

The propagation of the negative level value can be seen if we test "())hello()":

balanced "())hello()"
String.fold_left f 0 "())hello()"
String.fold_left f 1 "))hello()"
String.fold_left f 0 ")hello()"
String.fold_left f -1 "hello()"
String.fold_left f -1 "ello()"
String.fold_left f -1 "llo()"
String.fold_left f -1 "lo()"
String.fold_left f -1 "o()"
String.fold_left f -1 "()"
String.fold_left f -1 ")"
String.fold_left f -1 ""
-1
-1 = 0
false

One note about this approach: it does not short circuit. A string that starts with ) will clearly result in false but the entire string will need to be iterated over.

One way around this would be to have our locally scoped f function raise an exception on level being negative, and then to handle this exception by returning false.

exception Unbalanced_parens

let balanced str =
  let f level ch =
    if level < 0 then
      raise Unbalanced_parens
    else
      match ch with
      | '(' -> level + 1
      | ')' -> level - 1
      | _   -> level
  in
  match String.fold_left f 0 str with
  | 0 -> true
  | _ | exception Unbalanced_parens -> false

Now, if we test "())hello()":

balanced "())hello()"
String.fold_left f 0 "())hello()"
String.fold_left f 1 "))hello()"
String.fold_left f 0 ")hello()"
String.fold_left f -1 "hello()"
raise Unbalanced_parens
false