问:
Wordpress Shortcode setcookie Issue
No errors or warnings are generated when running the code below.

I just ran into a problem on wordpress when trying to create cookies inside of shortcode events.

In the code below, the test1 cookie is created just fine, however the test2 cookie is not created.

The verbiage 'Code Ran' does display however.

```<code>if ( ! function_exists('cookieset')) :
function cookieset( $atts, $content = null ) {
    extract( shortcode_atts( array(
        'name'     => 'cookieloc',
        'redirect' => '/',
        'expires'  => '365',
    ), $atts ) );
    setcookie("test2", 1, time()+3600, "/", ".domainname.com", false, true);
    return "Code Ran";
}
endif;

if ( ! function_exists('cookieloc_action') ) :

function cookieloc_action() {
    echo add_shortcode('cookieloc', 'cookieset');
    setcookie("test1", 1, time()+3600, "/", ".domainname.com", false, true);
}
endif;
</code>```

答:
It appears the Word Press does not buffer the entire page content, but progressively sends the content, thus I cannot send headers in an add_shortcode(...) function

Sadly, the order of execution is not provided in the API sections on wordpress...
http://codex.wordpress.org/Shortcode_API

Title: Wordpress Shortcode setcookie Issue

Body:
No errors or warnings are generated when running the code below.

I just ran into a problem on wordpress when trying to create cookies inside of shortcode events.

In the code below, the test1 cookie is created just fine, however the test2 cookie is not created.

The verbiage 'Code Ran' does display however.

if ( ! function_exists('cookieset')) :
function cookieset( $atts, $content = null ) {
    extract( shortcode_atts( array(
        'name'     => 'cookieloc',
        'redirect' => '/',
        'expires'  => '365',
    ), $atts ) );
    setcookie("test2", 1, time()+3600, "/", ".domainname.com", false, true);
    return "Code Ran";
}
endif;

if ( ! function_exists('cookieloc_action') ) :

function cookieloc_action() {
    echo add_shortcode('cookieloc', 'cookieset');
    setcookie("test1", 1, time()+3600, "/", ".domainname.com", false, true);
}
endif;


来源: stackexchange

问:
Check if two sets have a non-empty intersection
I wrote a function intersects that efficiently checks wether two sets have a non-empty intersection (at least, more efficient than checking the size of their intersection).

It works well, but now I would like to specialize this function for the type DataStructures.IntSet from the DataStructures library. I wrote the function below, which works, but is a bit messy.

As you can see, when the attribute inverse is true, I have to negate the current chunk. In an attempt to simplify the code, I wrote the function intersects2 which does the same work but without the need of multiples if/else.

But this code appears to be less efficient than the first one. I'm not sure, but I think the problem is that each call to op_u or op_v copy the parameter, as shown in the output below.

How can I rewrite this function such that it does not make any copy (ie. no allocation) and without several imbricated if/else? The full code, benchmarks and results can be found below.

```<code>using Random
using DataStructures
using BenchmarkTools

elems = [randstring(8) for i in 1:10000]
ii = rand(1:10000, 3000)
jj = rand(1:10000, 3000)

x1 = Set(elems[ii])
y1 = Set(elems[jj])

x2 = Set(ii)
y2 = Set(jj)

x3 = DataStructures.IntSet(ii)
y3 = DataStructures.IntSet(jj)

function intersects(u, v)
    for x in u
        if x in v
            return true
        end
    end
    false
end

function intersects(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if u.inverse
            if v.inverse
                if ~ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ~ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        else
            if v.inverse
                if ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        end
    end
    false
end

function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u = if u.inverse x->~x else x->x end
    op_v = if v.inverse x->~x else x->x end

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    false
end

println("Set{String}")
@btime intersects($x1, $y1)

println("Set{Int}")
@btime intersects($x2, $y2)

println("IntSet")
@btime intersects($x3, $y3)
@btime intersects2($x3, $y3)
</code>```

```<code>Set{String}
  190.163 ns (0 allocations: 0 bytes)
Set{Int}
  17.935 ns (0 allocations: 0 bytes)
IntSet
  7.099 ns (0 allocations: 0 bytes)
  90.000 ns (5 allocations: 80 bytes)
</code>```

答:
You could have avoided the nesting also with something like this, this is also a bit faster than your intersects(u::DataStructures.IntSet, v::DataStructures.IntSet) method, because of @inbounds:

```<code>function intersects4(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v)
        @inbounds if (u.inverse && v.inverse && ~ch_u[i] & ~ch_v[i] > 0) ||
           (u.inverse && ~ch_u[i] & ch_v[i] > 0) ||
           (v.inverse && ch_u[i] & ~ch_v[i] > 0) ||
           (ch_u[i] & ch_v[i] > 0)
            return true
        end
    end
    return false
end
</code>```

Are you sure there can not be a BoundsError if ch_u's lenght is larger than ch_v's and the function happens to run the whole loop? I did for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v) just in case, because I haven't tested your function thoroughly.

Great answer by @David Varela (I'll call his function intersects3), you can get even a bit faster than intersect4 above if you make sure there will be no BoundsError and use @inbounds, like this:

```<code>function intersects5(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u(x) = u.inverse ? ~x : x
    op_v(x) = v.inverse ? ~x : x

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v)
        @inbounds if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    return false
end
</code>```

```<code>julia> begin
           @btime intersects($x3, $y3)   # nested ifs and bound checks
           @btime intersects2($x3, $y3)  # with non inline-able ops
           @btime intersects3($x3, $y3)  # David's improvement
           @btime intersects4($x3, $y3)  # without ifs and with @inbounds
           @btime intersects5($x3, $y3)  # David's improvement with @inbounds
       end
7.184 ns (0 allocations: 0 bytes)
87.633 ns (5 allocations: 80 bytes)
6.500 ns (0 allocations: 0 bytes)
3.763 ns (0 allocations: 0 bytes)
3.079 ns (0 allocations: 0 bytes)
</code>```

Also in your code:

```<code>op_u = if u.inverse x -> ~x else x -> x end
</code>```

You could have also done:

```<code>op_u = u.inverse ? (~) : identity
</code>```

As ~ operator is just a function and an identity function already exists, anyway David's answer is better (because this won't inline either) and intersects5 is the fastest and more succinct of all, just wanted to mention it though.

ContentLicense: CC BY-SA 4.0

Body:
I wrote a function intersects that efficiently checks wether two sets have a non-empty intersection (at least, more efficient than checking the size of their intersection).

It works well, but now I would like to specialize this function for the type DataStructures.IntSet from the DataStructures library. I wrote the function below, which works, but is a bit messy.

As you can see, when the attribute inverse is true, I have to negate the current chunk. In an attempt to simplify the code, I wrote the function intersects2 which does the same work but without the need of multiples if/else.

But this code appears to be less efficient than the first one. I'm not sure, but I think the problem is that each call to op_u or op_v copy the parameter, as shown in the output below.

How can I rewrite this function such that it does not make any copy (ie. no allocation) and without several imbricated if/else? The full code, benchmarks and results can be found below.

using Random
using DataStructures
using BenchmarkTools

elems = [randstring(8) for i in 1:10000]
ii = rand(1:10000, 3000)
jj = rand(1:10000, 3000)

x1 = Set(elems[ii])
y1 = Set(elems[jj])

x2 = Set(ii)
y2 = Set(jj)

x3 = DataStructures.IntSet(ii)
y3 = DataStructures.IntSet(jj)

function intersects(u, v)
    for x in u
        if x in v
            return true
        end
    end
    false
end

function intersects(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if u.inverse
            if v.inverse
                if ~ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ~ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        else
            if v.inverse
                if ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        end
    end
    false
end

function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u = if u.inverse x->~x else x->x end
    op_v = if v.inverse x->~x else x->x end

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    false
end

println("Set{String}")
@btime intersects($x1, $y1)

println("Set{Int}")
@btime intersects($x2, $y2)

println("IntSet")
@btime intersects($x3, $y3)
@btime intersects2($x3, $y3)

Set{String}
  190.163 ns (0 allocations: 0 bytes)
Set{Int}
  17.935 ns (0 allocations: 0 bytes)
IntSet
  7.099 ns (0 allocations: 0 bytes)
  90.000 ns (5 allocations: 80 bytes)

Body:
You could have avoided the nesting also with something like this, this is also a bit faster than your intersects(u::DataStructures.IntSet, v::DataStructures.IntSet) method, because of @inbounds:

function intersects4(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v)
        @inbounds if (u.inverse && v.inverse && ~ch_u[i] & ~ch_v[i] > 0) ||
           (u.inverse && ~ch_u[i] & ch_v[i] > 0) ||
           (v.inverse && ch_u[i] & ~ch_v[i] > 0) ||
           (ch_u[i] & ch_v[i] > 0)
            return true
        end
    end
    return false
end

Are you sure there can not be a BoundsError if ch_u's lenght is larger than ch_v's and the function happens to run the whole loop? I did for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v) just in case, because I haven't tested your function thoroughly.

Great answer by @David Varela (I'll call his function intersects3), you can get even a bit faster than intersect4 above if you make sure there will be no BoundsError and use @inbounds, like this:

function intersects5(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u(x) = u.inverse ? ~x : x
    op_v(x) = v.inverse ? ~x : x

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in eachindex(length(ch_u) > length(ch_v) ? ch_u : ch_v)
        @inbounds if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    return false
end

julia> begin
           @btime intersects($x3, $y3)   # nested ifs and bound checks
           @btime intersects2($x3, $y3)  # with non inline-able ops
           @btime intersects3($x3, $y3)  # David's improvement
           @btime intersects4($x3, $y3)  # without ifs and with @inbounds
           @btime intersects5($x3, $y3)  # David's improvement with @inbounds
       end
7.184 ns (0 allocations: 0 bytes)
87.633 ns (5 allocations: 80 bytes)
6.500 ns (0 allocations: 0 bytes)
3.763 ns (0 allocations: 0 bytes)
3.079 ns (0 allocations: 0 bytes)

Also in your code:

op_u = if u.inverse x -> ~x else x -> x end

You could have also done:

op_u = u.inverse ? (~) : identity

As ~ operator is just a function and an identity function already exists, anyway David's answer is better (because this won't inline either) and intersects5 is the fastest and more succinct of all, just wanted to mention it though.


问:
Kivy Camera free resources issue
I want to use Camera to capture photos and scan barcode in my Android app. I added it in kv:

```<code><CameraForm>:
    FloatLayout:
        Camera:
            id: camera
            size_hint: (1, 0.8)
            pos_hint: {"center_x": 0.5, "top": 0.95}
            canvas.before:
                PushMatrix
                Rotate:
                    angle: -90 if app.isAndroid() else 0
                    origin: self.center
            canvas.after:
                PopMatrix

        MDRaisedButton:
            text: "Capture"
            size_hint: (None, None)
            height: "40dp"
            pos_hint: {"x": 0.2, "top": 0.1}
            on_press: root.capturePhoto()
</code>```

And python code:

```<code>class CameraForm(Screen):
    def __init__(self, *args, **kwargs):
        super(CameraForm, self).__init__(*args, **kwargs)
        self.fileName = None
        self.camera = None

    def initCamera(self):
        self.camera = self.ids.camera
        self.camera.resolution = (720, 480)
        self.camera.keep_ratio = True
        self.camera.play = True
        self.camera.allow_stretch = True

    def on_enter(self, *args):
        self.initCamera()

    def capturePhoto(self):
        imgTime = time.strftime("%Y%m%d_%H%M%S")
        self.fileName = MDApp.get_running_app().imagePath + "IMG_{}.png".format(imgTime)  # store image file
        self.camera.export_to_png(self.fileName)
        msgBox = MessageBox()
        msgBox.showMsg("Information", "Image has been successfully captured!", "OK", False)
</code>```

The similar code I have for Camera to scan Barcode. The problem is when I try to switch from Camera to Barcode camera then I got the following issues:

```<code>[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1113) SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072873821
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1125) SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072873821
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072873821
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'
</code>```

And the app crashes. So, I think it needs to free the Camera resources.

```<code>def on_leave(self, *args):
    self.camera.stop()
</code>```

When I try to leave camera screen it reports error:

AttributeError: 'Camera' object has no attribute 'stop'

But from the kivy docs: https://kivy.org/doc/stable/api-kivy.core.camera.html#kivy.core.camera.CameraBase.stop

stop() Added in 1.0.0 Release the camera

So, why stop() is not available for Camera? How to free the Camera resources? Thank you for the help.

答:
The kivy.core.camera.CameraBase class has a stop() method but the Camera widget (in your .kv file) is an instance of the kivy.uix.camera.Camera class and it does not have stop() method.

If you want to stop the camera, you can use the play property of Camera. Camera's doc.

Otherwise you can use self.camera._camera to directly access the CoreCamera instance in Camera (but I'm not sure if it is recommended).

I recommend that you look at Camera sources for a better understanding, especially line 102 and the definition of on_play().

Title: Kivy Camera free resources issue

Body:
I want to use Camera to capture photos and scan barcode in my Android app. I added it in kv:

<CameraForm>:
    FloatLayout:
        Camera:
            id: camera
            size_hint: (1, 0.8)
            pos_hint: {"center_x": 0.5, "top": 0.95}
            canvas.before:
                PushMatrix
                Rotate:
                    angle: -90 if app.isAndroid() else 0
                    origin: self.center
            canvas.after:
                PopMatrix

        MDRaisedButton:
            text: "Capture"
            size_hint: (None, None)
            height: "40dp"
            pos_hint: {"x": 0.2, "top": 0.1}
            on_press: root.capturePhoto()

And python code:

class CameraForm(Screen):
    def __init__(self, *args, **kwargs):
        super(CameraForm, self).__init__(*args, **kwargs)
        self.fileName = None
        self.camera = None

    def initCamera(self):
        self.camera = self.ids.camera
        self.camera.resolution = (720, 480)
        self.camera.keep_ratio = True
        self.camera.play = True
        self.camera.allow_stretch = True

    def on_enter(self, *args):
        self.initCamera()

    def capturePhoto(self):
        imgTime = time.strftime("%Y%m%d_%H%M%S")
        self.fileName = MDApp.get_running_app().imagePath + "IMG_{}.png".format(imgTime)  # store image file
        self.camera.export_to_png(self.fileName)
        msgBox = MessageBox()
        msgBox.showMsg("Information", "Image has been successfully captured!", "OK", False)

The similar code I have for Camera to scan Barcode. The problem is when I try to switch from Camera to Barcode camera then I got the following issues:

[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1113) SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -1072873821
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1125) SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072873821
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072873821
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
[ERROR  ] [OpenCV      ] Couldn't get image from Camera
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 144, in _update
    self._buffer = frame.imageData
AttributeError: 'NoneType' object has no attribute 'imageData'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\kivy\core\camera\camera_opencv.py", line 148, in _update
    self._buffer = frame.reshape(-1)
AttributeError: 'NoneType' object has no attribute 'reshape'

And the app crashes. So, I think it needs to free the Camera resources.

def on_leave(self, *args):
    self.camera.stop()

When I try to leave camera screen it reports error:

AttributeError: 'Camera' object has no attribute 'stop'

But from the kivy docs: https://kivy.org/doc/stable/api-kivy.core.camera.html#kivy.core.camera.CameraBase.stop

stop() Added in 1.0.0 Release the camera

So, why stop() is not available for Camera? How to free the Camera resources? Thank you for the help.


问:
benchmark for using base64 string instead of image reducing http requests
I am looking at replacing source of my images currently set to a image file in my css to a base64 string.  Instead of the browser needing to make several calls, one for the CSS file and then one for each image, base64 embedding means that all of the images are embedded within the CSS file itself.

So I am currently investigating introducing this. However I have an issue I would like some advice on, a known problem with this approach. That is in my tests a base64 encoded string image is somewhere around 150% the size of a regular image. This means it’s unusable for large images. While I am not too concerned regarding larger images, I am not sure when I should and shouldn't use it.

Is there a benchmark I should use, as in if the base64 more than 150% larger I should not use it etc?

What are others views on this and what from your own experiences may help with the decision of when to and not to use it?

答:
Base64 encoding requires very close to 4/3 of the original number of bytes, so a fair amount less than 150%, more like 133%.

I can only suggest that you benchmark this yourself and see whether your particular needs are better satisfied with the more complex approach, or whether you're better served sticking with the norm.

ContentLicense: CC BY-SA 3.0


问:
Nested for loop using dict
I am doing a Coursera python exercise and having trouble writing my code.

The question is as following:

Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.

The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

The sample text file is in this line:
http://www.pythonlearn.com/code/mbox-short.txt

And the expected output should be:

```<code>cwen@iupui.edu 5
</code>```

This is my code:

```<code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
    word = line.split()
    if line.startswith('From '):
        email = word[1]
        for sender in email:
            if sender not in count:
                count[sender] = count.get(sender, 0) + 1

bigcount = None
bigname = None
for name,count in count.items():
    if bigname is None or count > bigcount:
        bigname = name
        bigcount = count
print bigname, bigcount
</code>```

The output I have is:

```<code>. 1
</code>```

I think there is something wrong in "for sender in email" part, but couldn't figure out how it results in the undesired output.

答:
```<code>name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
name = "mbox-short.txt"
handle = open(name)
text = handle.read()
#words = text.split()

words = list()

for line in handle:
    if not line.startswith("From:") : continue
    line = line.split()
    words.append(line[1])

counts = dict()

for word in words:
           counts[word] = counts.get(word, 0) + 1

maxval = None
maxkey = None
for key,val in counts.items() :
#   if maxval == None : maxval = val
  if val > maxval:
      maxval = val
      maxkey = key

print (maxkey, maxval)
</code>```

Title: Nested for loop using dict

Body:
I am doing a Coursera python exercise and having trouble writing my code.

The question is as following:

Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.

The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

The sample text file is in this line:
http://www.pythonlearn.com/code/mbox-short.txt

And the expected output should be:

cwen@iupui.edu 5

This is my code:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
    word = line.split()
    if line.startswith('From '):
        email = word[1]
        for sender in email:
            if sender not in count:
                count[sender] = count.get(sender, 0) + 1

bigcount = None
bigname = None
for name,count in count.items():
    if bigname is None or count > bigcount:
        bigname = name
        bigcount = count
print bigname, bigcount

The output I have is:

. 1

I think there is something wrong in "for sender in email" part, but couldn't figure out how it results in the undesired output.


问:
Use list comprehension to find largest int value in kwargs that also contain a certain substring
Here's my code because I think it's easier to explain what I'm trying to do by showing what I'm doing first.

Let's say these are my kwargs passed to a function:

```<code>kwargs = {fastperiod=20, slowperiod=10, r=100}
</code>```

So I am trying to find the largest value of kwargs that also contain the substring period. In this case that would mean 20.

I am currently doing this with:

```<code>periods = []
    for kwarg in kwargs:
        if 'period' in kwarg:
            periods.append(kwargs.get(kwarg))
    max_ = max(periods)
</code>```

Which is not very terse. I feel like there has to be a way to achieve this with list comprehension.

The best I could come up with is:

```<code>max_ = max([i for i in kwargs.get(i) if 'period' in i])
</code>```

But I get an UnboundLocalError: local variable 'i' referenced before assignment

I am not sure how to check if kwarg contains period and then return the int value assigned to it at the same time.

答:
Use kwargs.items() to get the key and value as you iterate.

```<code>max([v for k, v in kwargs.items() if "period" in k])
</code>```

Body:
Here's my code because I think it's easier to explain what I'm trying to do by showing what I'm doing first.

Let's say these are my kwargs passed to a function:

kwargs = {fastperiod=20, slowperiod=10, r=100}

So I am trying to find the largest value of kwargs that also contain the substring period. In this case that would mean 20.

I am currently doing this with:

periods = []
    for kwarg in kwargs:
        if 'period' in kwarg:
            periods.append(kwargs.get(kwarg))
    max_ = max(periods)

Which is not very terse. I feel like there has to be a way to achieve this with list comprehension.

The best I could come up with is:

max_ = max([i for i in kwargs.get(i) if 'period' in i])

But I get an UnboundLocalError: local variable 'i' referenced before assignment

I am not sure how to check if kwarg contains period and then return the int value assigned to it at the same time.

Body:
Use kwargs.items() to get the key and value as you iterate.

max([v for k, v in kwargs.items() if "period" in k])


问:
Renaming Column names and then creating a data frame using renamed column in R
I am having a dataset name noaaFilename which is having multiple columns, out of those columns I need to change name of 3 columns (Dat, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. I am trying to do this, but unable to get result with column values.</p>

```<code>colnames(noaaFilename)

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaData <- data.frame("Date", "Time", "AtmosPressure")
</code>```

答:
After changing the names you need to subset columns from the dataframe</p>

```<code>noaaData <- noaaFilename[c('Date', 'Time', 'AtmosPressure')]
</code>```

Body:
I am having a dataset name noaaFilename which is having multiple columns, out of those columns I need to change name of 3 columns (Dat, HrMn, Slp) to (Date, Time, AtmosPressure) and then make a data frame of these 3 columns. I am trying to do this, but unable to get result with column values.

colnames(noaaFilename)

  names(noaaFilename)[names(noaaFilename) == "Date"] <- "Date"
  names(noaaFilename)[names(noaaFilename) == "HrMn"] <- "Time"
  names(noaaFilename)[names(noaaFilename) == "Slp"] <- "AtmosPressure"

  noaaData <- data.frame("Date", "Time", "AtmosPressure")

Body:
After changing the names you need to subset columns from the dataframe

noaaData <- noaaFilename[c('Date', 'Time', 'AtmosPressure')]


问:
Event handler incrementing loop issue
I'm using Xamarin.Forms to create a chatbot app. Any time I send a new message to the bot, the reply is gotten but increments itself by one i.e

```<code>User: Hi
Bot: Hello
User: How are you?
Bot: Good
Bot: Good
</code>```

In the code I'm using this:

```<code> public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                //This adds a new message to the messages collection
                Messages.Add(new ChatMessageModel() { Text = TextToSend, User = App.User });

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }
</code>```

After using a breakpoint on Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot }); I found out that it adds a new message each and everytime, therefore incrementing upon itself. I would like a way to stop this and have it happen only once.

EDIT: Entire Class

```<code>using BluePillApp.Models;
using BluePillApp.ViewModels.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
using Syn.Bot.Siml;
using Syn.Bot.Oscova;
using Syn.Bot.Oscova.Attributes;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BluePillApp.ViewModels
{
    /// <summary>
    /// View model for the ChatbotPage.xaml
    /// </summary>
    public class ChatbotPageViewModel : BaseViewModel
    {
        /// <summary>
        /// A field for TextToSend
        /// </summary>
        private string _texttosend;

        /// <summary>
        /// An Instance of a new SIML Oscova Chatbot
        /// </summary>
        public OscovaBot chatbot;

        /// <summary>
        /// A collection/list of chat message items
        /// </summary>
        public ObservableCollection<ChatMessageModel> Messages { get; set; } = new ObservableCollection<ChatMessageModel>();

        /// <summary>
        /// The text that the user inputs
        /// </summary>
        public string TextToSend
        {
            get
            {
                return _texttosend;
            }

            set
            {
                if (_texttosend != value)
                {
                    _texttosend = value;

                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// A command for sending the users messages
        /// </summary>
        public ICommand SendCommand { get; set; }

        /// <summary>
        /// ChatPageViewModel Constructor
        /// </summary>
        public ChatbotPageViewModel()
        {
            SendCommand = new RelayCommand(Send);

            chatbot = new OscovaBot();
            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
            Stream stream = assembly.GetManifestResourceStream("BluePillApp.Helpers.new.siml");

            chatbot.Import(XDocument.Load(stream));
            chatbot.Trainer.StartTraining();
        }

        /// <summary>
        /// This function sends a message
        /// </summary>
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };
                //This adds a new message to the messages collection
                Messages.Add(msgModel);

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }
    }
}

</code>```

答:
You debugged very well, now try to save that damn object:

```<code>var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };

//This adds a new message to the messages collection
Messages.Add(msgModel);
</code>```

then re-use it:

```<code>//This gets the chatbots response for each message
chatbot.MainUser.ResponseReceived += async (sender, args) =>
{
    msgModel.Text = args.Response.Text;
    msgModel.User = App.ChatBot;
    await Task.Delay(1500);
    Messages.Add(msgModel);
};
</code>```

I hope this resolves.

Title: Event handler incrementing loop issue

Body:
I'm using Xamarin.Forms to create a chatbot app. Any time I send a new message to the bot, the reply is gotten but increments itself by one i.e

User: Hi
Bot: Hello
User: How are you?
Bot: Good
Bot: Good

In the code I'm using this:

 public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                //This adds a new message to the messages collection
                Messages.Add(new ChatMessageModel() { Text = TextToSend, User = App.User });

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }

After using a breakpoint on Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot }); I found out that it adds a new message each and everytime, therefore incrementing upon itself. I would like a way to stop this and have it happen only once.

EDIT: Entire Class

using BluePillApp.Models;
using BluePillApp.ViewModels.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
using Syn.Bot.Siml;
using Syn.Bot.Oscova;
using Syn.Bot.Oscova.Attributes;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BluePillApp.ViewModels
{
    ///
    /// View model for the ChatbotPage.xaml
    ///
    public class ChatbotPageViewModel : BaseViewModel
    {
        ///
        /// A field for TextToSend
        ///
        private string _texttosend;

        ///
        /// An Instance of a new SIML Oscova Chatbot
        ///
        public OscovaBot chatbot;

        ///
        /// A collection/list of chat message items
        ///
        public ObservableCollection<ChatMessageModel> Messages { get; set; } = new ObservableCollection<ChatMessageModel>();

        ///
        /// The text that the user inputs
        ///
        public string TextToSend
        {
            get
            {
                return _texttosend;
            }

            set
            {
                if (_texttosend != value)
                {
                    _texttosend = value;

                    OnPropertyChanged();
                }
            }
        }

        ///
        /// A command for sending the users messages
        ///
        public ICommand SendCommand { get; set; }

        ///
        /// ChatPageViewModel Constructor
        ///
        public ChatbotPageViewModel()
        {
            SendCommand = new RelayCommand(Send);

            chatbot = new OscovaBot();
            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly;
            Stream stream = assembly.GetManifestResourceStream("BluePillApp.Helpers.new.siml");

            chatbot.Import(XDocument.Load(stream));
            chatbot.Trainer.StartTraining();
        }

        ///
        /// This function sends a message
        ///
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };
                //This adds a new message to the messages collection
                Messages.Add(msgModel);

                //This gets the chatbots response for each message
                chatbot.MainUser.ResponseReceived += async (sender, args) =>
                {
                    await Task.Delay(1500);
                    Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
                };

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }
    }
}

Body:
You debugged very well, now try to save that damn object:

var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };

//This adds a new message to the messages collection
Messages.Add(msgModel);

then re-use it:

//This gets the chatbots response for each message
chatbot.MainUser.ResponseReceived += async (sender, args) =>
{
    msgModel.Text = args.Response.Text;
    msgModel.User = App.ChatBot;
    await Task.Delay(1500);
    Messages.Add(msgModel);
};

I hope this resolves.


问:
Fatal error LNK1104: cannot open file 'libboost_log-vc141-mt-gd-1_64.lib'
I'm writing a program which utilizes Boost logging features and consequently, when attempting to build the said program, I'm getting the following error when generating code (on Visual Studio 2017):

1>LINK : fatal error LNK1104: cannot open file 'libboost_log-vc141-mt-gd-1_64.lib'

However, I can confirm the following:

boost_1_64_0\stage\lib has been added to "Additional Library Directories" under Linker -> General

libboost_log-vc141-mt-gd-1_64.lib is located under stage/lib since when unpacking Boost, I did a complete build with toolset set to 14.1

following relevant question's answers, I did add the specific .lib to "Additional Dependencies" under Linker -> Input

I feel like it's something obvious that I am missing. But, any help would be much appreciated.

答:
For me, I was using the below define for linking log libraries in order to use dynamically. I removed it and worked.</p>

```<code>//#define BOOST_LOG_DYN_LINK 1 // necessary when linking the boost_log library dynamically
</code>```

Body:
For me, I was using the below define for linking log libraries in order to use dynamically. I removed it and worked.

//#define BOOST_LOG_DYN_LINK 1 // necessary when linking the boost_log library dynamically


问:
Why does exponentiating a numpy.float64 return nan?
When I am raising a negative numpy.float64 to an exponent, I am receiving an nan. Why is the complex math not supported? Is the only workaround a cast to float?

```<code>>>> from numpy import float64, power
>>> r = float64(-12025.433836763057)
>>> p = 0.74
>>> r**p
nan
>>> power(r, p)
__main__:1: RuntimeWarning: invalid value encountered in power
nan
>>> float(r)**p
(-715.6124638577838+762.049873596874j)
>>>
</code>```

A suggested duplicate has a similar question, with an answer stating that this is a bug in numpy. Is this the end of the road?

答:
The numpy.float64 is probably represented under the hood by a C language data structure which is strongly typed. The python float is pythonic, and so plays nicely with the complex number handling that python provides.

See: https://docs.scipy.org/doc/numpy/reference/c-api.dtype.html

Body:
When I am raising a negative numpy.float64 to an exponent, I am receiving an nan. Why is the complex math not supported? Is the only workaround a cast to float?

>>> from numpy import float64, power
>>> r = float64(-12025.433836763057)
>>> p = 0.74
>>> r**p
nan
>>> power(r, p)
__main__:1: RuntimeWarning: invalid value encountered in power
nan
>>> float(r)**p
(-715.6124638577838+762.049873596874j)
>>>

A suggested duplicate has a similar question, with an answer stating that this is a bug in numpy. Is this the end of the road?


问:
How to center my asp.NET panels?
I've got panels containing tables to organize textboxes/labels, and I'd like to center them, but I can't figure out what attribute to use. I've tried to justify them in the design view, and horizontalalign:center in html, but to no avail. What's the best way to center panels containing tables?</p>

答:
I would apply CSS to them:

```<code>div.myPanelCss
{
    margin-left: auto;
    margin-right: auto;
}
</code>```

I believe Panels render as a div

Title: How to center my asp.NET panels?

Body:
I would apply CSS to them:

div.myPanelCss
{
    margin-left: auto;
    margin-right: auto;
}

I believe Panels render as a div


问:
Highlight all connected paths from start to end in Sankey graph using R
I want to highlight the whole path when i click on the node to know the whole story of specific node and here's an example- http://bl.ocks.org/git-ashish/8959771 .

Please check this link and you will find the function that highlight the path in javscript, but take care please , this function doesn't do what i want, it highlight links related to the clicked node and the links related to the target nodes. what i want is to highlight all links related to the clicked node.

d3 Sankey - Highlight all connected paths from start to end

Here's an example of what i need,

This is the whole graph,what i need is, when i click on Bangkok, it highlight all the nodes that in the same raw with Bangkok in the dataframe , like highlight the link to ClimateChange and EnergyShortage, .... then highlight Infrastructure&Ecosystems, and Leadership&strategy, and ....
That's what i want.
Here's another picture showing the nodes that related to Bangkok using shiny to analyze it .

Here's what happens when i use highlight_node_links which in the bl.ocks and the linked question, and that's wrong, and doesn't show the relation between nodes and Bangkoks.

Here's the data for Bangkok to show you how the columns related to each other, and when you use this data, it gonna generate the second picture only.

```<code>structure(list(City = c("Bangkok", "Bangkok", "Bangkok", "Bangkok",
"Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok",
"Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok"
), ResiliencyChallenge = c("ClimateChange", "ClimateChange",
"ClimateChange", "ClimateChange", "ClimateChange", "InfrastructureFaliure",
"EnergyShortage", "Pollution", "Pollution", "Pollution", "TransportationSystemFailure",
"TransportationSystemFailure", "TransportationSystemFailure",
"TransportationSystemFailure", "TransportationSystemFailure",
"TransportationSystemFailure"), CRI.Dimesnsion.1 = c("Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Leadership & Strategy", "Leadership & Strategy", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Leadership & Strategy"), Implementation.time.frame = c("Short-term",
"Short-term", "Short-term", "Short-term", "Short-term", "Mid-term",
"Long-term", "Short-term", "Short-term", "Mid-term", "Mid-term",
"Short-term", "Short-term", "Short-term", "Short-term", "Short-term"
), Goal = c("Goal13", "Goal13", "Goal13", "Goal13", "Goal13",
"Goal12", "Goal12", "Goal11", "Goal11", "Goal11", "Goal11", "Goal11",
"Goal11", "Goal11", "Goal11", "Goal11")), .Names = c("City",
"ResiliencyChallenge", "CRI.Dimesnsion.1", "Implementation.time.frame",
"Goal"), class = "data.frame", row.names = c(NA, -16L))
</code>```

答:
The implementation for this question is in this shiny app.

https://setsna2.shinyapps.io/sankey-shinyforallcities/

I had to modify networkD3 from inside, i installed it normally and copied it inside the directory that contains the shiny app and put the package inside R-lib.

I made some modification to sankeyNetwork.js function that plot the sankey graph.
Here's a picture for the directory, it shows the structure of the directory to reach the place that has sankeyNetwork.js to change it manually.

Please notice that the version of sankeyNetwork.js i used and uploaded in this question is old, it's from 2 years ago, so u can download the new version of networkD3 and just modify the part i'll mention next.

What i changed in sankeyNetwork.js is to add

```<code>    .on('mouseover', function(node) {
        Shiny.onInputChange("node_name", node.name);
    })
</code>```

Which means if someone hover on a node, i'll transfer the nodename as "node_name" variable to my R session by using Shiny.onInputChange, u can read more about this shiny function online.

Here's the sankeyNetwork.js i used to know what i mean.

Now, if someone hover on a node, i can get the name of this node and send it to R, and if he moved away his cursor, i won't get any name, that's the core idea.

You can check the code of my shiny app by clicking here

You can see part of Data0 variable here also Goals variable from here.

In R code, you gonna find some comments say "for debug use this code" or comments within the code, so if u run these comments, u will understand how the data looks like before running the shiny app to fully understand how sankey graphs reads the data and how it should look like.

In R code, you gonna find this part which is reading the node_name from sankeyNetwork.js

```<code>        NodeName <- reactive({
                if(length(input$node_name)>0){return(as.character(input$node_name))}
                else{return(0)}
        })
</code>```

Then the next part in the code is to check if the NodeName is in my Nodes dataframe, if it exists, then i'll get all the nodes that related to this node, then i'll get the links ids that connect these nodes with each other, and please notice that the links id start from 0 not from 1, because javascript starts from 0 and R starts from 1.

Now we have the NodeName that the user is hovering on, and the Links that related to this node, now we can make the sankey graph and save it in sn,  then i remove the old tooltip and add a new one.

Using onRender to modify sankey graph while using shiny and i used it to make the Highlighting function to modify sankey graph while running shiny and when the user hover on a node, i'll get the name of the node then gets the links ids and search for the links ids in the existed sankey graph and increase it's opacity.

Please note that if u run the application, u gonna get errors, u have to upload it on shinyapps.io to debug it, that was the way i was checking if my application works correct or not, maybe u can find another way to debug.

Body:
I want to highlight the whole path when i click on the node to know the whole story of specific node and here's an example- http://bl.ocks.org/git-ashish/8959771 .

Please check this link and you will find the function that highlight the path in javscript, but take care please , this function doesn't do what i want, it highlight links related to the clicked node and the links related to the target nodes. what i want is to highlight all links related to the clicked node.

d3 Sankey - Highlight all connected paths from start to end

Here's an example of what i need,

This is the whole graph,what i need is, when i click on Bangkok, it highlight all the nodes that in the same raw with Bangkok in the dataframe , like highlight the link to ClimateChange and EnergyShortage, .... then highlight Infrastructure&Ecosystems, and Leadership&strategy, and ....
That's what i want.
Here's another picture showing the nodes that related to Bangkok using shiny to analyze it .

Here's what happens when i use highlight_node_links which in the bl.ocks and the linked question, and that's wrong, and doesn't show the relation between nodes and Bangkoks.

Here's the data for Bangkok to show you how the columns related to each other, and when you use this data, it gonna generate the second picture only.

structure(list(City = c("Bangkok", "Bangkok", "Bangkok", "Bangkok",
"Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok",
"Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok", "Bangkok"
), ResiliencyChallenge = c("ClimateChange", "ClimateChange",
"ClimateChange", "ClimateChange", "ClimateChange", "InfrastructureFaliure",
"EnergyShortage", "Pollution", "Pollution", "Pollution", "TransportationSystemFailure",
"TransportationSystemFailure", "TransportationSystemFailure",
"TransportationSystemFailure", "TransportationSystemFailure",
"TransportationSystemFailure"), CRI.Dimesnsion.1 = c("Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Leadership & Strategy", "Leadership & Strategy", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Infrastructure & Ecosystems",
"Infrastructure & Ecosystems", "Leadership & Strategy"), Implementation.time.frame = c("Short-term",
"Short-term", "Short-term", "Short-term", "Short-term", "Mid-term",
"Long-term", "Short-term", "Short-term", "Mid-term", "Mid-term",
"Short-term", "Short-term", "Short-term", "Short-term", "Short-term"
), Goal = c("Goal13", "Goal13", "Goal13", "Goal13", "Goal13",
"Goal12", "Goal12", "Goal11", "Goal11", "Goal11", "Goal11", "Goal11",
"Goal11", "Goal11", "Goal11", "Goal11")), .Names = c("City",
"ResiliencyChallenge", "CRI.Dimesnsion.1", "Implementation.time.frame",
"Goal"), class = "data.frame", row.names = c(NA, -16L))

Body:
The implementation for this question is in this shiny app.

https://setsna2.shinyapps.io/sankey-shinyforallcities/

I had to modify networkD3 from inside, i installed it normally and copied it inside the directory that contains the shiny app and put the package inside R-lib.

I made some modification to sankeyNetwork.js function that plot the sankey graph.
Here's a picture for the directory, it shows the structure of the directory to reach the place that has sankeyNetwork.js to change it manually.

Please notice that the version of sankeyNetwork.js i used and uploaded in this question is old, it's from 2 years ago, so u can download the new version of networkD3 and just modify the part i'll mention next.

What i changed in sankeyNetwork.js is to add

    .on('mouseover', function(node) {
        Shiny.onInputChange("node_name", node.name);
    })

Which means if someone hover on a node, i'll transfer the nodename as "node_name" variable to my R session by using Shiny.onInputChange, u can read more about this shiny function online.

Here's the sankeyNetwork.js i used to know what i mean.

Now, if someone hover on a node, i can get the name of this node and send it to R, and if he moved away his cursor, i won't get any name, that's the core idea.

You can check the code of my shiny app by clicking here

You can see part of Data0 variable here also Goals variable from here.

In R code, you gonna find some comments say "for debug use this code" or comments within the code, so if u run these comments, u will understand how the data looks like before running the shiny app to fully understand how sankey graphs reads the data and how it should look like.

In R code, you gonna find this part which is reading the node_name from sankeyNetwork.js

        NodeName <- reactive({
                if(length(input$node_name)>0){return(as.character(input$node_name))}
                else{return(0)}
        })

Then the next part in the code is to check if the NodeName is in my Nodes dataframe, if it exists, then i'll get all the nodes that related to this node, then i'll get the links ids that connect these nodes with each other, and please notice that the links id start from 0 not from 1, because javascript starts from 0 and R starts from 1.

Now we have the NodeName that the user is hovering on, and the Links that related to this node, now we can make the sankey graph and save it in sn,  then i remove the old tooltip and add a new one.

Using onRender to modify sankey graph while using shiny and i used it to make the Highlighting function to modify sankey graph while running shiny and when the user hover on a node, i'll get the name of the node then gets the links ids and search for the links ids in the existed sankey graph and increase it's opacity.

Please note that if u run the application, u gonna get errors, u have to upload it on shinyapps.io to debug it, that was the way i was checking if my application works correct or not, maybe u can find another way to debug.


问:
cURL command parameters problem, not retrying the right number of times
Here's my cURL command:

```<code>/usr/bin/curl --ipv4 --connect-timeout 1 --retry 15 --retry-delay 2 --retry-max-time 15 --no-keepalive --no-tcp-nodelay -L --silent 'http://www.example.org' -v --trace-time
</code>```

When there's a network congestion issue, it doesn't retry the number of times specified... Here's the output I get:

```<code>13:29:01.884487 *   Trying 104.18.47.34...
13:29:02.382339 * After 498ms connect time, move on!
13:29:02.382512 * connect to 104.18.47.34 port 80 failed: Connection timed out
13:29:02.382595 *   Trying 104.18.46.34...
13:29:02.631165 * After 248ms connect time, move on!
13:29:02.631287 * connect to 104.18.46.34 port 80 failed: Connection timed out
13:29:02.631369 * Failed to connect to www.example.org port 80: Connection timed out
13:29:02.631423 * Closing connection 0
</code>```

Any idea what is wrong with my parameters?

Thank you.

答:
The issue was with my cURL version (7.58).

"Connection timed out" wasn't handled as a transient error, correctly, until version 7.67.0 (https://github.com/curl/curl/issues/4461).

I upgraded cURL to the latest available version (7.68) and haven't seen this error since.

Body:
Here's my cURL command:

/usr/bin/curl --ipv4 --connect-timeout 1 --retry 15 --retry-delay 2 --retry-max-time 15 --no-keepalive --no-tcp-nodelay -L --silent 'http://www.example.org' -v --trace-time

When there's a network congestion issue, it doesn't retry the number of times specified... Here's the output I get:

13:29:01.884487 *   Trying 104.18.47.34...
13:29:02.382339 * After 498ms connect time, move on!
13:29:02.382512 * connect to 104.18.47.34 port 80 failed: Connection timed out
13:29:02.382595 *   Trying 104.18.46.34...
13:29:02.631165 * After 248ms connect time, move on!
13:29:02.631287 * connect to 104.18.46.34 port 80 failed: Connection timed out
13:29:02.631369 * Failed to connect to www.example.org port 80: Connection timed out
13:29:02.631423 * Closing connection 0

Any idea what is wrong with my parameters?

Thank you.


问:
Dates with incorrect format
I want to convert this type of date Thu Oct 31 2019 15:07:23 GMT-0600 (Central Standard Time) to this 2019-10-08T15:07:38 and I'm using mommentjs to convert the date but when I try to implement the next code I only get this 2019-10-23T15:07:23-05:00.

```<code>const newDate = moment.parseZone(result).format();
</code>```

The variable result have this value Thu Oct 31 2019 15:07:23 GMT-0600 (Central Standard Time) and the result is this 2019-10-23T15:07:23-05:00. It doesn't matter if I need to use another library.

答:
try this:

const newDate = moment.parseZone(result).format("YYYY-MM-DDTHH:mm:ss");
```

docs: https://momentjs.com/docs/#/displaying/format/

Title: Dates with incorrect format

Body:
I want to convert this type of date Thu Oct 31 2019 15:07:23 GMT-0600 (Central Standard Time) to this 2019-10-08T15:07:38 and I'm using mommentjs to convert the date but when I try to implement the next code I only get this 2019-10-23T15:07:23-05:00.

const newDate = moment.parseZone(result).format();

The variable result have this value Thu Oct 31 2019 15:07:23 GMT-0600 (Central Standard Time) and the result is this 2019-10-23T15:07:23-05:00. It doesn't matter if I need to use another library.

Body:
try this:

const newDate = moment.parseZone(result).format("YYYY-MM-DDTHH:mm:ss");

docs: https://momentjs.com/docs/#/displaying/format/


问:
Capitalize with dplyr
I am doing data cleaning with dplyr.
One of the things I want to do is to capitalize values in certain columns.

```<code>    data$surname
    john
    Mary
    John
    mary
    ...
</code>```

I suppose I have to use the mutate function of dplyr with something like this

```<code>    titleCase <- function(x) {
    + s <- strsplit(as.character(x), " ")[[1]]
    + paste(toupper(substring(s, 1, 1)), substring(s, 2),
    + sep = "", collapse = " ")
    + }
</code>```

But how to combine both? I get all kinds of errors or truncated data frames

Thanks

答:
A little late to the party but you can use stringr package

```<code>library(stringr)
library(dplyr)

example1 <- tibble(names = c("john" ,"Mary", "John", "mary"))

example1 %>%
mutate(names = str_to_title(names))

##  names
##  <chr>
## 1 John
## 2 Mary
## 3 John
## 4 Mary
</code>```

This will still work if you want all terms capitalized

```<code>example2 <- tibble(names = c("john james" ,"Mary carey", "John Jack", "mary Harry"))

example2 %>%
mutate(names = str_to_title(names))

##  names
##  <chr>
## 1 John James
## 2 Mary Carey
## 3 John Jack
## 4 Mary Harry
</code>```

If you  only want the first term capitalized, str_to_sentence() will work

```<code>example2 %>%
mutate(names = str_to_sentence(names))

##  names
##  <chr>
## 1 John james
## 2 Mary carey
## 3 John jack
## 4 Mary harry
</code>```

Title: Capitalize with dplyr

Body:
I am doing data cleaning with dplyr.
One of the things I want to do is to capitalize values in certain columns.

    data$surname
    john
    Mary
    John
    mary
    ...

I suppose I have to use the mutate function of dplyr with something like this

    titleCase <- function(x) {
    + s <- strsplit(as.character(x), " ")[[1]]
    + paste(toupper(substring(s, 1, 1)), substring(s, 2),
    + sep = "", collapse = " ")
    + }

But how to combine both? I get all kinds of errors or truncated data frames

Thanks

Body:
A little late to the party but you can use stringr package

library(stringr)
library(dplyr)

example1 <- tibble(names = c("john" ,"Mary", "John", "mary"))

example1 %>%
mutate(names = str_to_title(names))

##  names
##  <chr>
## 1 John
## 2 Mary
## 3 John
## 4 Mary

This will still work if you want all terms capitalized

example2 <- tibble(names = c("john james" ,"Mary carey", "John Jack", "mary Harry"))

example2 %>%
mutate(names = str_to_title(names))

##  names
##  <chr>
## 1 John James
## 2 Mary Carey
## 3 John Jack
## 4 Mary Harry

If you  only want the first term capitalized, str_to_sentence() will work

example2 %>%
mutate(names = str_to_sentence(names))

##  names
##  <chr>
## 1 John james
## 2 Mary carey
## 3 John jack
## 4 Mary harry


问:
How to properly upload a local file to a server using mobaXterm?
I'm trying to upload a file from my local desktop to a server and I'm using this command:

```<code>scp myFile.txt cooluser@192.168.10.102:/opt/nicescada/web
</code>```

following the structure: scp filename user@ip:/remotePath.

But I get "Permission Denied". I tried using sudo , but I get the same message. I'm being able to download from the server to my local machine, so I assume I have all permissions needed.

What can be wrong in that line of code?

答:
Try and specify the full destination path:

```<code>scp myFile.txt cooluser@192.168.10.102:/opt/nicescada/web/myFile.txt
</code>```

Of course, double-check cooluser has the right to write (not just read) in that folder: 755, not 644 for the web parent folder.

Body:
I'm trying to upload a file from my local desktop to a server and I'm using this command:

scp myFile.txt cooluser@192.168.10.102:/opt/nicescada/web

following the structure: scp filename user@ip:/remotePath.

But I get "Permission Denied". I tried using sudo , but I get the same message. I'm being able to download from the server to my local machine, so I assume I have all permissions needed.

What can be wrong in that line of code?

Body:
Try and specify the full destination path:

scp myFile.txt cooluser@192.168.10.102:/opt/nicescada/web/myFile.txt

Of course, double-check cooluser has the right to write (not just read) in that folder: 755, not 644 for the web parent folder.


问:
The type of Meal.nutrition must be Output Type but got: undefined
I have come across this problem in setting up my server with GraphQL, Express.js, and MongoDB. It seems like some sort of reference error, I am not sure what the issue is, I have tried looking for my answer but cannot seem to find it.

The error I am getting on GraphiQL is this, I am not sure why

```<code>{
  "errors": [
    {
      "message": "The type of Meal.nutrition must be Output Type but got: undefined."
    }
  ]
}
</code>```

Anyway, on app.js
The code is

```<code>const express = require("express")
const app = express();
const userSchema = require("./graph-schema/userQueries")
const workoutSchema = require("./graph-schema/workoutQueries")
const mealSchema = require("./graph-schema/mealQueries")
const mongoose = require("mongoose")
const {mergeSchemas} = require("graphql-tools")

//connect to mongoDB atlase database
mongoose.connect("mongodb+srv://Z***98:*****@cluster0-epauj.mongodb.net/test?retryWrites=true&w=majority")
mongoose.connection.once("open", () => {
    console.log("Connected to database")
})

const combinedSchemas = mergeSchemas({
    schemas: [
        userSchema,
        mealSchema,
        workoutSchema
    ]
})

//this module allows express to communicate with graphql ;
//we use it as a single endpoint
const graphqlHTTP = require("express-graphql")

app.use("/graphql" , graphqlHTTP({
    schema: combinedSchemas,
    graphiql: true

}))

app.listen(4000, () => {
    console.log(`Listening on port 4000`)
})
</code>```

MealType is defined in a file called schema.js, which has all the other types (UserType, AuthType, WorkoutType), I have imported and exported I needed.

```<code>const graphql = require("graphql")
const Workout = require("../models/Workout.js")
const User = require("../models/User.js")
const Meal = require("../models/Meal")

const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

//describes what attributes and its types, a User has in each query
const UserType = new GraphQLObjectType({
    name: "User",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        email: {type: GraphQLString},
        password: {type: GraphQLString},
        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all the workouts created by a user
                return Workout.findById({userId: parent.id})
            }
        },
        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                //returns all the meals created by a user
                return Meal.findById({userId: parent.id})
            }
        }

    })
})

const WorkoutType = new GraphQLObjectType({
    name: "Workout",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        reps: {type: GraphQLInt},
        burnedCalories: {type: GraphQLInt},
        sets: {type: GraphQLInt},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the workout instance
                return User.findById(parent.userId)

            }
        }

    })
})

const AuthType = new GraphQLObjectType({
    name: "Authentication",
    fields: () => ({
        token: {type: GraphQLString},
        userId: {type: GraphQLString}
    })
})

const MealType = new GraphQLObjectType({
    name: "Meal",
    fields: () => ({
        id: {type: GraphQLID},
        calories: {type: GraphQLInt},
        servings: {type: GraphQLInt},
        nutrition: {
            carbohydrates: {type: GraphQLInt},
            fats: {type: GraphQLInt},
            protein: {type: GraphQLInt}
        },
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the meal instance
                return User.findById(parent.userId)
            }
        }

    })
})

module.exports = {
    AuthType,
    WorkoutType,
    UserType,
    MealType
}
</code>```

The Meal which will be saved onto MongoDB atlas looks like

```<code>const mealSchema = new Schema({
    name: String,
    calories: Number,
    servings: Number,
    nutrition: {
        carbohydrates: Number,
        fats: Number,
        protein: Number
    },
    userId: String
})
</code>```

And now the mutation and queries are for the meals are defined in a file called mealQueries.js

```<code>const graphql = require("graphql")
const {MealType} = require("./schema")
const Meal = require("../models/Meal.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const MealQuery = new GraphQLObjectType({
    name: "MealQueries",
    fields: () => ({
        meal: {
            type: MealType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                return Meal.findById(args.id)
            }
        },

        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                return Meal.find({})
            }
        }

    })

})

const MealMutation = new GraphQLObjectType({
    name: "MealMutation",
    addMeal: {
        type: MealType,
        args: {
            name: {type: GraphQLString},
            servings: {type: GraphQLInt},
            calories: {type: GraphQLInt},
            nutrition: {
                carbohydrates: {type: GraphQLInt},
                proteins: {type: GraphQLInt},
                fats: {type: GraphQLInt}
            },
            userId: {type: GraphQLID}
        },
        resolve(parent, args){

            let meal = new Meal({
                userId: args.userId,
                name: args.name,
                servings: args.servings,
                calories: args.calories,
                nutrition: {
                    carbohydrates: args.nutrition.carbohydrates,
                    fats: args.nutrition.fats,
                    proteins: args.nutrition.proteins
                }
            })

            return meal.save();
        }
    }

})

module.exports = new GraphQLSchema({
    query: MealQuery,
    mutation: MealMutation
})
</code>```

答:
You can't nest fields like this:

```<code>nutrition: {
  carbohydrates: {type: GraphQLInt},
  fats: {type: GraphQLInt},
  protein: {type: GraphQLInt}
},
</code>```

You need to create a separate type. You can do so inline if you don't need to reference it elsewhere in your schema:

```<code>nutrition: new GraphQLObjectType({
  name: 'Nutrition',
  fields: () => ({
    carbohydrates: { type: GraphQLInt },
    fats: { type: GraphQLInt },
    protein: { type: GraphQLInt },
  }),
}),
</code>```

Body:
I have come across this problem in setting up my server with GraphQL, Express.js, and MongoDB. It seems like some sort of reference error, I am not sure what the issue is, I have tried looking for my answer but cannot seem to find it.

The error I am getting on GraphiQL is this, I am not sure why

{
  "errors": [
    {
      "message": "The type of Meal.nutrition must be Output Type but got: undefined."
    }
  ]
}

Anyway, on app.js
The code is

const express = require("express")
const app = express();
const userSchema = require("./graph-schema/userQueries")
const workoutSchema = require("./graph-schema/workoutQueries")
const mealSchema = require("./graph-schema/mealQueries")
const mongoose = require("mongoose")
const {mergeSchemas} = require("graphql-tools")

//connect to mongoDB atlase database
mongoose.connect("mongodb+srv://Z***98:*****@cluster0-epauj.mongodb.net/test?retryWrites=true&w=majority")
mongoose.connection.once("open", () => {
    console.log("Connected to database")
})

const combinedSchemas = mergeSchemas({
    schemas: [
        userSchema,
        mealSchema,
        workoutSchema
    ]
})

//this module allows express to communicate with graphql ;
//we use it as a single endpoint
const graphqlHTTP = require("express-graphql")

app.use("/graphql" , graphqlHTTP({
    schema: combinedSchemas,
    graphiql: true

}))

app.listen(4000, () => {
    console.log(`Listening on port 4000`)
})

MealType is defined in a file called schema.js, which has all the other types (UserType, AuthType, WorkoutType), I have imported and exported I needed.

const graphql = require("graphql")
const Workout = require("../models/Workout.js")
const User = require("../models/User.js")
const Meal = require("../models/Meal")

const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

//describes what attributes and its types, a User has in each query
const UserType = new GraphQLObjectType({
    name: "User",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        email: {type: GraphQLString},
        password: {type: GraphQLString},
        workouts: {
            type: new GraphQLList(WorkoutType),
            resolve(parent, args){
                //returns all the workouts created by a user
                return Workout.findById({userId: parent.id})
            }
        },
        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                //returns all the meals created by a user
                return Meal.findById({userId: parent.id})
            }
        }

    })
})

const WorkoutType = new GraphQLObjectType({
    name: "Workout",
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        reps: {type: GraphQLInt},
        burnedCalories: {type: GraphQLInt},
        sets: {type: GraphQLInt},
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the workout instance
                return User.findById(parent.userId)

            }
        }

    })
})

const AuthType = new GraphQLObjectType({
    name: "Authentication",
    fields: () => ({
        token: {type: GraphQLString},
        userId: {type: GraphQLString}
    })
})

const MealType = new GraphQLObjectType({
    name: "Meal",
    fields: () => ({
        id: {type: GraphQLID},
        calories: {type: GraphQLInt},
        servings: {type: GraphQLInt},
        nutrition: {
            carbohydrates: {type: GraphQLInt},
            fats: {type: GraphQLInt},
            protein: {type: GraphQLInt}
        },
        user: {
            type: UserType,
            resolve(parent, args){
                //returns the user from the database that created the meal instance
                return User.findById(parent.userId)
            }
        }

    })
})

module.exports = {
    AuthType,
    WorkoutType,
    UserType,
    MealType
}

The Meal which will be saved onto MongoDB atlas looks like

const mealSchema = new Schema({
    name: String,
    calories: Number,
    servings: Number,
    nutrition: {
        carbohydrates: Number,
        fats: Number,
        protein: Number
    },
    userId: String
})

And now the mutation and queries are for the meals are defined in a file called mealQueries.js

const graphql = require("graphql")
const {MealType} = require("./schema")
const Meal = require("../models/Meal.js")
const {GraphQLObjectType, GraphQLID, GraphQLString, GraphQLSchema, GraphQLInt, GraphQLList} = graphql;

const MealQuery = new GraphQLObjectType({
    name: "MealQueries",
    fields: () => ({
        meal: {
            type: MealType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args){
                return Meal.findById(args.id)
            }
        },

        meals: {
            type: new GraphQLList(MealType),
            resolve(parent, args){
                return Meal.find({})
            }
        }

    })

})

const MealMutation = new GraphQLObjectType({
    name: "MealMutation",
    addMeal: {
        type: MealType,
        args: {
            name: {type: GraphQLString},
            servings: {type: GraphQLInt},
            calories: {type: GraphQLInt},
            nutrition: {
                carbohydrates: {type: GraphQLInt},
                proteins: {type: GraphQLInt},
                fats: {type: GraphQLInt}
            },
            userId: {type: GraphQLID}
        },
        resolve(parent, args){

            let meal = new Meal({
                userId: args.userId,
                name: args.name,
                servings: args.servings,
                calories: args.calories,
                nutrition: {
                    carbohydrates: args.nutrition.carbohydrates,
                    fats: args.nutrition.fats,
                    proteins: args.nutrition.proteins
                }
            })

            return meal.save();
        }
    }

})

module.exports = new GraphQLSchema({
    query: MealQuery,
    mutation: MealMutation
})

Body:
You can't nest fields like this:

nutrition: {
  carbohydrates: {type: GraphQLInt},
  fats: {type: GraphQLInt},
  protein: {type: GraphQLInt}
},

You need to create a separate type. You can do so inline if you don't need to reference it elsewhere in your schema:

nutrition: new GraphQLObjectType({
  name: 'Nutrition',
  fields: () => ({
    carbohydrates: { type: GraphQLInt },
    fats: { type: GraphQLInt },
    protein: { type: GraphQLInt },
  }),
}),


问:
Learning PHP but I've noticed the writer of the book I'm using calls objects in 2 different ways

Possible Duplicate:

  PHP class instantiation. To use or not to use the parenthesis?

I'm learning PHP from an O'reilly book "Learning PHP, MySQL and Javascript". I'm half way through learning about objects etc.

I've noticed that sometimes the writer calls objects in two different ways.

$example = new Object

$example = new Object()

They both seem to work fine for me. Is there a preferred way or best practice? Is there a reason for this?

答:
Personally I prefer to include the parenthesis. helps to remind you the constructor is a method that you can override.

But this could just be because I learned OOP in C++.

Whatever you do, just be consistent.


问:
How to scroll scrollView so that TextField move above Keyboard in SwiftUI?
I have setup a UI in which there are 6 fields in the ScrollView as the following:

```<code>...
         ScrollView {

                IndicatorTextField(
                    index: 0,
                    hint: "Full Name",
                    icon: .imageUserBlue,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 48)

                IndicatorTextField(
                    index: 1,
                    hint: "Email Address",
                    icon: .imageEmail,
                    activeFieldTag: self.$activeFieldTag,
                    type: .emailAddress
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 2,
                    hint: "Home Town",
                    icon: .imageLocation,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 3,
                    hint: "Password",
                    icon: .imageLock,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 4,
                    hint: "Date of Birth",
                    icon: .imageCalender,
                    activeFieldTag: self.$activeFieldTag,
                    type: .numbersAndPunctuation,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 5,
                    hint: "Gender",
                    icon: .imageUserRed,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink,
                    returnKey: .default
                ).padding(.top, 8)

                Spacer()
                    .frame(width: 0, height: -keyboardObserver.lastViewAdjustment)
            }
            .background(GeometryGetter(rect: $keyboardObserver.lastViewRect))
...
</code>```

Here is keyboardObserver

When the keyboard appears then I just change the Spacer height enough to scroll till last field.

Now, I want to auto scroll the firstResponder above the Keyboard.

Does anyone know about how to scroll ScrollView with SwiftUI code?

答:
I haven't found a way to scroll ScrollView in SwiftUI so far, but I used a workaround, where I tell the parent scroll view to scroll from a wrapper for UITextField: https://lostmoa.com/blog/ScrollTextFieldIntoVisibleRange/

I found it's an easier solution than wrapping UIScrollView.

Body:
I have setup a UI in which there are 6 fields in the ScrollView as the following:

...
         ScrollView {

                IndicatorTextField(
                    index: 0,
                    hint: "Full Name",
                    icon: .imageUserBlue,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 48)

                IndicatorTextField(
                    index: 1,
                    hint: "Email Address",
                    icon: .imageEmail,
                    activeFieldTag: self.$activeFieldTag,
                    type: .emailAddress
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 2,
                    hint: "Home Town",
                    icon: .imageLocation,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 3,
                    hint: "Password",
                    icon: .imageLock,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 4,
                    hint: "Date of Birth",
                    icon: .imageCalender,
                    activeFieldTag: self.$activeFieldTag,
                    type: .numbersAndPunctuation,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 5,
                    hint: "Gender",
                    icon: .imageUserRed,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink,
                    returnKey: .default
                ).padding(.top, 8)

                Spacer()
                    .frame(width: 0, height: -keyboardObserver.lastViewAdjustment)
            }
            .background(GeometryGetter(rect: $keyboardObserver.lastViewRect))
...

Here is keyboardObserver

When the keyboard appears then I just change the Spacer height enough to scroll till last field.

Now, I want to auto scroll the firstResponder above the Keyboard.

Does anyone know about how to scroll ScrollView with SwiftUI code?


问:
How to define conditional string types in Typescript like flow?
```<code>type UpsertMode = | 'add' | 'update' | 'delete';

interface IUpsertMembers {
  mode: UpsertMode;
}

const MagicButton = ({ mode: UpsertMode }) => {
  return (
    <button>{mode}</button>
  );
}

const UpsertMembers = ({ mode }: IUpsertMembers) => {
  return (
    <MagicButton mode={mode} />
  );
};

export default UpsertMembers;

</code>```

I am trying to use it inside a .tsx file and the type still turns out to be any

It gives an error saying

```<code>Binding element 'UpsertMode' implicitly has an 'any' type.  TS7031
</code>```

答:
Looks like your problem is in the binding of the mode variable.  You want MagicButton to take a single argument of type {mode: UpsertMode}, and then destructure it  into a function-local variable named mode.  To do that you have to write it like this:

```<code>const MagicButton = ({ mode }: { mode: UpsertMode }) => {
  return (
    <button>{ mode } < /button>
  );
}
</code>```

This is basically the same as the annotation you have in your UpsertMembers function.

The reason why ({ mode: UpsertMode }) => ... doesn't work is because that's just JavaScript and you have no type annotation.  It's similar to ({ mode: UpsertMode }: any) => ....   Here, {mode : UpsertMode} is doing an object destructuring where you assign to a new variable name.  Meaning that the mode property of the input has been destructured into a function-local variable named UpsertMode.  Not your intent, and leads to at least two fun errors:

since you had no type annotation, the type of UpsertMode in ({mode: UpsertMode}) is implicitly inferred to be any, which is an error with --noImplicitAny: Binding element 'UpsertMode' implicitly has an 'any' type.

since the function has no local variable named mode, your use of mode in the function is an error: Cannot find name 'mode'.

If you think that you shouldn't have to write mode twice just to get both a destructuring assignment binding and a type annotation, you're not alone.  There's an open issue, microsoft/TypeScript#29526, in which it's suggested to allow something like ({mode :: UpsertMode}) => ... to indicate that UpsertMode is a type and not a variable name.  If you want to increase the chance of this happening, you might want to head over to that issue and give it a .

Okay, hope that helps; good luck!

Playground link to code

Body:
type UpsertMode = | 'add' | 'update' | 'delete';

interface IUpsertMembers {
  mode: UpsertMode;
}

const MagicButton = ({ mode: UpsertMode }) => {
  return (
    <button>{mode}</button>
  );
}

const UpsertMembers = ({ mode }: IUpsertMembers) => {
  return (
    <MagicButton mode={mode} />
  );
};

export default UpsertMembers;

I am trying to use it inside a .tsx file and the type still turns out to be any

It gives an error saying

Binding element 'UpsertMode' implicitly has an 'any' type.  TS7031

Body:
Looks like your problem is in the binding of the mode variable.  You want MagicButton to take a single argument of type {mode: UpsertMode}, and then destructure it  into a function-local variable named mode.  To do that you have to write it like this:

const MagicButton = ({ mode }: { mode: UpsertMode }) => {
  return (
    <button>{ mode } < /button>
  );
}

This is basically the same as the annotation you have in your UpsertMembers function.

The reason why ({ mode: UpsertMode }) => ... doesn't work is because that's just JavaScript and you have no type annotation.  It's similar to ({ mode: UpsertMode }: any) => ....   Here, {mode : UpsertMode} is doing an object destructuring where you assign to a new variable name.  Meaning that the mode property of the input has been destructured into a function-local variable named UpsertMode.  Not your intent, and leads to at least two fun errors:

since you had no type annotation, the type of UpsertMode in ({mode: UpsertMode}) is implicitly inferred to be any, which is an error with --noImplicitAny: Binding element 'UpsertMode' implicitly has an 'any' type.

since the function has no local variable named mode, your use of mode in the function is an error: Cannot find name 'mode'.

If you think that you shouldn't have to write mode twice just to get both a destructuring assignment binding and a type annotation, you're not alone.  There's an open issue, microsoft/TypeScript#29526, in which it's suggested to allow something like ({mode :: UpsertMode}) => ... to indicate that UpsertMode is a type and not a variable name.  If you want to increase the chance of this happening, you might want to head over to that issue and give it a .

Okay, hope that helps; good luck!

Playground link to code


问:
FirebaseDynamicLinks.instance.getInitialLink() always returning null on Android
I'm using firebase_dynamic_links for passwordless login with firebase and getInitialLink() is always returning null on version 0.5.0+8.
If I use version 0.4.0+4 and retrieveDynamicLink() instead of getInitialLink() it works fine.

Since it's working in version 0.4.0+4 I assume the problem is not on Firebase settings.
This is how I'm sending the email:

```<code>final FirebaseAuth user = FirebaseAuth.instance;
    try {
      user.sendSignInWithEmailLink(
          email: _email,
          androidInstallIfNotAvailable: true,
          iOSBundleID: "com.mydomain.myappname",
          androidMinimumVersion: "16",
          androidPackageName: "com.mydomain.myappname",
          url: "https://myAppName.page.link/fJc4",
          handleCodeInApp: true);
    } catch (e) {
      _showDialog(e.toString());
      return false;
    }
</code>```

And then to retrieve it:

```<code>@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _retrieveDynamicLink();
    }
  }

  Future<void> _retrieveDynamicLink() async {
    final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
    print('data == ' + data.toString());

    final Uri deepLink = data?.link;
    print(deepLink.toString());

    if (deepLink != null) {
      _link = deepLink.toString();
      _signInWithEmailAndLink();
    }
    return deepLink.toString();
  }
</code>```

data is always null on the new version with getInitialLink(). It works on the previous version with retrieveDynamicLink().

I created a new project just to test it and the problem persists. The only other change I made to the project, besides the view files was add firebase_auth: ^0.15.0+1 to pubspc.yaml

Doctor summary (to see all details, run flutter doctor -v): [√]

Flutter (Channel stable, v1.9.1+hotfix.6, on Microsoft Windows
[Version 10.0.17763.864], locale pt-BR)

[√] Android toolchain - develop for Android devices (Android SDKversion 28.0.3)

[√] Android Studio (version 3.5)

[!] VS Code (version 1.40.0) X Flutter extension not installed; install from https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)

! Doctor found issues in 1 category.

Any help is appreciated.

答:
getInitialLink() only works if opened via a dynamic link (see plugin document), not when the application is active or in background (for this you need to call onLink).</p>

```<code>  void initDynamicLinks() async {
    final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
    final Uri deepLink = data?.link;    if (deepLink != null) {
      Navigator.pushNamed(context, deepLink.path);
    }

    FirebaseDynamicLinks.instance.onLink(
      onSuccess: (PendingDynamicLinkData dynamicLink) async {
        final Uri deepLink = dynamicLink?.link;

        if (deepLink != null) {
          Navigator.pushNamed(context, deepLink.path);
        }
      },
      onError: (OnLinkErrorException e) async {
        print('onLinkError');
        print(e.message);
      }
    );
  }
</code>```

Body:
I'm using firebase_dynamic_links for passwordless login with firebase and getInitialLink() is always returning null on version 0.5.0+8.
If I use version 0.4.0+4 and retrieveDynamicLink() instead of getInitialLink() it works fine.

Since it's working in version 0.4.0+4 I assume the problem is not on Firebase settings.
This is how I'm sending the email:

final FirebaseAuth user = FirebaseAuth.instance;
    try {
      user.sendSignInWithEmailLink(
          email: _email,
          androidInstallIfNotAvailable: true,
          iOSBundleID: "com.mydomain.myappname",
          androidMinimumVersion: "16",
          androidPackageName: "com.mydomain.myappname",
          url: "https://myAppName.page.link/fJc4",
          handleCodeInApp: true);
    } catch (e) {
      _showDialog(e.toString());
      return false;
    }

And then to retrieve it:

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _retrieveDynamicLink();
    }
  }

  Future<void> _retrieveDynamicLink() async {
    final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
    print('data == ' + data.toString());

    final Uri deepLink = data?.link;
    print(deepLink.toString());

    if (deepLink != null) {
      _link = deepLink.toString();
      _signInWithEmailAndLink();
    }
    return deepLink.toString();
  }

data is always null on the new version with getInitialLink(). It works on the previous version with retrieveDynamicLink().

I created a new project just to test it and the problem persists. The only other change I made to the project, besides the view files was add firebase_auth: ^0.15.0+1 to pubspc.yaml

Doctor summary (to see all details, run flutter doctor -v): [√]

Flutter (Channel stable, v1.9.1+hotfix.6, on Microsoft Windows
[Version 10.0.17763.864], locale pt-BR)

[√] Android toolchain - develop for Android devices (Android SDKversion 28.0.3)

[√] Android Studio (version 3.5)

[!] VS Code (version 1.40.0) X Flutter extension not installed; install from https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)

! Doctor found issues in 1 category.

Any help is appreciated.

Body:
getInitialLink() only works if opened via a dynamic link (see plugin document), not when the application is active or in background (for this you need to call onLink).

  void initDynamicLinks() async {
    final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
    final Uri deepLink = data?.link;    if (deepLink != null) {
      Navigator.pushNamed(context, deepLink.path);
    }

    FirebaseDynamicLinks.instance.onLink(
      onSuccess: (PendingDynamicLinkData dynamicLink) async {
        final Uri deepLink = dynamicLink?.link;

        if (deepLink != null) {
          Navigator.pushNamed(context, deepLink.path);
        }
      },
      onError: (OnLinkErrorException e) async {
        print('onLinkError');
        print(e.message);
      }
    );
  }


问:
How to prevent wrong values in an initializer list?
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

```<code>class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};
</code>```

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

```<code>class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};
</code>```

答:
You can delegate the verification and modification of the variable to a function.</p>

```<code>class a {
 public:
  a(int c) : b(ValidateAndTransformInputParameter(c)) {}
 private:
  const int b;
  int ValidateAndTransformInputParameter(int d) const {
    if (d < 100) {
      d = 100;
    }
    return d;
  }
};
</code>```

Body:
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};

Body:
You can delegate the verification and modification of the variable to a function.

class a {
 public:
  a(int c) : b(ValidateAndTransformInputParameter(c)) {}
 private:
  const int b;
  int ValidateAndTransformInputParameter(int d) const {
    if (d < 100) {
      d = 100;
    }
    return d;
  }
};


答:
Make a function:</p>

```<code>class a {
    int const b;

public:
    a(int const c)
        : b { initializeB(c) }
    {
    }

private:
    static int initializeB(int const c)
    {
        if (c < MIN_ALLOWED || c > MAX_ALLOWED) {
            // Take some mesure
            return -1; // example
        }
        return c;
    }
};
</code>```

Title: How to prevent wrong values in an initializer list?

Body:
Make a function:

class a {
    int const b;

public:
    a(int const c)
        : b { initializeB(c) }
    {
    }

private:
    static int initializeB(int const c)
    {
        if (c < MIN_ALLOWED || c > MAX_ALLOWED) {
            // Take some mesure
            return -1; // example
        }
        return c;
    }
};


问:
Efficient way to broadcast/iterate over dictionary values
I am trying use dictionary values in a calculation such as this:

```<code>mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)
</code>```

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
```

<p>Or if I do,</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)
</code>```

```<code>TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
</code>```

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)
```

```[16 25 36]
```

<p>Or I can do</p>

<pre class="lang-py prettyprint-override"><code>newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)
</code>```

[16 25 36]
```

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

答:
```<code>    for([key,value] in mydict.items()){

      mydict[key] = (value + 3 ) ** 2

      console.log(mydict[key]);

     }
</code>```

In this way you are accesing e. g 1 touching 'key1'. 1 + 3 ** 2.                                   first value from key 1: 16

Body:
I am trying use dictionary values in a calculation such as this:

mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

Or if I do,

import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)

TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)

[16 25 36]

Or I can do

newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)

[16 25 36]

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

Body:
    for([key,value] in mydict.items()){

      mydict[key] = (value + 3 ) ** 2

      console.log(mydict[key]);

     }

In this way you are accesing e. g 1 touching 'key1'. 1 + 3 ** 2.                                   first value from key 1: 16