问:
Using linear interpolation to predict value in matlab
I have a set of data and would like to use linear interpolation in Matlab to find the corresponding value of a specific point.

```<code>x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');
</code>```

After doing this, is there any way for me to find the value of x given a value of y? For example, when y = 3.5, x = ?

答:
Well, Since you want to use Linear Interpolation model in order to know interpolated value all you need is 2 samples around it.

For example, if you wonder when you get the value y = 3.5 all you need to find 2 adjacent points with one having value lower than 3.5 and the other value higher than 3.5.

Then all needed is to use Line Equation to infer the exact value of x at the point.

What I'm trying to say is if you only interested to find the x for a certain y value, there is no need to interpolate all data.

Body:
I have a set of data and would like to use linear interpolation in Matlab to find the corresponding value of a specific point.

x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');

After doing this, is there any way for me to find the value of x given a value of y? For example, when y = 3.5, x = ?


来源: stackexchange

问:
How to make particular sub-select options appear when the value of the parent select option is changed
I am creating Select option.

Example: It's a sort of code I will be using for categories. When user selects on of the parent select's option another select option to be displayed as sub category of that category.

My code:

```<code><form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select>
<option value="car">car</option>
<option value="phone">phone</option>
<option value="tv">tv</option>
</select>

<select>
<option value="toyota">toyota</option>
<option value="nissan">nissan</option>
<option value="bmw">BMW</option>
</select>
</form>
</code>```

答:
$("#select1").change(function () {
            if ($(this).data('options') == undefined) {
                $(this).data('options', $('#select2 option').clone());
            }
            var id = $(this).val();
            if (id == "all") {
                var options = $(this).data('options');
                $('#select2').html(options);
            }
            else {
                var options = $(this).data('options').filter('[data-name=' + id + ']');
                $('#select2').html(options);
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select1" id="select1">
        <option value="all">All</option>
        <option value="1">car</option>
        <option value="2">phone</option>
        <option value="3">tv</option>
    </select>

    <select name="select2" id="select2">
        <option value="all">All</option>
        <option data-name="1" value="toyota">toyota</option>
        <option data-name="1" value="nissan">nissan</option>
        <option data-name="1" value="bmw">bmw</option>
        <option data-name="2" value="Iphone">Iphone</option>
        <option data-name="2" value="LG">LG</option>
        <option data-name="2" value="Samsung">Samsung</option>
        <option data-name="3" value="Philips">Philips</option>
        <option data-name="3" value="Samsung">Samsung</option>
    </select></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating Select option.

Example: It's a sort of code I will be using for categories. When user selects on of the parent select's option another select option to be displayed as sub category of that category.

My code:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select>
<option value="car">car</option>
<option value="phone">phone</option>
<option value="tv">tv</option>
</select>

<select>
<option value="toyota">toyota</option>
<option value="nissan">nissan</option>
<option value="bmw">BMW</option>
</select>
</form>

Body:
$("#select1").change(function () {
            if ($(this).data('options') == undefined) {
                $(this).data('options', $('#select2 option').clone());
            }
            var id = $(this).val();
            if (id == "all") {
                var options = $(this).data('options');
                $('#select2').html(options);
            }
            else {
                var options = $(this).data('options').filter('[data-name=' + id + ']');
                $('#select2').html(options);
            }
        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select1" id="select1">
        <option value="all">All</option>
        <option value="1">car</option>
        <option value="2">phone</option>
        <option value="3">tv</option>
    </select>

    <select name="select2" id="select2">
        <option value="all">All</option>
        <option data-name="1" value="toyota">toyota</option>
        <option data-name="1" value="nissan">nissan</option>
        <option data-name="1" value="bmw">bmw</option>
        <option data-name="2" value="Iphone">Iphone</option>
        <option data-name="2" value="LG">LG</option>
        <option data-name="2" value="Samsung">Samsung</option>
        <option data-name="3" value="Philips">Philips</option>
        <option data-name="3" value="Samsung">Samsung</option>
    </select>


问:
How to configure DCOM configuration for Export To Excel?
I am implementing Export To Excel functionality in one of my asp.net application. I have two servers(QA and Development). In Development server it works fine but in QA server i am getting below error.

```<code>    An exception of type System.Runtime.InteropServices.COMException occurred and was
caught. Source:mscorlib;Message:Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a The
server process could not be started because the configured identity is incorrect.  Check the username and password. (Exception from HRESULT:
0x8000401A).;Target:System.MarshalByRefObject AllocateUninitializedObject(System.RuntimeType);StackTrace:   at
System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)     at
System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)     at
System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)     at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean&
bNeedSecurityCheck)     at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)     at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)     at
System.Activator.CreateInstance(Type type, Boolean nonPublic)     at System.Activator.CreateInstance(Type type)     at XXXXXXXXXXXXX  Method - XXXXXXXXXXXXX
</code>```

I have configured same thing in both servers but still QA server not working properly. What should i do next? Any idea...??

答:
I faced a similar issue where the identity was lost in between the session and I had to give the credentials again to fix it temporarily. While investigating it, I came across an article that suggested granting the domain account that is used as identity with 'Logon as a Batch job' privilege as the identity would be lost when the AD performs an update if the privilege is not granted.

https://support.microsoft.com/en-za/help/312497/prb-com-application-under-domain-account-fails-intermittently

https://www.brooksnet.com/faq/granting-logon-as-batch-privilege

Body:
I am implementing Export To Excel functionality in one of my asp.net application. I have two servers(QA and Development). In Development server it works fine but in QA server i am getting below error.

    An exception of type System.Runtime.InteropServices.COMException occurred and was
caught. Source:mscorlib;Message:Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a The
server process could not be started because the configured identity is incorrect.  Check the username and password. (Exception from HRESULT:
0x8000401A).;Target:System.MarshalByRefObject AllocateUninitializedObject(System.RuntimeType);StackTrace:   at
System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)     at
System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)     at
System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)     at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean&
bNeedSecurityCheck)     at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)     at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)     at
System.Activator.CreateInstance(Type type, Boolean nonPublic)     at System.Activator.CreateInstance(Type type)     at XXXXXXXXXXXXX  Method - XXXXXXXXXXXXX

I have configured same thing in both servers but still QA server not working properly. What should i do next? Any idea...??


问:
Getting error at console jQuery : not a function
In MVC I am getting following error :

jQuery.Deferred exception: $(...).parents(...).andSelf is not a function

I just Installed the latest version of jQuery via NUGET. I'm getting stuck because of the above mentioned error.

答:
I just replaced andSelf() with addBack() in jQuery min file .

Now working perfectly .


问:
error deploying an API rails app on heroku
i'm trying to deploy a simple rails app that access and retrieve data from the openweathermap API and display the info. Locally I could search and see the results, but after deploying to Heroku, I get an error everytime I try to retrieve data from the API. IN the logs, it says

ActionView::Template::Error (undefined method `[]' for nil:NilClass):
    2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     1:
Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %>

etc..

But I really don't know where to fix it

```<code>2017-03-28T22:34:26.249586+00:00 heroku[router]: at=info method=GET path="/assets/application-ee2ce37cbf576e743a25b85e1834b055fe1564a1a8b891ed64f7fd521f2f88dc.js" host=frozen-river-81321.herokuapp.com request_id=4954e1e4-8411-4365-b36f-87bddf0b5693 fwd="83.138.193.223" dyno=web.1 connect=0ms service=6ms status=304 bytes=48 protocol=https
2017-03-28T22:34:26.489479+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=b25b4025-5c8e-4e70-8008-ad3613062e57 fwd="83.138.193.223" dyno=web.1 connect=1ms service=1ms status=200 bytes=143 protocol=https
2017-03-28T22:34:30.360691+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=6148657c-8bdf-4ff0-b503-5b2f798c48bd fwd="83.138.193.223" dyno=web.1 connect=1ms service=48ms status=500 bytes=1669 protocol=https
2017-03-28T22:34:30.333448+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 22:34:30 +0000
2017-03-28T22:34:30.336021+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Processing by ForecastController#show as HTML
2017-03-28T22:34:30.336091+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T22:34:30.377650+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Completed 500 Internal Server Error in 41ms
2017-03-28T22:34:30.378635+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]
2017-03-28T22:34:30.378666+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] NoMethodError (undefined method `[]' for nil:NilClass):
2017-03-28T22:34:30.378724+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]
2017-03-28T22:34:30.378760+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] app/controllers/forecast_controller.rb:10:in `show'
2017-03-28T22:39:39.000000+00:00 app[api]: Build started by user
2017-03-28T22:39:59.041896+00:00 app[api]: Release v8 created by user
2017-03-28T22:39:59.041896+00:00 app[api]: Deploy fb86924 by user
2017-03-28T22:39:59.418597+00:00 heroku[web.1]: Restarting
2017-03-28T22:39:59.419192+00:00 heroku[web.1]: State changed from up to starting
2017-03-28T22:39:39.000000+00:00 app[api]: Build succeeded
2017-03-28T22:39:59.349997+00:00 app[api]: Release v8 created by user
2017-03-28T22:40:00.214967+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2017-03-28T22:40:00.229628+00:00 app[web.1]: === puma shutdown: 2017-03-28 22:40:00 +0000 ===
2017-03-28T22:40:00.229632+00:00 app[web.1]: - Goodbye!
2017-03-28T22:40:00.229478+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish
2017-03-28T22:40:00.230195+00:00 app[web.1]: Exiting
2017-03-28T22:40:00.540700+00:00 heroku[web.1]: Process exited with status 0
2017-03-28T22:40:02.360668+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 55627 -e production`
2017-03-28T22:40:06.219721+00:00 app[web.1]: => Booting Puma
2017-03-28T22:40:06.219741+00:00 app[web.1]: => Rails 5.0.2 application starting in production on http://0.0.0.0:55627
2017-03-28T22:40:06.219742+00:00 app[web.1]: => Run `rails server -h` for more startup options
2017-03-28T22:40:06.219743+00:00 app[web.1]: Puma starting in single mode...
2017-03-28T22:40:06.219748+00:00 app[web.1]: * Version 3.8.2 (ruby 2.2.6-p396), codename: Sassy Salamander
2017-03-28T22:40:06.219749+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-03-28T22:40:06.219844+00:00 app[web.1]: * Listening on tcp://0.0.0.0:55627
2017-03-28T22:40:06.220162+00:00 app[web.1]: Use Ctrl-C to stop
2017-03-28T22:40:06.219749+00:00 app[web.1]: * Environment: production
2017-03-28T22:40:06.598858+00:00 heroku[web.1]: State changed from starting to up
2017-03-28T22:40:42.536212+00:00 heroku[router]: at=info method=GET path="/" host=frozen-river-81321.herokuapp.com request_id=612b3cbc-181e-469d-9aaa-873bbf9968f2 fwd="83.138.193.223" dyno=web.1 connect=0ms service=52ms status=200 bytes=1849 protocol=http
2017-03-28T22:40:42.467816+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Started GET "/" for 83.138.193.223 at 2017-03-28 22:40:42 +0000
2017-03-28T22:40:42.469755+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Processing by ForecastController#index as HTML
2017-03-28T22:40:42.510151+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2]   Rendering forecast/index.html.erb within layouts/application
2017-03-28T22:40:42.514148+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2]   Rendered forecast/index.html.erb within layouts/application (3.9ms)
2017-03-28T22:40:42.515750+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Completed 200 OK in 46ms (Views: 6.8ms)
2017-03-28T22:40:43.593017+00:00 heroku[router]: at=info method=GET path="/assets/application-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css" host=frozen-river-81321.herokuapp.com request_id=4a90a1ba-f4e4-4f7c-a943-87d4f1a3970e fwd="83.138.193.223" dyno=web.1 connect=0ms service=2ms status=200 bytes=195 protocol=http
2017-03-28T22:40:43.575325+00:00 heroku[router]: at=info method=GET path="/assets/application-ee2ce37cbf576e743a25b85e1834b055fe1564a1a8b891ed64f7fd521f2f88dc.js" host=frozen-river-81321.herokuapp.com request_id=6135d581-15ab-473d-a87a-1596e7e03090 fwd="83.138.193.223" dyno=web.1 connect=0ms service=6ms status=200 bytes=46469 protocol=http
2017-03-28T22:40:44.234523+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=be9a2e95-846e-4d30-851b-81bafa7e56f7 fwd="83.138.193.223" dyno=web.1 connect=0ms service=1ms status=200 bytes=143 protocol=http
2017-03-28T22:40:47.756522+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=9c9cbecd-7e71-4e94-a776-a29666ef6f9d fwd="83.138.193.223" dyno=web.1 connect=0ms service=45ms status=500 bytes=1669 protocol=http
2017-03-28T22:40:47.716158+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 22:40:47 +0000
2017-03-28T22:40:47.717619+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Processing by ForecastController#show as HTML
2017-03-28T22:40:47.717714+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T22:40:47.757911+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Completed 500 Internal Server Error in 40ms
2017-03-28T22:40:47.758737+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]
2017-03-28T22:40:47.758792+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] NoMethodError (undefined method `[]' for nil:NilClass):
2017-03-28T22:40:47.758844+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]
2017-03-28T22:40:47.758878+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] app/controllers/forecast_controller.rb:10:in `show'

2017-03-28T23:12:19.347563+00:00 heroku[web.1]: Restarting
2017-03-28T23:12:19.348091+00:00 heroku[web.1]: State changed from up to starting
2017-03-28T23:12:20.005914+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2017-03-28T23:12:20.018999+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish
2017-03-28T23:12:20.019211+00:00 app[web.1]: === puma shutdown: 2017-03-28 23:12:20 +0000 ===
2017-03-28T23:12:20.019217+00:00 app[web.1]: - Goodbye!
2017-03-28T23:12:20.019356+00:00 app[web.1]: Exiting
2017-03-28T23:12:20.264562+00:00 heroku[web.1]: Process exited with status 0
2017-03-28T23:12:22.066287+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 36303 -e production`
2017-03-28T23:12:26.311385+00:00 app[web.1]: => Booting Puma
2017-03-28T23:12:26.311398+00:00 app[web.1]: => Rails 5.0.2 application starting in production on http://0.0.0.0:36303
2017-03-28T23:12:26.311399+00:00 app[web.1]: => Run `rails server -h` for more startup options
2017-03-28T23:12:26.311400+00:00 app[web.1]: Puma starting in single mode...
2017-03-28T23:12:26.311404+00:00 app[web.1]: * Version 3.8.2 (ruby 2.2.6-p396), codename: Sassy Salamander
2017-03-28T23:12:26.311405+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-03-28T23:12:26.311406+00:00 app[web.1]: * Environment: production
2017-03-28T23:12:26.311509+00:00 app[web.1]: * Listening on tcp://0.0.0.0:36303
2017-03-28T23:12:26.311880+00:00 app[web.1]: Use Ctrl-C to stop
2017-03-28T23:12:26.769039+00:00 heroku[web.1]: State changed from starting to up
2017-03-28T23:13:33.521802+00:00 heroku[router]: at=info method=GET path="/" host=frozen-river-81321.herokuapp.com request_id=455bb1ab-e6d2-4825-9628-c1553b31a785 fwd="83.138.193.223" dyno=web.1 connect=1ms service=53ms status=200 bytes=1849 protocol=http
2017-03-28T23:13:33.642413+00:00 heroku[router]: at=info method=GET path="/assets/application-d403d1f8080b3ad942ca24506e1f1740ea2e952a983bd838c871305f1d738e17.js" host=frozen-river-81321.herokuapp.com request_id=073f6766-124f-4294-8906-bec4e53e6866 fwd="83.138.193.223" dyno=web.1 connect=1ms service=5ms status=200 bytes=46527 protocol=http
2017-03-28T23:13:33.654785+00:00 heroku[router]: at=info method=GET path="/assets/application-38d14876a278d516415b9f33c99616f2f16aee4b8f502e55085ad10a5781bbdd.css" host=frozen-river-81321.herokuapp.com request_id=41a6d3e5-2b4c-4ce4-8fcf-c821a2c0f00f fwd="83.138.193.223" dyno=web.1 connect=1ms service=2ms status=200 bytes=217 protocol=http
2017-03-28T23:13:33.449653+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Started GET "/" for 83.138.193.223 at 2017-03-28 23:13:33 +0000
2017-03-28T23:13:33.454539+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Processing by ForecastController#index as HTML
2017-03-28T23:13:33.487661+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785]   Rendering forecast/index.html.erb within layouts/application
2017-03-28T23:13:33.494523+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785]   Rendered forecast/index.html.erb within layouts/application (6.7ms)
2017-03-28T23:13:33.496670+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Completed 200 OK in 44ms (Views: 10.8ms)
2017-03-28T23:13:34.546011+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=51712a1f-3d81-4a80-bc1a-3d8ea6415c30 fwd="83.138.193.223" dyno=web.1 connect=1ms service=2ms status=200 bytes=143 protocol=http
2017-03-28T23:13:39.242712+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=9630d05d-78ea-4e76-9c22-17a05ce56b42 fwd="83.138.193.223" dyno=web.1 connect=2ms service=53ms status=500 bytes=1669 protocol=http
2017-03-28T23:13:39.198411+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Processing by ForecastController#show as HTML
2017-03-28T23:13:39.197228+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 23:13:39 +0000
2017-03-28T23:13:39.198518+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T23:13:39.236523+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Rendering forecast/show.html.erb within layouts/application
2017-03-28T23:13:39.238896+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Completed 500 Internal Server Error in 40ms
2017-03-28T23:13:39.238659+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Rendered forecast/show.html.erb within layouts/application (2.0ms)
2017-03-28T23:13:39.240291+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]
2017-03-28T23:13:39.240332+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] ActionView::Template::Error (undefined method `[]' for nil:NilClass):
2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     1: <h1>Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %></h1>
2017-03-28T23:13:39.240643+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     2: <p>Find me in app/views/forecast/show.html.erb</p>
2017-03-28T23:13:39.240645+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     4: <div class="result">
2017-03-28T23:13:39.240644+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     3: <% if !@w.nil?  %>
2017-03-28T23:13:39.240671+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]
2017-03-28T23:13:39.240709+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] app/views/forecast/show.html.erb:1:in `_app_views_forecast_show_html_erb__4480134760202078404_70214950094520
</code>```

答:
Your log said:

```<code>ActionView::Template::Error (undefined method `[]' for nil:NilClass): 2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] 1:

Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %>
</code>```

Look like your variable @w or @w["sys"] is nil. I think you should check it.

```<code>Forecast for <%=@w["name"] if @w.present? %> , <%=@w["sys"]["country"] if @w.present? && if @w["sys"].present? %>
</code>```

Hope I can help!

Body:
i'm trying to deploy a simple rails app that access and retrieve data from the openweathermap API and display the info. Locally I could search and see the results, but after deploying to Heroku, I get an error everytime I try to retrieve data from the API. IN the logs, it says

ActionView::Template::Error (undefined method `[]' for nil:NilClass):
    2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     1:
Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %>

etc..

But I really don't know where to fix it

2017-03-28T22:34:26.249586+00:00 heroku[router]: at=info method=GET path="/assets/application-ee2ce37cbf576e743a25b85e1834b055fe1564a1a8b891ed64f7fd521f2f88dc.js" host=frozen-river-81321.herokuapp.com request_id=4954e1e4-8411-4365-b36f-87bddf0b5693 fwd="83.138.193.223" dyno=web.1 connect=0ms service=6ms status=304 bytes=48 protocol=https
2017-03-28T22:34:26.489479+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=b25b4025-5c8e-4e70-8008-ad3613062e57 fwd="83.138.193.223" dyno=web.1 connect=1ms service=1ms status=200 bytes=143 protocol=https
2017-03-28T22:34:30.360691+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=6148657c-8bdf-4ff0-b503-5b2f798c48bd fwd="83.138.193.223" dyno=web.1 connect=1ms service=48ms status=500 bytes=1669 protocol=https
2017-03-28T22:34:30.333448+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 22:34:30 +0000
2017-03-28T22:34:30.336021+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Processing by ForecastController#show as HTML
2017-03-28T22:34:30.336091+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T22:34:30.377650+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] Completed 500 Internal Server Error in 41ms
2017-03-28T22:34:30.378635+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]
2017-03-28T22:34:30.378666+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] NoMethodError (undefined method `[]' for nil:NilClass):
2017-03-28T22:34:30.378724+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd]
2017-03-28T22:34:30.378760+00:00 app[web.1]: [6148657c-8bdf-4ff0-b503-5b2f798c48bd] app/controllers/forecast_controller.rb:10:in `show'
2017-03-28T22:39:39.000000+00:00 app[api]: Build started by user
2017-03-28T22:39:59.041896+00:00 app[api]: Release v8 created by user
2017-03-28T22:39:59.041896+00:00 app[api]: Deploy fb86924 by user
2017-03-28T22:39:59.418597+00:00 heroku[web.1]: Restarting
2017-03-28T22:39:59.419192+00:00 heroku[web.1]: State changed from up to starting
2017-03-28T22:39:39.000000+00:00 app[api]: Build succeeded
2017-03-28T22:39:59.349997+00:00 app[api]: Release v8 created by user
2017-03-28T22:40:00.214967+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2017-03-28T22:40:00.229628+00:00 app[web.1]: === puma shutdown: 2017-03-28 22:40:00 +0000 ===
2017-03-28T22:40:00.229632+00:00 app[web.1]: - Goodbye!
2017-03-28T22:40:00.229478+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish
2017-03-28T22:40:00.230195+00:00 app[web.1]: Exiting
2017-03-28T22:40:00.540700+00:00 heroku[web.1]: Process exited with status 0
2017-03-28T22:40:02.360668+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 55627 -e production`
2017-03-28T22:40:06.219721+00:00 app[web.1]: => Booting Puma
2017-03-28T22:40:06.219741+00:00 app[web.1]: => Rails 5.0.2 application starting in production on http://0.0.0.0:55627
2017-03-28T22:40:06.219742+00:00 app[web.1]: => Run `rails server -h` for more startup options
2017-03-28T22:40:06.219743+00:00 app[web.1]: Puma starting in single mode...
2017-03-28T22:40:06.219748+00:00 app[web.1]: * Version 3.8.2 (ruby 2.2.6-p396), codename: Sassy Salamander
2017-03-28T22:40:06.219749+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-03-28T22:40:06.219844+00:00 app[web.1]: * Listening on tcp://0.0.0.0:55627
2017-03-28T22:40:06.220162+00:00 app[web.1]: Use Ctrl-C to stop
2017-03-28T22:40:06.219749+00:00 app[web.1]: * Environment: production
2017-03-28T22:40:06.598858+00:00 heroku[web.1]: State changed from starting to up
2017-03-28T22:40:42.536212+00:00 heroku[router]: at=info method=GET path="/" host=frozen-river-81321.herokuapp.com request_id=612b3cbc-181e-469d-9aaa-873bbf9968f2 fwd="83.138.193.223" dyno=web.1 connect=0ms service=52ms status=200 bytes=1849 protocol=http
2017-03-28T22:40:42.467816+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Started GET "/" for 83.138.193.223 at 2017-03-28 22:40:42 +0000
2017-03-28T22:40:42.469755+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Processing by ForecastController#index as HTML
2017-03-28T22:40:42.510151+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2]   Rendering forecast/index.html.erb within layouts/application
2017-03-28T22:40:42.514148+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2]   Rendered forecast/index.html.erb within layouts/application (3.9ms)
2017-03-28T22:40:42.515750+00:00 app[web.1]: [612b3cbc-181e-469d-9aaa-873bbf9968f2] Completed 200 OK in 46ms (Views: 6.8ms)
2017-03-28T22:40:43.593017+00:00 heroku[router]: at=info method=GET path="/assets/application-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css" host=frozen-river-81321.herokuapp.com request_id=4a90a1ba-f4e4-4f7c-a943-87d4f1a3970e fwd="83.138.193.223" dyno=web.1 connect=0ms service=2ms status=200 bytes=195 protocol=http
2017-03-28T22:40:43.575325+00:00 heroku[router]: at=info method=GET path="/assets/application-ee2ce37cbf576e743a25b85e1834b055fe1564a1a8b891ed64f7fd521f2f88dc.js" host=frozen-river-81321.herokuapp.com request_id=6135d581-15ab-473d-a87a-1596e7e03090 fwd="83.138.193.223" dyno=web.1 connect=0ms service=6ms status=200 bytes=46469 protocol=http
2017-03-28T22:40:44.234523+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=be9a2e95-846e-4d30-851b-81bafa7e56f7 fwd="83.138.193.223" dyno=web.1 connect=0ms service=1ms status=200 bytes=143 protocol=http
2017-03-28T22:40:47.756522+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=9c9cbecd-7e71-4e94-a776-a29666ef6f9d fwd="83.138.193.223" dyno=web.1 connect=0ms service=45ms status=500 bytes=1669 protocol=http
2017-03-28T22:40:47.716158+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 22:40:47 +0000
2017-03-28T22:40:47.717619+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Processing by ForecastController#show as HTML
2017-03-28T22:40:47.717714+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T22:40:47.757911+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] Completed 500 Internal Server Error in 40ms
2017-03-28T22:40:47.758737+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]
2017-03-28T22:40:47.758792+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] NoMethodError (undefined method `[]' for nil:NilClass):
2017-03-28T22:40:47.758844+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d]
2017-03-28T22:40:47.758878+00:00 app[web.1]: [9c9cbecd-7e71-4e94-a776-a29666ef6f9d] app/controllers/forecast_controller.rb:10:in `show'

2017-03-28T23:12:19.347563+00:00 heroku[web.1]: Restarting
2017-03-28T23:12:19.348091+00:00 heroku[web.1]: State changed from up to starting
2017-03-28T23:12:20.005914+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2017-03-28T23:12:20.018999+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish
2017-03-28T23:12:20.019211+00:00 app[web.1]: === puma shutdown: 2017-03-28 23:12:20 +0000 ===
2017-03-28T23:12:20.019217+00:00 app[web.1]: - Goodbye!
2017-03-28T23:12:20.019356+00:00 app[web.1]: Exiting
2017-03-28T23:12:20.264562+00:00 heroku[web.1]: Process exited with status 0
2017-03-28T23:12:22.066287+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 36303 -e production`
2017-03-28T23:12:26.311385+00:00 app[web.1]: => Booting Puma
2017-03-28T23:12:26.311398+00:00 app[web.1]: => Rails 5.0.2 application starting in production on http://0.0.0.0:36303
2017-03-28T23:12:26.311399+00:00 app[web.1]: => Run `rails server -h` for more startup options
2017-03-28T23:12:26.311400+00:00 app[web.1]: Puma starting in single mode...
2017-03-28T23:12:26.311404+00:00 app[web.1]: * Version 3.8.2 (ruby 2.2.6-p396), codename: Sassy Salamander
2017-03-28T23:12:26.311405+00:00 app[web.1]: * Min threads: 5, max threads: 5
2017-03-28T23:12:26.311406+00:00 app[web.1]: * Environment: production
2017-03-28T23:12:26.311509+00:00 app[web.1]: * Listening on tcp://0.0.0.0:36303
2017-03-28T23:12:26.311880+00:00 app[web.1]: Use Ctrl-C to stop
2017-03-28T23:12:26.769039+00:00 heroku[web.1]: State changed from starting to up
2017-03-28T23:13:33.521802+00:00 heroku[router]: at=info method=GET path="/" host=frozen-river-81321.herokuapp.com request_id=455bb1ab-e6d2-4825-9628-c1553b31a785 fwd="83.138.193.223" dyno=web.1 connect=1ms service=53ms status=200 bytes=1849 protocol=http
2017-03-28T23:13:33.642413+00:00 heroku[router]: at=info method=GET path="/assets/application-d403d1f8080b3ad942ca24506e1f1740ea2e952a983bd838c871305f1d738e17.js" host=frozen-river-81321.herokuapp.com request_id=073f6766-124f-4294-8906-bec4e53e6866 fwd="83.138.193.223" dyno=web.1 connect=1ms service=5ms status=200 bytes=46527 protocol=http
2017-03-28T23:13:33.654785+00:00 heroku[router]: at=info method=GET path="/assets/application-38d14876a278d516415b9f33c99616f2f16aee4b8f502e55085ad10a5781bbdd.css" host=frozen-river-81321.herokuapp.com request_id=41a6d3e5-2b4c-4ce4-8fcf-c821a2c0f00f fwd="83.138.193.223" dyno=web.1 connect=1ms service=2ms status=200 bytes=217 protocol=http
2017-03-28T23:13:33.449653+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Started GET "/" for 83.138.193.223 at 2017-03-28 23:13:33 +0000
2017-03-28T23:13:33.454539+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Processing by ForecastController#index as HTML
2017-03-28T23:13:33.487661+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785]   Rendering forecast/index.html.erb within layouts/application
2017-03-28T23:13:33.494523+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785]   Rendered forecast/index.html.erb within layouts/application (6.7ms)
2017-03-28T23:13:33.496670+00:00 app[web.1]: [455bb1ab-e6d2-4825-9628-c1553b31a785] Completed 200 OK in 44ms (Views: 10.8ms)
2017-03-28T23:13:34.546011+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=frozen-river-81321.herokuapp.com request_id=51712a1f-3d81-4a80-bc1a-3d8ea6415c30 fwd="83.138.193.223" dyno=web.1 connect=1ms service=2ms status=200 bytes=143 protocol=http
2017-03-28T23:13:39.242712+00:00 heroku[router]: at=info method=GET path="/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" host=frozen-river-81321.herokuapp.com request_id=9630d05d-78ea-4e76-9c22-17a05ce56b42 fwd="83.138.193.223" dyno=web.1 connect=2ms service=53ms status=500 bytes=1669 protocol=http
2017-03-28T23:13:39.198411+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Processing by ForecastController#show as HTML
2017-03-28T23:13:39.197228+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Started GET "/forecast/show?utf8=%E2%9C%93&lat=76.26&lon=78.5&commit=Search" for 83.138.193.223 at 2017-03-28 23:13:39 +0000
2017-03-28T23:13:39.198518+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Parameters: {"utf8"=>"✓", "lat"=>"76.26", "lon"=>"78.5", "commit"=>"Search"}
2017-03-28T23:13:39.236523+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Rendering forecast/show.html.erb within layouts/application
2017-03-28T23:13:39.238896+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] Completed 500 Internal Server Error in 40ms
2017-03-28T23:13:39.238659+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]   Rendered forecast/show.html.erb within layouts/application (2.0ms)
2017-03-28T23:13:39.240291+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]
2017-03-28T23:13:39.240332+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] ActionView::Template::Error (undefined method `[]' for nil:NilClass):
2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     1:
Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %>

2017-03-28T23:13:39.240643+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     2:
Find me in app/views/forecast/show.html.erb

2017-03-28T23:13:39.240645+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     4:

2017-03-28T23:13:39.240644+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]     3: <% if !@w.nil?  %>
2017-03-28T23:13:39.240671+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42]
2017-03-28T23:13:39.240709+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] app/views/forecast/show.html.erb:1:in `_app_views_forecast_show_html_erb__4480134760202078404_70214950094520

Body:
Your log said:

ActionView::Template::Error (undefined method `[]' for nil:NilClass): 2017-03-28T23:13:39.240642+00:00 app[web.1]: [9630d05d-78ea-4e76-9c22-17a05ce56b42] 1:

Forecast for <%=@w["name"] %> , <%=@w["sys"]["country"] %>

Look like your variable @w or @w["sys"] is nil. I think you should check it.

Forecast for <%=@w["name"] if @w.present? %> , <%=@w["sys"]["country"] if @w.present? && if @w["sys"].present? %>

Hope I can help!


问:
win32: check if window is minimized
How can one check whether a window is minimized using the win32 api?</p>

答:
Try GetWindowLong and test for the WS_MINIMIZE style:

```<code>LONG lStyles = GetWindowLong(GWL_STYLE);

if( lStyles & WS_MINIMIZE )
    ATLTRACE(_T("minimized"));
else
    ATLTRACE(_T("not minimized"));
</code>```

You can also query for GWL_EXSTYLES

ContentLicense: CC BY-SA 2.5

Title: win32: check if window is minimized

Body:
Try GetWindowLong and test for the WS_MINIMIZE style:

LONG lStyles = GetWindowLong(GWL_STYLE);

if( lStyles & WS_MINIMIZE )
    ATLTRACE(_T("minimized"));
else
    ATLTRACE(_T("not minimized"));

You can also query for GWL_EXSTYLES


问:
Notification not showing in Oreo
Normal Notification Builder doesn't show notifications on Android O.

How could I show notification on Android 8 Oreo?

Is there any new piece of code to add for showing notification on Android O?

答:
In Android O it's a must to use a channel with your Notification Builder

below is a sample code :

```<code>// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
            .setContentTitle("New Message")
            .setContentText("You've received new messages.")
            .setSmallIcon(R.drawable.ic_notify_status)
            .setChannelId(CHANNEL_ID)
            .build();
</code>```

Or with Handling compatibility by:

```<code>NotificationCompat notification =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setChannelId(CHANNEL_ID).build();
</code>```

Now make it notify

```<code>NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
mNotificationManager.notify(notifyID , notification);
</code>```

or if you want a simple fix then use the following code:

```<code>NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       mNotificationManager.createNotificationChannel(mChannel);
    }
</code>```

Updates:
NotificationCompat.Builder reference

```<code>NotificationCompat.Builder(Context context)
</code>```

This constructor was deprecated in API level 26.0.0
so you should use

```<code>Builder(Context context, String channelId)
</code>```

so no need to setChannelId with the new constructor.

And you should use the latest of AppCompat library currently 26.0.2

```<code>compile "com.android.support:appcompat-v7:26.0.+"
</code>```

Source from Android Developers Channel on Youtube

Also, you could check official Android Docs

ContentLicense: CC BY-SA 4.0

Title: Notification not showing in Oreo

Body:
In Android O it's a must to use a channel with your Notification Builder

below is a sample code :

// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
            .setContentTitle("New Message")
            .setContentText("You've received new messages.")
            .setSmallIcon(R.drawable.ic_notify_status)
            .setChannelId(CHANNEL_ID)
            .build();

Or with Handling compatibility by:

NotificationCompat notification =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setChannelId(CHANNEL_ID).build();

Now make it notify

NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
mNotificationManager.notify(notifyID , notification);

or if you want a simple fix then use the following code:

NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       mNotificationManager.createNotificationChannel(mChannel);
    }

Updates:
NotificationCompat.Builder reference

NotificationCompat.Builder(Context context)

This constructor was deprecated in API level 26.0.0
so you should use

Builder(Context context, String channelId)

so no need to setChannelId with the new constructor.

And you should use the latest of AppCompat library currently 26.0.2

compile "com.android.support:appcompat-v7:26.0.+"

Source from Android Developers Channel on Youtube

Also, you could check official Android Docs


问:
Using a Regular Expression to Find Phone Numbers in all Files of a File Share
I have another issue just whipping me.  I borrowed the following code (I can't recall from where) that looked super promising for determining phone numbers present in all files in a file share. The code absolutely makes sense to me, and that is why I am confused why it is not working. I test it with a document that I created in which I placed a phone number.  It returned nothing. Any help would be greatly appreciated. </p>

```<code>foreach ($file in Get-ChildItem -Recurse  | Select-String -pattern '^\d{3}-\d{3}-\d{4}' | Select-Object -Unique Path) {$file.path}
</code>```

答:
The problem is most likely that the

```<code>^\d{3}-\d{3}-\d{4}
</code>```

regex requires the phone number to be first characters in a document (or a line) while in the actual documents it may be somewhere in the middle.

Change the ^ anchor to \b (word boundary). You may also want to add this word boundary anchor after the potential phone number:

```<code>\b\d{3}-\d{3}-\d{4}\b
</code>```

Body:
I have another issue just whipping me.  I borrowed the following code (I can't recall from where) that looked super promising for determining phone numbers present in all files in a file share. The code absolutely makes sense to me, and that is why I am confused why it is not working. I test it with a document that I created in which I placed a phone number.  It returned nothing. Any help would be greatly appreciated.

foreach ($file in Get-ChildItem -Recurse  | Select-String -pattern '^\d{3}-\d{3}-\d{4}' | Select-Object -Unique Path) {$file.path}

Body:
The problem is most likely that the

^\d{3}-\d{3}-\d{4}

regex requires the phone number to be first characters in a document (or a line) while in the actual documents it may be somewhere in the middle.

Change the ^ anchor to \b (word boundary). You may also want to add this word boundary anchor after the potential phone number:

\b\d{3}-\d{3}-\d{4}\b


问:
How to animate SVG polygon points?
I have created a line chart with SVG (polygon points) that I would like animated.

I would like the points to all start animating from the X axis, and when finished animating, the result to look like the following image.

It seems there is no simple way to achieve this, with the googling I have done. Any tips would be most appreciated, thanks.

答:
I have done something in the past, this was however with a single control point of a SVG Bezier curve. However I think you can apply the same principle. I think you need to do the following steps

Create an array with y values of the curves

Create a jQuery animate function with a step method for each y value [jquery animate1

animate example

```<code>$({ n: 0 }).animate({ n: 40}, {
        duration: 1000,
        step: function(calculatedYValue, fx) {
            //update graphs with calculatedYValue
            console.log(parseInt(calculatedYValue), 10);
        }
    });
</code>```

Title: How to animate SVG polygon points?

Body:
I have done something in the past, this was however with a single control point of a SVG Bezier curve. However I think you can apply the same principle. I think you need to do the following steps

Create an array with y values of the curves

Create a jQuery animate function with a step method for each y value [jquery animate1

animate example

$({ n: 0 }).animate({ n: 40}, {
        duration: 1000,
        step: function(calculatedYValue, fx) {
            //update graphs with calculatedYValue
            console.log(parseInt(calculatedYValue), 10);
        }
    });


问:
vlcj webcam stream in java
I am trying to make a simple program that will live stream from my webcam.

```<code>public static void main(String[] args) throws Exception
{
    int port = nextAvailable();
    //String media = "/root/Desktop/525600.mp4";
    String media = "/dev/video0";
    String[] options = {":sout=#duplicate{dst=rtp{sdp=rtsp://:"+port+"/stream},dst=display}", ":sout-all", ":sout-keep"};
    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(args);
    HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
    mediaPlayer.playMedia(media,options);
    System.out.println("Using port: "+port);
    Thread.currentThread().join();
}
</code>```

if I use the commented media (/root/Desktop/525600.mp4), the stream works without any issues. However, I do not know how to stream from the webcam. I tried /dev/video0 but it gives the following errors:

[00007fae70008f78] core access error: read error: Invalid argument

[00007fae70008f78] filesystem access error: read error: Invalid
  argument

[00007fae7000d3d8] core stream error: cannot pre fill buffer

What am I doing wrong?

答:
Also you can refer to this :-

https://github.com/sarxos/webcam-capture/tree/master/webcam-capture-examples/webcam-capture-live-streaming

Title: vlcj webcam stream in java

Body:
I am trying to make a simple program that will live stream from my webcam.

public static void main(String[] args) throws Exception
{
    int port = nextAvailable();
    //String media = "/root/Desktop/525600.mp4";
    String media = "/dev/video0";
    String[] options = {":sout=#duplicate{dst=rtp{sdp=rtsp://:"+port+"/stream},dst=display}", ":sout-all", ":sout-keep"};
    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(args);
    HeadlessMediaPlayer mediaPlayer = mediaPlayerFactory.newHeadlessMediaPlayer();
    mediaPlayer.playMedia(media,options);
    System.out.println("Using port: "+port);
    Thread.currentThread().join();
}

if I use the commented media (/root/Desktop/525600.mp4), the stream works without any issues. However, I do not know how to stream from the webcam. I tried /dev/video0 but it gives the following errors:

[00007fae70008f78] core access error: read error: Invalid argument

[00007fae70008f78] filesystem access error: read error: Invalid
  argument

[00007fae7000d3d8] core stream error: cannot pre fill buffer

What am I doing wrong?


问:
Showing UNKNOWN number of data as Column Name
In hql ( or mysql)  I wouldl ike to create hql (or mysql) query which brings the desiredView. I have three tables. I called them as Table A, Table B, Table C.
And I have desired view which I want to get.

```<code>Table A
Aid         RegNum  BID         Value
2CE7D0A7    2000000 D5981DFC    1
9D3C13AA    2000000 C58566C5    32
9DDB90C4    2000000 812E9E75    5343
</code>```

Table B is connected to Table A by Table B's foreign key in Table A

```<code>Table B

BID             ColumnName              Index
D5981DFC        Question1               0
C58566C5        Question2               1
812E9E75        Question3               2
</code>```

Table C has foreign key in Table A as well. Reg Num. Reg num is primary key in Table C

```<code>Table C

Name        Surname     RegNum
Etibar      Hasanov     2000000
</code>```

As you see there are column's names which are datas in Table B

```<code>DesiredView
Name        Surname     RegNum      Question1       Question2       Question3
Etibar      Hasanov     2000000     1               32              5343
</code>```

In the example there are 3 rows in table A and table B, it is not static, I know that I can use case if it was static. However I am looking for query in which number of columns is dependent on number of questions in table B, it there are 3 questions then in total I will have 6 columns in desiredView, if 4 there will be 7 and so on.

答:
If you create a procedure in MySQL then you can achieve the dynamic behavior which you want.

Please create a procedure and add below code inside the procedure and it will provide the dynamic output.

```<code>SELECT GROUP_CONCAT('SUM(IF(B.ColumnName = ''', ColumnName, ''', A.Value, 0)) AS ', ColumnName) INTO @str
FROM TableB;

SET @s = CONCAT('select C.Name, C.Surname, C.RegNum, ', @str, 'from TableC C inner join TableA A on C.RegNum = A.RegNum inner join TableB B on A.BID = B.BID group by C.RegNum');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Body:
In hql ( or mysql)  I wouldl ike to create hql (or mysql) query which brings the desiredView. I have three tables. I called them as Table A, Table B, Table C.
And I have desired view which I want to get.

Table A
Aid         RegNum  BID         Value
2CE7D0A7    2000000 D5981DFC    1
9D3C13AA    2000000 C58566C5    32
9DDB90C4    2000000 812E9E75    5343

Table B is connected to Table A by Table B's foreign key in Table A

Table B

BID             ColumnName              Index
D5981DFC        Question1               0
C58566C5        Question2               1
812E9E75        Question3               2

Table C has foreign key in Table A as well. Reg Num. Reg num is primary key in Table C

Table C

Name        Surname     RegNum
Etibar      Hasanov     2000000

As you see there are column's names which are datas in Table B

DesiredView
Name        Surname     RegNum      Question1       Question2       Question3
Etibar      Hasanov     2000000     1               32              5343

In the example there are 3 rows in table A and table B, it is not static, I know that I can use case if it was static. However I am looking for query in which number of columns is dependent on number of questions in table B, it there are 3 questions then in total I will have 6 columns in desiredView, if 4 there will be 7 and so on.

Body:
If you create a procedure in MySQL then you can achieve the dynamic behavior which you want.

Please create a procedure and add below code inside the procedure and it will provide the dynamic output.

SELECT GROUP_CONCAT('SUM(IF(B.ColumnName = ''', ColumnName, ''', A.Value, 0)) AS ', ColumnName) INTO @str
FROM TableB;

SET @s = CONCAT('select C.Name, C.Surname, C.RegNum, ', @str, 'from TableC C inner join TableA A on C.RegNum = A.RegNum inner join TableB B on A.BID = B.BID group by C.RegNum');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
Replace div with another div (ASP.NET MVC)
I have PartialView

Here is code

```<code>  <div id="question1" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question1)
</div>
<div id="question2" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question2)
</div>
<div id="question3" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question3)
</div>
<div  id="question4" style="font-size:20px; margin-bottom:10px;">
    @Html.DisplayFor(modelItem => Model.Question4)
</div>
</code>```

I call PartialView via AJAX

Code here:

```<code><script>
$(document).ready(function () {
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)

    $.ajax({
        type: "GET",
        url: "/interwier/QuestionBlock",
        data: { id: id },
        success: function (data) {
            $("#questions").html(data);

        },
        error: function () {
            alert("Smth wrong in controller");
        }
    });
});
</code>```

How I can display div with id=question1 when I click button replace it with div with id= question2? Button is not in PartialView.

Update

I decide to change logic and delete PartialView

I make code in div like this

```<code> <div id="questions" class="qustion-div-one">
        <div id="question1" style="font-size:20px; margin-bottom:10px;">
            @Html.DisplayFor(modelItem => Model.Question1)
        </div>
        <div id="question2" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question2)
        </div>
        <div id="question3" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question3)
        </div>
        <div id="question4" style="font-size:20px; margin-bottom:10px; display:none">
            @Html.DisplayFor(modelItem => Model.Question4)
        </div>
    </div>
</code>```

I need on button click make question1 hidden, and question2 visible, on next click question2 will be hidden and question3 visible and etc.

Or just simple remove question1 and change  for question2 etc.

How I can do this?

UPDATE 2

I try to do this script

```<code> $('#next').click(function () {
    $('#questions>div').toggle();
});
</code>```

but it opens all 3 divs, but i need question2 div

答:
Can you explain better what your desired result would be in this case? Maybe what you want is to replace the JQuery $.ajax call with the JQuery method load (Docs), see "Loading Page Fragments" sub title. You could dynamically construct the "suffixed selector expression" to replace a specific part of your page, e.g.

```<code>$( "#question1" ).load( "/interwier/QuestionBlock #question2" );
</code>```

But I'm not sure I got your question right.

Body:
I have PartialView

Here is code

    @Html.DisplayFor(modelItem => Model.Question1)

    @Html.DisplayFor(modelItem => Model.Question2)

    @Html.DisplayFor(modelItem => Model.Question3)

    @Html.DisplayFor(modelItem => Model.Question4)

I call PartialView via AJAX

Code here:

Body:
Can you explain better what your desired result would be in this case? Maybe what you want is to replace the JQuery $.ajax call with the JQuery method load (Docs), see "Loading Page Fragments" sub title. You could dynamically construct the "suffixed selector expression" to replace a specific part of your page, e.g.

$( "#question1" ).load( "/interwier/QuestionBlock #question2" );

But I'm not sure I got your question right.


问:
android 7.0 Notification icon appearing white square
I am using the below snippet to generate notifications in my android app.

```<code>private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}
</code>```

It works in android 5 and 6 but for android nougat it is not working

答:
Following the docs from the Android API:

Status bar icons are composed simply of white pixels on a transparent backdrop, with alpha blending used for smooth edges and internal texture where appropriate.

Your whole image but the transparent parts is going to be converted to white (being originally white or having colors).

One solution is to create a silhouette icon with color, by this way you can use the same image in all Android APIs. One example could be this icon:

In lower versions of Android you would see the black face, in the last versions you will see the same face but with white color. That's because of the transparent parts (it seems SO removes the transparency, you can get the original from here) of the image.

Body:
I am using the below snippet to generate notifications in my android app.

private void sendNotification(String contentText, String message) {

    Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("clear","clear");
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
     Intent.FLAG_ACTIVITY_CLEAR_TASK);

   PendingIntent piResult = PendingIntent.getActivity(this, 0, resultIntent,0);

    NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setColor(ContextCompat.getColor(getApplicationContext(),R.color.red))
            .setContentTitle("title")
            .setContentText(message)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources()
            ,R.drawable.notification))
            .setContentIntent(piResult);

    NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder);

    int i;
    for(i=0; i<messageList.size();i++){
        notification.addLine(messageList.get(i));
    }
    notification.setBigContentTitle("title");
    notification.setSummaryText(contentText);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID,notification.build());
}

It works in android 5 and 6 but for android nougat it is not working


问:
RTL shows numbers at the end of lines
Trying to display a hebrew string that starts with a number, always displays the number at the end of the string like so: 1. יום שישי בבוקר

but I need the number to be displayed at the right side of the text-

any solution to that?

It happens with UILabel & UITextField & UITextView

and trying to write the number at the left side also produce the same resault.

Playing with combinations of UITextAlignment will doesn't help.

答:
Building on Mo's great answer:

This is the code Obj-C:

```<code>NSString *RTFstr = "1. בבוקר"; //This could be any right-to-left string
NSString *directionalString = [@"\u200F" stringByAppendingString:[note text]];
[someUITextView setString:directionalString];
</code>```

And it actually works...

Title: RTL shows numbers at the end of lines

Body:
Building on Mo's great answer:

This is the code Obj-C:

NSString *RTFstr = "1. בבוקר"; //This could be any right-to-left string
NSString *directionalString = [@"\u200F" stringByAppendingString:[note text]];
[someUITextView setString:directionalString];

And it actually works...


问:
Python tkinter Text display GUI using anchor = W
I am trying use anchor = W to align all the text in single line, but not able to do it.

GUI Script

I want to display all in single line with number, like example:
I also want to display the enumerate at start, tried its not working.

```<code>1.U1a1400     3C      CAN Initialisation is Failure - no sub type information
2.U000188     3C      High Speed CAN Communication Bus - bus off
</code>```

Code is as below:

```<code>import pypyodbc
from Tkinter import *
from DataStructure import *
row = ''
dtc_code = ''

def UserInput():
global UI_MainForm
global row
global dtc_code
UI_MainForm = Tk()

#Initialization of Main Window

UI_MainForm.geometry("1000x575+500+50")
UI_MainForm.title("Script")

# labelframe = LabelFrame(UI_MainForm,text="Please select :",width=400, height=800,bd = 2)
# labelframe.pack(fill="both")
# labelframe.config(relief=RIDGE)
# for xx,yy in zip(DTC_CODE,FAULT_TYPES):
    # temp_text1 = '{0} - {1}'.format(xx,yy)

    for dtccodes,faulttypes in zip(DTC_CODE,FAULT_TYPES):
            temp_text = '{0}      {1}'.format(dtccodes,faulttypes)

        Label(UI_MainForm, text= temp_text).pack(anchor = W)

    for menu1,menu2 in zip(DTC_Description,DTC_Description1):
            temp_text = '{0} - {1}'.format(menu1,menu2)
        Label(UI_MainForm, text= temp_text).pack(anchor = W)

    # for menu2 in DTC_Description1:
        # Label(labelframe, text= menu2).pack(anchor = W,pady = 2)

# Label(labelframe, text=array2).pack(anchor = E,pady = 2)

UI_MainForm.mainloop()
return;

response = '59 02 FF DA 14 00 3C C0 01 88 3C 5B 18 2F 3C C3 00 00 3C E1 00 00 3C E1 01 00 3C C3 00 57 3C E0 1A 54 3C 50 24 00 3C'

DTCLogged = response.split(' ')

DTCLogged = DTCLogged[3:]
print DTCLogged
DTCLoggedLen = len(DTCLogged)
print DTCLoggedLen
NumberOfDTC = DTCLoggedLen/4
print NumberOfDTC
loopindex = 0
DTCRecord =[]
DTC_CODE = []
FAULT_TYPES = []
DTC_Description = []
DTC_Description1 = []
while (loopindex+4) <= DTCLoggedLen:

Record = DTCLogged[loopindex]+' '+DTCLogged[loopindex+1]+' '+DTCLogged[loopindex+2]
# print Record
#print DTCLogged[loopindex]
DTCRecord.append(Record)

if((int(DTCLogged[loopindex], 16) & 0xC0) == 0):
  dtc_designator = 'P'
  #print dtc_designator
elif((int(DTCLogged[loopindex], 16) & 0xC0) == 64):
   dtc_designator = 'C'
   #print dtc_designator
elif((int(DTCLogged[loopindex], 16) & 0xC0) == 128):
   dtc_designator = 'B'
   #print dtc_designator
else:
   dtc_designator = 'U';
   #print dtc_designator

#y = int(DTCLogged[loopindex], 16) & 0x30
global dtc_designator1
if((int(DTCLogged[loopindex], 16) & 0x30) == 0):
  dtc_designator1 = '0'
  #print dtc_designator1
elif((int(DTCLogged[loopindex], 16) & 0x30) == 16):
   dtc_designator1 = '1'
   #print dtc_designator1
elif((int(DTCLogged[loopindex], 16) & 0x30) == 32):
   dtc_designator1 = '2'
   #print dtc_designator1
else:
   dtc_designator = '3';
   #print dtc_designator1

z = int(DTCLogged[loopindex], 16) & 0x0F
global dtc_designator2
dtc_designator2 = hex(z)[2:]
#print dtc_designator2

dtc_code = dtc_designator + dtc_designator1 + dtc_designator2 + DTCLogged[loopindex+1]
# print dtc_code

dtc_code1 = dtc_code + DTCLogged[loopindex+2]
# Value = []
DTC_CODE.append(dtc_code1)
# return Value

fault_type = DTCLogged[loopindex+3]
FAULT_TYPES.append(fault_type)
</code>```

connecting to MS ACCESS:

```<code>cursor1.execute("SELECT Field2 FROM DTC_CODES Where Field1 = '{}'".format(dtc_code))

for row in cursor1.fetchone():
   print row
DTC_Description.append(row)

cursor2 = connection.cursor()
cursor2.execute("SELECT Field2 FROM FAULT_TYPES Where Field1 = '{}'".format(DTCLogged[loopindex+2]))
for row1 in cursor2.fetchone():
    DTC_Description1.append(row1)

loopindex = loopindex+4

UserInput()
</code>```

答:
anchor=W specifies which side the text inside the label appears. It has no affect on where the label appears in relation to other labels.

Unless you specify otherwise, pack uses the option side='top'. Thus, Label(UI_MainForm, text= temp_text).pack(anchor = W) will place this label below anything else in the window.

If you want everything in a horizontal line, use side='left':

```<code>Label(UI_MainForm, text= temp_text).pack(side='left', anchor = W)
</code>```

Body:
I am trying use anchor = W to align all the text in single line, but not able to do it.

GUI Script

I want to display all in single line with number, like example:
I also want to display the enumerate at start, tried its not working.

1.U1a1400     3C      CAN Initialisation is Failure - no sub type information
2.U000188     3C      High Speed CAN Communication Bus - bus off

Code is as below:

import pypyodbc
from Tkinter import *
from DataStructure import *
row = ''
dtc_code = ''

def UserInput():
global UI_MainForm
global row
global dtc_code
UI_MainForm = Tk()

#Initialization of Main Window

UI_MainForm.geometry("1000x575+500+50")
UI_MainForm.title("Script")

# labelframe = LabelFrame(UI_MainForm,text="Please select :",width=400, height=800,bd = 2)
# labelframe.pack(fill="both")
# labelframe.config(relief=RIDGE)
# for xx,yy in zip(DTC_CODE,FAULT_TYPES):
    # temp_text1 = '{0} - {1}'.format(xx,yy)

    for dtccodes,faulttypes in zip(DTC_CODE,FAULT_TYPES):
            temp_text = '{0}      {1}'.format(dtccodes,faulttypes)

        Label(UI_MainForm, text= temp_text).pack(anchor = W)

    for menu1,menu2 in zip(DTC_Description,DTC_Description1):
            temp_text = '{0} - {1}'.format(menu1,menu2)
        Label(UI_MainForm, text= temp_text).pack(anchor = W)

    # for menu2 in DTC_Description1:
        # Label(labelframe, text= menu2).pack(anchor = W,pady = 2)

# Label(labelframe, text=array2).pack(anchor = E,pady = 2)

UI_MainForm.mainloop()
return;

response = '59 02 FF DA 14 00 3C C0 01 88 3C 5B 18 2F 3C C3 00 00 3C E1 00 00 3C E1 01 00 3C C3 00 57 3C E0 1A 54 3C 50 24 00 3C'

DTCLogged = response.split(' ')

DTCLogged = DTCLogged[3:]
print DTCLogged
DTCLoggedLen = len(DTCLogged)
print DTCLoggedLen
NumberOfDTC = DTCLoggedLen/4
print NumberOfDTC
loopindex = 0
DTCRecord =[]
DTC_CODE = []
FAULT_TYPES = []
DTC_Description = []
DTC_Description1 = []
while (loopindex+4) <= DTCLoggedLen:

Record = DTCLogged[loopindex]+' '+DTCLogged[loopindex+1]+' '+DTCLogged[loopindex+2]
# print Record
#print DTCLogged[loopindex]
DTCRecord.append(Record)

if((int(DTCLogged[loopindex], 16) & 0xC0) == 0):
  dtc_designator = 'P'
  #print dtc_designator
elif((int(DTCLogged[loopindex], 16) & 0xC0) == 64):
   dtc_designator = 'C'
   #print dtc_designator
elif((int(DTCLogged[loopindex], 16) & 0xC0) == 128):
   dtc_designator = 'B'
   #print dtc_designator
else:
   dtc_designator = 'U';
   #print dtc_designator

#y = int(DTCLogged[loopindex], 16) & 0x30
global dtc_designator1
if((int(DTCLogged[loopindex], 16) & 0x30) == 0):
  dtc_designator1 = '0'
  #print dtc_designator1
elif((int(DTCLogged[loopindex], 16) & 0x30) == 16):
   dtc_designator1 = '1'
   #print dtc_designator1
elif((int(DTCLogged[loopindex], 16) & 0x30) == 32):
   dtc_designator1 = '2'
   #print dtc_designator1
else:
   dtc_designator = '3';
   #print dtc_designator1

z = int(DTCLogged[loopindex], 16) & 0x0F
global dtc_designator2
dtc_designator2 = hex(z)[2:]
#print dtc_designator2

dtc_code = dtc_designator + dtc_designator1 + dtc_designator2 + DTCLogged[loopindex+1]
# print dtc_code

dtc_code1 = dtc_code + DTCLogged[loopindex+2]
# Value = []
DTC_CODE.append(dtc_code1)
# return Value

fault_type = DTCLogged[loopindex+3]
FAULT_TYPES.append(fault_type)

connecting to MS ACCESS:

cursor1.execute("SELECT Field2 FROM DTC_CODES Where Field1 = '{}'".format(dtc_code))

for row in cursor1.fetchone():
   print row
DTC_Description.append(row)

cursor2 = connection.cursor()
cursor2.execute("SELECT Field2 FROM FAULT_TYPES Where Field1 = '{}'".format(DTCLogged[loopindex+2]))
for row1 in cursor2.fetchone():
    DTC_Description1.append(row1)

loopindex = loopindex+4

UserInput()

Body:
anchor=W specifies which side the text inside the label appears. It has no affect on where the label appears in relation to other labels.

Unless you specify otherwise, pack uses the option side='top'. Thus, Label(UI_MainForm, text= temp_text).pack(anchor = W) will place this label below anything else in the window.

If you want everything in a horizontal line, use side='left':

Label(UI_MainForm, text= temp_text).pack(side='left', anchor = W)


问:
How to add Web Service Response into NSDictionary in objective C, IOS
I am getting response form asp.net web services and when I try to convert that NSData response in NSDictionary format that time it stores nil. Then how to convert it into NSDictionary?
Thanks in Advance

Here is my code:

```<code>  -(void)jsonresponse:(NSMutableString *)json
   {
    NSData *data=[json dataUsingEncoding:NSUTF8StringEncoding];

NSError *error=nil;

NSDictionary *json1=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

tableArray= [NSMutableArray array];
   // menuArray=[NSMutableArray array];

for (NSDictionary *dic in [json1 objectForKey:@"Table"])
{
    [tableArray addObject:@{@"StudentId" : [dic objectForKey:@"StudentId"],
                         @"UserID" : [dic objectForKey:@"UserID"],
                         @"StudentName" : [dic objectForKey:@"StudentName"],
                         @"UserTypeName" : [dic objectForKey:@"UserTypeName"],
                         @"Path" : [dic objectForKey:@"Path"],
                         @"UnreadMessageCount" : [dic objectForKey:@"UnreadMessageCount"],
                         @"LastMessageTime" : [dic objectForKey:@"LastMessageTime"],
                         @"Image" : [dic objectForKey:@"Image"]}];

}

NSLog(@"table Array is==%@",tableArray);

for (NSDictionary *dic in [json1 objectForKey:@"Table1"])
{
    [menuArray addObject:@{@"MenuName":[dic objectForKey:@"MenuName"],
                           @"MenuName1" : [dic objectForKey:@"UserID"],
                           @"Icon" : [dic objectForKey:@"Icon"],
                           @"URL" : [dic objectForKey:@"URL"],
                           @"UserTypeConst" : [dic objectForKey:@"Path"]}];
}
 //   [self performSegueWithIdentifier:@"loginbutton" sender:nil];

NSLog(@"Menu Array is==%@",menuArray);
}
</code>```

Here is my response

```<code>{
"Table": [{
    "StudentId": "755",
    "UserID": "1618",
    "StudentName": "VRITEE SHAH",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "103",
    "LastMessageTime": "12/02/2016 16:52:30",
    "Image": ""
}, {
    "StudentId": "2629",
    "UserID": "5380",
    "StudentName": "NILESH PINGALE",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "68",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2630",
    "UserID": "5386",
    "StudentName": "MEGAN ABRAHANM",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "190",
    "LastMessageTime": "12/07/2016 17:04:06",
    "Image": ""
}, {
    "StudentId": "2828",
    "UserID": "5784",
    "StudentName": "VAIBHAVI JOSHI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "21",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2866",
    "UserID": "5856",
    "StudentName": "ISHITA BACHANI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "2",
    "LastMessageTime": "10/30/2016 10:52:48",
    "Image": ""
}],
"Table1": [{
    "MenuName": "Student Info",
    "MenuName1": "Profile ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/student_info.png ",
    "URL": "StudentProfile ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Calendar ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/calender.png ",
    "URL": "Calendar ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Time Table ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/timetable.png ",
    "URL": "TimeTable ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "View Attendance ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_attendance.png ",
    "URL": "ViewAttendance ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Map View ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/map_view.png ",
    "URL": "MapView ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Alerts & Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/alerts&notification.png ",
    "URL": "AlertsNotification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Transportation Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/transportation_desk.png ",
    "URL": "TransportationDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/notification.png ",
    "URL": "Notification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Principal’s Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/principal_desk.png ",
    "URL": "PrincipalDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Digital Diary ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/digital_diary.png ",
    "URL": "DigitalDiary ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Assignment ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/assignment.png ",
    "URL": "Assignment ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "View Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_bill.png ",
    "URL": "ViewBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Pay Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/pay_bill.png ",
    "URL": "PayBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Online Payment History ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/onlinepayment_history.png ",
    "URL": "OnlinePaymentHistory ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Change Password",
    "MenuName1": "Change Password ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/change_password.png ",
    "URL": "ChangePassword ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Delete User",
    "MenuName1": "Delete User ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/delete.png ",
    "URL": "DeleteUser ",
    "UserTypeConst": "PAR"
}]
</code>```

}

答:
```<code>- (NSDictionary *)getJsonObjectfromString:(NSString*)jsonString{

    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error;
    id json = [NSJSONSerialization JSONObjectWithData:data
                                              options:0
                                                error:&error];
    return json;
}
</code>```

Body:
I am getting response form asp.net web services and when I try to convert that NSData response in NSDictionary format that time it stores nil. Then how to convert it into NSDictionary?
Thanks in Advance

Here is my code:

  -(void)jsonresponse:(NSMutableString *)json
   {
    NSData *data=[json dataUsingEncoding:NSUTF8StringEncoding];

NSError *error=nil;

NSDictionary *json1=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

tableArray= [NSMutableArray array];
   // menuArray=[NSMutableArray array];

for (NSDictionary *dic in [json1 objectForKey:@"Table"])
{
    [tableArray addObject:@{@"StudentId" : [dic objectForKey:@"StudentId"],
                         @"UserID" : [dic objectForKey:@"UserID"],
                         @"StudentName" : [dic objectForKey:@"StudentName"],
                         @"UserTypeName" : [dic objectForKey:@"UserTypeName"],
                         @"Path" : [dic objectForKey:@"Path"],
                         @"UnreadMessageCount" : [dic objectForKey:@"UnreadMessageCount"],
                         @"LastMessageTime" : [dic objectForKey:@"LastMessageTime"],
                         @"Image" : [dic objectForKey:@"Image"]}];

}

NSLog(@"table Array is==%@",tableArray);

for (NSDictionary *dic in [json1 objectForKey:@"Table1"])
{
    [menuArray addObject:@{@"MenuName":[dic objectForKey:@"MenuName"],
                           @"MenuName1" : [dic objectForKey:@"UserID"],
                           @"Icon" : [dic objectForKey:@"Icon"],
                           @"URL" : [dic objectForKey:@"URL"],
                           @"UserTypeConst" : [dic objectForKey:@"Path"]}];
}
 //   [self performSegueWithIdentifier:@"loginbutton" sender:nil];

NSLog(@"Menu Array is==%@",menuArray);
}

Here is my response

{
"Table": [{
    "StudentId": "755",
    "UserID": "1618",
    "StudentName": "VRITEE SHAH",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "103",
    "LastMessageTime": "12/02/2016 16:52:30",
    "Image": ""
}, {
    "StudentId": "2629",
    "UserID": "5380",
    "StudentName": "NILESH PINGALE",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "68",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2630",
    "UserID": "5386",
    "StudentName": "MEGAN ABRAHANM",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "190",
    "LastMessageTime": "12/07/2016 17:04:06",
    "Image": ""
}, {
    "StudentId": "2828",
    "UserID": "5784",
    "StudentName": "VAIBHAVI JOSHI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "21",
    "LastMessageTime": "12/05/2016 14:41:51",
    "Image": ""
}, {
    "StudentId": "2866",
    "UserID": "5856",
    "StudentName": "ISHITA BACHANI",
    "UserTypeName": "Student",
    "Path": "",
    "UnreadMessageCount": "2",
    "LastMessageTime": "10/30/2016 10:52:48",
    "Image": ""
}],
"Table1": [{
    "MenuName": "Student Info",
    "MenuName1": "Profile ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/student_info.png ",
    "URL": "StudentProfile ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Calendar ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/calender.png ",
    "URL": "Calendar ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "Time Table ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/timetable.png ",
    "URL": "TimeTable ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Student Info",
    "MenuName1": "View Attendance ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_attendance.png ",
    "URL": "ViewAttendance ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Map View ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/map_view.png ",
    "URL": "MapView ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Alerts & Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/alerts&notification.png ",
    "URL": "AlertsNotification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Transportation",
    "MenuName1": "Transportation Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/transportation_desk.png ",
    "URL": "TransportationDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Notification ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/notification.png ",
    "URL": "Notification ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Principal’s Desk ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/principal_desk.png ",
    "URL": "PrincipalDesk ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Digital Diary ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/digital_diary.png ",
    "URL": "DigitalDiary ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Notification/Alerts",
    "MenuName1": "Assignment ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/assignment.png ",
    "URL": "Assignment ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "View Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/view_bill.png ",
    "URL": "ViewBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Pay Bill ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/pay_bill.png ",
    "URL": "PayBill ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Payment Info",
    "MenuName1": "Online Payment History ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/onlinepayment_history.png ",
    "URL": "OnlinePaymentHistory ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Change Password",
    "MenuName1": "Change Password ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/change_password.png ",
    "URL": "ChangePassword ",
    "UserTypeConst": "PAR"
}, {
    "MenuName": "Delete User",
    "MenuName1": "Delete User ",
    "Icon": "http://192.168.0.125:85/Images/NavigationIcon/delete.png ",
    "URL": "DeleteUser ",
    "UserTypeConst": "PAR"
}]

}


问:
Can we use CASE in FROM Clause. SELECT * FROM (Case if 1=1 then TABLE1 else TABLE2 end)
Can we use CASE in FROM Clause. like *SELECT * FROM (Case if 1=1 then TABLE1 else TABLE2 end)*

答:
This query is wrong with the syntax, what should show next to Where is either a table or a table set.

The correct syntax would be:

```<code>if (1=1) -------------------------be careful here will always be true
begin
SELECT * FROM TABLE1
end

else
begin
SELECT * FROM TABLE2
end
</code>```

Body:
This query is wrong with the syntax, what should show next to Where is either a table or a table set.

The correct syntax would be:

if (1=1) -------------------------be careful here will always be true
begin
SELECT * FROM TABLE1
end

else
begin
SELECT * FROM TABLE2
end


问:
Java: how to compare two strings in order to obtain the portions where they differ?
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

```<code>String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
</code>```

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

```<code>private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
</code>```

Calling getAllSubsequences on these two strings:

```<code>String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
</code>```

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

答:
My code might not be the most compact but I've written it like that for clarity :

```<code>public static void main(String[] args) throws InterruptedException, FileNotFoundException, ExecutionException {

    String s1 = "x4.printString(\"Bianca.()\").y1();";
    String s2 = "sb.printString(\"Bianca.()\").length();";

    List<String> result = new ArrayList<>();
    result.addAll(getDifferences(s1, s2));
    result.addAll(getDifferences(s2, s1));

    System.out.println(result);
}

public static List<String> getDifferences(String s1, String s2){
    if(s1 == null){
        return Collections.singletonList(s2);
    }
    if(s2 == null){
        return Collections.singletonList(s1);
    }
    int minimalLength = Math.min(s1.length(),s2.length());
    List<String> result = new ArrayList<>();
    StringBuilder buffer = new StringBuilder(); // keep the consecutive differences
    for(int i = 0; i<minimalLength; i++ ){
        char c = s1.charAt(i);
        if(c == s2.charAt(i)){
            if( buffer.length() > 0){
                result.add(buffer.toString());
                buffer = new StringBuilder();
            }
        } else {
            buffer.append(c);
        }
    }
    if(s1.length() > minimalLength){
        buffer.append(s1.substring(minimalLength)); // add the rest
    }
    if(buffer.length() > 0){
        result.add(buffer.toString()); //flush buffer
    }
    return result;
}
</code>```

However, note that also returns the non-words characters as you didn't specified you wanted to remove them (but they don't figure in your expected output).

Body:
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}

Calling getAllSubsequences on these two strings:

String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

Body:
My code might not be the most compact but I've written it like that for clarity :

public static void main(String[] args) throws InterruptedException, FileNotFoundException, ExecutionException {

    String s1 = "x4.printString(\"Bianca.()\").y1();";
    String s2 = "sb.printString(\"Bianca.()\").length();";

    List<String> result = new ArrayList<>();
    result.addAll(getDifferences(s1, s2));
    result.addAll(getDifferences(s2, s1));

    System.out.println(result);
}

public static List<String> getDifferences(String s1, String s2){
    if(s1 == null){
        return Collections.singletonList(s2);
    }
    if(s2 == null){
        return Collections.singletonList(s1);
    }
    int minimalLength = Math.min(s1.length(),s2.length());
    List<String> result = new ArrayList<>();
    StringBuilder buffer = new StringBuilder(); // keep the consecutive differences
    for(int i = 0; i<minimalLength; i++ ){
        char c = s1.charAt(i);
        if(c == s2.charAt(i)){
            if( buffer.length() > 0){
                result.add(buffer.toString());
                buffer = new StringBuilder();
            }
        } else {
            buffer.append(c);
        }
    }
    if(s1.length() > minimalLength){
        buffer.append(s1.substring(minimalLength)); // add the rest
    }
    if(buffer.length() > 0){
        result.add(buffer.toString()); //flush buffer
    }
    return result;
}

However, note that also returns the non-words characters as you didn't specified you wanted to remove them (but they don't figure in your expected output).


问:
Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks
I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

```<code>pd.DataFrame(np.random.randn(2, 10),
    columns=['Very Long Column Title ' + str(i) for i in range(10)])
</code>```

DataFrame with wrapped column names

But if I have fewer columns, the titles will not wrap:

```<code>pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
</code>```

DataFrame does not wrap column names

I have also tried to manually insert a newline:

```<code>import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])
</code>```

But that gives the same output as above.

I've found similar for answers on this topic:

Can I set variable column widths in pandas?

will truncate column widths, but will not affect the title and will not wrap the text

Pretty printing newlines inside a string in a Pandas DataFrame

This again touches on column contents but not the title

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.

答:
Here is an answer that does not involve changing the IPython properties:</p>

```<code>df = pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
</code>```

Body:
I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

pd.DataFrame(np.random.randn(2, 10),
    columns=['Very Long Column Title ' + str(i) for i in range(10)])

DataFrame with wrapped column names

But if I have fewer columns, the titles will not wrap:

pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])

DataFrame does not wrap column names

I have also tried to manually insert a newline:

import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])

But that gives the same output as above.

I've found similar for answers on this topic:

Can I set variable column widths in pandas?

will truncate column widths, but will not affect the title and will not wrap the text

Pretty printing newlines inside a string in a Pandas DataFrame

This again touches on column contents but not the title

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.

Body:
Here is an answer that does not involve changing the IPython properties:

df = pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])


问:
best optimal solution for streaming rails server logs to browser
I am looking for a best optimal way to stream my Rails server logs over to the browser. Have tried using browser_log gem which is not working in my case.Please suggest me any such type of gem available or any optimal way to stream the logs.

I am performing a tedious  background job on my server which require  an hour or so to complete so need logs in that case to  keep a track of the job

答:
Probably you can use rollbar.com

It has a gem and browse your log in very usefull form. For example, use system and browser of user. This features you can see at https://rollbar.com/demo/demo/

For less than 5000 errors in month id free. After overflow disabled to end of month


问:
what after extracting my DATA?
Actually, I have a project to deal with. I'm Asking for help.
My project is in the field of Business intelligence and creating datawarehouses.
I extracted Data that I need (ETL) and then what should I do ?
I am working with MS SQL Server 2014.
How to create my dimensions and my Fact table?
looking for advises
Please do accept my salvation.</p>

答:
This is a big question!  Unfortunately, Stack Overflow's Q&A format isn't the best place to answer this.  But here are few pointers:

Everything starts with the requirements.  Before you write any code, figure out exactly what your data warehouse will be used for (it can also be helpful to work out what your data warehouse will not be used for).

Analyse the raw data.  Make sure you know what is and is not available.  Be aware of the source systems shortcomings.  Example: If your reports need to split your customers by country, is this data available?  If so, is it consistently populated (some records have US, others USA, others still America)?   Make a plan for dealing with these issues (see data cleansing below).

Prototype your data model.  Excel and Power BI are great places to test the design.  Once you start using a database it becomes much harder to change.  Get it right at the very beginning and your life will be much easier.

Pick an ETL tool.  Make sure you understand it, and it plays to the strengths of you and your team.  I like SSIS.

Import the raw data into staging tables.  This can help to simplify the analysis phase.

Cleanse the data.  In a data warehouse, you have 100% control over every row, column and cell.  Make use of this fact.  Ensure only quality, useful, well-conformed data makes it into your published tables.

Like all projects, planning and administration is the key.  Writing code and building tables comes last.

Here are some resources which should help you:

Kimball Group.  Ralph Kimball literally wrote the book on data warehousing (see next tip).  His company's website contains a few hints and tips.

If you cannot attend a training course, buy a good book.  I'd recommend this one.  It's a big subject.  Blogs and the internet can only teach you so much.

Download and try out Adventure Works DW.  This is a sample data warehouse and ETL package, built by Microsoft.  It demonstrates some the techniques you can use in SSIS.

Title: what after extracting my DATA?


问:
Grep pattern from file (list) into same line
I have two files (see below) and want to grep the patterns in file 1 from file 2 (2 columns). I think it is really easy but I could not find any clue how to grep the matches to the same line

```<code>File1
ABC
DEF
GHI

File 2
ABC SeqX
ABC SeqY
ABC SeqP
DEF SeqW
DEF SeqO
GHI SeqR
GHI Seql
</code>```

The output should look like this:

```<code>    ABC SeqX SeqY SeqP
    DEF SeqW SeqO
    GHI SeqR Seql
</code>```

I know it has to be something like: grep -f file 1 file2 > output

答:
Short awk solution:

```<code>awk 'FNR==NR{a[$1]=a[$1]" "$2; next}{if($1 in a) print $1a[$i]}' file2 file1
</code>```

The output:

```<code>ABC SeqX SeqY SeqP
DEF SeqW SeqO
GHI SeqR Seql
</code>```

Body:
I have two files (see below) and want to grep the patterns in file 1 from file 2 (2 columns). I think it is really easy but I could not find any clue how to grep the matches to the same line

File1
ABC
DEF
GHI

File 2
ABC SeqX
ABC SeqY
ABC SeqP
DEF SeqW
DEF SeqO
GHI SeqR
GHI Seql

The output should look like this:

    ABC SeqX SeqY SeqP
    DEF SeqW SeqO
    GHI SeqR Seql

I know it has to be something like: grep -f file 1 file2 > output

Body:
Short awk solution:

awk 'FNR==NR{a[$1]=a[$1]" "$2; next}{if($1 in a) print $1a[$i]}' file2 file1

The output:

ABC SeqX SeqY SeqP
DEF SeqW SeqO
GHI SeqR Seql