问:
Linq - how to replace a lists property with value from another list where both keys are equal
I have 2 lists groupoptions and dataIndicator

```<code>class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}
</code>```

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

```<code>var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };
</code>```

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

```<code>var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })
</code>```

答:
my problem was i wanted to do it inside a constructor that was being created inside a Linq Select...i did the following instead of join

```<code>var list = xyz.Select(x => new groupoptions()
        {
          GroupName = dataIndicator.Where(d => d.IndicatorID.ToString().Equals(x.Key.ToString())).First().IndicatorDescription
            }
</code>```

P.S. First is taken because there will always be one record that matches..Also i was doing a mistake of comparing with headerid when i should have compared to indicatorid property.

Body:
I have 2 lists groupoptions and dataIndicator

class groupoptions{
  ...
  GroupName string
}

class dataIndicator{
  ...
 HeaderID int
 IndicatorDescription
}

currently my groupname possible values are 4 or 5 or 11

first i want to get all dataindicators where headerid  is equal to GroupName, then replace those GroupNames with dataindicator's IndicatorDescription

What would be the Linq syntax for this?

UPDATE

using join

var newList = from first in dataIndicator
                      join second in groupedoptions
                      on first.HeaderID.ToString() equals second.GroupName
                      select new { first,second };

What next?
PROBLEM: i want to do it inside a constructor that is being created inside a Linq Select

var list = xyz.Select(x => new groupoptions(){
   GroupName = x.Key.ToString();
 })

Body:
my problem was i wanted to do it inside a constructor that was being created inside a Linq Select...i did the following instead of join

var list = xyz.Select(x => new groupoptions()
        {
          GroupName = dataIndicator.Where(d => d.IndicatorID.ToString().Equals(x.Key.ToString())).First().IndicatorDescription
            }

P.S. First is taken because there will always be one record that matches..Also i was doing a mistake of comparing with headerid when i should have compared to indicatorid property.


来源: stackexchange

问:
Scrapy-Splash running Tor Proxy
I try to build proxy settings of splash. Here I assign Tor or Polipo port address to set_proxy, but it doesn't work. I get 504 error:

```<code> function main(splash)
            local host = "localhost"
            local port = 8123
            --local type = "SOCKS5"

            splash:on_request(function (request)
               request:set_proxy{host, port}
        end)

        splash:go(splash.args.url)
        splash:wait(0.5)
        local image = assert(splash:png{render_all=true})
        return {png=image}
    end
    """

    url = 'https://www.torproject.org/'
</code>```

In polipo.config(9150 is tor port):

```<code>socksParentProxy = localhost:9150
diskCacheRoot=""
#socksProxyType = socks5
</code>```

In settings.py:

```<code>HTTP_PROXY = 'http://127.0.0.1:8123'
DOWNLOADER_MIDDLEWARES = {
    'thefork.middlewares.RandomUserAgentMiddleware': 400,
    'thefork.middlewares.ProxyMiddleware': 410,
</code>```

How can I fix this, or is there an easier way to use splash with Tor?

答: The problem I believe is in the middleware you have installed. Try setting the proxy manually on every request. This is how I solved my issue. It tries to proxy every request and when you send a request to splash it attempts to go to your localhost through the proxy and fails.</p>

ContentLicense: CC BY-SA 3.0

Title: Scrapy-Splash running Tor Proxy

Body:
I try to build proxy settings of splash. Here I assign Tor or Polipo port address to set_proxy, but it doesn't work. I get 504 error:

 function main(splash)
            local host = "localhost"
            local port = 8123
            --local type = "SOCKS5"

            splash:on_request(function (request)
               request:set_proxy{host, port}
        end)

        splash:go(splash.args.url)
        splash:wait(0.5)
        local image = assert(splash:png{render_all=true})
        return {png=image}
    end
    """

    url = 'https://www.torproject.org/'

In polipo.config(9150 is tor port):

socksParentProxy = localhost:9150
diskCacheRoot=""
#socksProxyType = socks5

In settings.py:

HTTP_PROXY = 'http://127.0.0.1:8123'
DOWNLOADER_MIDDLEWARES = {
    'thefork.middlewares.RandomUserAgentMiddleware': 400,
    'thefork.middlewares.ProxyMiddleware': 410,

How can I fix this, or is there an easier way to use splash with Tor?


问:
Android Link Error
I'm running Ubuntu 10.10

I'm NOT using the NDK

I compiled my ARM shared library in DS-5 (ARM's development toolset, http://www.keil.com/arm/ds5/ ).  When I placed them under libs/armeabi and call System.loadLibrary() it can't find them.

Here's the class:

```<code>package org.me.testds5;

//a JNI wrapper class
public class WrapMyNative
{
    static
    {
            //ERROR HERE
            //note that calling
            //System.loadLibrary("libAddSub"); generates the same error
        System.loadLibrary("AddSub");
    }

    //some native functions
    public native int add(int a, int b);
    public native int sub(int n, int m);

}
</code>```

The library's exact name is libAddSub.so

The LogCat:

```<code>11-30 04:54:11.273: ERROR/AndroidRuntime(372): FATAL EXCEPTION: main
11-30 04:54:11.273: ERROR/AndroidRuntime(372): java.lang.ExceptionInInitializerError
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at org.me.testds5.TestDS5.onCreate(TestDS5.java:13)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.os.Looper.loop(Looper.java:123)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.reflect.Method.invokeNative(Native Method)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.reflect.Method.invoke(Method.java:521)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at dalvik.system.NativeStart.main(Native Method)
11-30 04:54:11.273: ERROR/AndroidRuntime(372): Caused by: java.lang.UnsatisfiedLinkError: Library AddSub not found
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.Runtime.loadLibrary(Runtime.java:461)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.System.loadLibrary(System.java:557)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at org.me.testds5.WrapMyNative.<clinit>(WrapMyNative.java:7)
</code>```

答:
First, you really should use the ndk rather than some other gcc build such as codesourcery, and especially rather than a non-gcc compiler which may not even produce object files in a compatible format.

Second, as an experiment try using system.load() instead which takes a full pathname.  But still be prepared for problems if you aren't using the ndk gcc.

ContentLicense: CC BY-SA 2.5

Title: Android Link Error

Body:
I'm running Ubuntu 10.10

I'm NOT using the NDK

I compiled my ARM shared library in DS-5 (ARM's development toolset, http://www.keil.com/arm/ds5/ ).  When I placed them under libs/armeabi and call System.loadLibrary() it can't find them.

Here's the class:

package org.me.testds5;

//a JNI wrapper class
public class WrapMyNative
{
    static
    {
            //ERROR HERE
            //note that calling
            //System.loadLibrary("libAddSub"); generates the same error
        System.loadLibrary("AddSub");
    }

    //some native functions
    public native int add(int a, int b);
    public native int sub(int n, int m);

}

The library's exact name is libAddSub.so

The LogCat:

11-30 04:54:11.273: ERROR/AndroidRuntime(372): FATAL EXCEPTION: main
11-30 04:54:11.273: ERROR/AndroidRuntime(372): java.lang.ExceptionInInitializerError
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at org.me.testds5.TestDS5.onCreate(TestDS5.java:13)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.os.Looper.loop(Looper.java:123)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at android.app.ActivityThread.main(ActivityThread.java:4627)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.reflect.Method.invokeNative(Native Method)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.reflect.Method.invoke(Method.java:521)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at dalvik.system.NativeStart.main(Native Method)
11-30 04:54:11.273: ERROR/AndroidRuntime(372): Caused by: java.lang.UnsatisfiedLinkError: Library AddSub not found
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.Runtime.loadLibrary(Runtime.java:461)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at java.lang.System.loadLibrary(System.java:557)
11-30 04:54:11.273: ERROR/AndroidRuntime(372):     at org.me.testds5.WrapMyNative.<clinit>(WrapMyNative.java:7)


问:
get proportion of each group's value counts after group_by dplyr R
In python pandas I was able to simply do df.groupby(x,y).value_counts(normalize=True) to get the proportion of each value in a group. However I've been unable to find a way to do this in R.

I've grouped my df by x and y and have summarized to calculate the frequency,
as such df %>% group_by(x,y) %>% summarize(count=n()) but I'd like to instead see the proportion of each y for each x.

```<code>x   y  count
1   A   22
1   B   65
1   C   94
1   D   40
2   D   34
2   E   1
2   F   6
3   E   4
3   F   13
</code>```

for example, the new column of proportions should have

```<code>x   y   proportion
1   A   0.0995475
1   B   0.2941176
1   C   0.4253393
1   D   0.1809955
2   D   0.8292683
2   E   0.024390
2   F   0.1463415
3   E   0.2352941
3   F   0.7647059
</code>```

Body:
In python pandas I was able to simply do df.groupby(x,y).value_counts(normalize=True) to get the proportion of each value in a group. However I've been unable to find a way to do this in R.

I've grouped my df by x and y and have summarized to calculate the frequency,
as such df %>% group_by(x,y) %>% summarize(count=n()) but I'd like to instead see the proportion of each y for each x.

x   y  count
1   A   22
1   B   65
1   C   94
1   D   40
2   D   34
2   E   1
2   F   6
3   E   4
3   F   13

for example, the new column of proportions should have

x   y   proportion
1   A   0.0995475
1   B   0.2941176
1   C   0.4253393
1   D   0.1809955
2   D   0.8292683
2   E   0.024390
2   F   0.1463415
3   E   0.2352941
3   F   0.7647059

Body:
In case, we need a base R option, this can be done with ave

transform(df1, proportion = count/ave(count, x, FUN = sum))[-3]
#  x y proportion
#1 1 A 0.09954751
#2 1 B 0.29411765
#3 1 C 0.42533937
#4 1 D 0.18099548
#5 2 D 0.82926829
#6 2 E 0.02439024
#7 2 F 0.14634146
#8 3 E 0.23529412
#9 3 F 0.76470588


问:
using + in the variables passed to a url
I am trying to do a call to url

```<code>http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415
</code>```

If you look at var1 that I am passing value 'CD14+ MDM in GM-CSF 3 days then 3days IFN-γ'.

When in the controller I try to get this var 1 using request.params.get("var1"), i get 'CD14  MDM in GM-CSF 3 days then 3days IFN-γ' with missing + and instead getting extra space after CD14

How can I pass + in my variable in url

答: This has an answer here. It says that + needs to be encoded as %2B.

Body:
I am trying to do a call to url

http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415

If you look at var1 that I am passing value 'CD14+ MDM in GM-CSF 3 days then 3days IFN-γ'.

When in the controller I try to get this var 1 using request.params.get("var1"), i get 'CD14  MDM in GM-CSF 3 days then 3days IFN-γ' with missing + and instead getting extra space after CD14

How can I pass + in my variable in url


答:
If you are intended to use plus as a data component, instead of url component, You should pass %2B instead.

Javascript :

var url = "http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415";

//NOTE: this following wil lreplace all + to %2B
url = url.replace(/\+/g,"%2B");

console.log("new : ",url);```

Title: using + in the variables passed to a url


问:
Cannot start MongoDB: System error 1067 in Windows
After setting up MongoDB service on Windows Server 2008 R2 this error was raised. </p>

```<code>C:\mongodb\bin>net start MongoDB
The Mongo DB service is starting.
The Mongo DB service could not be started.

A system error has occurred.

System error 1067 has occurred.

The process terminated unexpectedly.
</code>```

答:
If you are in the Windows. you should change the mongodb's config in the System disk.For example

1) I change C:\Windows\system32\mongodb.exe.

2) And I make the path  in D:\mongodb\mongod.cfg .Before this,you should remove previous.

3) Finally , you can net the serve. net start mongodb.

I hope it can help you .English is not very good ,please forgive me.
enter image description here

Body:
After setting up MongoDB service on Windows Server 2008 R2 this error was raised.

C:\mongodb\bin>net start MongoDB
The Mongo DB service is starting.
The Mongo DB service could not be started.

A system error has occurred.

System error 1067 has occurred.

The process terminated unexpectedly.


问:
Adding Bootstrap Margin
This seems so simple, but I can't seem to get it to work.  All I want is to apply spacing between the right side of the screen and the four wide column I have created.  I have tried adding:

```<code>.spacer{
    margin-right: 2%;
}
</code>```

onto a containing div unsuccessfully.  I have it working on my eight wide column but I can't seem to replicate it.  Jfiddle: https://jsfiddle.net/fru2yv1f/

```<code><div class="col-lg-12">
    <div class="row row-top">
        <div class="col-lg-8">
            <div class="horizontal-spacer text-center border-green">
                <div class="vert-center">
                    <h1 id="page-two-heading">Page two Heading</h1>
                    <p id="page-two-sub-heading">Information that is useful, hopefully!</p>
                </div>
            </div>
    </div>
        <div id="side-text" class="col-lg-4 hidden-md hidden-sm hidden-xs border-green">
            <div class="vert-center">
            <h3>This Area Will Disappear on Screen Resize</h3>
            <p>text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text</p>
            </div>
        </div>
        </div>
</code>```

答:
Give the margin to the vert-center. Actually you are using all the 12 columns of the bootstrap grid and when you are adding margin-right to the div having col-lg-4 it is exceeding the total width of the 12 columns and hence not working properly.

example snippet

.vert-center {
margin-right: 2%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="col-lg-12">
    <div class="row row-top">
        <div class="col-lg-8">
            <div class="horizontal-spacer text-center border-green">
                <div class="vert-center">
                    <h1 id="page-two-heading">Page two Heading</h1>
                    <p id="page-two-sub-heading">Information that is useful, hopefully!</p>
                </div>
            </div>
    </div>
        <div id="side-text" class="col-lg-4 hidden-md hidden-sm hidden-xs border-green">
            <div class="vert-center">
            <h3>This Area Will Disappear on Screen Resize</h3>
            <p>text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text</p>
            </div>
        </div>
        </div></code>```

Title: Adding Bootstrap Margin

Body:
This seems so simple, but I can't seem to get it to work.  All I want is to apply spacing between the right side of the screen and the four wide column I have created.  I have tried adding:

.spacer{
    margin-right: 2%;
}

onto a containing div unsuccessfully.  I have it working on my eight wide column but I can't seem to replicate it.  Jfiddle: https://jsfiddle.net/fru2yv1f/

Page two Heading

Information that is useful, hopefully!

This Area Will Disappear on Screen Resize

text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text

Body:
Give the margin to the vert-center. Actually you are using all the 12 columns of the bootstrap grid and when you are adding margin-right to the div having col-lg-4 it is exceeding the total width of the 12 columns and hence not working properly.

example snippet

.vert-center {
margin-right: 2%;
}

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="col-lg-12">
    <div class="row row-top">
        <div class="col-lg-8">
            <div class="horizontal-spacer text-center border-green">
                <div class="vert-center">
                    <h1 id="page-two-heading">Page two Heading</h1>
                    <p id="page-two-sub-heading">Information that is useful, hopefully!</p>
                </div>
            </div>
    </div>
        <div id="side-text" class="col-lg-4 hidden-md hidden-sm hidden-xs border-green">
            <div class="vert-center">
            <h3>This Area Will Disappear on Screen Resize</h3>
            <p>text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text</p>
            </div>
        </div>
        </div>


问:
Does Garmin provide Step count of the user in their API?
I went through the Garmin's Connect API documentation here But nowhere it mentions that they provide Step count of the user. This data is critical for my app.

Can someone kindly answer this question, please?

答:
Wonder if this might help?... includes "steps" and more...

https://developer.garmin.com/connect-iq/api-docs/
Class: Toybox::ActivityMonitor::History

Hope it helps,
Chip


问:
php cake find() using OR condition
I need a basic "or" in my if else condition in php cake.

```<code>$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);
</code>```

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

答:
You can also use IN to retrieve similar type of Data instead of OR conditions.

Example :

```<code>$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array(
            'record.builder_name IN'=>array(
                 'rey',
                 'norbert'
             )
         )
     )
);
</code>```

Title: php cake find() using OR condition

Body:
I need a basic "or" in my if else condition in php cake.

$oTourRecords =  $this->Record->find('all', array(
    'conditions' => array(
        'record.builder_name' => 'rey',
            'or' => array(
                'record.builder_name' => 'norbert',
            )
         )
     )
);

basically i need to get if the record contain builder_name = rey or "norbert"
this one returns null.

Body:
You can also use IN to retrieve similar type of Data instead of OR conditions.

Example :

$oTourRecords =  $this->Record->find('all', array(
        'conditions' => array(
            'record.builder_name IN'=>array(
                 'rey',
                 'norbert'
             )
         )
     )
);


问:
Java script, PHP
I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code

```<code><script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
    location.href = 'Logout.php';
}
function pageHidden(evt){
    if (str==='delete')
        logout();
}

    window.addEventListener("pagehide", pageHidden, false);
    </script >
</code>```

Examples I tried....

```<code>// 1st approach
//window.addEventListener("beforeunload", function (e) {
///   var confirmationMessage = "Do you want to leave?";

//    (e || window.event).returnValue = confirmationMessage;
    //  return confirmationMessage;
//  });

// 2nd approach
     //  window.onbeforeunload = myUnloadEvent;
     // function myUnloadEvent() {
     //     console.log("Do your actions in here")
     //  }
// 3rd approach

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});
</code>```

checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....

Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.

答:
You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:

```<code>session_set_cookie_params(0);
session_start();
</code>```

session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.

Hope this helps! :)

Title: Java script, PHP

Body:
I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code

Examples I tried....

// 1st approach
//window.addEventListener("beforeunload", function (e) {
///   var confirmationMessage = "Do you want to leave?";

//    (e || window.event).returnValue = confirmationMessage;
    //  return confirmationMessage;
//  });

// 2nd approach
     //  window.onbeforeunload = myUnloadEvent;
     // function myUnloadEvent() {
     //     console.log("Do your actions in here")
     //  }
// 3rd approach

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});

checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....

Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.

Body:
You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:

session_set_cookie_params(0);
session_start();

session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.

Hope this helps! :)


问:
Making android listview layout scrollable
I have an xml file that has the layout in ASCII form:

```<code>---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>
</code>```

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?

答:
You can use <ScrollView> as your layout container

something along the line of

```<code><ScrollView>
    <LinearLayout>
    // your layout here
    </LinearLayout>
</ScrollView>
</code>```

the reason why we need the LinearLayout inside is that ScrollView can only have one direct child

Body:
I have an xml file that has the layout in ASCII form:

---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?

Body:
You can use <ScrollView> as your layout container

something along the line of

<ScrollView>
    <LinearLayout>
    // your layout here
    </LinearLayout>
</ScrollView>

the reason why we need the LinearLayout inside is that ScrollView can only have one direct child


问:
Error trying to insert data into a mySql database
In these days I tried to write a sort of registration-login system with php and mySql and somehow I managed to do it; now I want to put all the things in a new page with a pop up window: you press the button "register" or "login" and on the screen appears a window with all the stuff and things, that's what I did:

```<code><!DOCTYPE html>
<html>
<head>
<title>FindMyChamp</title>
</head>
<body>
<style type="text/css">
    .popUpBox{
        display: none;
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,0.4);
    }
    .popUpBoxBody{
        margin: 15% auto;
        padding: 15px;
        background-color: #fefefe;
        width: 30%;
    }
    .closeBtn{
        float: right;
        font-size: 28px;
    }
    .container{
        width: 300px;
        clear: both;
        display: block;
      margin-left: auto;
      margin-right: auto;
      text-align: center;
    }
    .container input{
        width: 100%;
        clear: both;
    }
    #send{
        width: 50%;
    }
</style>

<h1>Test</h1>
<p id="popUpTrigger">Register</p>
<p>Login</p>
<div id="divPopUp" class="popUpBox">
    <div class="popUpBoxBody">
        <span id="popUpCloser" class="closeBtn">×</span>
        <div class="container">
            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                Username: <input type="text" name="username">
                Password: <input type="password" name="password">
                Repeat Password: <input type="password" name="passwordCheck"><br><br>
                <input value="Send" id="send" type="submit" name="sub">
            </form>
            <?php include('registration.php') ?>
        </div>
    </div>
</div>
<script type="text/javascript">
    var btnOpen = document.getElementById("popUpTrigger");
    var popUp = document.getElementById("divPopUp");
    var btnClose = document.getElementById("popUpCloser")
    btnOpen.onclick = function(){
        popUp.style.display = "block";
    }
    btnClose.onclick = function(){
        popUp.style.display ="none";
    }
</script>
</code>```

register.php:

```<code><?php
function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
if(isset($_POST["sub"])){
    $username = $password = $passwordCheck = "";
    $flag = true;
    $con = mysql_connect('localhost','root','Testpass');
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        //Controllo se i campi sono vuoti
        if(empty($_POST["username"])){
            echo "The field 'Username' is required<br>";
        } else{
            $username = test_input($_POST["username"]);
        }
        if(empty($_POST["password"])){
            echo "The field 'Password' is required<br>";
            $flag = false;
        } else{
            $password = test_input($_POST["password"]);
        }
        if(empty($_POST["passwordCheck"])){
            echo "The field 'Repeat Password' is required<br>";
            $flag = false;
        } else{
            $passwordCheck = test_input($_POST["passwordCheck"]);
        }
    }
    if($password == $passwordCheck && $password != ""){
        mysql_select_db('tutorials');
        $checkUsernameDuplicate = mysql_query("SELECT * FROM registration WHERE username = '$username'");
        if(mysql_num_rows($checkUsernameDuplicate) <= 0){
            $cost = 10;
            $salt = strtr(base64_encode(mcrypt_create_iv(16,MCRYPT_DEV_URANDOM)), '+', '.');
            $salt = sprintf("$2a$%02d$", $cost). $salt;
            $hash = crypt($password, $salt);
            $sql = "INSERT INTO registration(username,password) VALUES('$username','$hash')";
            $retvalue = mysql_query($sql,$con);
            if(!$retvalue){
                echo "Something went wrong";
            } else{
                echo "Dati inseriti";
                //header("Location: http://localhost/database/login.php");
                exit();
            }

        } else{
                echo "Username aldready taken";
        }
        mysql_close($con);
    }
    elseif($flag){
        echo "<p style='color: red;'>The two password must match</p>";
    }
}
?>
</code>```

Everything works fine, but, when I press the button 'send' the window disappears and all the datas are send to the database, that's ok but I want that the windows remains until the user decides to close it. How can I do that?

答:
use ajax, you can execute your code in register.php without refreshing your page
http://api.jquery.com/jquery.ajax/</p>

Body:
In these days I tried to write a sort of registration-login system with php and mySql and somehow I managed to do it; now I want to put all the things in a new page with a pop up window: you press the button "register" or "login" and on the screen appears a window with all the stuff and things, that's what I did:

<!DOCTYPE html>

<title>FindMyChamp</title>

Test

Register

Login

        ×

            <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                Username: <input type="text" name="username">
                Password: <input type="password" name="password">
                Repeat Password: <input type="password" name="passwordCheck">

                <input value="Send" id="send" type="submit" name="sub">
            </form>
            <?php include('registration.php') ?>

register.php:

<?php
function test_input($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
if(isset($_POST["sub"])){
    $username = $password = $passwordCheck = "";
    $flag = true;
    $con = mysql_connect('localhost','root','Testpass');
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        //Controllo se i campi sono vuoti
        if(empty($_POST["username"])){
            echo "The field 'Username' is required
";
        } else{
            $username = test_input($_POST["username"]);
        }
        if(empty($_POST["password"])){
            echo "The field 'Password' is required
";
            $flag = false;
        } else{
            $password = test_input($_POST["password"]);
        }
        if(empty($_POST["passwordCheck"])){
            echo "The field 'Repeat Password' is required
";
            $flag = false;
        } else{
            $passwordCheck = test_input($_POST["passwordCheck"]);
        }
    }
    if($password == $passwordCheck && $password != ""){
        mysql_select_db('tutorials');
        $checkUsernameDuplicate = mysql_query("SELECT * FROM registration WHERE username = '$username'");
        if(mysql_num_rows($checkUsernameDuplicate) <= 0){
            $cost = 10;
            $salt = strtr(base64_encode(mcrypt_create_iv(16,MCRYPT_DEV_URANDOM)), '+', '.');
            $salt = sprintf("$2a$%02d$", $cost). $salt;
            $hash = crypt($password, $salt);
            $sql = "INSERT INTO registration(username,password) VALUES('$username','$hash')";
            $retvalue = mysql_query($sql,$con);
            if(!$retvalue){
                echo "Something went wrong";
            } else{
                echo "Dati inseriti";
                //header("Location: http://localhost/database/login.php");
                exit();
            }

        } else{
                echo "Username aldready taken";
        }
        mysql_close($con);
    }
    elseif($flag){
        echo "
The two password must match
";
    }
}
?>

Everything works fine, but, when I press the button 'send' the window disappears and all the datas are send to the database, that's ok but I want that the windows remains until the user decides to close it. How can I do that?


问:
reuse objects removed from realm database
I want to reuse realm objects which are once removed from database.

Lets say, I have removed one object from database.

```<code>Story story = realm.where(Story.class).equalTo("id","id").findFirst();

story.deleteFromRealm();
</code>```

Now, I want to pool the removed object and want to reuse it with different "id"(primary key) instead of creating a new object every single time.

The current implementation does not allow me to do this and throws an exception.

My question is, is there another way to achieve the same thing.
If not, should this be a feature added to realm.

The requested code which throws the exception

```<code>Story story1 = StoryObjPool.getInstance().getStory();
            if(story1 != null){
                story1.setId(1234);
            }
</code>```

The exception

```<code>java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

at io.realm.BaseRealm.checkIfValid(BaseRealm.java:348)
at io.realm.StoryRealmProxy.realmSet$id(StoryRealmProxy.java:177)
at com.hn.nishant.nvhn.model.Story.setId(Story.java:98)
</code>```

答:
```<code>Story story = realm.where(Story.class).equalTo("id","id").findFirst();
// create standalone object that not reference to realm
Story stoyStandalone = realm.copyFromRealm(story);

story.deleteFromRealm();

// save standalone object to realm
stoyStandalone.setId(...);
realm.copyToRealm(stoyStandalone);
</code>```

Body:
I want to reuse realm objects which are once removed from database.

Lets say, I have removed one object from database.

Story story = realm.where(Story.class).equalTo("id","id").findFirst();

story.deleteFromRealm();

Now, I want to pool the removed object and want to reuse it with different "id"(primary key) instead of creating a new object every single time.

The current implementation does not allow me to do this and throws an exception.

My question is, is there another way to achieve the same thing.
If not, should this be a feature added to realm.

The requested code which throws the exception

Story story1 = StoryObjPool.getInstance().getStory();
            if(story1 != null){
                story1.setId(1234);
            }

The exception

java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

at io.realm.BaseRealm.checkIfValid(BaseRealm.java:348)
at io.realm.StoryRealmProxy.realmSet$id(StoryRealmProxy.java:177)
at com.hn.nishant.nvhn.model.Story.setId(Story.java:98)


问:
TFS, get username by GUID
TFS 2015 update 2.

Some TFS REST endpoints (e. g. release details) return a reference to a user as a combination of display name and a GUID.

How can I retrieve the Windows username for the said user?

答:
You could not directly use Rest API to get what you need on TFS 2015 update 2.

You have to use Client API such as IIdentityManagementService.ReadIdentity
method to achieve it.

```<code>ConfigurationServer.GetService<IIdentityManagementService>().ReadIdentities(guid, ....)
</code>```

For more details please refer this blog which can give you help.

Title: TFS, get username by GUID

Body:
You could not directly use Rest API to get what you need on TFS 2015 update 2.

You have to use Client API such as IIdentityManagementService.ReadIdentity
method to achieve it.

ConfigurationServer.GetService<IIdentityManagementService>().ReadIdentities(guid, ....)

For more details please refer this blog which can give you help.


问:
How do I overwrite the value of a specific child under a key in Firebase using onClick?
I've been trying to get this to work for over a week now, but I keep running into the same issue. I'm trying to be able to update specifically the child pickup value with a on click listener, that is in my recyclerview.

I know I need to query the key from Firebase and that's the part I don't know how to do. Then set the value to the text that I will have set in the .setValue()

Here is my database tree:

```<code>           Chat
  -KgR30muFg-X6xmrqaXA
  address: "123 ST"
  confirm: ""
  description: "Destin: Customer Name  :Jhon"
  phone: "8678876678"
  pickup: ""
  title: "oliver2jason@gmail.com  02:54:44"

  -KgR34XayCVHu2Lveg62
  address: "125 ST"
  confirm: ""
  description: "Miramar: Customer Name  :Nathan "
  phone: "929292929"
  pickup: ""
  title: "oliver2jason@gmail.com  02:55:19"
</code>```

here is my code

```<code>public class Home extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference myref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myref= FirebaseDatabase.getInstance().getReference().child("Chat");
    FirebaseRecyclerAdapter<Blog,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Blog,BlogViewHolder>(
            Blog.class,
            R.layout.individual_row,
            BlogViewHolder.class,
            myref
    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setAddress(model.getAddress());
            viewHolder.setPhone(model.getPhone());
            viewHolder.setPickup(model.getPickup());
            viewHolder.setConfirm(model.getConfirm());

        }
    };
    recyclerView.setAdapter(recyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
    View mView;
    TextView textView_title;
    TextView textView_decription;
    TextView textView_address;
    TextView textView_phone;
    TextView textView_pickup;
    TextView textView_confirm;
    Button bconfirm;
    Button bpickup;

    public BlogViewHolder(View itemView) {
        super(itemView);
        mView=itemView;
        textView_title = (TextView)itemView.findViewById(R.id.title);
        textView_decription = (TextView) itemView.findViewById(R.id.description);
        textView_address = (TextView) itemView.findViewById(address);
        textView_phone = (TextView) itemView.findViewById(phone);
        textView_pickup = (TextView) itemView.findViewById(pickup);
        textView_confirm = (TextView) itemView.findViewById(R.id.confirm);
        bconfirm = (Button) itemView.findViewById(R.id.bcomfirm);
        bpickup = (Button) itemView.findViewById(R.id.bpickup);

    }
    public void setTitle(String title)
    {
        textView_title.setText(title+"");
    }
    public void setDescription(String description)
    {
        textView_decription.setText(description);
    }

    public void setAddress(String address) {
        textView_address.setText(address);
    }

    public void setPhone(String phone) {
        textView_phone.setText(phone);
    }
    public void setPickup(String pickup) {
        textView_pickup.setText(pickup);
    }
    public void setConfirm(String confirm) {
        textView_confirm.setText(confirm);
    }
}
}
</code>```

答:
First you have to get the key of the record that you will be updating then code the onClick method for the button that will update the pickup value:</p>

```<code>FirebaseRecyclerAdapter<Blog,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Blog,BlogViewHolder>(
            Blog.class,
            R.layout.individual_row,
            BlogViewHolder.class,
            myref){
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setAddress(model.getAddress());
            viewHolder.setPhone(model.getPhone());
            viewHolder.setPickup(model.getPickup());
            viewHolder.setConfirm(model.getConfirm());
            //Get Record Key
            final String key = this.getRef(position).getKey();

            //Update the Record
            viewHolder.bpickup.setOnClickListener(new OnClickListener(){
                public void onClick(View v) {
                    myref.child(key).child("pickup").setValue("yourValue");
                }
            };
        }
    };
    recyclerView.setAdapter(recyclerAdapter);
</code>```

Body:
I've been trying to get this to work for over a week now, but I keep running into the same issue. I'm trying to be able to update specifically the child pickup value with a on click listener, that is in my recyclerview.

I know I need to query the key from Firebase and that's the part I don't know how to do. Then set the value to the text that I will have set in the .setValue()

Here is my database tree:

           Chat
  -KgR30muFg-X6xmrqaXA
  address: "123 ST"
  confirm: ""
  description: "Destin: Customer Name  :Jhon"
  phone: "8678876678"
  pickup: ""
  title: "oliver2jason@gmail.com  02:54:44"

  -KgR34XayCVHu2Lveg62
  address: "125 ST"
  confirm: ""
  description: "Miramar: Customer Name  :Nathan "
  phone: "929292929"
  pickup: ""
  title: "oliver2jason@gmail.com  02:55:19"

here is my code

public class Home extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference myref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myref= FirebaseDatabase.getInstance().getReference().child("Chat");
    FirebaseRecyclerAdapter<Blog,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Blog,BlogViewHolder>(
            Blog.class,
            R.layout.individual_row,
            BlogViewHolder.class,
            myref
    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setAddress(model.getAddress());
            viewHolder.setPhone(model.getPhone());
            viewHolder.setPickup(model.getPickup());
            viewHolder.setConfirm(model.getConfirm());

        }
    };
    recyclerView.setAdapter(recyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
    View mView;
    TextView textView_title;
    TextView textView_decription;
    TextView textView_address;
    TextView textView_phone;
    TextView textView_pickup;
    TextView textView_confirm;
    Button bconfirm;
    Button bpickup;

    public BlogViewHolder(View itemView) {
        super(itemView);
        mView=itemView;
        textView_title = (TextView)itemView.findViewById(R.id.title);
        textView_decription = (TextView) itemView.findViewById(R.id.description);
        textView_address = (TextView) itemView.findViewById(address);
        textView_phone = (TextView) itemView.findViewById(phone);
        textView_pickup = (TextView) itemView.findViewById(pickup);
        textView_confirm = (TextView) itemView.findViewById(R.id.confirm);
        bconfirm = (Button) itemView.findViewById(R.id.bcomfirm);
        bpickup = (Button) itemView.findViewById(R.id.bpickup);

    }
    public void setTitle(String title)
    {
        textView_title.setText(title+"");
    }
    public void setDescription(String description)
    {
        textView_decription.setText(description);
    }

    public void setAddress(String address) {
        textView_address.setText(address);
    }

    public void setPhone(String phone) {
        textView_phone.setText(phone);
    }
    public void setPickup(String pickup) {
        textView_pickup.setText(pickup);
    }
    public void setConfirm(String confirm) {
        textView_confirm.setText(confirm);
    }
}
}

Body:
First you have to get the key of the record that you will be updating then code the onClick method for the button that will update the pickup value:

FirebaseRecyclerAdapter<Blog,BlogViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Blog,BlogViewHolder>(
            Blog.class,
            R.layout.individual_row,
            BlogViewHolder.class,
            myref){
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setAddress(model.getAddress());
            viewHolder.setPhone(model.getPhone());
            viewHolder.setPickup(model.getPickup());
            viewHolder.setConfirm(model.getConfirm());
            //Get Record Key
            final String key = this.getRef(position).getKey();

            //Update the Record
            viewHolder.bpickup.setOnClickListener(new OnClickListener(){
                public void onClick(View v) {
                    myref.child(key).child("pickup").setValue("yourValue");
                }
            };
        }
    };
    recyclerView.setAdapter(recyclerAdapter);


问:
To Reduce a String
I was solving a problem to reduce the form to it's non-reducible form. This was the question.

Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after  operation.

Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!

If the final string is empty, print Empty String; otherwise, print the final non-reducible string.

Sample Input 0

aaabccddd

Sample Output 0

abd

Sample Input 1

baab

Sample Output 1

Empty String

Sample Input 2

aa

Sample Output 2

Empty String

Explanation

Sample Case 0:
Shil can perform the following sequence of operations to get the final string:

Thus, we print .

Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
aaabccddd -> abccddd

abccddd   -> abddd

abddd     -> abd

Thus we print abd

Sample case 1:
baab -> bb

bb   -> Empty String.

And what I have done till now is try to solve it through StringBuilder in Java.But some of testcases pass while other's don't and I can't find out what's the error?

Here is the code that I have tried so far.

```<code>import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    StringBuilder sb = new StringBuilder(scan.nextLine());
    for(int i = 0; i < sb.length()-1; i++)
        {
            if(sb.charAt(i) == sb.charAt(i+1))
                sb.delete(i,i+2);
                i  = 0;
        }
    if(sb.length() == 0)
        System.out.println("Empty String");
    else
        System.out.println(sb.toString());
}
</code>```

}

Inputs like  aaabccddd

and aa pass.But when the input is baab it fails.

答:
Try this:</p>

```<code>    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder sb =new StringBuilder(in.nextLine());

   for (int i=0; i<sb.length()-1; i++){
        if(sb.charAt(i)==sb.charAt(i+1)){
            sb.delete(i, i+2);
            i=-1;

     }
    }
    if(sb.length()==0){
        System.out.println("Empty String");
    }else{
        System.out.println(sb);
    }
   }
</code>```

ContentLicense: CC BY-SA 4.0

Title: To Reduce a String

Body:
I was solving a problem to reduce the form to it's non-reducible form. This was the question.

Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after  operation.

Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!

If the final string is empty, print Empty String; otherwise, print the final non-reducible string.

Sample Input 0

aaabccddd

Sample Output 0

abd

Sample Input 1

baab

Sample Output 1

Empty String

Sample Input 2

aa

Sample Output 2

Empty String

Explanation

Sample Case 0:
Shil can perform the following sequence of operations to get the final string:

Thus, we print .

Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
aaabccddd -> abccddd

abccddd   -> abddd

abddd     -> abd

Thus we print abd

Sample case 1:
baab -> bb

bb   -> Empty String.

And what I have done till now is try to solve it through StringBuilder in Java.But some of testcases pass while other's don't and I can't find out what's the error?

Here is the code that I have tried so far.

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    StringBuilder sb = new StringBuilder(scan.nextLine());
    for(int i = 0; i < sb.length()-1; i++)
        {
            if(sb.charAt(i) == sb.charAt(i+1))
                sb.delete(i,i+2);
                i  = 0;
        }
    if(sb.length() == 0)
        System.out.println("Empty String");
    else
        System.out.println(sb.toString());
}

}

Inputs like  aaabccddd

and aa pass.But when the input is baab it fails.

Body:
Try this:

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder sb =new StringBuilder(in.nextLine());

   for (int i=0; i<sb.length()-1; i++){
        if(sb.charAt(i)==sb.charAt(i+1)){
            sb.delete(i, i+2);
            i=-1;

     }
    }
    if(sb.length()==0){
        System.out.println("Empty String");
    }else{
        System.out.println(sb);
    }
   }


问:
Matrix in C++ (print middle row, print middle col, etc)
I keep getting segmentation error. Any help would be appreciated. I am a student so please go easy on me. Thank you.

Background:
I have to print the matrix, the sum of all the elements, show the upper half, show the lower half, print the middle row, print the middle column.
The dimensions of the matrix are read in followed by N*M values.

```<code>#include <iostream>
#include <stdlib.h>

using namespace std;

void printMatrix(int** matrix, int n, int m)
{
     cout << "Printed matrix: " << endl;
    for(int i=0; i<n; i++)
    {
            for (int j=0; j<m; j++)
            {
                    cout << matrix[i][j] << "\t";
            }
            cout << endl;
    }
};

void getSum(int** matrix, int n, int m)
{
    int sum=0;
    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    sum += matrix[i][j];
            }
    }
    cout << "The sum of all numbers is: " << sum << endl;
 };

void printUpper(int** matrix, int n, int m)
{
    if(n != m)
    {
            cout << "The matrix is not square.\n";
            return;
    }

    cout << "The upper half of the array: \n";
    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    if(j<i)
                    {
                            cout << "\t";
                            continue;
                    }
                    cout << matrix[i][j] << "\t";
            }
            cout << endl;
    }
}

void printMiddleRow(int** matrix, int n, int m)
{
    if(n%2==0)
    {
            cout << "Error! The number of rows is even. Cannnot print the middle.\n";
            return;
    }
    cout << "The middle row: " << endl;
    int mid = n/2;
    for(int i=0; i<m; i++)
    {
            cout << matrix[mid][i] << "\t";
    }
    cout << endl;
};

void printMiddleCol(int** matrix, int n, int m)
{
    if(m%2==0)
    {
            cout << "Error! The number of columns is even. Cannot print the middle.\n";
            return;
    }

    cout << "The middle column: \n";
    int mid = m/2;

    for(int i=0; i<m; i++)
    {
            cout << matrix[i][mid] << "\t";
    }
    cout << endl;
};

int main(int argc, char* argv[])
{
    if(argc<0)//checks to make sure user inputs dimensions of array
            cout << "Error! More command line arguments are required.\n";

    int n = atoi(argv[1]);
    int m = atoi(argv[2]);

    int** matrix = new int*[n];
    for(int i=0; i<n; i++)
    {
            matrix[i] = new int[m];
    }

    int cur = 3;

    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    matrix[i][j] = atoi(argv[cur]);
                    cur++;
            }
    }

    cout << "Please choose from the following options: \n";
    cout << "1. Print the matrix.\n";
    cout << "2. Sum all of the elements.\n";
    cout << "3. Show the upper half.\n";
    cout << "4. Show the middle row.\n";
    cout << "5. Show the middle column.\n";

    int choice;
    cout << "Enter selection: ";
    cin >> choice;

    switch(choice)
    {
            case(1):
                    printMatrix(matrix, n, m);
                    break;
            case(2):
                    getSum(matrix, n, m);
                    break;
            case(3):
                    printUpper(matrix, n, m);
                    break;
            case(4):
                    printMiddleRow(matrix, n, m);
                    break;
            case(5):
                    printMiddleCol(matrix, n, m);
                    break;
            default:
                    cout << "Invalid selection. Goodbye.\n";
    }
    return 0;
}
</code>```

答: In the printMiddleCol function, the range for the "for loop" is given 0 to m, it should be 0 to n. Please correct it.</p>

Body:
I keep getting segmentation error. Any help would be appreciated. I am a student so please go easy on me. Thank you.

Background:
I have to print the matrix, the sum of all the elements, show the upper half, show the lower half, print the middle row, print the middle column.
The dimensions of the matrix are read in followed by N*M values.

#include <iostream>
#include <stdlib.h>

using namespace std;

void printMatrix(int** matrix, int n, int m)
{
     cout << "Printed matrix: " << endl;
    for(int i=0; i<n; i++)
    {
            for (int j=0; j<m; j++)
            {
                    cout << matrix[i][j] << "\t";
            }
            cout << endl;
    }
};

void getSum(int** matrix, int n, int m)
{
    int sum=0;
    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    sum += matrix[i][j];
            }
    }
    cout << "The sum of all numbers is: " << sum << endl;
 };

void printUpper(int** matrix, int n, int m)
{
    if(n != m)
    {
            cout << "The matrix is not square.\n";
            return;
    }

    cout << "The upper half of the array: \n";
    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    if(j<i)
                    {
                            cout << "\t";
                            continue;
                    }
                    cout << matrix[i][j] << "\t";
            }
            cout << endl;
    }
}

void printMiddleRow(int** matrix, int n, int m)
{
    if(n%2==0)
    {
            cout << "Error! The number of rows is even. Cannnot print the middle.\n";
            return;
    }
    cout << "The middle row: " << endl;
    int mid = n/2;
    for(int i=0; i<m; i++)
    {
            cout << matrix[mid][i] << "\t";
    }
    cout << endl;
};

void printMiddleCol(int** matrix, int n, int m)
{
    if(m%2==0)
    {
            cout << "Error! The number of columns is even. Cannot print the middle.\n";
            return;
    }

    cout << "The middle column: \n";
    int mid = m/2;

    for(int i=0; i<m; i++)
    {
            cout << matrix[i][mid] << "\t";
    }
    cout << endl;
};

int main(int argc, char* argv[])
{
    if(argc<0)//checks to make sure user inputs dimensions of array
            cout << "Error! More command line arguments are required.\n";

    int n = atoi(argv[1]);
    int m = atoi(argv[2]);

    int** matrix = new int*[n];
    for(int i=0; i<n; i++)
    {
            matrix[i] = new int[m];
    }

    int cur = 3;

    for(int i=0; i<n; i++)
    {
            for(int j=0; j<m; j++)
            {
                    matrix[i][j] = atoi(argv[cur]);
                    cur++;
            }
    }

    cout << "Please choose from the following options: \n";
    cout << "1. Print the matrix.\n";
    cout << "2. Sum all of the elements.\n";
    cout << "3. Show the upper half.\n";
    cout << "4. Show the middle row.\n";
    cout << "5. Show the middle column.\n";

    int choice;
    cout << "Enter selection: ";
    cin >> choice;

    switch(choice)
    {
            case(1):
                    printMatrix(matrix, n, m);
                    break;
            case(2):
                    getSum(matrix, n, m);
                    break;
            case(3):
                    printUpper(matrix, n, m);
                    break;
            case(4):
                    printMiddleRow(matrix, n, m);
                    break;
            case(5):
                    printMiddleCol(matrix, n, m);
                    break;
            default:
                    cout << "Invalid selection. Goodbye.\n";
    }
    return 0;
}


问:
Implementing next button which will notify thread
I know that there is some questions about this but it seems like I did not understand the concept or there is something wrong with it.

Basically, what I am trying to do is, there is a algorithm which will proceed as;

```<code>for(step=0;step<value;step++){
//Do something;
}
</code>```

But it should be an option so user can see how it perform algorithm each step if he check the isStepped checkbox;
So what I came up with is

```<code> public void run() {
for (int step = 0; step < f; step++) {
        if (isStepped) {
            try {
                wait();//Here is the problem
            } catch (InterruptedException ex) {
                Logger.getLogger(MainThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        }
</code>```

And on the Menuside;

```<code>private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {

    MyThread.notify();

}
</code>```

So when a nextbuttonclicked, thread should wake up but it seems it wont...
What causes this problem, and how can I overcome?

答:
Wait is defined in Object not in Thread and monitoring of a thread is not very much predicted ..

To wait and notify on an object you would require a lock with synchronized statement.

To create a lock object:

```<code>private final Object lock = new Object();
</code>```

To Wait on lock object:

```<code>synchronized (lock) {
                        lock.wait();
                }
</code>```

To Notify on lock object:

```<code>synchronized (lock)
            {
                lock.notify();
            }
</code>```

This should help to achieve your goal.

Body:
I know that there is some questions about this but it seems like I did not understand the concept or there is something wrong with it.

Basically, what I am trying to do is, there is a algorithm which will proceed as;

for(step=0;step<value;step++){
//Do something;
}

But it should be an option so user can see how it perform algorithm each step if he check the isStepped checkbox;
So what I came up with is

 public void run() {
for (int step = 0; step < f; step++) {
        if (isStepped) {
            try {
                wait();//Here is the problem
            } catch (InterruptedException ex) {
                Logger.getLogger(MainThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        }

And on the Menuside;

private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {

    MyThread.notify();

}

So when a nextbuttonclicked, thread should wake up but it seems it wont...
What causes this problem, and how can I overcome?

Body:
Wait is defined in Object not in Thread and monitoring of a thread is not very much predicted ..

To wait and notify on an object you would require a lock with synchronized statement.

To create a lock object:

private final Object lock = new Object();

To Wait on lock object:

synchronized (lock) {
                        lock.wait();
                }

To Notify on lock object:

synchronized (lock)
            {
                lock.notify();
            }

This should help to achieve your goal.


问:
Preview of google drive files without login
How we can get preview of google drive files in web without login into google account. In current scenario only public files are visible through embed link, we need to show preview of file in iframe which are not public and without login. </p>

答:
I think "Publish" is what is you need. The file can still be "Private".

Publish and embed Google Docs, Sheets, Slides & Forms
To make a document, spreadsheet, or presentation, available for a large audience to see, publish a file. After you publish your file, you’ll have a URL that you can send to anyone or embed into your website.


问:
Statistics: combinations in Python
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat  libraries. Something like a function of the type:

```<code>comb = calculate_combinations(n, r)
</code>```

I need the number of possible combinations, not the actual combinations, so itertools.combinations does not interest me.

Finally, I want to avoid using factorials, as the numbers I'll be calculating the combinations for can get too big and the factorials are going to be monstrous.

This seems like a REALLY easy to answer question, however I am being drowned in questions about generating all the actual combinations, which is not what I want.

答:
If your program has an upper bound to n (say n <= N) and needs to repeatedly compute nCr (preferably for >>N times), using lru_cache can give you a huge performance boost:

```<code>from functools import lru_cache

@lru_cache(maxsize=None)
def nCr(n, r):
    return 1 if r == 0 or r == n else nCr(n - 1, r - 1) + nCr(n - 1, r)
</code>```

Constructing the cache (which is done implicitly) takes up to O(N^2) time. Any subsequent calls to nCr will return in O(1).

Title: Statistics: combinations in Python

Body:
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat  libraries. Something like a function of the type:

comb = calculate_combinations(n, r)

I need the number of possible combinations, not the actual combinations, so itertools.combinations does not interest me.

Finally, I want to avoid using factorials, as the numbers I'll be calculating the combinations for can get too big and the factorials are going to be monstrous.

This seems like a REALLY easy to answer question, however I am being drowned in questions about generating all the actual combinations, which is not what I want.

Body:
If your program has an upper bound to n (say n <= N) and needs to repeatedly compute nCr (preferably for >>N times), using lru_cache can give you a huge performance boost:

from functools import lru_cache

@lru_cache(maxsize=None)
def nCr(n, r):
    return 1 if r == 0 or r == n else nCr(n - 1, r - 1) + nCr(n - 1, r)

Constructing the cache (which is done implicitly) takes up to O(N^2) time. Any subsequent calls to nCr will return in O(1).


问:
how do I change the button color in js?
This is my code it is called when a button is clicked in html I dont know why the button is not going black/white Actually it worked just fine before I put my php code in my html file The alert with "asdf" is just to check if my code executing or not

function checkp(event){

```<code>var x=event.currentTarget;
var button_type=document.getElementsByTagName("button");

for(var i=0;i<button_type.length;i++)
    {
        if(button_type[i].id==x.id){
    //  alert(button_type[i].id);
            var index=i;
        }

     }
        var start=0;
        var end=button_type.length;

        for(var q=start;q<=end;q++)
            {
                if(q==index)
                    {       alert("asdf");
                            button_type[q].style.filter="grayscale(0)";
                            button_type[q].style.padding="3cm";
                    }

            else{
                            button_type[q].style.filter="grayscale(100%)";
                            button_type[q].style.padding="";

                }
            }
    }
</code>```

This is how my buttons are declared in html

```<code>    <button  id ="love" type="button" ><img src="love.png"  alt="notfound"  width="30" height="30"/></button>

    <button  id ="haha" type="button" ><img src="haha.png"  alt="notfound"  width="30" height="30"/>  </button>
    <button  id ="wow"  type="button" ><img src="wow.jpg"  alt="notfound"  width="30" height="30"/>  </button>
    <button  id ="Angry"type="button" ><img src="angry.png"  alt="notfound"  width="30" height="30"/> </button>
    <button  id ="sad"  type="button" ><img src="sad.png"   alt="notfound" width="30" height="30"/>    </button>

     and this is how I called the js function
var x=document.getElementsByTagName("button");
for(var v=0;v<x.length;v++)
    {
         x[v].addEventListener("click",checkp,false);
      }
</code>```

答:
Can you share the html?

Does the ID of each of your buttons start from 0 and increment by 1?

If not, then there is an error with this line as id = "" and not a number.

```<code>LINE 6: if(button_type[i].id==x.id){
</code>```

What are you trying to achieve with this code? If you tell us what you want it to do with some html then i can definitely help!

Title: how do I change the button color in js?

Body:
This is my code it is called when a button is clicked in html I dont know why the button is not going black/white Actually it worked just fine before I put my php code in my html file The alert with "asdf" is just to check if my code executing or not

function checkp(event){

var x=event.currentTarget;
var button_type=document.getElementsByTagName("button");

for(var i=0;i<button_type.length;i++)
    {
        if(button_type[i].id==x.id){
    //  alert(button_type[i].id);
            var index=i;
        }

     }
        var start=0;
        var end=button_type.length;

        for(var q=start;q<=end;q++)
            {
                if(q==index)
                    {       alert("asdf");
                            button_type[q].style.filter="grayscale(0)";
                            button_type[q].style.padding="3cm";
                    }

            else{
                            button_type[q].style.filter="grayscale(100%)";
                            button_type[q].style.padding="";

                }
            }
    }

This is how my buttons are declared in html

    <button  id ="love" type="button" ></button>

    <button  id ="haha" type="button" >  </button>
    <button  id ="wow"  type="button" >  </button>
    <button  id ="Angry"type="button" > </button>
    <button  id ="sad"  type="button" >    </button>

     and this is how I called the js function
var x=document.getElementsByTagName("button");
for(var v=0;v<x.length;v++)
    {
         x[v].addEventListener("click",checkp,false);
      }

Body:
Can you share the html?

Does the ID of each of your buttons start from 0 and increment by 1?

If not, then there is an error with this line as id = "" and not a number.

LINE 6: if(button_type[i].id==x.id){

What are you trying to achieve with this code? If you tell us what you want it to do with some html then i can definitely help!


问:
SQL Server & C# : not returning any results
```<code>private void searchMulti(string searchType, string searchTerm)
    {
        {
            {
                var query = "";
                cb_Surname.Items.Clear();
                txt_patient_search.Clear();
                if (patient_NHSID.Equals(null) != true)
                {
                    pbar_search.Value = 2;
                    var connectionString = Settings.Default.CMTA_DBConnectionString;
                    using (var con = new SqlConnection(connectionString))
                    {
                        if (searchType != "NHSID")
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
                        }
                        else
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = @p1";
                        }

                        using (var qry_search = new SqlCommand(query))
                        {
                            qry_search.Connection = con;
                            qry_search.Parameters.Add("@p1", SqlDbType.VarChar).Value = searchTerm;
                            qry_search.Parameters.Add("@p2", SqlDbType.VarChar).Value = searchType;

                            con.Open();
                            qry_search.ExecuteNonQuery();
                            int firstIteration = 0;

                            using (var rdr = qry_search.ExecuteReader())
                            {
                                if (rdr.HasRows)
                                {
                                    //Found Valid Patient Event
                                    pbar_search.Value = 6;
                                    pbox_tick.Show();
                                    foundValidPatient = true;
                                    ////////////////////////////

                                    while (rdr.Read())
                                    {
                                        if (firstIteration == 0)
                                        {
                                            pbar_search.Value = 8;
                                            cb_Surname.Text = rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                              rdr.GetString(2);
                                            firstIteration = 1;
                                        }
                                        cb_Surname.Items.Add(rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                             rdr.GetString(2));
                                    }
                                }
                                else
                                {
                                    //Patient Not Found
                                    pbox_cross.Show();
                                    patientSelected = false;
                                    foundValidPatient = false;
                                }
                                con.Close();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Valid Text");
                    pbar_search.Value = 0;
                    pbox_cross.Show();
                }
            }
        }
    }
</code>```

The method above isn't working. It should query the SQL Server database for a user entered term (such as textbox value) and query it for a searchtype (firstname) however when debugging the SQL query is executed but no rows are returned.

If I run the command without the parameters and insert actual values i.e (WHERE FirstName = 'Alan') it works perfectly.

What have I done incorrectly with this SQL query?

```<code>query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
</code>```

Many thanks!

答:
You can't pass a column name in as a parameter, but what you can do is add it to your query string explicitly. You also might consider putting square brackets around the column name in case someone has a column name that is also a SQL keyword.

I have two examples of formatting a string with your column name in [] below:

```<code>if (searchType != "NHSID")
{
    query = $@"SELECT * FROM Patient WHERE [{searchType}] = '@p1'";
}
else
{
    query = string.Format(@"SELECT * FROM Patient WHERE [{0}] = @p1", searchType);
}
</code>```

Body:
private void searchMulti(string searchType, string searchTerm)
    {
        {
            {
                var query = "";
                cb_Surname.Items.Clear();
                txt_patient_search.Clear();
                if (patient_NHSID.Equals(null) != true)
                {
                    pbar_search.Value = 2;
                    var connectionString = Settings.Default.CMTA_DBConnectionString;
                    using (var con = new SqlConnection(connectionString))
                    {
                        if (searchType != "NHSID")
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";
                        }
                        else
                        {
                            query = @"SELECT * FROM Patient WHERE @p2 = @p1";
                        }

                        using (var qry_search = new SqlCommand(query))
                        {
                            qry_search.Connection = con;
                            qry_search.Parameters.Add("@p1", SqlDbType.VarChar).Value = searchTerm;
                            qry_search.Parameters.Add("@p2", SqlDbType.VarChar).Value = searchType;

                            con.Open();
                            qry_search.ExecuteNonQuery();
                            int firstIteration = 0;

                            using (var rdr = qry_search.ExecuteReader())
                            {
                                if (rdr.HasRows)
                                {
                                    //Found Valid Patient Event
                                    pbar_search.Value = 6;
                                    pbox_tick.Show();
                                    foundValidPatient = true;
                                    ////////////////////////////

                                    while (rdr.Read())
                                    {
                                        if (firstIteration == 0)
                                        {
                                            pbar_search.Value = 8;
                                            cb_Surname.Text = rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                              rdr.GetString(2);
                                            firstIteration = 1;
                                        }
                                        cb_Surname.Items.Add(rdr.GetInt64(0) + " - " + rdr.GetString(1) + " - " +
                                                             rdr.GetString(2));
                                    }
                                }
                                else
                                {
                                    //Patient Not Found
                                    pbox_cross.Show();
                                    patientSelected = false;
                                    foundValidPatient = false;
                                }
                                con.Close();
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter Valid Text");
                    pbar_search.Value = 0;
                    pbox_cross.Show();
                }
            }
        }
    }

The method above isn't working. It should query the SQL Server database for a user entered term (such as textbox value) and query it for a searchtype (firstname) however when debugging the SQL query is executed but no rows are returned.

If I run the command without the parameters and insert actual values i.e (WHERE FirstName = 'Alan') it works perfectly.

What have I done incorrectly with this SQL query?

query = @"SELECT * FROM Patient WHERE @p2 = '@p1' ";

Many thanks!

Body:
You can't pass a column name in as a parameter, but what you can do is add it to your query string explicitly. You also might consider putting square brackets around the column name in case someone has a column name that is also a SQL keyword.

I have two examples of formatting a string with your column name in [] below:

if (searchType != "NHSID")
{
    query = $@"SELECT * FROM Patient WHERE [{searchType}] = '@p1'";
}
else
{
    query = string.Format(@"SELECT * FROM Patient WHERE [{0}] = @p1", searchType);
}


问:
Remove the "This is the format of your plot grid:" in a plotly subplot in a Jupyter Notebook
When using Plotly in a Jupyter Notebook plotting an offline iplot figure with subplots, before the figure I get the output:

```<code>This is the format of your plot grid:
[ (1,1) x1,y1 ]    [ (1,2) x2,y2 ]    [ (1,3) x3,y3 ]    [ (1,4) x4,y4 ]
[ (2,1) x5,y5 ]    [ (2,2) x6,y6 ]    [ (2,3) x7,y7 ]    [ (2,4) x8,y8 ]
[ (3,1) x9,y9 ]    [ (3,2) x10,y10 ]  [ (3,3) x11,y11 ]  [ (3,4) x12,y12 ]
[ (4,1) x13,y13 ]  [ (4,2) x14,y14 ]  [ (4,3) x15,y15 ]  [ (4,4) x16,y16 ]
</code>```

How do I remove this from the output?

Example code:

```<code>import plotly as pl
import plotly.graph_objs as go
import numpy as np

fig = pl.tools.make_subplots(cols=4, rows=4)

for col in range(1, 5):
    for row in range(1, 5):
        x = np.random.rand(500)
        trace = go.Histogram(x=x, histnorm='density')
        fig.append_trace(trace, row, col)

pl.offline.iplot(fig)
</code>```

答:
Figured it out, set the print_grid parameter to False:

```<code>fig = pl.tools.make_subplots(cols=4, rows=4, print_grid=False)
</code>```

Which I found in

```<code>help(pl.tools.make_subplots)
</code>```

Body:
When using Plotly in a Jupyter Notebook plotting an offline iplot figure with subplots, before the figure I get the output:

This is the format of your plot grid:
[ (1,1) x1,y1 ]    [ (1,2) x2,y2 ]    [ (1,3) x3,y3 ]    [ (1,4) x4,y4 ]
[ (2,1) x5,y5 ]    [ (2,2) x6,y6 ]    [ (2,3) x7,y7 ]    [ (2,4) x8,y8 ]
[ (3,1) x9,y9 ]    [ (3,2) x10,y10 ]  [ (3,3) x11,y11 ]  [ (3,4) x12,y12 ]
[ (4,1) x13,y13 ]  [ (4,2) x14,y14 ]  [ (4,3) x15,y15 ]  [ (4,4) x16,y16 ]

How do I remove this from the output?

Example code:

import plotly as pl
import plotly.graph_objs as go
import numpy as np

fig = pl.tools.make_subplots(cols=4, rows=4)

for col in range(1, 5):
    for row in range(1, 5):
        x = np.random.rand(500)
        trace = go.Histogram(x=x, histnorm='density')
        fig.append_trace(trace, row, col)

pl.offline.iplot(fig)

Body:
Figured it out, set the print_grid parameter to False:

fig = pl.tools.make_subplots(cols=4, rows=4, print_grid=False)

Which I found in

help(pl.tools.make_subplots)


问:
How to tell sympy to keep exact numbers as exact in integrate?
When I typed

```<code>>python
> from sympy import *
> x=symbols('x')
> integrate(1/4/sin(1/3*x),x)
</code>```

The output was

```<code>0.375*log(cos(0.333333333333333*x) - 1) - 0.375*log(cos(0.333333333333333*x) + 1)
</code>```

What should one do to tell sympy not to convert exact input to floating point? I know I could type the following instead

```<code>integrate(S('1/4')/sin(S('1/3')*x),x)
</code>```

And now the result is

```<code> 3*log(cos(x/3) - 1)/8 - 3*log(cos(x/3) + 1)/8
</code>```

But I'd like to get this result, without having to wrap each number with S('') as in the above.

Is there an option or module one needs to import for this?

Using

```<code>>conda list sympy
sympy                     1.0                      py36_0
</code>```

On linux.

答:
without having to wrap each number with S('')

This can be avoided by wrapping the entire expression in S(''):

```<code>integrate(S('1/4/sin(1/3*x)'), x)
</code>```

tell sympy not to convert exact input to floating point

It's not SymPy who evaluates 1/3 as a floating point number; it's Python. In sin(1/3*x), the division 1/3 occurs on Python level before SymPy objects such as x get involved.

Aside: with a more mathematically natural way of expressing the same formula,

```<code>integrate(1/(4*sin(x/3)), x)
</code>```

one does not need S() at all, since there is no division of scalars here. Indeed, 1/(4*sin(x/3)) parses as

```<code>Mul(Rational(1, 4), Pow(sin(Mul(Rational(1, 3), Symbol('x'))), Integer(-1)))
</code>```

while 1/4/sin(1/3*x) parses as

```<code>Mul(Float('0.25', prec=15), Pow(sin(Mul(Float('0.33333333333333331', prec=15), Symbol('x'))), Integer(-1)))
</code>```

Body:
When I typed

>python
> from sympy import *
> x=symbols('x')
> integrate(1/4/sin(1/3*x),x)

The output was

0.375*log(cos(0.333333333333333*x) - 1) - 0.375*log(cos(0.333333333333333*x) + 1)

What should one do to tell sympy not to convert exact input to floating point? I know I could type the following instead

integrate(S('1/4')/sin(S('1/3')*x),x)

And now the result is

 3*log(cos(x/3) - 1)/8 - 3*log(cos(x/3) + 1)/8

But I'd like to get this result, without having to wrap each number with S('') as in the above.

Is there an option or module one needs to import for this?

Using

>conda list sympy
sympy                     1.0                      py36_0

On linux.

Body:
without having to wrap each number with S('')

This can be avoided by wrapping the entire expression in S(''):

integrate(S('1/4/sin(1/3*x)'), x)

tell sympy not to convert exact input to floating point

It's not SymPy who evaluates 1/3 as a floating point number; it's Python. In sin(1/3*x), the division 1/3 occurs on Python level before SymPy objects such as x get involved.

Aside: with a more mathematically natural way of expressing the same formula,

integrate(1/(4*sin(x/3)), x)

one does not need S() at all, since there is no division of scalars here. Indeed, 1/(4*sin(x/3)) parses as

Mul(Rational(1, 4), Pow(sin(Mul(Rational(1, 3), Symbol('x'))), Integer(-1)))

while 1/4/sin(1/3*x) parses as

Mul(Float('0.25', prec=15), Pow(sin(Mul(Float('0.33333333333333331', prec=15), Symbol('x'))), Integer(-1)))


问:
.net / c# test wanted for a non techical MD
Dear all i am looking for an half finished .net application to test my .net c# applicants.

As I come from a differnt coding background, it is difficult for me to assess people skills hence a great test would do a good job!

Regarding checking candidates' test performance, I can ask a friend, no problem !

Does a practical test exist out there? Would I need to pay for it?

答: it sounds a nice idea but I am still keen on getting a proper c# test done infront of a PC within a controlled environment where the developer would need to read the code, understand what it does and add his necessary amends.</p>

OwnerDisplayName: frank publisher

LastEditorDisplayName: Tom Anderson


问:
MVC + IIS7 = CSS Issue
I have a web site running via IIS7 on Vista. The site is running on port 88, so http://localhost:88 should render the default /Home/Index view.

This works correctly, as do all other views.

However, one problem is resident. My script paths point to /Scripts/[FILE] and my CSS paths point to /Content/[FILE]. My assumption was that the /Content or /Scripts folder would always be at the root of the site as I have no intention to run this site in a virtual directory setting. Whenever the pages render, they have NO CSS or script! So everything looks wonky and the scripting obviously doesn't work, hence a lot of the views don't work either.

This is a very odd problem, one that I'm sure is a result of my lack of knowledge hosting things under IIS7. I'd appreciate any help anyone could offer. Thanks a lot!

答: From Control Panel, go to Turn Windows features on or off, then check Static Content in sub-sub-sub node of IIS.</p>

Title: MVC + IIS7 = CSS Issue


问:
Xpath - identify text that contains string 'AB' in 5th and 6th characters of a word
I am trying to write a matching XPath rule but I can't seem to pin point words with the exact letters in the 5th and 6th position.

example 'ab' in 'qwerabqwert'

```<code>/location1[Variable='variable1'][item1[contains(.,'AB')] or item1[contains(.,'ab')]
</code>```

Please help.

答:
You can use the substring() function in the below way:

```<code>/location1[Variable='variable1'][item1[substring(., 5, 2) = ('AB', 'ab')]]
</code>```

Body:
I am trying to write a matching XPath rule but I can't seem to pin point words with the exact letters in the 5th and 6th position.

example 'ab' in 'qwerabqwert'

/location1[Variable='variable1'][item1[contains(.,'AB')] or item1[contains(.,'ab')]

Please help.

Body:
You can use the substring() function in the below way:

/location1[Variable='variable1'][item1[substring(., 5, 2) = ('AB', 'ab')]]


问:
Laravel 5.2 CSRF Token expires too quickly
I am working on Laravel 5.2 application and I am facing this issue for all my views.

The CSRF token is getting expired too quickly. In fact, I am just occupying the time to fill up the form and as soon as I submit it,I get TokenMismatchException exception.

I tried to search for the problem on Google, found git for some similar issues and even tried on Laracast for similar problem without any success.

My .env file has some lines like this:

```<code>CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
</code>```

And this is my post method for login:

```<code>public function postLogin(CookieJar $cookieJar, Request $request)
    {

        $this->validate($request, [
           'email1' => 'required|email',
            'password' => 'required|string'
        ]);
        if($user = User::whereEmail($request->email1)->first() ) {
            if(Hash::check($request['password'], $user->getAttributes()['password'])) {

                if(!$user->getAttributes()['is_active']) {
                    return redirect('/login')->withErrors('Your Account is not Activated Yet!');
                } else if($user->getAttributes()['is_deleted']) {
                    return redirect('/login')->withErrors('Your Account is Banned!');
                } else {
                    # Success
                    $cookie = Cookie::make('user_id', $user->getAttributes()['id'], 864000);
                    return redirect('/')->with('message', 'You have Successfully Logged In!')->withCookie($cookie);
                }
            } else {
                return redirect('/login')->withErrors('Your Login Information is Wrong!');
            }
        } else {
            return redirect('/login')->withErrors('Your Login Information is Wrong!');
        }
    }
</code>```

Please help me.

Added .env file content and postLogin method.

答:
You could have a problem with sessions not being saved in your environment. Perhaps do php artisan cache:clear or manually clean and reset priveleges in storage/framework/sessions/ if sessions are saved to file.

I'm assuming you already add the token to your form properly with csrf_token() or something that provides it.

Body:
I am working on Laravel 5.2 application and I am facing this issue for all my views.

The CSRF token is getting expired too quickly. In fact, I am just occupying the time to fill up the form and as soon as I submit it,I get TokenMismatchException exception.

I tried to search for the problem on Google, found git for some similar issues and even tried on Laracast for similar problem without any success.

My .env file has some lines like this:

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

And this is my post method for login:

public function postLogin(CookieJar $cookieJar, Request $request)
    {

        $this->validate($request, [
           'email1' => 'required|email',
            'password' => 'required|string'
        ]);
        if($user = User::whereEmail($request->email1)->first() ) {
            if(Hash::check($request['password'], $user->getAttributes()['password'])) {

                if(!$user->getAttributes()['is_active']) {
                    return redirect('/login')->withErrors('Your Account is not Activated Yet!');
                } else if($user->getAttributes()['is_deleted']) {
                    return redirect('/login')->withErrors('Your Account is Banned!');
                } else {
                    # Success
                    $cookie = Cookie::make('user_id', $user->getAttributes()['id'], 864000);
                    return redirect('/')->with('message', 'You have Successfully Logged In!')->withCookie($cookie);
                }
            } else {
                return redirect('/login')->withErrors('Your Login Information is Wrong!');
            }
        } else {
            return redirect('/login')->withErrors('Your Login Information is Wrong!');
        }
    }

Please help me.

Added .env file content and postLogin method.