问:
How get Id of element when i click on the element
I have 2 div(HTML) element and id is div1 and div2, When I click on any div then I want id of current div... idea?</p>

```<code><div id="div1"></div>
<div id="div2"></div>

<div id="displayid"></div>
</code>```

```<code>if(clickedDivId = this.id){
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        clickedDivId = this.id;
        event.stopPropagation();

    };
}
}

document.getElementById("displayid").innerHTML = ??clickedDivId??how;
</code>```

答:
try by modifying your own code</p>

```<code>var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        e.stopPropagation();
        clickedDivId = this.id;
        document.getElementById("displayid").innerHTML = this.id;

    };
}
</code>```

Body:
I have 2 div(HTML) element and id is div1 and div2, When I click on any div then I want id of current div... idea?

if(clickedDivId = this.id){
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        clickedDivId = this.id;
        event.stopPropagation();

    };
}
}

document.getElementById("displayid").innerHTML = ??clickedDivId??how;

Body:
try by modifying your own code

var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        e.stopPropagation();
        clickedDivId = this.id;
        document.getElementById("displayid").innerHTML = this.id;

    };
}


来源: stackexchange

问:
How to display drop down menu when any text from whole page is selected?
I want to display selection list menu when any text from any element is selected. I used "onselect" attribute but it seems to be only working only with "input" element. How can i show list similar to list when we right click anything on browser for every element?

It works when i select text in input element and not when i select text from h1 element.

```<code><!DOCTYPE html>
<html>
<body id="myText">

<h1 onselect="myFunction()">Select some of the text: <input type="text" value="Hello world!" /></h1>

<script>
function myFunction() {
  alert("You selected some text!");
}
</script>

</body>
</html>
</code>```

答:
You can do with mouseup event handler and window.getSelection() along with onselect event handler.

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

Note that Selected text from window.getSelection() is slightly different due to browser.

It cannot be obtained from input/textarea element in most browsers.

(As far as I know, Only Chrome can obtain both input/textarea and other elements.)

Therefore, it is preferred that using a combination of onselect and mouseup event handler.

In mouseup handler, you have to omit input/textarea element to prevent handling selection event twice in some cases.

```<code><h1>Select some of the text: <input type="text" value="Hello world!" /></h1>

<script>
function myFunction() {
  alert("You selected some text!");
}

document.onselect = function() {
  myFunction();
}

document.onmouseup = function(e) {
  var element = document.elementFromPoint(e.clientX, e.clientY);
  if (!element || (element.tagName == 'INPUT') || (element.tagName == 'TEXTAREA')) {
    return;
  }

  var selObj = window.getSelection();
  var selText = selObj.toString();
  if (selText.length == 0) {
    return;
  }

  myFunction();
};
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to display selection list menu when any text from any element is selected. I used "onselect" attribute but it seems to be only working only with "input" element. How can i show list similar to list when we right click anything on browser for every element?

It works when i select text in input element and not when i select text from h1 element.

<!DOCTYPE html>

Select some of the text: <input type="text" value="Hello world!" />

Body:
You can do with mouseup event handler and window.getSelection() along with onselect event handler.

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

Note that Selected text from window.getSelection() is slightly different due to browser.

It cannot be obtained from input/textarea element in most browsers.

(As far as I know, Only Chrome can obtain both input/textarea and other elements.)

Therefore, it is preferred that using a combination of onselect and mouseup event handler.

In mouseup handler, you have to omit input/textarea element to prevent handling selection event twice in some cases.

<h1>Select some of the text: <input type="text" value="Hello world!" /></h1>

<script>
function myFunction() {
  alert("You selected some text!");
}

document.onselect = function() {
  myFunction();
}

document.onmouseup = function(e) {
  var element = document.elementFromPoint(e.clientX, e.clientY);
  if (!element || (element.tagName == 'INPUT') || (element.tagName == 'TEXTAREA')) {
    return;
  }

  var selObj = window.getSelection();
  var selText = selObj.toString();
  if (selText.length == 0) {
    return;
  }

  myFunction();
};
</script>


问:
How is the web.config handled by the ConfigurationManager from .NET?
On a project I am working on, we usually keep our application settings defined in a separate file.  This is how it has been done for many years, and going forward we would like to keep all system configurations in one file.  I was considering to use the web.config  section so I can just load the configurations that I need from my C# code running on the server using the ConfigurationManager class.

If I use our own way for the application settings, I would load it in a session and have it available for the application by loading values from the session.  After some reading online it looks like some of the performance issues behind using the session is that we have to deserialize the values from the session object.

Does IIS deserialize the web.config values each time we read values using the ConfigurationManager?

Thank you,
Vijay Selvaraj

答:
No, configuration sections are deserialized into the custom classes that reflect them only when the configuration file is re-read (such as when the app pool is recycled, a change to web.config is detected, and a couple of other conditions).

See also this question.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to execute interface without abstract method?
When the program is executing, it executed if it comments in the interface method and nested interface method.
     So, how it's executing process.
Is it taking as a default method?

```<code>interface it2
{
//void m1(); with this comment program is executing so, how it is
prosessing
interface it1
{
//void m2();with this comment also program is executing so, how it is
prosessing
}
};
class Demo implements it2.it1
{
 void m1()
{
    System.out.println("m1 method");

}

public  void m2()
{
    System.out.println("m2 method");
}
public static void main(String[] args)

{
    Demo t= new Demo();
    t.m1();
    t.m2();
}

}
</code>```

OUTPUT-
    m1 method
    m2 method

答:
Lets first tidy up and correct your code so that it is readable:

```<code>public interface It2 {
    void m1();

    public interface It1 {
        void m2();
    }
}

public class Demo implements It2.It1 {
    public void m1() {
        System.out.println("m1 method");
    }

    public void m2() {
        System.out.println("m2 method");
    }

    public static void main(String[] args) {
        Demo t = new Demo();
        t.m1();
        t.m2();
    }
}
</code>```

I think your confusion is that you think there is some relationship between the m1 method in It2 the m1 method in Demo.

In fact there is no relationship.

The Demo class is implementing It1 not It2.  So Demo::m2 is the implementation of It1::m2,  but Demo::m1 is not implementing any interface method.

Therefore, when you comment out the declaration of m1 in It2, it makes no difference.

One way to demonstrate this is to add @Override annotations:

```<code>    @Override
    public void m1() {
        System.out.println("m1 method");
    }

    @Override
    public void m2() {
        System.out.println("m2 method");
    }
</code>```

The compiler will give a compilation for the m1 method saying that it doesn't override or implement anything.  There won't be a compilation error for m2.

So, how it's executing process. Is it taking as a default method?

No.  There are no default methods here.

Body:
When the program is executing, it executed if it comments in the interface method and nested interface method.
     So, how it's executing process.
Is it taking as a default method?

interface it2
{
//void m1(); with this comment program is executing so, how it is
prosessing
interface it1
{
//void m2();with this comment also program is executing so, how it is
prosessing
}
};
class Demo implements it2.it1
{
 void m1()
{
    System.out.println("m1 method");

}

public  void m2()
{
    System.out.println("m2 method");
}
public static void main(String[] args)

{
    Demo t= new Demo();
    t.m1();
    t.m2();
}

}

OUTPUT-
    m1 method
    m2 method

Body:
Lets first tidy up and correct your code so that it is readable:

public interface It2 {
    void m1();

    public interface It1 {
        void m2();
    }
}

public class Demo implements It2.It1 {
    public void m1() {
        System.out.println("m1 method");
    }

    public void m2() {
        System.out.println("m2 method");
    }

    public static void main(String[] args) {
        Demo t = new Demo();
        t.m1();
        t.m2();
    }
}

I think your confusion is that you think there is some relationship between the m1 method in It2 the m1 method in Demo.

In fact there is no relationship.

The Demo class is implementing It1 not It2.  So Demo::m2 is the implementation of It1::m2,  but Demo::m1 is not implementing any interface method.

Therefore, when you comment out the declaration of m1 in It2, it makes no difference.

One way to demonstrate this is to add @Override annotations:

    @Override
    public void m1() {
        System.out.println("m1 method");
    }

    @Override
    public void m2() {
        System.out.println("m2 method");
    }

The compiler will give a compilation for the m1 method saying that it doesn't override or implement anything.  There won't be a compilation error for m2.

So, how it's executing process. Is it taking as a default method?

No.  There are no default methods here.


问:
opencv read error:[h264 @ 0x8f915e0] error while decoding MB 53 20, bytestream -7
My configuration:

```<code>  ubuntu 16.04
  opencv 3.3.1
  gcc version 5.4.0 20160609
  ffmpeg version 3.4.2-1~16.04.york0
</code>```

and I built opencv with:

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON_EXECUTABLE=$(which python) -D OPENCV_EXTRA_MODULES_PATH=/home/xxx/opencv_contrib/modules -D WITH_QT=ON -D WITH_OPENGL=ON -D WITH_IPP=ON -D WITH_OPENNI2=ON -D WITH_V4L=ON -D WITH_FFMPEG=ON -D WITH_GSTREAMER=OFF -D WITH_OPENMP=ON -D WITH_VTK=ON -D BUILD_opencv_java=OFF -D BUILD_opencv_python3=OFF -D WITH_CUDA=ON -D ENABLE_FAST_MATH=1 -D WITH_NVCUVID=ON -D CUDA_FAST_MATH=ON -D BUILD_opencv_cnn_3dobj=OFF -D FORCE_VTK=ON  -D WITH_CUBLAS=ON -D CUDA_NVCC_FLAGS="-D_FORCE_INLINES" -D WITH_GDAL=ON -D WITH_XINE=ON -D BUILD_EXAMPLES=OFF -D BUILD_DOCS=ON -D BUILD_PERF_TESTS=OFF -D BUILD_TESTS=OFF  -D BUILD_opencv_dnn=OFF -D BUILD_PROTOBUF=OFF -D opencv_dnn_BUILD_TORCH_IMPORTER=OFF -D opencv_dnn_PERF_CAFFE=OFF -D opencv_dnn_PERF_CLCAFFE=OFF -DBUILD_opencv_dnn_modern=OFF -D CUDA_ARCH_BIN=6.1 ..
</code>```

and use these python code to read and show:

```<code>import cv2
from com.xxx.cv.core.Image import Image

capture=cv2.VideoCapture("rtsp://192.168.10.184:554/mpeg4?username=xxx&password=yyy")
while True:
    grabbed,content=capture.read()
    if grabbed:
        Image(content).show()
        doSomething()
    else:
        print "nothing grabbed.."
</code>```

Everytime, after reading about 50 frames,it will give an error like:

```<code>[h264 @ 0x8f915e0] error while decoding MB 53 20, bytestream -7
</code>```

then nothing can be grabbed further,and the strange thing is:

```<code>1,comment doSomething() or
2,keep doSomething() and recording the stream from same IPCamera,then run
  code against recorded video
</code>```

both cases,code works fine,can anyone tell how to solve this problem?Thank in advance!

答:
This works only for video streaming :

all you gotta do is initialize cv2.VideoCapture again if the return is False. :)

worked for me.

```<code>vs = cv2.VideoCapture("rtsp://bla:bla@192.168.x.x")
while True:
    ret,frame = vs.read()
    if not(ret):
        st = time.time()
        vs = cv2.VideoCapture("rtsp://bla:bla@192.168.x.x")
        print("tot time lost due to reinitialization : ",time.time()-st)
        continue

    cv2.imshow("Current frame", frame)
    cv2.waitKey(0)
</code>```

Body:
My configuration:

  ubuntu 16.04
  opencv 3.3.1
  gcc version 5.4.0 20160609
  ffmpeg version 3.4.2-1~16.04.york0

and I built opencv with:

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON_EXECUTABLE=$(which python) -D OPENCV_EXTRA_MODULES_PATH=/home/xxx/opencv_contrib/modules -D WITH_QT=ON -D WITH_OPENGL=ON -D WITH_IPP=ON -D WITH_OPENNI2=ON -D WITH_V4L=ON -D WITH_FFMPEG=ON -D WITH_GSTREAMER=OFF -D WITH_OPENMP=ON -D WITH_VTK=ON -D BUILD_opencv_java=OFF -D BUILD_opencv_python3=OFF -D WITH_CUDA=ON -D ENABLE_FAST_MATH=1 -D WITH_NVCUVID=ON -D CUDA_FAST_MATH=ON -D BUILD_opencv_cnn_3dobj=OFF -D FORCE_VTK=ON  -D WITH_CUBLAS=ON -D CUDA_NVCC_FLAGS="-D_FORCE_INLINES" -D WITH_GDAL=ON -D WITH_XINE=ON -D BUILD_EXAMPLES=OFF -D BUILD_DOCS=ON -D BUILD_PERF_TESTS=OFF -D BUILD_TESTS=OFF  -D BUILD_opencv_dnn=OFF -D BUILD_PROTOBUF=OFF -D opencv_dnn_BUILD_TORCH_IMPORTER=OFF -D opencv_dnn_PERF_CAFFE=OFF -D opencv_dnn_PERF_CLCAFFE=OFF -DBUILD_opencv_dnn_modern=OFF -D CUDA_ARCH_BIN=6.1 ..

and use these python code to read and show:

import cv2
from com.xxx.cv.core.Image import Image

capture=cv2.VideoCapture("rtsp://192.168.10.184:554/mpeg4?username=xxx&password=yyy")
while True:
    grabbed,content=capture.read()
    if grabbed:
        Image(content).show()
        doSomething()
    else:
        print "nothing grabbed.."

Everytime, after reading about 50 frames,it will give an error like:

[h264 @ 0x8f915e0] error while decoding MB 53 20, bytestream -7

then nothing can be grabbed further,and the strange thing is:

1,comment doSomething() or
2,keep doSomething() and recording the stream from same IPCamera,then run
  code against recorded video

both cases,code works fine,can anyone tell how to solve this problem?Thank in advance!

Body:
This works only for video streaming :

all you gotta do is initialize cv2.VideoCapture again if the return is False. :)

worked for me.

vs = cv2.VideoCapture("rtsp://bla:bla@192.168.x.x")
while True:
    ret,frame = vs.read()
    if not(ret):
        st = time.time()
        vs = cv2.VideoCapture("rtsp://bla:bla@192.168.x.x")
        print("tot time lost due to reinitialization : ",time.time()-st)
        continue

    cv2.imshow("Current frame", frame)
    cv2.waitKey(0)


问:
Recieveing a SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry error
I'm not sure where this error is coming from. I don't see how it would be trying to add the duplicate into my DB. Ideas? Am I calling the source incorrectly? I've narrowed it down to where I know it has to do with the signature section. I only have one column in the DB for id's</p>

```<code>public function hellosign(Request $request, $id) {
        $auth = $request->user("api");
        if(empty($auth)) return response()->json(['error'=>"No auth user found!"], 401);

        $recruitment = Recruitment::whereId($id)->first();
        if(empty($recruitment)){
            return response()->json(['error' => "Agent not found!"]);
        }

        $email = $recruitment->email;
        if(empty($email)) {
            return response()->json(['error' => "Please provide an email!"]);
        }

        $template = "onboarding_contract";

        Helper::graph("hellosign.create.".$template, 1);
        $client = new HelloSign\Client(config('hellosign.apikey'));
        $sign = new HelloSign\TemplateSignatureRequest;
        if(config('app.env') != "production") $sign->enableTestMode();
        $sign->setTitle("Onboarding Sales Team");
        $sign->setSubject('Please enter your information');
        $sign->setMessage('Please find below the Onboarding Sales Team information for review.');
        $sign->setTemplateId('****************');
        $sign->setSigner('Associate', $recruitment->email, $recruitment->first_name." ".$recruitment->last_name);
        $sign->setCustomFieldValue('rets_id_id_reference', "_".$id."_onboarding");
        $sign->setCustomFieldValue('template', $template);

        // Fields
        $json = [
            // Section 1
            'associate_name'     => $recruitment->name,
            'license'            => $recruitment->license,
            'start_at'           => $recruitment->start_at,
            'commission_agent'   => $recruitment->commission_agent * 100,
            'commission_other'   => $recruitment->commission_other * 100,
            'commission_lead'    => $recruitment->commission_lead * 100,
            // 'eo_coverage'        => "",
        ];

        foreach($json as $field => $value) {
            $sign->setCustomFieldValue($field, $value);
        }

        // Hellosign
        $sign_url = "";
        Trace::log('hellosign_create_onboarding', $json, $id, $auth->id);

        // Save query
        $signature = new Signature;
        $signature->uuid = "_".$id."_onboarding";
        $signature->template = $template;
        $signature->email = $recruitment->email;
        $signature->rets_id = "";
        $signature->id = $id;
        $signature->author_id = (Auth::check() ? Auth::user()->id : null);
        //$signature->reference = $reference;
        $signature->json = json_encode($json);
        $signature->save();

        // Send it
        $response = $client->sendTemplateSignatureRequest($sign);

        return response()->json(['ok']);
    }
</code>```

答:
Remove the $signature->id = $id; let mysql automatically add the unique id

```<code>$signature = new Signature;
$signature->uuid = "_".$id."_onboarding";
$signature->template = $template;
$signature->email = $recruitment->email;
$signature->rets_id = "";
$signature->author_id = (Auth::check() ? Auth::user()->id : null);
//$signature->reference = $reference;
$signature->json = json_encode($json);
$signature->save();
</code>```

Body:
I'm not sure where this error is coming from. I don't see how it would be trying to add the duplicate into my DB. Ideas? Am I calling the source incorrectly? I've narrowed it down to where I know it has to do with the signature section. I only have one column in the DB for id's

public function hellosign(Request $request, $id) {
        $auth = $request->user("api");
        if(empty($auth)) return response()->json(['error'=>"No auth user found!"], 401);

        $recruitment = Recruitment::whereId($id)->first();
        if(empty($recruitment)){
            return response()->json(['error' => "Agent not found!"]);
        }

        $email = $recruitment->email;
        if(empty($email)) {
            return response()->json(['error' => "Please provide an email!"]);
        }

        $template = "onboarding_contract";

        Helper::graph("hellosign.create.".$template, 1);
        $client = new HelloSign\Client(config('hellosign.apikey'));
        $sign = new HelloSign\TemplateSignatureRequest;
        if(config('app.env') != "production") $sign->enableTestMode();
        $sign->setTitle("Onboarding Sales Team");
        $sign->setSubject('Please enter your information');
        $sign->setMessage('Please find below the Onboarding Sales Team information for review.');
        $sign->setTemplateId('****************');
        $sign->setSigner('Associate', $recruitment->email, $recruitment->first_name." ".$recruitment->last_name);
        $sign->setCustomFieldValue('rets_id_id_reference', "_".$id."_onboarding");
        $sign->setCustomFieldValue('template', $template);

        // Fields
        $json = [
            // Section 1
            'associate_name'     => $recruitment->name,
            'license'            => $recruitment->license,
            'start_at'           => $recruitment->start_at,
            'commission_agent'   => $recruitment->commission_agent * 100,
            'commission_other'   => $recruitment->commission_other * 100,
            'commission_lead'    => $recruitment->commission_lead * 100,
            // 'eo_coverage'        => "",
        ];

        foreach($json as $field => $value) {
            $sign->setCustomFieldValue($field, $value);
        }

        // Hellosign
        $sign_url = "";
        Trace::log('hellosign_create_onboarding', $json, $id, $auth->id);

        // Save query
        $signature = new Signature;
        $signature->uuid = "_".$id."_onboarding";
        $signature->template = $template;
        $signature->email = $recruitment->email;
        $signature->rets_id = "";
        $signature->id = $id;
        $signature->author_id = (Auth::check() ? Auth::user()->id : null);
        //$signature->reference = $reference;
        $signature->json = json_encode($json);
        $signature->save();

        // Send it
        $response = $client->sendTemplateSignatureRequest($sign);

        return response()->json(['ok']);
    }

Body:
Remove the $signature->id = $id; let mysql automatically add the unique id

$signature = new Signature;
$signature->uuid = "_".$id."_onboarding";
$signature->template = $template;
$signature->email = $recruitment->email;
$signature->rets_id = "";
$signature->author_id = (Auth::check() ? Auth::user()->id : null);
//$signature->reference = $reference;
$signature->json = json_encode($json);
$signature->save();


问:
How to run webviews in multiple threads
My assigment says to create a simple web browser where webpage is saved in a card and later on you can retrieve it.

Each card/webpage need to run on it's own thread.

I've already setted up webview and myWebViewClient to load links, and a 2nd activity where i display and can add new webpages. Selecting ListView item is calling loadUrl(url) in MainActivity on a WebView, but that's not the desireable outcome, I need to run webview in a thread, put it away on a stack, and later resume it's task somehow.

答:
You can not directly run the webview in the background as In Android, all the views needs to be run on UI thread.

For your task, you can do one thing, load the html data in bacground and then set that html response to webview in onPost method of Asyntask

Title: How to run webviews in multiple threads


问:
How to "close" database when the query happens?
```<code>$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}
</code>```

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

答:
You can LOCK TABLE table WRITE before and UNLOCK TABLE table after the queries.

http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

Body:
$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.


问:
flask_login, How to get current_user from a new thread?
I'm new to flask_login library. In my codebase, after user login, I can get the current user information from current_user of flask_login library. The simplified test code is below:

```<code>from threading import Thread
from flask_login import current_user

def test():
    print("current_user = ", current_user)   # None
worker = Thread(target=test)
worker.start()
print("current_user = ", current_user)       #  <XXX.auth.view.User object at 0x119b2b250>
</code>```

So I'm very confusing why I can't get the current user information from a separate thread, even after I deliberately import again before the first print statement.

Thanks.

答:
current_user is a thread-local value - it will behave as a separate variable in every thread. You must pass it between threads if you need it elsewhere.

Perhaps your call would become:

from threading import Thread
from flask_login import current_user

user = current_user

def test(user):
    print("current_user = ", user)

worker = Thread(target=test, args=(user,))
worker.start()

print("current_user = ", user)
```

<hr>

<p>Relevant line from the <code>flask_login</code> source:</p>

<pre class="lang-py prettyprint-override"><code>current_user = LocalProxy(lambda: _get_user())
</code>```

https://github.com/maxcountryman/flask-login/blob/d22f80d166ee260d44e0d2d9ea973b784ef3621b/flask_login/utils.py#L26

Relevant discussion of werkzeug's implementations of locals from the werkzeug docs:

Werkzeug provides its own implementation of local data storage called
  werkzeug.local. This approach provides a similar functionality to
  thread locals but also works with greenlets.

https://werkzeug.palletsprojects.com/en/0.15.x/local/#werkzeug.local.LocalProxy

Body:
I'm new to flask_login library. In my codebase, after user login, I can get the current user information from current_user of flask_login library. The simplified test code is below:

from threading import Thread
from flask_login import current_user

def test():
    print("current_user = ", current_user)   # None
worker = Thread(target=test)
worker.start()
print("current_user = ", current_user)       #  <XXX.auth.view.User object at 0x119b2b250>

So I'm very confusing why I can't get the current user information from a separate thread, even after I deliberately import again before the first print statement.

Thanks.

Body:
current_user is a thread-local value - it will behave as a separate variable in every thread. You must pass it between threads if you need it elsewhere.

Perhaps your call would become:

from threading import Thread
from flask_login import current_user

user = current_user

def test(user):
    print("current_user = ", user)

worker = Thread(target=test, args=(user,))
worker.start()

print("current_user = ", user)

Relevant line from the flask_login source:

current_user = LocalProxy(lambda: _get_user())

https://github.com/maxcountryman/flask-login/blob/d22f80d166ee260d44e0d2d9ea973b784ef3621b/flask_login/utils.py#L26

Relevant discussion of werkzeug's implementations of locals from the werkzeug docs:

Werkzeug provides its own implementation of local data storage called
  werkzeug.local. This approach provides a similar functionality to
  thread locals but also works with greenlets.

https://werkzeug.palletsprojects.com/en/0.15.x/local/#werkzeug.local.LocalProxy


问:
Azure Event Hub connectivity issues with Spring Cloud Stream Kafka
We use Azure Event Hubs with the Kafka integration option. Our services are on Java, Spring Boot, Spring Cloud Stream. They are deployed on Azure AKS. We have enabled service endpoints on the virtual network of the cluster for Azure Event Hubs.

Most of the time, everything works fine.

From time to time, the producers cannot publish to Kafka. We lose messages, which are usually critical for the overall data consistency.

When that happens, we see some errors in the logs (I've broken them down to multiple lines for readability):

First example from the logs:

```<code>2019-02-21 22:11:04.681 WARN 1 --- [ad | producer-2]
o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-2]
Got error produce response with correlation id 6 on topic-partition _topic-name_-1,
retrying (4 attempts left). Error: NETWORK_EXCEPTION
</code>```

Second example:

```<code>org.apache.kafka.common.errors.TimeoutException:
Expiring 1 record(s) for _topic-name_-1:
30096 ms has passed since batch creation plus linger time
</code>```

The consumers also experience occasional connectivity issues:

```<code>2019-02-22 03:03:59.733 INFO 1 --- [container-0-C-1]
o.a.k.c.c.internals.AbstractCoordinator :
[Consumer clientId=consumer-6, groupId=my-super-service]
Group coordinator my-super-hub.servicebus.windows.net:9093
(id: 2147483647 rack: null) is unavailable or invalid, will attempt rediscovery
</code>```

Does anyone have similar issues with Azure Event Hub and perhaps some ideas on what might be the problem?

答:
You will need to set the max connection idle time.

connections.max.idle.ms

Good luck.

Body:
We use Azure Event Hubs with the Kafka integration option. Our services are on Java, Spring Boot, Spring Cloud Stream. They are deployed on Azure AKS. We have enabled service endpoints on the virtual network of the cluster for Azure Event Hubs.

Most of the time, everything works fine.

From time to time, the producers cannot publish to Kafka. We lose messages, which are usually critical for the overall data consistency.

When that happens, we see some errors in the logs (I've broken them down to multiple lines for readability):

First example from the logs:

2019-02-21 22:11:04.681 WARN 1 --- [ad | producer-2]
o.a.k.clients.producer.internals.Sender : [Producer clientId=producer-2]
Got error produce response with correlation id 6 on topic-partition _topic-name_-1,
retrying (4 attempts left). Error: NETWORK_EXCEPTION

Second example:

org.apache.kafka.common.errors.TimeoutException:
Expiring 1 record(s) for _topic-name_-1:
30096 ms has passed since batch creation plus linger time

The consumers also experience occasional connectivity issues:

2019-02-22 03:03:59.733 INFO 1 --- [container-0-C-1]
o.a.k.c.c.internals.AbstractCoordinator :
[Consumer clientId=consumer-6, groupId=my-super-service]
Group coordinator my-super-hub.servicebus.windows.net:9093
(id: 2147483647 rack: null) is unavailable or invalid, will attempt rediscovery

Does anyone have similar issues with Azure Event Hub and perhaps some ideas on what might be the problem?


问:
Convert date to specific format in javascript?
Hi i want to convert the current date to a format as follows in javascript:
Apr 12, 2011 06:42:03.

Any suggestions?????

答:
Have you looked at this

```<code>dateFormat(now, "mmm dd, yyyy hh:MM:ss");
</code>```

it is light weight (1.2 KB) and supports the following formats

d     Day of the month as digits; no leading zero for single-digit days.

dd    Day of the month as digits; leading zero for single-digit days.

ddd   Day of the week as a three-letter abbreviation.

dddd  Day of the week as its full name.

m     Month as digits; no leading zero for single-digit months.

mm    Month as digits; leading zero for single-digit months.

mmm   Month as a three-letter abbreviation.

mmmm  Month as its full name.

yy    Year as last two digits; leading zero for years less than 10.

yyyy  Year represented by four digits.

h     Hours; no leading zero for single-digit hours (12-hour clock).

hh    Hours; leading zero for single-digit hours (12-hour clock).

H     Hours; no leading zero for single-digit hours (24-hour clock).

HH    Hours; leading zero for single-digit hours (24-hour clock).

M     Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.

MM    Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.

s     Seconds; no leading zero for single-digit seconds.

ss    Seconds; leading zero for single-digit seconds.

l or L    Milliseconds. l gives 3 digits. L gives 2 digits.

t     Lowercase, single-character time marker string: a or p.

tt    Lowercase, two-character time marker string: am or pm.

T     Uppercase, single-character time marker string: A or P. Uppercase T unlike CF's t to allow for user-specified casing.

TT    Uppercase, two-character time marker string: AM or PM. Uppercase TT unlike CF's tt to allow for user-specified casing.

Z     US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500

o     GMT/UTC timezone offset, e.g. -0500 or +0230.

S     The date's ordinal suffix (st, nd, rd, or th). Works well with d.

'…' or "…"    Literal character sequence. Surrounding quotes are removed.

UTC:  Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The "UTC:" prefix is removed.

Body:
Have you looked at this

dateFormat(now, "mmm dd, yyyy hh:MM:ss");

it is light weight (1.2 KB) and supports the following formats

d     Day of the month as digits; no leading zero for single-digit days.

dd    Day of the month as digits; leading zero for single-digit days.

ddd   Day of the week as a three-letter abbreviation.

dddd  Day of the week as its full name.

m     Month as digits; no leading zero for single-digit months.

mm    Month as digits; leading zero for single-digit months.

mmm   Month as a three-letter abbreviation.

mmmm  Month as its full name.

yy    Year as last two digits; leading zero for years less than 10.

yyyy  Year represented by four digits.

h     Hours; no leading zero for single-digit hours (12-hour clock).

hh    Hours; leading zero for single-digit hours (12-hour clock).

H     Hours; no leading zero for single-digit hours (24-hour clock).

HH    Hours; leading zero for single-digit hours (24-hour clock).

M     Minutes; no leading zero for single-digit minutes. Uppercase M unlike CF timeFormat's m to avoid conflict with months.

MM    Minutes; leading zero for single-digit minutes. Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.

s     Seconds; no leading zero for single-digit seconds.

ss    Seconds; leading zero for single-digit seconds.

l or L    Milliseconds. l gives 3 digits. L gives 2 digits.

t     Lowercase, single-character time marker string: a or p.

tt    Lowercase, two-character time marker string: am or pm.

T     Uppercase, single-character time marker string: A or P. Uppercase T unlike CF's t to allow for user-specified casing.

TT    Uppercase, two-character time marker string: AM or PM. Uppercase TT unlike CF's tt to allow for user-specified casing.

Z     US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500

o     GMT/UTC timezone offset, e.g. -0500 or +0230.

S     The date's ordinal suffix (st, nd, rd, or th). Works well with d.

'…' or "…"    Literal character sequence. Surrounding quotes are removed.

UTC:  Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The "UTC:" prefix is removed.


问:
Firebase Functions.EventContext becomes undefined after update
fuctions.EventContext gives error when trying to get uid after updating to latest firebase (6.10.0)

I had a test project working fine. I updated firebase tools, typescript and create a new project with the same code. Suddenly the project gives error on EventContext.auth.uid . When mouseover context or auth it says
Object is possibly 'undefined'.ts(2532)

```<code>export const onAccountTransferCreated = functions.database
.ref('/data_transfer/from_data/user_data/{transferPas}')
.onCreate(async(snapshot, context) => {

console.log(`Snapshot = ${snapshot.toJSON}`)
console.log(`Context = ${context.auth.uid}`)
admin.auth().getUser(context.auth.uid)
</code>```

答:
context is an EventContext type object.  As you can see from the API documentation for its auth property, it might be null or undefined:

This field is only populated for Realtime Database triggers and
  Callable functions. For an unauthenticated user, this field is null.
  For Firebase admin users and event types that do not provide user
  information, this field will not exist.

The TypeScript definition for EventContext.auth is this:

```<code>export interface EventContext {
    auth?: {
        uid: string;
        token: object;
    };
}
</code>```

Notice the ? after auth.  That means the property doesn't have to exist.

TypeScript (in strict mode) is warning you that you could have a problem at runtime when this property is missing.  You must check it before you use it:

```<code>export const onAccountTransferCreated = functions.database
.ref('/data_transfer/from_data/user_data/{transferPas}')
.onCreate(async(snapshot, context) => {

    console.log(`Snapshot = ${snapshot.toJSON}`)
    if (context.auth) {
        console.log(`Context = ${context.auth.uid}`)
        admin.auth().getUser(context.auth.uid)
    }
})
</code>```

Or, you can turn of TypeScript strict mode, which I don't recommend.  It's always better to do the check in order to avoid crashes at runtime.

Body:
fuctions.EventContext gives error when trying to get uid after updating to latest firebase (6.10.0)

I had a test project working fine. I updated firebase tools, typescript and create a new project with the same code. Suddenly the project gives error on EventContext.auth.uid . When mouseover context or auth it says
Object is possibly 'undefined'.ts(2532)

export const onAccountTransferCreated = functions.database
.ref('/data_transfer/from_data/user_data/{transferPas}')
.onCreate(async(snapshot, context) => {

console.log(`Snapshot = ${snapshot.toJSON}`)
console.log(`Context = ${context.auth.uid}`)
admin.auth().getUser(context.auth.uid)

Body:
context is an EventContext type object.  As you can see from the API documentation for its auth property, it might be null or undefined:

This field is only populated for Realtime Database triggers and
  Callable functions. For an unauthenticated user, this field is null.
  For Firebase admin users and event types that do not provide user
  information, this field will not exist.

The TypeScript definition for EventContext.auth is this:

export interface EventContext {
    auth?: {
        uid: string;
        token: object;
    };
}

Notice the ? after auth.  That means the property doesn't have to exist.

TypeScript (in strict mode) is warning you that you could have a problem at runtime when this property is missing.  You must check it before you use it:

export const onAccountTransferCreated = functions.database
.ref('/data_transfer/from_data/user_data/{transferPas}')
.onCreate(async(snapshot, context) => {

    console.log(`Snapshot = ${snapshot.toJSON}`)
    if (context.auth) {
        console.log(`Context = ${context.auth.uid}`)
        admin.auth().getUser(context.auth.uid)
    }
})

Or, you can turn of TypeScript strict mode, which I don't recommend.  It's always better to do the check in order to avoid crashes at runtime.


问:
finding CORRECT api to use in bing websearch package
I'm currently at my wits end right now in dealing with azure. I'm currently using (trying to) the package py-ms-cognitive specifically the bing websearch module. The documentation seems straightforward. "Sign up for MS azure account to get an API key to place here:"

```<code>>>> from py_ms_cognitive import PyMsCognitiveImageSearch
>>> search_term = "puppies"
>>> search_service = PyMsCognitiveImageSearch('API_KEY', search_term)
>>> first_fifty_result = search_service.search(limit=50, format='json') #1-50
</code>```

I sign up for an azure account, and so far I'm kind of lost in which kind of API I need for this specific package my intuition (as well as others who are with me that are as lost as I am) tells me its a Cognitive services - Websearch API, I do that and bam two keys, I try both of them within this:

```<code>PyMsCognitiveImageSearch('API_KEY', search_term)
</code>```

So far after running the debugger I continually get this response:

```<code>b'{ "error":{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }}'
</code>```

I try creating a different project to see if that works, same thing, I've tried looking through these previously posted questions 'A' and 'B'. I've checked to see if my subscription location is the same as the API endpoints to which one is "global" with no option of changing it and the other set to my current region. I've tried using my sub ID, the generated APIs (both 1 and 2) and at this point anything that looks like an API key, all provide the same response. I'm not entirely sure what to do next because any other documentation I do find is either not relevant or entirely too abstract to be applicable. Any aid would be most appreciated.

答:
So here we go,

All cognitive services APIs now run on v7.0, where as the package I listed earlier runs on v5.0,

All you have to do is change one character in the source code and voila "black magic."

pull request for all who are curious

Change:

```<code>SEARCH_WEB_BASE = 'https://api.cognitive.microsoft.com/bing/v5.0/search'
</code>```

to:

```<code>SEARCH_WEB_BASE = 'https://api.cognitive.microsoft.com/bing/v7.0/search'
</code>```

Body:
I'm currently at my wits end right now in dealing with azure. I'm currently using (trying to) the package py-ms-cognitive specifically the bing websearch module. The documentation seems straightforward. "Sign up for MS azure account to get an API key to place here:"

>>> from py_ms_cognitive import PyMsCognitiveImageSearch
>>> search_term = "puppies"
>>> search_service = PyMsCognitiveImageSearch('API_KEY', search_term)
>>> first_fifty_result = search_service.search(limit=50, format='json') #1-50

I sign up for an azure account, and so far I'm kind of lost in which kind of API I need for this specific package my intuition (as well as others who are with me that are as lost as I am) tells me its a Cognitive services - Websearch API, I do that and bam two keys, I try both of them within this:

PyMsCognitiveImageSearch('API_KEY', search_term)

So far after running the debugger I continually get this response:

b'{ "error":{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }}'

I try creating a different project to see if that works, same thing, I've tried looking through these previously posted questions 'A' and 'B'. I've checked to see if my subscription location is the same as the API endpoints to which one is "global" with no option of changing it and the other set to my current region. I've tried using my sub ID, the generated APIs (both 1 and 2) and at this point anything that looks like an API key, all provide the same response. I'm not entirely sure what to do next because any other documentation I do find is either not relevant or entirely too abstract to be applicable. Any aid would be most appreciated.

Body:
So here we go,

All cognitive services APIs now run on v7.0, where as the package I listed earlier runs on v5.0,

All you have to do is change one character in the source code and voila "black magic."

pull request for all who are curious

Change:

SEARCH_WEB_BASE = 'https://api.cognitive.microsoft.com/bing/v5.0/search'

to:

SEARCH_WEB_BASE = 'https://api.cognitive.microsoft.com/bing/v7.0/search'


问:
Getting Child Windows Handles
Currently there are several ways to get a ChildWindow handle; FindWindowEx (uses parent handle, plus window caption), GetWindow (uses parent handle, and Z-Order), and EnumChildWindows. None are satisfactory for my application.

Would like to use something like FindWindowEx, but this requires knowledge of the contents of the TextBox (caption) that's used by FindWindowsEx. This works if the TextBox contents is static, but in most cases the contents change and and would be unknown to the Application trying to find the TextBox handle.

Does anyone know of a Win32 API that would function like FindWindowEX, using the Parent Handle, but instead of the ChildWindow caption, looks for a user specified TAG property for the ChildWindow that would remain static?

答:
The GetDlgItem function accepts the parent window handle and child item ID.

It is not limited to dialog boxes despite the name.

You can use the GetDlgItem function with any parent-child window pair, not just with dialog boxes.

Title: Getting Child Windows Handles


问:
List Scheduled Queries in BigQuery
I have a need to (programatically) analyse the details of Scheduled Queries in BigQuery (eg which tables are updated and which tables accessed in the SQL). I have done something similar for the BQ Tables/Views using Apps Script BigQuery.Tables.list(), but I cannot find an API to access the Scheduled Queries.

The UI is able to list them, so I feel this should be possible programmatically, e.g. via a REST API. Does anyone know if this is possible, what interface is supported (Apps Script, REST ...), and possibly an example of how to use it.

答:
Here is a shell script that will notify you in Slack if any of your scheduled queries fail. Simply integrate into your existing workflow (as blocking or non blocking) or have it on a separate Cron job. I have used httpie to send my HTTP post but you can also use curl or others. Also, you can also change your HTTP post for any other action.

See link for potential states of transfer state object

```<code>#1/bin/bash

sudo apt-get install httpie

location=US
authToken="$(gcloud auth print-access-token)"
projectId=$(gcloud config get-value project 2>\dev\null)

scheduled_queries=$(curl  -H "Authorization: Bearer $authToken" https://bigquerydatatransfer.googleapis.com/v1/projects/$projectId/locations/$location/transferConfigs?dataSourceIds=scheduled_query)

# pretty print results
echo $scheduled_queries | python -m json.tool

length=$(echo "$scheduled_queries" | grep FAILED)
if [ $length -gt 0 ]; then
    echo A SCHEDULED TRANSFER HAS FAILED
    http POST https://hooks.slack.com/services/<your slack channel> text="A SCHEDULED TRANSFER HAS FAILED: HERE IS STDOUT  >>> $scheduled_queries"

else
    echo No errors in scheduled transfers
fi
</code>```

If running outside the cloud or on something that hasn't already authenticated, you will need to authenticate before hand. To do this use before the above:

```<code>echo $PROD_KEY >> temp_json.json
bash gcloud auth activate-service-account --key-file=temp_json.json --project=$PROJ_NAME_PROD
</code>```

where $PROD_KEY is the service key for whatever you are trying to access.

Title: List Scheduled Queries in BigQuery

Body:
Here is a shell script that will notify you in Slack if any of your scheduled queries fail. Simply integrate into your existing workflow (as blocking or non blocking) or have it on a separate Cron job. I have used httpie to send my HTTP post but you can also use curl or others. Also, you can also change your HTTP post for any other action.

See link for potential states of transfer state object

#1/bin/bash

sudo apt-get install httpie

location=US
authToken="$(gcloud auth print-access-token)"
projectId=$(gcloud config get-value project 2>\dev\null)

scheduled_queries=$(curl  -H "Authorization: Bearer $authToken" https://bigquerydatatransfer.googleapis.com/v1/projects/$projectId/locations/$location/transferConfigs?dataSourceIds=scheduled_query)

# pretty print results
echo $scheduled_queries | python -m json.tool

length=$(echo "$scheduled_queries" | grep FAILED)
if [ $length -gt 0 ]; then
    echo A SCHEDULED TRANSFER HAS FAILED
    http POST https://hooks.slack.com/services/<your slack channel> text="A SCHEDULED TRANSFER HAS FAILED: HERE IS STDOUT  >>> $scheduled_queries"

else
    echo No errors in scheduled transfers
fi

If running outside the cloud or on something that hasn't already authenticated, you will need to authenticate before hand. To do this use before the above:

echo $PROD_KEY >> temp_json.json
bash gcloud auth activate-service-account --key-file=temp_json.json --project=$PROJ_NAME_PROD

where $PROD_KEY is the service key for whatever you are trying to access.


问:
Pentaho server login problems after java JDK change from Oracle to Amazon Coretto
We use the BI server from Pentaho (Community ed.). Since we have to change the Java-JRE from Oracle to the Opend JDK from Amazon Coretto, there is a problem after starting the server when a user wants to log in (empty page). The login page itself is showing normally - if there is a correct login the described problem occures.

Windows Server 2012 R2
Amazon Corretto\jdk1.8.0_212
pentaho-server-ce-8.2.0.0-342

Tried to include .jar files missing, reinstall, local install - nothing worked. Therefore, we have attached the whole Catalina and access-log from last "normal trial" to get a lean output.

Log Catalina:

27-May-2019 14:32:25.018 INFO [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
27-May-2019 14:32:25.018 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8080"]
27-May-2019 14:32:25.112 INFO [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"]
27-May-2019 14:32:25.143 INFO [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina]
27-May-2019 14:32:26.033 INFO [FelixShutdown] org.apache.cxf.management.jmx.InstrumentationManagerImpl.unregister unregistering MBean org.apache.cxf:bus.id=pentaho-metaverse-web-cxf590120556,type=Bus.Service.Endpoint,service="{http://service.metaverse.pentaho.org/}MetaverseService",port="MetaverseService",instance.id=1796025488
27-May-2019 14:32:26.033 INFO [FelixShutdown] org.apache.cxf.management.jmx.InstrumentationManagerImpl.unregister unregistering MBean org.apache.cxf:bus.id=pentaho-metaverse-web-cxf590120556,WorkQueueManager=Bus.WorkQueueManager,type=WorkQueueManager,instance.id=531601800
27-May-2019 14:32:26.033 INFO [FelixShutdown] org.apache.cxf.management.jmx.InstrumentationManagerImpl.unregister unregistering MBean org.apache.cxf:bus.id=pentaho-metaverse-web-cxf590120556,type=Bus,instance.id=590120556
27-May-2019 14:32:26.596 INFO [FelixShutdown] org.apache.cxf.management.jmx.InstrumentationManagerImpl.unregister unregistering MBean org.apache.cxf:bus.id=get-fields-core-cxf634285651,type=Bus.Service.Endpoint,service="{http://endpoint.getfields.pentaho.org/}GetFieldsEndpoint",port="GetFieldsEndpoint",instance.id=1950245397

[...]

org.pentaho.platform.api.engine.ObjectFactoryException: Failed to retrieve object with key [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Failed to retrieve object with key [ApplicationContext].]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
27-May-2019 14:32:27.658 SEVERE [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [pentaho] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@3da0db51]) and a value of type [java.util.ArrayList] (value [[org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen des Objekts mit Schlüssel [ApplicationContext]., org.pentaho.platform.api.engine.ObjectFactoryException: Fehler beim Abrufen

[...]

Rest of file-log: https://ufile.io/8wtti6pm

答:
OpenJDK is supported by Pentaho 8.2, but it looks like Amazon Corretto is not compatible for whatever reason. There are differences between Amazon Corretto and standard OpenJDk; those differences must be causing the issues you're seeing.

Differences Amazon Corretto and OpenJDK


问:
The way to pass multi-values to JQuery from PHP via JSON?
In PHP server side I have these values which want to pass back to JQuery to update client side infomation.

E.g:

```<code>fileSN  fileTotalNumber fileTotalSize
1       3               455
2       4               555
3       1               755
4       1               155
</code>```

The PHP code to get each data:

```<code>$fileData = array();

while($row =  mysqli_fetch_array( $load_files_data_result, MYSQL_ASSOC)){

        $fileSN  = $row['file_sn'];
        $fileTotalNumber = $row['fileTotalNumber '];
        $fileTotalSize= $row['fileTotalNumber '];

        // only one data here , and need more data associated with fileSN
        $fileData[$fileSN] = $fileTotalNumber;

    }

return json_encode($fileIds);
</code>```

And at the client side,my HTML code :

```<code><ul>
  <li fileSN='1' fileTotalNumber='3' fileTotalSize='345'>update li information</li>
  ...
</ul>
</code>```

My JQuery code :

```<code>$.ajax({
  ...
  success: function(result){
    result = jQuery.parseJSON( result );

    $.each(result, function(index, value) {

         //  need more values to update other attributes

         $('#'+obj.FMMWID+'UL li[fileSN='+index+']')
         .addClass('igtomdSelectedItem')
         .attr('allfiles',value);
         //console.log(value)
    });
  }
});
</code>```

Thank you very much!!

答:
If you create an associative array of your table information like:

```<code>$tableData[$rownumber]['field1'] = 'fieldvalue';
$tableData[$rownumber]['field2'] = '2ndFieldValue';
</code>```

And do that for all your rows and fields, you can then encode that array using json_encode().

So if you return your data to jQuery as data  you can then access stuff like:

```<code>data[0].field1
</code>```

Where 0 is a valid row number and field1 is one of the array fields.

Body:
In PHP server side I have these values which want to pass back to JQuery to update client side infomation.

E.g:

fileSN  fileTotalNumber fileTotalSize
1       3               455
2       4               555
3       1               755
4       1               155

The PHP code to get each data:

$fileData = array();

while($row =  mysqli_fetch_array( $load_files_data_result, MYSQL_ASSOC)){

        $fileSN  = $row['file_sn'];
        $fileTotalNumber = $row['fileTotalNumber '];
        $fileTotalSize= $row['fileTotalNumber '];

        // only one data here , and need more data associated with fileSN
        $fileData[$fileSN] = $fileTotalNumber;

    }

return json_encode($fileIds);

And at the client side,my HTML code :

update li information

  ...

My JQuery code :

$.ajax({
  ...
  success: function(result){
    result = jQuery.parseJSON( result );

    $.each(result, function(index, value) {

         //  need more values to update other attributes

         $('#'+obj.FMMWID+'UL li[fileSN='+index+']')
         .addClass('igtomdSelectedItem')
         .attr('allfiles',value);
         //console.log(value)
    });
  }
});

Thank you very much!!

Body:
If you create an associative array of your table information like:

$tableData[$rownumber]['field1'] = 'fieldvalue';
$tableData[$rownumber]['field2'] = '2ndFieldValue';

And do that for all your rows and fields, you can then encode that array using json_encode().

So if you return your data to jQuery as data  you can then access stuff like:

data[0].field1

Where 0 is a valid row number and field1 is one of the array fields.


问:
Merge two Excel sheet data into one with help of same column data
```<code>Excel1
Column1     Column2         Column3
 1           A           [xyz-5536]A
 2           B           [xyz-5537]B
 3           C           [xyz-5538]C
 4           D           [xyz-5539]D
</code>```

This is one type of traceability report having different items

```<code>Excel2
Column1        Result1      Result2
[xyz-5536]A    Pass         fail
[xyz-5537]B    fail         pass
[xyz-5538]C    pass         fail
[xyz-5539]D    fail         pass
</code>```

I have two excels as above , I want to create a new sheet with result as excel1 will append data by mapping ID in Square bracket and append result1 & result2

I tried it through macros

```<code>Column1     Column2         Column3      Result1    Result2
1            A           [xyz-5536]A     pass     fail
2            B           [xyz-5537]B     fail     pass
3            C           [xyz-5538]C     pass     fail
4            D           [xyz-5539]D     fail     pass
</code>```

It should like above table. It should only refer one item from column3 one time. I am new to Python.

答:
One simple way is to use the pandas module.

You can:

read an excel file with the read_excel method (doc). You

merge your data with the merge method (doc)

drop duplicated columns with drop methods (doc)

export your data to a new excel file with to_excel method (doc)

Here the code assuming you have two excels files:

```<code># import modules
import pandas as pd

# filename
filename_1 = "Excel1.xlsx"
filename_2 = "Excel2.xlsx"

# Pandas files
df_1 = pd.read_excel(filename_1)
df_2 = pd.read_excel(filename_2)
print(df_1)
#    Column1 Column2      Column3
# 0        1       A  [xyz-5536]A
# 1        2       B  [xyz-5537]B
# 2        3       C  [xyz-5538]C
# 3        4       D  [xyz-5539]D
print(df_2)
#        Column1 Result1 Result2
# 0  [xyz-5536]A    Pass    fail
# 1  [xyz-5537]B    fail    pass
# 2  [xyz-5538]C    pass    fail
# 3  [xyz-5539]D    fail    pass

# Merge the two dataframe
df_new = df_1.merge(df_2, left_on="Column3",
                   right_on="Column1", suffixes=('', '_df2'))
print(df_new)
#    Column1 Column2      Column3  Column1_df2 Result1 Result2
# 0        1       A  [xyz-5536]  A[xyz-5536]A    Pass     fail
# 1        2       B  [xyz-5537]  B[xyz-5537]B    fail     pass
# 2        3       C  [xyz-5538]  C[xyz-5538]C    pass     fail
# 3        4       D  [xyz-5539]  D[xyz-5539]D    fail     pass

# Remove the duplicated columns
df_new = df_new.drop(["Column1_df2"], axis=1)
print(df_new)
# Column1 Column2      Column3  Result1 Result2
# 0        1       A[xyz-5536]A    Pass    fail
# 1        2       B[xyz-5537]B    fail    pass
# 2        3       C[xyz-5538]C    pass    fail
# 3        4       D[xyz-5539]D    fail    pass

# Export to a new xlsx file
df_new.to_excel("new_file.xlsx", index=False)
</code>```

Body:
Excel1
Column1     Column2         Column3
 1           A           [xyz-5536]A
 2           B           [xyz-5537]B
 3           C           [xyz-5538]C
 4           D           [xyz-5539]D

This is one type of traceability report having different items

Excel2
Column1        Result1      Result2
[xyz-5536]A    Pass         fail
[xyz-5537]B    fail         pass
[xyz-5538]C    pass         fail
[xyz-5539]D    fail         pass

I have two excels as above , I want to create a new sheet with result as excel1 will append data by mapping ID in Square bracket and append result1 & result2

I tried it through macros

Column1     Column2         Column3      Result1    Result2
1            A           [xyz-5536]A     pass     fail
2            B           [xyz-5537]B     fail     pass
3            C           [xyz-5538]C     pass     fail
4            D           [xyz-5539]D     fail     pass

It should like above table. It should only refer one item from column3 one time. I am new to Python.

Body:
One simple way is to use the pandas module.

You can:

read an excel file with the read_excel method (doc). You

merge your data with the merge method (doc)

drop duplicated columns with drop methods (doc)

export your data to a new excel file with to_excel method (doc)

Here the code assuming you have two excels files:

# import modules
import pandas as pd

# filename
filename_1 = "Excel1.xlsx"
filename_2 = "Excel2.xlsx"

# Pandas files
df_1 = pd.read_excel(filename_1)
df_2 = pd.read_excel(filename_2)
print(df_1)
#    Column1 Column2      Column3
# 0        1       A  [xyz-5536]A
# 1        2       B  [xyz-5537]B
# 2        3       C  [xyz-5538]C
# 3        4       D  [xyz-5539]D
print(df_2)
#        Column1 Result1 Result2
# 0  [xyz-5536]A    Pass    fail
# 1  [xyz-5537]B    fail    pass
# 2  [xyz-5538]C    pass    fail
# 3  [xyz-5539]D    fail    pass

# Merge the two dataframe
df_new = df_1.merge(df_2, left_on="Column3",
                   right_on="Column1", suffixes=('', '_df2'))
print(df_new)
#    Column1 Column2      Column3  Column1_df2 Result1 Result2
# 0        1       A  [xyz-5536]  A[xyz-5536]A    Pass     fail
# 1        2       B  [xyz-5537]  B[xyz-5537]B    fail     pass
# 2        3       C  [xyz-5538]  C[xyz-5538]C    pass     fail
# 3        4       D  [xyz-5539]  D[xyz-5539]D    fail     pass

# Remove the duplicated columns
df_new = df_new.drop(["Column1_df2"], axis=1)
print(df_new)
# Column1 Column2      Column3  Result1 Result2
# 0        1       A[xyz-5536]A    Pass    fail
# 1        2       B[xyz-5537]B    fail    pass
# 2        3       C[xyz-5538]C    pass    fail
# 3        4       D[xyz-5539]D    fail    pass

# Export to a new xlsx file
df_new.to_excel("new_file.xlsx", index=False)


问:
Counting words with more than x characters in a string in C# using lambda expressions
I wrote a program to count words in a sentence that have x number of matching characters. The input string is a multi line string and I need to consider only alternate lines based on given criteria. Also in those filtered lines, I need to further select alternate words and then check if those filtered words match the characters for intersection.

E.g. let's say I have a input string as below and need to find words with 2 or more vowels in them:

```<code>string myString = "1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";
</code>```

now let's say I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these
 matching words.

E.g. with criteria of selecting every 2nd line, filtered lines will be {2, 4, 6}. Similarly every 3rd word in these filtered line will be line 2: {"the", "Wars"}, for line 4: {"of", "before"} and for line 6: {"be", "after"}.

For these filtered words, matching words with 2 or more vowels will be {"before"} in line number 4 and word {"after"} in line 6. So the final output will be wordCount = 2 and since these words are from line 4 and 6 so total lineCount = 2.

I wrote the below code using nested for loops that produces the desired output.

```<code>public static void Main(string[] args)
    {
        int vowelCount = 2; // match words with 2 or more vowels
        int skipWord = 3; // Consider every 3rd word only
        int skipLine = 2; // Consider every 2nd line only
        int wordCount = 0;
        int lineCount = 0;

        string myString = @"1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";";

        List<string> myList = myString.Split(Environment.NewLine).ToList();
        List<string> lineWords = new List<string>();
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        for (int i = skipLine; i <= myList.Count; i += skipLine)
        {
            int origWordCount = wordCount;
            lineWords = myList[i - 1].Split(' ').ToList();
            for (int j = skipWord; j <= lineWords.Count; j += skipWord)
            {
                char[] wordArr = lineWords[j-1].ToLower().ToCharArray();
                int match = vowels.Intersect(wordArr).Count();
                if (match >= vowelCount)
                    wordCount++;
            }
            if (wordCount > origWordCount)
                lineCount++;
        }

        Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);
</code>```

Above code works great but wondering if there is a way to do it without nested loops. I read about linq and lambda expressions but not sure how to use them here.

All comments are appreciated.

答:
Is it wise to put everything in one big LINQ query? This will make it more difficult to understand your code, test it, implement changes or reuse parts of it.

Consider writing separate LINQ-like functions that do only parts of your code. This is called an extension method. See extension methods demystified

I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these matching words.

So create functions:

Input: a string; Output: the string divided in a sequence of lines

Input: a sequence of Lines; Output: sequence of every 2nd line (or every n-th line)

Input: a Line; output: words in the line

Input: a sequence of words; output: the 3rd word in the sequence (or every n-th word)

Input: a word; output: the number of vowels in the word

Most of them are pretty easy:

```<code>IEnumerable<string> ToLines(this text)
{
    // TODO: check text not null
    using (var reader = new StringReader(text))
    {
        var line = reader.ReadLine();
        while (line != null)
        {
            yield return line;
            line = reader.ReadLine();
        }
    }
}

IEnumerable<string> KeepEvery2ndLine(this IEnumerable<string> lines)
{
    // TODO: check lines not null
    int lineNr = 0;
    foreach (var line in lines
    {
        ++lineNr;
        if (lineNr%2 == 0)
            yield return line;
    }
}

IEnumerable<string> ToWords(this string line)
{
    // TODO: check line not null
    // when is a word a word? do you need to consider tabs? semicolons?
    // is a number like 12 a word?
}
</code>```

Advise: use Regex to separate the line into words. See how to split string in words

By the way: if "12" is a word, how many vowels does it have: zero or two? ("twelve" has two vowels)

I won't write all the functions. You'll get the gist.

Because you split your task up in smaller tasks, it is fairly easy to understand what each function should do, it is easy to implement, easy to test, easy to change.

Once you've got them, your query is fairly simple:

```<code>var result = inputText.ToLines()
                      .KeepEvery2ndLine()
                      .ToWords()
                      .KeepEvery3rdWord()
                      .CountVowels();
</code>```

Body:
I wrote a program to count words in a sentence that have x number of matching characters. The input string is a multi line string and I need to consider only alternate lines based on given criteria. Also in those filtered lines, I need to further select alternate words and then check if those filtered words match the characters for intersection.

E.g. let's say I have a input string as below and need to find words with 2 or more vowels in them:

string myString = "1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";

now let's say I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these
 matching words.

E.g. with criteria of selecting every 2nd line, filtered lines will be {2, 4, 6}. Similarly every 3rd word in these filtered line will be line 2: {"the", "Wars"}, for line 4: {"of", "before"} and for line 6: {"be", "after"}.

For these filtered words, matching words with 2 or more vowels will be {"before"} in line number 4 and word {"after"} in line 6. So the final output will be wordCount = 2 and since these words are from line 4 and 6 so total lineCount = 2.

I wrote the below code using nested for loops that produces the desired output.

public static void Main(string[] args)
    {
        int vowelCount = 2; // match words with 2 or more vowels
        int skipWord = 3; // Consider every 3rd word only
        int skipLine = 2; // Consider every 2nd line only
        int wordCount = 0;
        int lineCount = 0;

        string myString = @"1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";";

        List<string> myList = myString.Split(Environment.NewLine).ToList();
        List<string> lineWords = new List<string>();
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        for (int i = skipLine; i <= myList.Count; i += skipLine)
        {
            int origWordCount = wordCount;
            lineWords = myList[i - 1].Split(' ').ToList();
            for (int j = skipWord; j <= lineWords.Count; j += skipWord)
            {
                char[] wordArr = lineWords[j-1].ToLower().ToCharArray();
                int match = vowels.Intersect(wordArr).Count();
                if (match >= vowelCount)
                    wordCount++;
            }
            if (wordCount > origWordCount)
                lineCount++;
        }

        Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);

Above code works great but wondering if there is a way to do it without nested loops. I read about linq and lambda expressions but not sure how to use them here.

All comments are appreciated.

Body:
Is it wise to put everything in one big LINQ query? This will make it more difficult to understand your code, test it, implement changes or reuse parts of it.

Consider writing separate LINQ-like functions that do only parts of your code. This is called an extension method. See extension methods demystified

I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these matching words.

So create functions:

Input: a string; Output: the string divided in a sequence of lines

Input: a sequence of Lines; Output: sequence of every 2nd line (or every n-th line)

Input: a Line; output: words in the line

Input: a sequence of words; output: the 3rd word in the sequence (or every n-th word)

Input: a word; output: the number of vowels in the word

Most of them are pretty easy:

IEnumerable<string> ToLines(this text)
{
    // TODO: check text not null
    using (var reader = new StringReader(text))
    {
        var line = reader.ReadLine();
        while (line != null)
        {
            yield return line;
            line = reader.ReadLine();
        }
    }
}

IEnumerable<string> KeepEvery2ndLine(this IEnumerable<string> lines)
{
    // TODO: check lines not null
    int lineNr = 0;
    foreach (var line in lines
    {
        ++lineNr;
        if (lineNr%2 == 0)
            yield return line;
    }
}

IEnumerable<string> ToWords(this string line)
{
    // TODO: check line not null
    // when is a word a word? do you need to consider tabs? semicolons?
    // is a number like 12 a word?
}

Advise: use Regex to separate the line into words. See how to split string in words

By the way: if "12" is a word, how many vowels does it have: zero or two? ("twelve" has two vowels)

I won't write all the functions. You'll get the gist.

Because you split your task up in smaller tasks, it is fairly easy to understand what each function should do, it is easy to implement, easy to test, easy to change.

Once you've got them, your query is fairly simple:

var result = inputText.ToLines()
                      .KeepEvery2ndLine()
                      .ToWords()
                      .KeepEvery3rdWord()
                      .CountVowels();


问:
Radio button value returns undefined
The buttons are visible and working, however when submit is clicked It should assign the value of the checked radio button(for each of the 3groups) to a variable,but the value returned is always undefined.

I expect the output to be the value or an object containing the values due to a group of buttons

severityFormValue.on("click", (e) => {
  const loggedVia = $('input[name=loggedVia]:checked').val()
  const allStable = $('input[name = allStable]:checked').val()
  const EnvDown = $('input[name = EnvDown]:checked').val()
});
```

<pre class="lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="dropdown">
       <button class="dropbtn" id="CCR_DACEbtn">CCR DACE ▼</button>
       <div id="drowdownCCR_DACEID" class="dropdown-content">
               Submitted by:
               <input type="radio" name="loggedVia" value="phone" checked> phone
               <input type="radio" name="loggedVia" value="email"> email<br>
               All services stable?
               <input type="radio" name="allStable" value="Yes"> Yes
               <input type="radio" name="allStable" value="No" checked> No
               <input type="radio" name="allStable" value="N/A"> N/A <br>
               Environment Down?
               <input type="radio" name="EnvDown" value="Yes"> Yes
               <input type="radio" name="EnvDown" value="No" checked> No
               <input type="radio" name="EnvDown" value="N/A"> N/A <br>
               <button type="button" id="severityFormSubmit" >Submit</button>
       </div>
   </div>`
</code>```

答:
The name of the second group of radio inputs is AllStable, not allStable, hence the selector won't find them as it's case-sensitive. Fix that and the code you've shown works fine:

var severityFormValue = $('#severityFormSubmit');

severityFormValue.on("click", (e) => {
  const loggedVia = $('input[name="LoggedVia"]:checked').val()
  const allStable = $('input[name="AllStable"]:checked').val();
  const envDown = $('input[name="EnvDown"]:checked').val()

  console.log(loggedVia);
  console.log(allStable);
  console.log(envDown);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
  <button class="dropbtn" id="CCR_DACEbtn">CCR DACE ▼</button>
  <div id="drowdownCCR_DACEID" class="dropdown-content">
    Submitted by:
    <input type="radio" name="LoggedVia" value="phone" checked> phone
    <input type="radio" name="LoggedVia" value="email"> email<br>

    All services stable?
    <input type="radio" name="AllStable" value="Yes"> Yes
    <input type="radio" name="AllStable" value="No" checked> No
    <input type="radio" name="AllStable" value="N/A"> N/A <br>

    Environment Down?
    <input type="radio" name="EnvDown" value="Yes"> Yes
    <input type="radio" name="EnvDown" value="No" checked> No
    <input type="radio" name="EnvDown" value="N/A"> N/A <br>
    <button type="button" id="severityFormSubmit">Submit</button>
  </div>
</div></code>```

Also note that I changed the EnvDown variable name to envDown and the loggedVia name attribute to LoggedVia to maintain consistency with their counterpart values.

Title: Radio button value returns undefined

Body:
The buttons are visible and working, however when submit is clicked It should assign the value of the checked radio button(for each of the 3groups) to a variable,but the value returned is always undefined.

I expect the output to be the value or an object containing the values due to a group of buttons

severityFormValue.on("click", (e) => {
  const loggedVia = $('input[name=loggedVia]:checked').val()
  const allStable = $('input[name = allStable]:checked').val()
  const EnvDown = $('input[name = EnvDown]:checked').val()
});

       <button class="dropbtn" id="CCR_DACEbtn">CCR DACE ▼</button>

               Submitted by:
               <input type="radio" name="loggedVia" value="phone" checked> phone
               <input type="radio" name="loggedVia" value="email"> email

               All services stable?
               <input type="radio" name="allStable" value="Yes"> Yes
               <input type="radio" name="allStable" value="No" checked> No
               <input type="radio" name="allStable" value="N/A"> N/A

               Environment Down?
               <input type="radio" name="EnvDown" value="Yes"> Yes
               <input type="radio" name="EnvDown" value="No" checked> No
               <input type="radio" name="EnvDown" value="N/A"> N/A

               <button type="button" id="severityFormSubmit" >Submit</button>

`

Body:
The name of the second group of radio inputs is AllStable, not allStable, hence the selector won't find them as it's case-sensitive. Fix that and the code you've shown works fine:

var severityFormValue = $('#severityFormSubmit');

severityFormValue.on("click", (e) => {
  const loggedVia = $('input[name="LoggedVia"]:checked').val()
  const allStable = $('input[name="AllStable"]:checked').val();
  const envDown = $('input[name="EnvDown"]:checked').val()

  console.log(loggedVia);
  console.log(allStable);
  console.log(envDown);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
  <button class="dropbtn" id="CCR_DACEbtn">CCR DACE ▼</button>
  <div id="drowdownCCR_DACEID" class="dropdown-content">
    Submitted by:
    <input type="radio" name="LoggedVia" value="phone" checked> phone
    <input type="radio" name="LoggedVia" value="email"> email<br>

    All services stable?
    <input type="radio" name="AllStable" value="Yes"> Yes
    <input type="radio" name="AllStable" value="No" checked> No
    <input type="radio" name="AllStable" value="N/A"> N/A <br>

    Environment Down?
    <input type="radio" name="EnvDown" value="Yes"> Yes
    <input type="radio" name="EnvDown" value="No" checked> No
    <input type="radio" name="EnvDown" value="N/A"> N/A <br>
    <button type="button" id="severityFormSubmit">Submit</button>
  </div>
</div>

Also note that I changed the EnvDown variable name to envDown and the loggedVia name attribute to LoggedVia to maintain consistency with their counterpart values.


问:
Why does my Selenium command not work?
I'm writing a selenium script that should only start testing after all ajax calls have completed.

Several forums have suggested that I use the following condition (in the waitForCondition command):

```<code>selenium.browserbot.getCurrentWindow().jQuery.active == 0
</code>```

Unfortunately this keeps throwing an error:

jQuery is undefined

JQuery is definitely defined on my site. I have also tried substituting the jQuery with $, but get the same error.

Any ideas?

答:
If this is in Firefox it could be wrapped in a XPCNativeWrapper. To get around that the "best practice" way to get the window is to called getUserWindow() which handles unwrapping object to become useable.

This is also assuming that jQuery isnt being loaded asynchronously.

Title: Why does my Selenium command not work?

Body:
I'm writing a selenium script that should only start testing after all ajax calls have completed.

Several forums have suggested that I use the following condition (in the waitForCondition command):

selenium.browserbot.getCurrentWindow().jQuery.active == 0

Unfortunately this keeps throwing an error:

jQuery is undefined

JQuery is definitely defined on my site. I have also tried substituting the jQuery with $, but get the same error.

Any ideas?


问:
Android - What is the name of this button?
When the soft keyboard is active, the back button is switched to this one

What is the name of the button? And what is the method that is called after pressing it?

答:
I assume that you are referring to the downward-pointing triangle on the left side of the navigation bar.

What is the name of the button?

BACK.

And what is the method that is called after pressing it?

In this case, nothing. The input method editor will be closed.

If there is no input method editor open, onBackPressed() will be called on the foreground activity.


问:
Navigation Between tableView to detailedTableView through XIB file
I have a tableView. In that on clicking on a particular row I want to send some data to another XIB file through didSelectRowAtIndexPath.

At present I am able to navigate between the XIB via this

```<code> abc *vc = [[abc alloc] init];

 [self.navigationController pushViewController:vc animated:YES];
</code>```

but havent achieved data passing yet. Can somebody help ?

答:
Add a property of type string in abc class as below :

```<code>@property (nonatomic, strong) NSString *passedString;
</code>```

In your code after initialisation of the viewcontrller object pass the details to the property as below :

```<code> abc *vc = [[abc alloc] init];
 vc. passedString = @"Pass The String Value Here."   //If you pass empty string it would show the empty sting in abc ViewController
 [self.navigationController pushViewController:vc animated:YES];
</code>```

Hope this helps.

Body:
I have a tableView. In that on clicking on a particular row I want to send some data to another XIB file through didSelectRowAtIndexPath.

At present I am able to navigate between the XIB via this

 abc *vc = [[abc alloc] init];

 [self.navigationController pushViewController:vc animated:YES];

but havent achieved data passing yet. Can somebody help ?

Body:
Add a property of type string in abc class as below :

@property (nonatomic, strong) NSString *passedString;

In your code after initialisation of the viewcontrller object pass the details to the property as below :

 abc *vc = [[abc alloc] init];
 vc. passedString = @"Pass The String Value Here."   //If you pass empty string it would show the empty sting in abc ViewController
 [self.navigationController pushViewController:vc animated:YES];

Hope this helps.


答: You need transactions.</p>

Title: How to "close" database when the query happens?

Body:
$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

Body: You need transactions.


问:
GridView Footer row is null
Footer is set to visible and I can see it's being created. However when total (table sums) are passed over to it, there's error indicating GridView2.FooterRow is null...
totTable refers to a DataTable carrying totals.

aspx:

```<code>ShowHeader="true" ShowFooter="true" FooterStyle-CssClass="FooterStyle"
</code>```

cs:

```<code> DataRow dr = totTable.Rows[0];
 foreach (DataControlField col in GridView2.Columns)
                {
                    foreach (DataColumn dc in totTable.Columns)
                    {
                        int i = GridView2.Columns.IndexOf(col);
                        GridView2.FooterRow.Cells[i].Text = dr[i].ToString();

                    }
                }
</code>```

What's the root cause behind this?

答:
Add the footer on the OnLoad method of the GridView.

<asp:GridView ID="Gv"
  runat="server"
  ShowFooter="true"
  OnLoad="Gv_Load">
```

Title: GridView Footer row is null

Body:
Footer is set to visible and I can see it's being created. However when total (table sums) are passed over to it, there's error indicating GridView2.FooterRow is null...
totTable refers to a DataTable carrying totals.

aspx:

ShowHeader="true" ShowFooter="true" FooterStyle-CssClass="FooterStyle"

cs:

 DataRow dr = totTable.Rows[0];
 foreach (DataControlField col in GridView2.Columns)
                {
                    foreach (DataColumn dc in totTable.Columns)
                    {
                        int i = GridView2.Columns.IndexOf(col);
                        GridView2.FooterRow.Cells[i].Text = dr[i].ToString();

                    }
                }

What's the root cause behind this?


问:
Is there a way to determine the type of edit used with onEdit in a Google Sheets Script?
I need to know if a user is deleting a row, editing a cell, or pasting a bunch of cells. I keep looking through documentation and I cannot find a way to determine what the user's action is. Is there a way in to know what kind of action is used in onEdit?</p>

答:
This is not currently possible using onEdit(). The most you can find from an Edit Event Object is the old / new values of the cell. Note: This only works if it's only one cell being edited.

You could, for example, use e.range to determine the range that has been edited but it will not tell you the type of edit that has taken place.


问:
Replace multiple (special) characters - most efficient way?
At the texts that I have, I want to replace the following special characters with a single space:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

```<code>(Hello World)] *!
</code>```

to become this:

```<code>Hello World
</code>```

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

答:
```<code>s = '''
def translate_():
    symbols = '`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/'
    s = '~this@is!a^test @'
    t = str.maketrans(dict.fromkeys(symbols, ' '))
    s.translate(t)
    return s

def replace_():
    symbols = '`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/'
    s = '~this@is!a^test @'
    for symbol in symbols:
        s = s.replace(symbol, ' ')
    return s
'''

print(timeit.timeit('replace_()', setup=s, number=100000))
print(timeit.timeit('translate_()', setup=s, number=100000))
</code>```

Will print:

0.7663131961598992

0.4139239452779293

So replacing with translate is nearly 2 times faster than using several replaces.

Body:
At the texts that I have, I want to replace the following special characters with a single space:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

(Hello World)] *!

to become this:

Hello World

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

Body:
s = '''
def translate_():
    symbols = '`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/'
    s = '~this@is!a^test @'
    t = str.maketrans(dict.fromkeys(symbols, ' '))
    s.translate(t)
    return s

def replace_():
    symbols = '`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/'
    s = '~this@is!a^test @'
    for symbol in symbols:
        s = s.replace(symbol, ' ')
    return s
'''

print(timeit.timeit('replace_()', setup=s, number=100000))
print(timeit.timeit('translate_()', setup=s, number=100000))

Will print:

0.7663131961598992

0.4139239452779293

So replacing with translate is nearly 2 times faster than using several replaces.


问:
how to auto increment with 1 after deleting data from table
i'm deleting previous data and trying to insert new list of data,id values are keep on increment because of auto-increment. is it possible to have new auto increment id with 1 ?

and i tried with  ALTER TABLE table AUTO_INCREMENT = 1; its not working for me.

答:
Use this query while deleting your old 20 Records.

```<code>truncate table YourTableName;
</code>```

It will reset the database structure and if you insert new record it will start from 1(one) id again.

Body:
Use this query while deleting your old 20 Records.

truncate table YourTableName;

It will reset the database structure and if you insert new record it will start from 1(one) id again.


问:
Server CPU and GPU With LAMP
I am trying to figure out more about the hardware that can be utilized when running a php application or even a c++ compiled php app using HipHop.  I would like to setup a microserver and use the GPU to help the CPU process requests...

Anyone?

答:
PHP alone does not have the ability to leverage the GPU.  This was recently discussed on the php internals developer list.

Keep in mind that GPUs excel at certain types of workloads, while they're not that great for others.  PHP wouldn't be able to really take advantage of GPU acceleration because the work it performs isn't really the best kind for a GPU.

If you really want to play with HipHop and random high performance stuff, you might want to begin following Open Parallel.  They've been working with an Intel technology called Threading Building Blocks and have been integrating it into HipHop by adding new functions that can call callbacks asynchronously, with outstanding results.  There was a great deal of interest when they introduced their work to the HipHop group.

However, there is no sign whatsoever of CUDA support, or really any GPU support at all in HipHop.  To be honest, HipHop is not the right solution for the majority of PHP users.  If you are trying to squeeze performance out of code, you should be profiling it.

Title: Server CPU and GPU With LAMP


问:
php chat notifications - how to autoplay a sound After receiving a new message
I want to make an audio file start automatically after receiving a new message.

It works now but does not stop. I want it to work only when receiving any new messages.

```<code><?php
include_once("header.php");
$path = "";
$TID = $_POST["TID"];
$x_res = "SELECT * FROM chat WHERE t_id='$UID' AND f_id='$TID' AND t_id_show='0' ";
$f_sql = mysqli_query($CONFIG, $x_res);
$fetch_chat = mysqli_num_rows($f_sql);
if($fetch_chat > 0){
    if($fetch_chat +1){
        echo '<iframe src="style/SD.mp3" allow="autoplay" style="display:none" ></iframe>';
    }
    echo '<q dir="ltr" style="color:red;" > '.$fetch_chat.' </q>';
}
?>
</code>```

This is the code I want to edit to play only when I receive any new messages.

```<code><?php
if($fetch_chat +1){
    echo '<iframe src="style/SD.mp3" allow="autoplay" style="display:none" ></iframe>';
}
?>
</code>```

Body:
I want to make an audio file start automatically after receiving a new message.

It works now but does not stop. I want it to work only when receiving any new messages.

<?php
include_once("header.php");
$path = "";
$TID = $_POST["TID"];
$x_res = "SELECT * FROM chat WHERE t_id='$UID' AND f_id='$TID' AND t_id_show='0' ";
$f_sql = mysqli_query($CONFIG, $x_res);
$fetch_chat = mysqli_num_rows($f_sql);
if($fetch_chat > 0){
    if($fetch_chat +1){
        echo '';
    }
    echo '<q dir="ltr" style="color:red;" > '.$fetch_chat.' </q>';
}
?>

This is the code I want to edit to play only when I receive any new messages.

<?php
if($fetch_chat +1){
    echo '';
}
?>


问:
Check if passed argument value is nil or empty
I am trying to re-write the C# code which i have wrote previously to Swift.

```<code>public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}
</code>```

I am not able to write if statement effectively in swift.

答:
In Swift you can write,

```<code>func right(value: String, length: Int) -> String {
    if value.count <= length {
        return value
    } else {
        let index = value.index(value.startIndex, offsetBy: value.count-length)
        return String(value[..<index])
    }
}
</code>```

There is no need to check for empty string. It will be covered in the else condition itself.

Example:

```<code>right(value: "abcdefgh", length: 3) //abcde
</code>```

Body:
I am trying to re-write the C# code which i have wrote previously to Swift.

public static string Right( string value, int length)
{
    if (String.IsNullOrEmpty(value)) return string.Empty;
    return value.Length <= length ? value : value.Substring(value.Length - length);
}

I am not able to write if statement effectively in swift.

Body:
In Swift you can write,

func right(value: String, length: Int) -> String {
    if value.count <= length {
        return value
    } else {
        let index = value.index(value.startIndex, offsetBy: value.count-length)
        return String(value[..<index])
    }
}

There is no need to check for empty string. It will be covered in the else condition itself.

Example:

right(value: "abcdefgh", length: 3) //abcde


问:
greater/less than signs are not escaped
i am trying to escape strings in server side (Node.js & Express.js) which contains greater/less than signs (<, >) and i use this code on server side

```<code>socket.on('message', function(data) {
   data.message = data.message.replace(/\</g,"<")   //for <
   data.message = data.message.replace(/\>/g,">")   //for >
   io.in(socket.current_room).emit('message',{message :data.message, id: socket.id});
});
</code>```

and on client side (inside socket.on('message') function)

```<code>output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">` + message + '</p></div></div>'
</code>```

it replaces the signs but it displays them as replaced, for example: user send message: <hello>, message will displayeed as <hello>.
How can i fix it? Thank you!

答:
Just use a second replace on the client side - and you're using template literals so you can use the ${} pattern:

```<code>output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">${message.replace(/\&lt\;/g, "<").replace(/\&gt\;/g, ">")}</p></div></div>`
</code>```

Title: greater/less than signs are not escaped

Body:
i am trying to escape strings in server side (Node.js & Express.js) which contains greater/less than signs (<, >) and i use this code on server side

socket.on('message', function(data) {
   data.message = data.message.replace(/\</g,"<")   //for <
   data.message = data.message.replace(/\>/g,">")   //for >
   io.in(socket.current_room).emit('message',{message :data.message, id: socket.id});
});

and on client side (inside socket.on('message') function)

output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">` + message + '

'

it replaces the signs but it displays them as replaced, for example: user send message: <hello>, message will displayeed as <hello>.
How can i fix it? Thank you!

Body:
Just use a second replace on the client side - and you're using template literals so you can use the ${} pattern:

output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">${message.replace(/\&lt\;/g, "<").replace(/\&gt\;/g, ">")}</p></div></div>`


问:
from jquery scope call to class function
I want to call from Jquery scope (which is in the same class) to same class function/method. How I should do?

I tried:

displayTemplate.findWithAttr(action);

or

this.findWithAttr(action);

Response

"this.findWithAttr is not a function"

Here is my code.

```<code>class displayTemplate{
  findWithAttr(action) {
    //to do something with action
  }
  router(action){
    if(action == "something"){
      $( "#confirm_dialog_msg" ).text("text?");
         $( "#dialog-confirm" ).dialog({
           buttons: {
             "yes": function() {
                $( this ).dialog( "close" );

               //how in this area call to "findWithAttr" function above?
                this.findWithAttr(action);

             },
             "No": function() {
               //..
             }
           }
        });
      }
  //...
  }
}
</code>```

答:
You may want to use lambda expressions instead of nested functions.
One of the differences between them is that lambda expressions keep parent context instead of having their own.

So to do that you simply change

```<code>"yes": function() {
</code>```

to

```<code>"yes": () => {
</code>```

Body:
I want to call from Jquery scope (which is in the same class) to same class function/method. How I should do?

I tried:

displayTemplate.findWithAttr(action);

or

this.findWithAttr(action);

Response

"this.findWithAttr is not a function"

Here is my code.

class displayTemplate{
  findWithAttr(action) {
    //to do something with action
  }
  router(action){
    if(action == "something"){
      $( "#confirm_dialog_msg" ).text("text?");
         $( "#dialog-confirm" ).dialog({
           buttons: {
             "yes": function() {
                $( this ).dialog( "close" );

               //how in this area call to "findWithAttr" function above?
                this.findWithAttr(action);

             },
             "No": function() {
               //..
             }
           }
        });
      }
  //...
  }
}

Body:
You may want to use lambda expressions instead of nested functions.
One of the differences between them is that lambda expressions keep parent context instead of having their own.

So to do that you simply change

"yes": function() {

to

"yes": () => {


问:
Iterating over substrings of equal size
I want to convert my String object to Enumerable of its 1-sized substrings (not chars), how can I do this efficiently in Ruby?</p>

答:
In Ruby 1.9 (and 1.8.7) you can use each_char to reliably iterate over the characters of a string, including proper handling of multi-byte chars and stuff. In earlier releases, each_char does not exist and indexing will return byte codes rather than single char strings. In this case, you can use

```<code>"abcdefg".split(//u)
</code>```

which will split the string in a UTF-8 aware way.

There's some nice discussion here.

OwnerDisplayName: Dmitriy Matveev

ContentLicense: CC BY-SA 2.5

Title: Iterating over substrings of equal size

Body:
In Ruby 1.9 (and 1.8.7) you can use each_char to reliably iterate over the characters of a string, including proper handling of multi-byte chars and stuff. In earlier releases, each_char does not exist and indexing will return byte codes rather than single char strings. In this case, you can use

"abcdefg".split(//u)

which will split the string in a UTF-8 aware way.

There's some nice discussion here.

OwnerDisplayName: Dave Ray