问:
Mongodb shell mongo: Only one usage of each socket address (protocol/network address/port) is normally permitted. for socket: 0.0.0.0:27017
It was fine 2 days ago, Now mongod does not work. Even echo ps -A | grep mongo printed nothing, yet it warns about error: "Only one usage of each socket address". How to kill that? I have also tried with different random port. How can they fail as well?

```<code>D:\mongodb-win32-x86_64-2.2.3\bin>mongod
mongod --help for help and startup options
Sun Mar 03 18:10:03 [initandlisten] MongoDB starting : pid=6292 port=27017 dbpat
h=\data\db\ 64-bit host=Sadaf
Sun Mar 03 18:10:03 [initandlisten] db version v2.2.3, pdfile version 4.5
Sun Mar 03 18:10:03 [initandlisten] git version: f570771a5d8a3846eb7586eaffcf4c2
f4a96bf08
Sun Mar 03 18:10:03 [initandlisten] build info: windows sys.getwindowsversion(ma
jor=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB
_VERSION=1_49
Sun Mar 03 18:10:03 [initandlisten] options: {}
Sun Mar 03 18:10:03 [initandlisten] journal dir=/data/db/journal
Sun Mar 03 18:10:03 [initandlisten] recover : no journal files present, no recov
ery needed
Sun Mar 03 18:10:04 [initandlisten] ERROR: listen(): bind() failed errno:10048 O
nly one usage of each socket address (protocol/network address/port) is normally
 permitted. for socket: 0.0.0.0:27017
Sun Mar 03 18:10:04 [websvr] ERROR: listen(): bind() failed errno:10048 Only one
 usage of each socket address (protocol/network address/port) is normally permit
ted. for socket: 0.0.0.0:28017
Sun Mar 03 18:10:04 [initandlisten] now exiting
Sun Mar 03 18:10:04 dbexit:
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to close listening sockets..
.
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to flush diaglog...
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to close sockets...
Sun Mar 03 18:10:04 [initandlisten] shutdown: waiting for fs preallocator...
Sun Mar 03 18:10:04 [initandlisten] shutdown: lock for final commit...
Sun Mar 03 18:10:04 [initandlisten] shutdown: final commit...
Sun Mar 03 18:10:04 [initandlisten] shutdown: closing all files...
Sun Mar 03 18:10:04 [initandlisten] closeAllFiles() finished
Sun Mar 03 18:10:04 [initandlisten] journalCleanup...
Sun Mar 03 18:10:04 [initandlisten] removeJournalFiles
Sun Mar 03 18:10:04 [initandlisten] shutdown: removing fs lock...
Sun Mar 03 18:10:04 dbexit: really exiting now

D:\mongodb-win32-x86_64-2.2.3\bin>echo ps -A | grep mongo

D:\mongodb-win32-x86_64-2.2.3\bin>
</code>```

答:
Open command prompt in Administrator mode

run net stop MongoDB

Body:
It was fine 2 days ago, Now mongod does not work. Even echo ps -A | grep mongo printed nothing, yet it warns about error: "Only one usage of each socket address". How to kill that? I have also tried with different random port. How can they fail as well?

D:\mongodb-win32-x86_64-2.2.3\bin>mongod
mongod --help for help and startup options
Sun Mar 03 18:10:03 [initandlisten] MongoDB starting : pid=6292 port=27017 dbpat
h=\data\db\ 64-bit host=Sadaf
Sun Mar 03 18:10:03 [initandlisten] db version v2.2.3, pdfile version 4.5
Sun Mar 03 18:10:03 [initandlisten] git version: f570771a5d8a3846eb7586eaffcf4c2
f4a96bf08
Sun Mar 03 18:10:03 [initandlisten] build info: windows sys.getwindowsversion(ma
jor=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB
_VERSION=1_49
Sun Mar 03 18:10:03 [initandlisten] options: {}
Sun Mar 03 18:10:03 [initandlisten] journal dir=/data/db/journal
Sun Mar 03 18:10:03 [initandlisten] recover : no journal files present, no recov
ery needed
Sun Mar 03 18:10:04 [initandlisten] ERROR: listen(): bind() failed errno:10048 O
nly one usage of each socket address (protocol/network address/port) is normally
 permitted. for socket: 0.0.0.0:27017
Sun Mar 03 18:10:04 [websvr] ERROR: listen(): bind() failed errno:10048 Only one
 usage of each socket address (protocol/network address/port) is normally permit
ted. for socket: 0.0.0.0:28017
Sun Mar 03 18:10:04 [initandlisten] now exiting
Sun Mar 03 18:10:04 dbexit:
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to close listening sockets..
.
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to flush diaglog...
Sun Mar 03 18:10:04 [initandlisten] shutdown: going to close sockets...
Sun Mar 03 18:10:04 [initandlisten] shutdown: waiting for fs preallocator...
Sun Mar 03 18:10:04 [initandlisten] shutdown: lock for final commit...
Sun Mar 03 18:10:04 [initandlisten] shutdown: final commit...
Sun Mar 03 18:10:04 [initandlisten] shutdown: closing all files...
Sun Mar 03 18:10:04 [initandlisten] closeAllFiles() finished
Sun Mar 03 18:10:04 [initandlisten] journalCleanup...
Sun Mar 03 18:10:04 [initandlisten] removeJournalFiles
Sun Mar 03 18:10:04 [initandlisten] shutdown: removing fs lock...
Sun Mar 03 18:10:04 dbexit: really exiting now

D:\mongodb-win32-x86_64-2.2.3\bin>echo ps -A | grep mongo

D:\mongodb-win32-x86_64-2.2.3\bin>


来源: stackexchange

问:
Analyze c# code with sonarQube: MSBUILD version problems
I need to analyze various C# files  (not a project, just .cs files put under the same directory).

I tried the analysis in 2 different ways and I have errors in each of it. Could someone help solve any of those errors?

1- I tried the analysis like mentioned here

By executing C:\sonar-scanner\bin\sonar-scanner.bat  in the root file, I have this error

```<code>ERROR: Error during SonarQube Scanner execution
java.lang.IllegalArgumentException: Custom and 3rd party Roslyn analyzers
are only by MSBuild 14. Either use MSBuild 14, or disable the custom/3rd
party Roslyn analyzers in your quality profile.
</code>```

2- I tired creating a project and analyzing with SonarQube Scanner for MSBuild

But at the end, I have this error that appears

```<code>The SonarQube MSBuild integration failed: SonarQube was unable to collect
the required information about your projects.
Possible causes:
 1. The project has not been built - the project must be built in between
the begin and end steps
 2. An unsupported version of MSBuild has been used to build the project.
 Currently MSBuild 14.0 upwards are supported
 3. The begin, build or end steps have not all been launched from the
 same folder
 Generation of the sonar-properties file failed. Unable to complete
 SonarQube analysis.
</code>```

I have Visual Studio 2015,2012,2010,2008 installed. How can I verify that I am using the correct MSBUILD verison (14) because I checked C:\Program Files (x86)\MSBuild and I found the version 14 there.

Is there another issue to handle ?

At the end, I need to be able to do the analysis in both the first and seocnd way.

Thank you in advance!

答:
2- I tired creating a project and analyzing with SonarQube Scanner for MSBuild

According to the document, we need execute following commands from the root folder of the project you want to analyze:

```<code>SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end
</code>```

But the command MSBuild.exe is a external command, can not be recognized by Windows in an arbitrary directory, you should add the MSBuild path "C:\Program Files (x86)\MSBuild\14.0\Bin" in to your system environment to make the begin, build or end steps are all launched from the same folder.

ContentLicense: CC BY-SA 3.0

Body:
I need to analyze various C# files  (not a project, just .cs files put under the same directory).

I tried the analysis in 2 different ways and I have errors in each of it. Could someone help solve any of those errors?

1- I tried the analysis like mentioned here

By executing C:\sonar-scanner\bin\sonar-scanner.bat  in the root file, I have this error

ERROR: Error during SonarQube Scanner execution
java.lang.IllegalArgumentException: Custom and 3rd party Roslyn analyzers
are only by MSBuild 14. Either use MSBuild 14, or disable the custom/3rd
party Roslyn analyzers in your quality profile.

2- I tired creating a project and analyzing with SonarQube Scanner for MSBuild

But at the end, I have this error that appears

The SonarQube MSBuild integration failed: SonarQube was unable to collect
the required information about your projects.
Possible causes:
 1. The project has not been built - the project must be built in between
the begin and end steps
 2. An unsupported version of MSBuild has been used to build the project.
 Currently MSBuild 14.0 upwards are supported
 3. The begin, build or end steps have not all been launched from the
 same folder
 Generation of the sonar-properties file failed. Unable to complete
 SonarQube analysis.

I have Visual Studio 2015,2012,2010,2008 installed. How can I verify that I am using the correct MSBUILD verison (14) because I checked C:\Program Files (x86)\MSBuild and I found the version 14 there.

Is there another issue to handle ?

At the end, I need to be able to do the analysis in both the first and seocnd way.

Thank you in advance!

Body:
2- I tired creating a project and analyzing with SonarQube Scanner for MSBuild

According to the document, we need execute following commands from the root folder of the project you want to analyze:

SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe end

But the command MSBuild.exe is a external command, can not be recognized by Windows in an arbitrary directory, you should add the MSBuild path "C:\Program Files (x86)\MSBuild\14.0\Bin" in to your system environment to make the begin, build or end steps are all launched from the same folder.


问:
40001 error in PostgreSQL
I have simple table "Counters":

```<code>"CounterId" SERIAL (PK)

"CounterName" VARCHAR(50) NOT NULL (UNIQUE INDEX)

"Value" BIGINT NOT NULL
</code>```

When two serializable transactions (actually there are many transactions like this in same time) executing queries:

```<code>SELECT NULL
FROM "Counters"
WHERE "CounterName" = @Value FOR UPDATE

SELECT "CounterId", "CounterName", "Value"
FROM "Counters"
WHERE "CounterName" = @Value
LIMIT 2
</code>```

(this query executes by Entity Framework in same connection and transaction)

```<code>UPDATE "Counters" SET "Value" = @Value WHERE "CounterId" = @CounterId
</code>```

One of transactions is rolled back with error 40001

could not serialize access due to read/write dependencies among transactions

I'm retrying error transactions (5 times), but still have this error occurs.

Maybe this caused by different predicates in first and third queries?

答:
If two transactions like the one you describe above run concurrently, the following will happen:

Transaction 1 locks a row with SELECT ... FOR UPDATE.

Transaction 2 tries to lock the same row and is blocked.

Transaction 1 modifies the value and commits.

Transaction 2 is unblocked, and before it locks the row, it has to recheck if the row version it is about to lock is still the most current version. Because of the modification by Transaction 1, that is no longer the case, and a serialization error is thrown.

There is no way to avoid that problem if several transactions with isolation level REPEATABLE READ or higher are trying to modify the same rows. Be ready to retry often!

It seems like the transaction actually locks more rows than it modifies. That exacerbates the problem. Only lock those rows that you need to change!

Title: 40001 error in PostgreSQL

Body:
I have simple table "Counters":

"CounterId" SERIAL (PK)

"CounterName" VARCHAR(50) NOT NULL (UNIQUE INDEX)

"Value" BIGINT NOT NULL

When two serializable transactions (actually there are many transactions like this in same time) executing queries:

SELECT NULL
FROM "Counters"
WHERE "CounterName" = @Value FOR UPDATE

SELECT "CounterId", "CounterName", "Value"
FROM "Counters"
WHERE "CounterName" = @Value
LIMIT 2

(this query executes by Entity Framework in same connection and transaction)

UPDATE "Counters" SET "Value" = @Value WHERE "CounterId" = @CounterId

One of transactions is rolled back with error 40001

could not serialize access due to read/write dependencies among transactions

I'm retrying error transactions (5 times), but still have this error occurs.

Maybe this caused by different predicates in first and third queries?


问:
Mesos build error
I'm begginer on Ubuntu and i'm trying to install Mesos. During the "make" I have this error:

```<code>../3rdparty/libprocess/3rdparty/glog-0.3.3/.libs/libglog.a(libglog_la-logging.o):(.data.rel.ro._ZTCN6google10LogMessage9LogStreamE0_So[_ZTVN6google10LogMessage9LogStreamE]+0x48): undefined reference to `virtual thunk to std::basic_ostream<char, std::char_traits<char> >::~basic_ostream()'
collect2: error: ld returned 1 exit status
make[2]: *** [libmesos.la] Error 1
make[2]: Leaving directory `/home/MyName/mesos-0.20.1/build/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/MyName/mesos-0.20.1/build/src'
make: *** [all-recursive] Error 1
</code>```

please help me with the start programming in mesos.
Thanks!

答:
Try to run:

```<code>/home/MyName/mesos-0.20.1/configure
</code>```

And then:

```<code>making install
</code>```

Title: Mesos build error

Body:
I'm begginer on Ubuntu and i'm trying to install Mesos. During the "make" I have this error:

../3rdparty/libprocess/3rdparty/glog-0.3.3/.libs/libglog.a(libglog_la-logging.o):(.data.rel.ro._ZTCN6google10LogMessage9LogStreamE0_So[_ZTVN6google10LogMessage9LogStreamE]+0x48): undefined reference to `virtual thunk to std::basic_ostream<char, std::char_traits<char> >::~basic_ostream()'
collect2: error: ld returned 1 exit status
make[2]: *** [libmesos.la] Error 1
make[2]: Leaving directory `/home/MyName/mesos-0.20.1/build/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/MyName/mesos-0.20.1/build/src'
make: *** [all-recursive] Error 1

please help me with the start programming in mesos.
Thanks!

Body:
Try to run:

/home/MyName/mesos-0.20.1/configure

And then:

making install


问:
Dispose() is not called for View
In a viewpager, i have added a view in 10 pages. My requirement is need to dispose unused view contents (ie) currently 1 view is displayed in viewpager and need to dispose unused 9 views contents. So i have override the Dispose() as like below.

```<code>  protected override void Dispose(bool disposing)
    {
        DisposeContent();
        base.Dispose(disposing);
    }
</code>```

But, the dispose() is not being called, when navigates to next page.

Can you please help me out how to dispose the unused view contents?

答: Dispose would only get called when you pop a page, when u move from one page to another, a forward navigation, the page is still alive and would be available in the navigation stack. When a page is removed (when performing back navigation) the page will get disposed. </p>

Title: Dispose() is not called for View

Body:
In a viewpager, i have added a view in 10 pages. My requirement is need to dispose unused view contents (ie) currently 1 view is displayed in viewpager and need to dispose unused 9 views contents. So i have override the Dispose() as like below.

  protected override void Dispose(bool disposing)
    {
        DisposeContent();
        base.Dispose(disposing);
    }

But, the dispose() is not being called, when navigates to next page.

Can you please help me out how to dispose the unused view contents?


问:
File upload using ajax and JavaScript function
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

```<code><script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</code>```

答:
If you only have one image and are using your input in a form, you can get the object by using FormData().And sending it when you click on a submit button. When passing it to AJAX use the variable (formdata) to tell AJAX what data to send. Hope this helps:

```<code>  function myFunction(event){
       event.preventDefault();
      var formdata = new FormData();
     formdata.append("images[]",images);
      $.ajax({
        type: 'GET',
        url: 'ajax.php',
        data: formdata,
        beforeSend: function() {},
        success: function(data) {
           alert(data);
       }
     });
   }
</code>```

If you are uploading multiple images:

```<code>  <form id="yourform" method="POST" enctype="multipart/form-data">
      <input type="file" name="images[]" id="up" onchange="myFunction()"
    multiple/>
   </form>
</code>```

Body:
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<input type="file" name="images" id="up" onchange="myFunction()" />

Body:
If you only have one image and are using your input in a form, you can get the object by using FormData().And sending it when you click on a submit button. When passing it to AJAX use the variable (formdata) to tell AJAX what data to send. Hope this helps:

  function myFunction(event){
       event.preventDefault();
      var formdata = new FormData();
     formdata.append("images[]",images);
      $.ajax({
        type: 'GET',
        url: 'ajax.php',
        data: formdata,
        beforeSend: function() {},
        success: function(data) {
           alert(data);
       }
     });
   }

If you are uploading multiple images:

  <form id="yourform" method="POST" enctype="multipart/form-data">
      <input type="file" name="images[]" id="up" onchange="myFunction()"
    multiple/>
   </form>


问:
Why AppCompat does not support the current theme features windowActionBar: false
Why AppCompat does not support the current theme features  { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false

```<code>    IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
    at android.app.ActivityThread.access$1100(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
    at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.github.paolorotolo.appintro.AppIntroBase.onCreate(AppIntroBase.java:79)
    at com.infos.activities.Activity_Splash.onCreate(Activity_Splash.kt:27)
    at android.app.Activity.performCreate(Activity.java:6321)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread
</code>```

my Theme style

```<code> <!-- Base application theme. -->
    <style name="MyTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>

        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@color/windowBackground</item>
        <item name="colorButtonNormal">@color/colorPrimary</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>
</code>```

答:
go to your styles.xml and change you main theme parent with NoActionBar
like this

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
 </style>
</code>```

Body:
Why AppCompat does not support the current theme features  { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false

    IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
    at android.app.ActivityThread.access$1100(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
    at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
    at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.github.paolorotolo.appintro.AppIntroBase.onCreate(AppIntroBase.java:79)
    at com.infos.activities.Activity_Splash.onCreate(Activity_Splash.kt:27)
    at android.app.Activity.performCreate(Activity.java:6321)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread

my Theme style

Body:
go to your styles.xml and change you main theme parent with NoActionBar
like this

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
 </style>


问:
jQuery Get Value of Input Field in the next Div Nest
I am trying to get value of the input field nested in the next div with class 'fullaccountcode' but it keeps on returning empty when I alert the result.

HTML:

```<code><div class="row">
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">
          </div>
                    <div class="col-xs-1 show-slash">
                        <span>/</span>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">
                    </div>
                    <div class="col-xs-1 show-slash">
                        <span>/</span>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">
                    </div>
                </div>
</code>```

JS:

```<code>$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll('.fullaccountcode').eq(0).val());
});
</code>```

JSFiddle Demo

答:
You can use $(this).parent().next().next().find("input").val()

$(document).on("keyup","#mcode",function() {
   console.log($(this).parent().next().next().find("input").val());
    alert($(this).parent().next().next().find("input").val());
  });```
<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>
<div class="row">
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">
              </div>
      <div class="col-xs-1 show-slash">
       <span>/</span>
      </div>
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">
      </div>
      <div class="col-xs-1 show-slash">
       <span>/</span>
      </div>
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">
      </div>
     </div></code>```

Body:
I am trying to get value of the input field nested in the next div with class 'fullaccountcode' but it keeps on returning empty when I alert the result.

HTML:

                        <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">

                        /

                        <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">

                        /

                        <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">

JS:

$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll('.fullaccountcode').eq(0).val());
});

JSFiddle Demo

Body:
You can use $(this).parent().next().next().find("input").val()

$(document).on("keyup","#mcode",function() {
   console.log($(this).parent().next().next().find("input").val());
    alert($(this).parent().next().next().find("input").val());
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">
              </div>
      <div class="col-xs-1 show-slash">
       <span>/</span>
      </div>
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">
      </div>
      <div class="col-xs-1 show-slash">
       <span>/</span>
      </div>
      <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
       <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">
      </div>
     </div>


问:
PHP & MySQL - not inserting into database
I've got an problem in my code. The insert is not working. The code is below.

HTML:

```<code><form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>
</code>```

PHP:

```<code><?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "<p class='success'>Image uploaded successfully</p>";
    } else {
        $msg = "<p class='error'>There was a problem uploading the image</p>";
    }
}
?>
</code>```

Everything is fine except the inserting into database.

答:
Your query is fine, it should work.

But you're allowing SQL injections, so if you send within parameter single quotes your query will not work as expected and will throw out an error...

You should first:

clear passed strings (use mysqli_real_escape_string), http://php.net/manual/en/mysqli.real-escape-string.php

Check if mysqli_query executed if not then use mysqli_error to find out what error caused your query to not work: http://php.net/manual/en/mysqli.error.php

Body:
I've got an problem in my code. The insert is not working. The code is below.

HTML:

<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="size" value="1000000">
    <input type="text" placeholder="headline of the news" name="title">
    <input type="file" accept="image/*" name="image">
    <select name="side" value="side">
        <option>Left</option>
        <option>Header</option>
        <option>Main</option>
        <option>Ending</option>
    </select>
    <textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
    <input type="submit" name="go" value="Post">
</form>

PHP:

<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
    $target = "images/".basename($_FILES['image']['name']);
    $title = $_POST['title'];
    $image = $_FILES['image']['name'];
    $side = $_POST['side'];
    $desc = $_POST['desc'];
    $sql = "INSERT INTO contents (title, image, side, description)
    VALUES ('$title', '$image', '$side', '$desc')";
    $result = mysqli_query($db, $sql);
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $msg = "
Image uploaded successfully
";
    } else {
        $msg = "
There was a problem uploading the image
";
    }
}
?>

Everything is fine except the inserting into database.


问:
multiple radio tbns give checked = true in backend
I have 3 radiobtns (for different ways to log in on an application. But somehow it gives back true to 2 of the radioboxes when I ask if they are checked though there's only 1 checked. I already checked a thousand times that there's nowhere in the backend something that trigger it to be true but that's not the case. Anyone got any ideas what I'm doing wrong?

Frontend:

```<code> <asp:RadioButton ID="rdr_username" runat="server" GroupName="log" value="username"
                       onclick="$('#eidimage').hide();$('#cardimg').hide();$('#usernamepassword').show();$('#ctl00_ContentPlaceHolder1_txtUsername').focus()" />

<asp:RadioButton ID="rdr_eid" runat="server" name="type" GroupName="log" value="eid"
                        onclick="$('#usernamepassword').hide();$('#cardimg').hide();$('#eidimage').show();" />

<asp:RadioButton ID="ad_id" runat="server" name="type" GroupName="log" value="eid"
                        onclick="$('#usernamepassword').hide();$('#cardimg').show();$('#eidimage').hide();" />
</code>```

Backend:

```<code> Protected Sub btnAanmelden_Click2(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAanmelden.Click
        If rdr_username.Checked Then
            'do something

        ElseIf rdr_eid.Checked Then
         'do something

        ElseIf ad_id.Checked Then
            'do something
        End If

    End Sub
</code>```

答:
your 'value' for RadioButton ID="rdr_eid" and RadioButton ID="ad_id" are the same, either have different values for each radio button,  or remove the value attribute altogether.

Note: .Checked gets or sets the value from the radio button, because the value is  value="eid" for button rdr_eid and ad_id, if button two is checked, then button three also returns true, likewise if button three is checked, button two is true too.

Body:
I have 3 radiobtns (for different ways to log in on an application. But somehow it gives back true to 2 of the radioboxes when I ask if they are checked though there's only 1 checked. I already checked a thousand times that there's nowhere in the backend something that trigger it to be true but that's not the case. Anyone got any ideas what I'm doing wrong?

Frontend:

 <asp:RadioButton ID="rdr_username" runat="server" GroupName="log" value="username"
                       onclick="$('#eidimage').hide();$('#cardimg').hide();$('#usernamepassword').show();$('#ctl00_ContentPlaceHolder1_txtUsername').focus()" />

<asp:RadioButton ID="rdr_eid" runat="server" name="type" GroupName="log" value="eid"
                        onclick="$('#usernamepassword').hide();$('#cardimg').hide();$('#eidimage').show();" />

<asp:RadioButton ID="ad_id" runat="server" name="type" GroupName="log" value="eid"
                        onclick="$('#usernamepassword').hide();$('#cardimg').show();$('#eidimage').hide();" />

Backend:

 Protected Sub btnAanmelden_Click2(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAanmelden.Click
        If rdr_username.Checked Then
            'do something

        ElseIf rdr_eid.Checked Then
         'do something

        ElseIf ad_id.Checked Then
            'do something
        End If

    End Sub


问:
AngularJS hiding input field
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

```<code><h2>Welcome to Mail Service</h2>

<form action="/action_page.php">
  <div class="imgcontainer">
    <img src="images/img_avatar2.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label><b>Username</b></label><br>
    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
    <label><b>Password</b></label><br>
    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>

    <!-- NAME INPUT FIELD -->
    <div class="textField-hidden">
        <label><b>Name</b></label><br>
        <input type="text" placeholder="Enter Name" ng-model="user.name">
    </div><br>

    <button type="submit" ng-click="login()">Login</button><br>
    <button type="submit" ng-click="register()">Register</button>
  </div>

</form>
</code>```

AngularJS Controller:

```<code>app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);
</code>```

答:
You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:

```<code>$scope.showName = false;

$scope.login = function() {
  // Your code
  $scope.showName = false;
}

$scope.register = function() {
  // Your code
  $scope.showName = false;
}
</code>```

Change your HTML accordingly:

```<code><input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">
</code>```

In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.

Title: AngularJS hiding input field

Body:
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?

HTML:

Welcome to Mail Service

<form action="/action_page.php">

    Username

    <input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username">

    Password

    <input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password">

        Name

        <input type="text" placeholder="Enter Name" ng-model="user.name">

    <button type="submit" ng-click="login()">Login</button>

    <button type="submit" ng-click="register()">Register</button>

</form>

AngularJS Controller:

app.controller('LoginCtrl', ['$scope', '$resource', '$location',
    function($scope, $resource, $location)
    {
        $scope.login = function()
        {
            var loginRequest = $resource('/api/login');

            loginRequest.save($scope.user, function(response)
            {
            });
        };

        $scope.register = function()
        {
            var registerRequest = $resource('/api/register');

            loginRequest.save($scope.user, function(response)
            {
            });
        };
    }]);

Body:
You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:

$scope.showName = false;

$scope.login = function() {
  // Your code
  $scope.showName = false;
}

$scope.register = function() {
  // Your code
  $scope.showName = false;
}

Change your HTML accordingly:

<input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">

In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.


问:
(psycopg2.OperationalError) SSL SYSCALL error: Software caused connection abort
I am using apache with mod_wsgi in windows platform to deploy my flask application. I am using sqlalchemy to connect redshift database with connection pool(size 10).
After few days suddenly I am getting follwoing error.

(psycopg2.OperationalError) SSL SYSCALL error: Software caused connection abort

Can anybody suggest why I am getting this error and how to fix?

If I do the apache restart then this error gone. But after few days it again comeback.

答: I solved this error by turning DEBUG=False in my config file [and/or in the run.py]. Hope it helps someone.


问:
Does upgrading jQuery UI 1.7.2 to 1.8.7 result in a performance improvement?
My site is only using dialogs and buttons from jQuery UI. In general things are working fine, but from time to time some users are facing light performance issues; the system is not as responsive as it should be in their opinion.

Upgrading from jQuery 1.4.2 to 1.4.4 really did a good job, because there are lots of find()/filter() calls in my code. Should I expect some performance benefits from upgrading jQuery UI?

答: The release notes say it's lighter - I'd hazard a guess that helped it be a bit quicker too.</p>

ContentLicense: CC BY-SA 2.5


问:
Keep element fixed while Safari navigation bar collapes on iOS
I'm developing a web site based on the Hyde theme for Jekyll.

This layout uses a fixed navigation bar on the left with 100% width. This is working fine in most situations.

In Safari on iOS, however, the height of the viewport changes while the user is scrolling as the browsers top navigation bar collapses. If this happens, the navigation bar's size is not updated until the scroll stops, leaving an area in the lower left corner that is not covered by the navigation bar:

(Notice the text extends below the navigation bar. This screenshot was taken while the page was in motion.)

This video shows the problem in action.

Is there any way to force Safari to update the navigation bar's height while the scroll is in progress?

答:
Add the below styles to fix the issue

```<code>html,body{
    -webkit-overflow-scrolling: touch;
}
</code>```

Here you find the reference

Body:
Add the below styles to fix the issue

html,body{
    -webkit-overflow-scrolling: touch;
}

Here you find the reference


问:
NetSuite - using "anyof" with multiple parameters
I am trying to have a searchFilter in a script that would put in many parameters for internalid. For example, my code for the filter is below. An example for the values of listIds is "11276, 1234, 7895".

What I am trying to figure out is what format listIds should be if I want the above input? Do I need csv values or an array or something else?

I can't find anything in SuiteAnswers or Stackoverflow for this. I am going to just try an array first (which is my gut instinct) and see from there but was hoping to save some time. If I determine the answer, I will be posting it for others.

var listIDs = "11276, 1234, 7895";
var a_filters = [];
a_filters.push(new nlobjSearchFilter('internalid', null, 'anyof', listIDs));
```

答:
You can actually write like this:</p>

```<code>filters: ['internalid', 'ANY', ["1397","1251"]]
</code>```

Body:
You can actually write like this:

filters: ['internalid', 'ANY', ["1397","1251"]]


问:
count the number of points at the end of a string
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

```<code>string sample = "This.is.a.sample.string.....";
</code>```

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

```<code>\.*$
</code>```

should be used in such a case.

答:
Using Regex:

```<code>int points = Regex.Match("This.is.a.sample.string....", @"^[\w\W]*?([.]*+)$").Groups[1].Value.Length;
</code>```

Description:

*+ = Matches as many characters as possible

*? = Matches as few characters as possible.

Body:
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

string sample = "This.is.a.sample.string.....";

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

\.*$

should be used in such a case.

Body:
Using Regex:

int points = Regex.Match("This.is.a.sample.string....", @"^[\w\W]*?([.]*+)$").Groups[1].Value.Length;

Description:

*+ = Matches as many characters as possible

*? = Matches as few characters as possible.


问:
Any Node.js HTTP request module that works both in the server and in the browser when bundled with Webpack?
I need a request module that works both in the Node.js server and in the client, when bundled with Webpack.

My requirements are really basic. I just need to do some HTTP Ajax requests, like get and post. Automatic JSON parsing would be awesome.

I'm taking a look at Request, which seems solid by the number of commits and downloads, but the website doesn't mention whether it works while bundled in the browser.

Any suggestion?

答:
I use axios

Promise based HTTP client for the browser and node.js

Features

Make XMLHttpRequests from the browser

Make http requests from node.js

Supports the Promise API

Intercept request and response

Transform request and response data

Cancel requests

Automatic transforms for JSON data

Client side support for protecting against XSRF


问:
How define a couple of setIntervals and clear them with delay
I need to randomly change characters of a text and after some delay fix them.

There is my code:

SOME TEXT

```

It seems i have no a good understanding of how setInterval work! :(

EDIT:

With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.

Can someone guide me?

答:
basicly setInterval execute a function with a iteration in time. and setInterval gives you a promise to cancel it any time you want.

```<code>var myPromise = setInterval(function(){
  //some code here
},delayMiliseconds);
</code>```

to cancel this code

```<code>clearInterval(myPromise);
</code>```

Body:
I need to randomly change characters of a text and after some delay fix them.

There is my code:

SOME TEXT

It seems i have no a good understanding of how setInterval work! :(

EDIT:

With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.

Can someone guide me?

Body:
basicly setInterval execute a function with a iteration in time. and setInterval gives you a promise to cancel it any time you want.

var myPromise = setInterval(function(){
  //some code here
},delayMiliseconds);

to cancel this code

clearInterval(myPromise);


问:
how to config nignx proxy root path to tomcat server but service static content directly at same time
i want   nginx to  service http://myhost.com/v2 staic content directly ,

but proxy  http://myhost.com/ to http://mytomcat:8080/

my config of /etc/nginx/sites-enabled/default

```<code>   location /v2/static {

    }

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
            proxy_set_header Host               $host;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8080/;
    }
</code>```

now , got HTTP ERROR 404 when accessing  http://myhost.com/ ,but http://mytomcat:8080/ is working,

any one can tell me how to config nginx ?

答:
Set port_in_redirect off; Set your config exactly as below:

```<code>location / {
        proxy_pass http://127.0.0.1:8080/;
        port_in_redirect off;
        proxy_redirect  off;
        proxy_set_header  Host  $http_host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
}
</code>```

Hope that helps

Body:
i want   nginx to  service http://myhost.com/v2 staic content directly ,

but proxy  http://myhost.com/ to http://mytomcat:8080/

my config of /etc/nginx/sites-enabled/default

   location /v2/static {

    }

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri $uri/ =404;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
            proxy_set_header Host               $host;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8080/;
    }

now , got HTTP ERROR 404 when accessing  http://myhost.com/ ,but http://mytomcat:8080/ is working,

any one can tell me how to config nginx ?

Body:
Set port_in_redirect off; Set your config exactly as below:

location / {
        proxy_pass http://127.0.0.1:8080/;
        port_in_redirect off;
        proxy_redirect  off;
        proxy_set_header  Host  $http_host;
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
}

Hope that helps


问:
Frequent concurrent method calls in Java data-logger
I'm implementing a Java Data-logger which reads, at precise intervals of time, some datas from different production machines. To avoid having one call blocking the following ones, I was thinking of making a new thread for every call to the parser class.

However, this would require the creation of many threads, and then to stop them, every 10 seconds (which is my reading interval). A non-concurrent approach would cause me to have many delays when the parser gets an exception (due to the possible timeouts of the IoT devices i'm using) making the next calls to be delayed.

```<code>while(!error){

//JDBC connections and other calls here
//Queryresult is a ResultSet that returns all the machine addresses needing to be read

    while(queryresult.next()){
                        //Parser.ParseSpeedV is the method I need to call concurrently
                        Double v = Parser.ParseSpeedV(..Params..);
                        Double s = v*queryresult.getDouble("const");
                        st = conn.createStatement();
                        st.executeUpdate("INSERT INTO ...");
                    }
st.close();
Thread.sleep(10000);
}
</code>```

What is the best way to achieve a concurrent method calls (to the method ParseSpeedV) without having the overhead caused by thousands of thread starting every day?

答:
What you want to use is a ScheduledExecutorService. It allows you to add tasks that are repeated at a fixed rate or fixed delay. So you can i.E. add a task that fetches data from a device every 10 seconds. The Executor service then makes sure that it is run in that interval with resonably low deviation.</p>

```<code>final ScheduledExecutorService myScheduledExecutor = Executors.newScheduledThreadPool(16);
myScheduledExecutor.scheduleAtFixedRate(myTask, 0L, 10L, TimeUnit.SECONDS);
</code>```

Body:
I'm implementing a Java Data-logger which reads, at precise intervals of time, some datas from different production machines. To avoid having one call blocking the following ones, I was thinking of making a new thread for every call to the parser class.

However, this would require the creation of many threads, and then to stop them, every 10 seconds (which is my reading interval). A non-concurrent approach would cause me to have many delays when the parser gets an exception (due to the possible timeouts of the IoT devices i'm using) making the next calls to be delayed.

while(!error){

//JDBC connections and other calls here
//Queryresult is a ResultSet that returns all the machine addresses needing to be read

    while(queryresult.next()){
                        //Parser.ParseSpeedV is the method I need to call concurrently
                        Double v = Parser.ParseSpeedV(..Params..);
                        Double s = v*queryresult.getDouble("const");
                        st = conn.createStatement();
                        st.executeUpdate("INSERT INTO ...");
                    }
st.close();
Thread.sleep(10000);
}

What is the best way to achieve a concurrent method calls (to the method ParseSpeedV) without having the overhead caused by thousands of thread starting every day?

Body:
What you want to use is a ScheduledExecutorService. It allows you to add tasks that are repeated at a fixed rate or fixed delay. So you can i.E. add a task that fetches data from a device every 10 seconds. The Executor service then makes sure that it is run in that interval with resonably low deviation.

final ScheduledExecutorService myScheduledExecutor = Executors.newScheduledThreadPool(16);
myScheduledExecutor.scheduleAtFixedRate(myTask, 0L, 10L, TimeUnit.SECONDS);


问:
OpenLayers layer disappear when zooming out
I generated a map using openlayer and I'm adding a baundary using openSpace, OpenSpace.Layer.Boundary, but when I zoom out after a specific level my layer disappears, how can I keep the layer displaying? OpenSpace uses openLayer in the background, so if you can tell me how you would prevent a layer from disappearing on zooming out I guess I can apply the solution to openSpace.

Thank you

答:
Have you looked for scale based rules? It's very common to to use them, and maybe somewhere in the process you involountarily set them or they were generated for you.

Can you post some code to show what you try to do?


问:
Does windows require a user-mode driver to be signed?
I have an inf file for a user-mode driver for a device.

Does windows require me to get this driver signed?
Are there any risks of not having this driver signed?

I know that kernel-mode drivers need to be signed.

答:
The accepted answer is right about Windows 7, but things are different starting with Windows 8 and now 10.

User-mode drivers, like the Printer driver will install and work in an
  x64-based computer. A dialog will appear to the user during
  installation asking for approval to install the driver. Beginning in
  Windows 8 and later versions of Windows, installation will not proceed
  unless these driver packages are also signed.

https://learn.microsoft.com/en-us/windows-hardware/drivers/install/windows-driver-signing-tutorial


问:
string.replace() cannot replace char " \" "
I have below json from request post in my MVC model

```<code>"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}
</code>```

I don't know why the json object filled with (\") instead only (") but when I check the value with allert in html, it not content (\")

So I want to replace (/") with (")

```<code>[Authorization()]
[HttpPost()]
public ActionResult Update(VModel vModel)
{
   string JsonArray = (vModel.JsonVar).Replace('\"',' ');
}
</code>```

but result still

```<code>"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}
</code>```

how can?

答:
Probably you've mistaken VS debugger output with the real string. Try to open the actual string in the debugger (press loupe).
But if you actually need to replace \" with " use this code:

```<code>string JsonArray = JsonVar.Replace("\\\"", "\"");
</code>```

Or you can just delete all slashes with

```<code>string JsonArray = JsonVar.Replace("\\", string.Empty);
</code>```

Body:
I have below json from request post in my MVC model

"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}

I don't know why the json object filled with (\") instead only (") but when I check the value with allert in html, it not content (\")

So I want to replace (/") with (")

[Authorization()]
[HttpPost()]
public ActionResult Update(VModel vModel)
{
   string JsonArray = (vModel.JsonVar).Replace('\"',' ');
}

but result still

"{\"Brand\":\"\",\"Name\":\"apotik AA\",\"Desc\":\"\",\"Address\":\"Address\",\"Phone\":\"\",\"Tag\":\"\",\"City\":\"BEKASI\",\"Status\":\"0\"}

how can?

Body:
Probably you've mistaken VS debugger output with the real string. Try to open the actual string in the debugger (press loupe).
But if you actually need to replace \" with " use this code:

string JsonArray = JsonVar.Replace("\\\"", "\"");

Or you can just delete all slashes with

string JsonArray = JsonVar.Replace("\\", string.Empty);


问:
Sharing config file between puphpet and puppet
Is it possible to share a config file between puphpet and puppet?

The scenario is;
our development team is using vagrant and puphpet in dev.environments. Once they are ready with a release, I would like to have a clone of their setup (php modules etc) and apply this using puppet on our production servers...

The ideal way would be to simply apply the config.yaml file directly in puppet, but I'm not sure if they "speak the same language"?

答:
No, it is not possible. PuPHPet uses its own baked-in Puppet, and the code for that is here.

What you could do, of course, is write your own wrapper around PuPHPet that hooks into the bits there that you want to build a PuPHPet-like production environment, minus Vagrant. It wouldn't be too hard.


问:
Preventing XSS (Cross-site Scripting)
Let's say I have a simple ASP.NET MVC blog application and I want to allow readers to add comments to a blog post.  If I want to prevent any type of XSS shenanigans, I could HTML encode all comments so that they become harmless when rendered.  However, what if I wanted to some basic functionality like hyperlinks, bolding, italics, etc?

I know that StackOverflow uses the WMD Markdown Editor, which seems like a great choice for what I'm trying to accomplish, if not for the fact that it supports both HTML and Markdown which leaves it open to XSS attacks.

答: If you need to do it in the browser: http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer</p>

OwnerDisplayName: Kevin Pang

ContentLicense: CC BY-SA 4.0

Title: Preventing XSS (Cross-site Scripting)

LastEditorDisplayName: Allain Lalonde


问:
Javascript namespace and problem with IE7
I implemented a Javascript namespacing solution based on this answer to another stack overflow question: How do I declare a namespace in JavaScript?

Let's call this isigma-ns.js:

```<code>var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};
</code>```

I include this script in my page, plus other stuff:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
    <title>Isigma Signature Widget</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>

    <!-- Required javascript and styles for isigma widget-->
    <script type="text/javascript" src="/isme/media/signwidget/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="/isme/media/signwidget/isigma-ns.js"></script>
    <script type="text/javascript">
    $(function(){
        $("#applet").isigmaSignatureApplet({
            purpose: ISIGMA.SIGN,
            url: the_url,
            language: 'es'
        });
    });
    </script>
</code>```

...etc...

It works fine in Firefox, IE8, Chrome, Opera... but fails in IE7 with the message "ISIGMA is not defined" - referring to the line where I make a reference to ISIGMA.SIGN.

Any hints about what can be wrong here? Is there anything wrong with IE7 processing order of Javascript files? Any other guess?

Note: for a full reference, the whole thing is running in http://app.portasigma.com/isme/signwidget/iframe/ and the namespace JS file is really named http://app.portasigma.com/isme/media/signwidget/jquery-isigmaWidget.js

答:
You need to remove the last comma after all the properties/methods you have defined.

older versions of IE choked on this.

```<code>var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },<====-- if this is the LAST property/method, you need to omit the comma.

  // etc...
};
</code>```

Update: another potential issue can arise from "self-closing" script tags. Be sure you have no external scripts referenced like this:

```<code><script src="..."/><!--prone to parsing bugs/errors-->
</code>```

vs.

```<code><script src="..."></script><!--correct-->
</code>```

Body:
I implemented a Javascript namespacing solution based on this answer to another stack overflow question: How do I declare a namespace in JavaScript?

Let's call this isigma-ns.js:

var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },

  // etc...

  signURL: function(cert, url) {
    // etc...
  }
};

I include this script in my page, plus other stuff:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Isigma Signature Widget</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>

...etc...

It works fine in Firefox, IE8, Chrome, Opera... but fails in IE7 with the message "ISIGMA is not defined" - referring to the line where I make a reference to ISIGMA.SIGN.

Any hints about what can be wrong here? Is there anything wrong with IE7 processing order of Javascript files? Any other guess?

Note: for a full reference, the whole thing is running in http://app.portasigma.com/isme/signwidget/iframe/ and the namespace JS file is really named http://app.portasigma.com/isme/media/signwidget/jquery-isigmaWidget.js

Body:
You need to remove the last comma after all the properties/methods you have defined.

older versions of IE choked on this.

var ISIGMA = {
  messages: {
    noValidId: "No valid ID found",
    reason: "Reason",
    // etc...
  },

  language: "ca",
  SIGN: 2,
  PAUSE: 400,
  params: {},

  init: function(params) {
    // etc...
  },

  delay: function(callback) {
    // etc...
  },<====-- if this is the LAST property/method, you need to omit the comma.

  // etc...
};

Update: another potential issue can arise from "self-closing" script tags. Be sure you have no external scripts referenced like this:

<script src="..."/><!--prone to parsing bugs/errors-->

vs.

<script src="..."></script><!--correct-->


问:
Get a user Asp .net MVC C#
I am trying to get an Application User by its Id but it is always returning null. I need it to chow its details on the edit view but because it is null, my edit view has all fields empty.

This is my controller:

```<code>public ActionResult Edit(string id) {

  ApplicationDbContext db = new ApplicationDbContext();
  ApplicationUser user = db.Users.Find(id);
  return View(user);
}

[HttpPost]
public ActionResult Edit(ApplicationUser user) {
    if (ModelState.IsValid) {
      ApplicationDbContext db = new ApplicationDbContext();
      db.Entry(user).State = EntityState.Modified;
      db.SaveChanges();
      return RedirectToAction("Index");

      return View(user);
    }
</code>```

The problem is that the "db.Users.Find(id);" is returning null. Instead of that If I do the following code everything works:

```<code>public ActionResult Edit(string id) {

  ApplicationDbContext db = new ApplicationDbContext();

  ApplicationUser user = new ApplicationUser();
  user.Email = "test@gmail.com";
  //(...)

  return View(user);
}
</code>```

Can you give me an idea of what can be wrong with this?

Thanks in advance for any help.

Update:
Thanks for all your comments. As some of you pointed out the reason is actually very simple - I am searching for id's that don't exist on the DB. However I don't know how it is happening. When I show my ids on a table (check code below), the ids are different from the ones I can see on my table on SQL Object Explorer. How can that happen? Every other information (name and email) is right.

```<code>@model IEnumerable<FMS.Models.ApplicationUser>
<table class="table table-striped table-hover ">
  <thead>
    <tr>
      <th>Name</th>
      <th>E-mail</th>
      <th>ID</th>
    </tr>
  </thead>
  <tbody>

    @foreach (var user in Model) {
    <tr>
      <td>@user.Name</td>
      <td>@user.Email</td>
      <td>@user.Id</td>
      <td class="pull-right">
        @Html.ActionLink("Edit", "Edit", new { id = user.Id})
      </td>
    </tr>

    }

  </tbody>
</table>
</code>```

Update 2:
I just noticed that every time I refresh the view, the id's on the ID column are different! What can be causing this?

答:
You can find the user with:

```<code>db.Users.FirstOrDefault(u => u.Id.Equals(id))
</code>```

and if it returns null maybe you do not have such a user

Title: Get a user Asp .net MVC C#

Body:
I am trying to get an Application User by its Id but it is always returning null. I need it to chow its details on the edit view but because it is null, my edit view has all fields empty.

This is my controller:

public ActionResult Edit(string id) {

  ApplicationDbContext db = new ApplicationDbContext();
  ApplicationUser user = db.Users.Find(id);
  return View(user);
}

[HttpPost]
public ActionResult Edit(ApplicationUser user) {
    if (ModelState.IsValid) {
      ApplicationDbContext db = new ApplicationDbContext();
      db.Entry(user).State = EntityState.Modified;
      db.SaveChanges();
      return RedirectToAction("Index");

      return View(user);
    }

The problem is that the "db.Users.Find(id);" is returning null. Instead of that If I do the following code everything works:

public ActionResult Edit(string id) {

  ApplicationDbContext db = new ApplicationDbContext();

  ApplicationUser user = new ApplicationUser();
  user.Email = "test@gmail.com";
  //(...)

  return View(user);
}

Can you give me an idea of what can be wrong with this?

Thanks in advance for any help.

Update:
Thanks for all your comments. As some of you pointed out the reason is actually very simple - I am searching for id's that don't exist on the DB. However I don't know how it is happening. When I show my ids on a table (check code below), the ids are different from the ones I can see on my table on SQL Object Explorer. How can that happen? Every other information (name and email) is right.

@model IEnumerable<FMS.Models.ApplicationUser>

      Name
      E-mail
      ID

    @foreach (var user in Model) {

      @user.Name
      @user.Email
      @user.Id

        @Html.ActionLink("Edit", "Edit", new { id = user.Id})

    }

Update 2:
I just noticed that every time I refresh the view, the id's on the ID column are different! What can be causing this?

Body:
You can find the user with:

db.Users.FirstOrDefault(u => u.Id.Equals(id))

and if it returns null maybe you do not have such a user


问:
Changing printer settings via command line
I have a Brother PT-9800PCN label printer that uses 6mm to 36mm tapes.
Is there a way of changing the default paper size (width, length, orientation) via command line?
I'm generating 18x113mm and 24x50mm labels in pdfs using fpdf and when sending the pdfs to the printer via php it only prints on what paper size is set as default.
I've tried commands with Adobe, Foxit and Sumatra.
I've also tried Verypdf pdfprint command line that has the option to set the paper size with the same outcome.
Was thinking that if I change via command line the default paper size and then send the print job it should work.

答:
Export:

```<code>RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Ss /n "printer" /a "C:\A4-format.dat"
</code>```

Import:

```<code>RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Sr /n "printer" /a "C:\A4-format.dat"
</code>```

Body:
Export:

RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Ss /n "printer" /a "C:\A4-format.dat"

Import:

RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Sr /n "printer" /a "C:\A4-format.dat"


问:
MVC optimization using ScriptBundle
I have the following script bundle

```<code>bundles.Add(new ScriptBundle("~/bundles/jqueryBootstrap").Include(
                    "~/Scripts/jquery-{version}.js","~/Scripts/bootstrap.js",
                     "~/Scripts/jquery-ui-{version}.js"));
    #if DEBUG
            BundleTable.EnableOptimizations = false;
#else
        BundleTable.EnableOptimizations = true;
#endif
</code>```

in web.config

```<code><compilation debug="false" targetFramework="4.0">
</code>```

when i run the application in debug, there is no problem but when i run in release mode i got the error:

jqueryBootstrap:17 -- Uncaught SyntaxError: Unexpected token )

Any idea

答:
Thank you
Somehow when i removed "~/Scripts/jquery-ui-{version}.js" to separate bundle it worked fine.

Title: MVC optimization using ScriptBundle

Body:
I have the following script bundle

bundles.Add(new ScriptBundle("~/bundles/jqueryBootstrap").Include(
                    "~/Scripts/jquery-{version}.js","~/Scripts/bootstrap.js",
                     "~/Scripts/jquery-ui-{version}.js"));
    #if DEBUG
            BundleTable.EnableOptimizations = false;
#else
        BundleTable.EnableOptimizations = true;
#endif

in web.config

<compilation debug="false" targetFramework="4.0">

when i run the application in debug, there is no problem but when i run in release mode i got the error:

jqueryBootstrap:17 -- Uncaught SyntaxError: Unexpected token )

Any idea


问:
Android ffmpeg fails on second run
I have a problem with https://github.com/WritingMinds/ffmpeg-android-java. It's Java wrapper lib for ffmpeg on Android and is was working pretty good. But is seems that you can not run two video encodings in a row. Actually it will encode video only once in a lifetime. Every next time you try to encode a video it will freeze. This is the output that I get when it freeze:

```<code>Build.CPU_ABI : arm64-v8a
Loading FFmpeg for armv7 CPU
Running publishing updates method
ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 4.8 (GCC)
  configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
  libavutil      55. 17.103 / 55. 17.103
  libavcodec     57. 24.102 / 57. 24.102
  libavformat    57. 25.100 / 57. 25.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 31.100 /  6. 31.100
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.101 /  2.  0.101
  libpostproc    54.  0.100 / 54.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/storage/emulated/0/WhatsApp/Media/WhatsApp Video/VID-20160731-WA0005.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 1
    compatible_brands: mp41mp42isom
    creation_time   : 2016-07-31 17:24:29
  Duration: 00:00:13.63, start: 0.000000, bitrate: 1641 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 544x960, 1573 kb/s, 30 fps, 30 tbr, 600 tbn, 1200 tbc (default)
    Metadata:
      creation_time   : 2016-07-31 17:24:29
      handler_name    : Core Media Video
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      creation_time   : 2016-07-31 17:24:29
      handler_name    : Core Media Audio
</code>```

I'm not sure what is going on. It seems like ffmpeg leaves something after the first encoding that locks it for any future encoding. And it will work only if i uninstall and then reinstall application.

If you kill an app from background this issue remains.

If you kill it and restart the device issue remains.

If you use force quit in the settings the issue remains.

Only reinstall enables me to encode new video once. After that nothing works.

答:
It was actually quite simple. I've been using same output filename in both tries. And ffmpeg was asking me if I want to overwrite an existing one. The problem was that this lib didn't log that line. onProgress listener would log last line before that and it was looking like it freezes. </p>

<p>The solution is to add "-y" which would overwrite output file without asking. </p>

Title: Android ffmpeg fails on second run

Body:
I have a problem with https://github.com/WritingMinds/ffmpeg-android-java. It's Java wrapper lib for ffmpeg on Android and is was working pretty good. But is seems that you can not run two video encodings in a row. Actually it will encode video only once in a lifetime. Every next time you try to encode a video it will freeze. This is the output that I get when it freeze:

Build.CPU_ABI : arm64-v8a
Loading FFmpeg for armv7 CPU
Running publishing updates method
ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 4.8 (GCC)
  configuration: --target-os=linux --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi- --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
  libavutil      55. 17.103 / 55. 17.103
  libavcodec     57. 24.102 / 57. 24.102
  libavformat    57. 25.100 / 57. 25.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 31.100 /  6. 31.100
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.101 /  2.  0.101
  libpostproc    54.  0.100 / 54.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/storage/emulated/0/WhatsApp/Media/WhatsApp Video/VID-20160731-WA0005.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 1
    compatible_brands: mp41mp42isom
    creation_time   : 2016-07-31 17:24:29
  Duration: 00:00:13.63, start: 0.000000, bitrate: 1641 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 544x960, 1573 kb/s, 30 fps, 30 tbr, 600 tbn, 1200 tbc (default)
    Metadata:
      creation_time   : 2016-07-31 17:24:29
      handler_name    : Core Media Video
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      creation_time   : 2016-07-31 17:24:29
      handler_name    : Core Media Audio

I'm not sure what is going on. It seems like ffmpeg leaves something after the first encoding that locks it for any future encoding. And it will work only if i uninstall and then reinstall application.

If you kill an app from background this issue remains.

If you kill it and restart the device issue remains.

If you use force quit in the settings the issue remains.

Only reinstall enables me to encode new video once. After that nothing works.

Body:
It was actually quite simple. I've been using same output filename in both tries. And ffmpeg was asking me if I want to overwrite an existing one. The problem was that this lib didn't log that line. onProgress listener would log last line before that and it was looking like it freezes.

The solution is to add "-y" which would overwrite output file without asking.


问:
Why doesn't `Box::new` return an `Option` or `Result`?
I don't understand why Box::new doesn't return an Option or Result.

The allocation can fail because memory is not unlimited, or something else could happen; what is the behavior in such cases? I can't find any information about it.

答:
This is a language design decision. You have to consider not just the logic of a single operation (Box::new, for example) but how it will affect the language ergonomics. If we were to handle the memory allocation errors with the Return mechanics then these errors would've started to bubble up pretty much everywhere. Even if the method doesn't allocate any memory on the heap currently, it might resort to it in the future. Suddenly a simple change in implementation would be stuck because you'd have to change the API, which with semantic versioning means a major release. All that for a little benefit, because the out of memory handling isn't very reliable or useful in the presence of swapping and memory killers (often you should stop allocating the memory long before you get an out of memory error).

The subject was much discussed on reddit.

One proposed solution I've seen is to treat the out of memory as a panic, unwinding and terminating the corresponding task.


问:
Servicem8 API Notes, Bulk "active" = 0,
I am trying to mark all the notes made by a particular users uuid to 0 so they do not show, altho i am only able to do them one at a time.

When i post via rest for one line it works fine see image below
one field update

altho if i try multiple note uuid i get a ok responce but it wont update the fields see below

multiple field updaes

any suggestions?

答: The ServiceM8 API doesn't support bulk/batch record updates, to update multiple records you will need to submit a request to the API for each record change required.</p>

Title: Servicem8 API Notes, Bulk "active" = 0,


问:
count the number of points at the end of a string
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

```<code>string sample = "This.is.a.sample.string.....";
</code>```

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

```<code>\.*$
</code>```

should be used in such a case.

答:
Using Linq:

```<code>var test = "this.is.a.test........";
var count = test.ToCharArray().Reverse().TakeWhile(q => q == '.').Count();
</code>```

Convert string to array, reverse, then take while character = '.'.  Count result.

Body:
I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.

How can this be done?

string sample = "This.is.a.sample.string.....";

for the example above the correct answer would be 5 because there are 5 points at the end of the string.

because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions

\.*$

should be used in such a case.

Body:
Using Linq:

var test = "this.is.a.test........";
var count = test.ToCharArray().Reverse().TakeWhile(q => q == '.').Count();

Convert string to array, reverse, then take while character = '.'.  Count result.


问:
Command to Change DB Column in Ruby on Rails
Is there a quick console command I can run to change the type I have for an object? It's currently a Ruby Date type, but I would like it to be a Ruby Time type.

I started with this scaffold command:

```<code>$ rails generate scaffold Post title:string content:text postdate:date
</code>```

But wish I would have done the following:

```<code>$ rails generate scaffold Post title:string content:text postdate:time
</code>```

Is there a command and can run to make the update?

答:
Sometimes you have to write some actual code, even in Rails. Try creating migration and then using change_column method. Something like

```<code>change_column :my_table, :my_column, :new_type
</code>```

You put this in your db migration file, not in shell.

Body:
Is there a quick console command I can run to change the type I have for an object? It's currently a Ruby Date type, but I would like it to be a Ruby Time type.

I started with this scaffold command:

$ rails generate scaffold Post title:string content:text postdate:date

But wish I would have done the following:

$ rails generate scaffold Post title:string content:text postdate:time

Is there a command and can run to make the update?

Body:
Sometimes you have to write some actual code, even in Rails. Try creating migration and then using change_column method. Something like

change_column :my_table, :my_column, :new_type

You put this in your db migration file, not in shell.


问:
Selenium FireFoxDriver unable to connect
I've been attempting to use Selenium to drive Firefox for the fist time. I used virtually identical code to drive Chrome without issue.  However, when I attempt to use the Firefox driver, the browser opens, stalls, and then, after about 60 seconds, I get an error report that reads as follows:

```<code>Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox   console output:
4474-a285-3208198ce6fd}","syncGUID":"dcskEFBTLyBH","location":"app-global","version":"48.0.1","type":"theme","internalName":"classic/1.0","updateURL":null,"updateKey":null,"optionsURL":null,"optionsType":null,"aboutURL":null,"icons":{"32":"icon.png","48":"icon.png"},"iconURL":null,"icon64URL":null,"defaultLocale":{"name":"Default","description":"The default theme.","creator":"Mozilla","homepageURL":null,"contributors":["Mozilla Contributors"]},"visible":true,"active":true,"userDisabled":false,"appDisabled":false,"descriptor":"C:\\Program Files\\Mozilla Firefox\\browser\\extensions\\{972ce4c6-7e08-4474-a285-3208198ce6fd}.xpi","installDate":1471881400240,"updateDate":1471881400240,"applyBackgroundUpdates":1,"skinnable":true,"size":21905,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":false,"hasBinaryComponents":false,"strictCompatibility":true,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"48.0.1","maxVersion":"48.0.1"}],"targetPlatforms":[],"seen":true}
1472056603181   addons.xpi  DEBUG   getModTime: Recursive scan of {972ce4c6-7e08-4474-a285-3208198ce6fd}
</code>```

I've checked other guides and all they recommend is that I update my .jar files. I am using selenium-java-3.0.0-beta2 and Firefox 48.0.1 to test so my files are up to date. I would like to get this to run properly.

UPDATE: code still does not work and I've set the System property to set the geckodriver properly. However, I still cannot get the driver to function properly. It won't even launch the browser any more.

```<code>import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class SimpleFireFoxDriver {

public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver","C:\\Selenium\\geckodriver.exe");

    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);

   WebDriver driver = new FirefoxDriver();

   driver.get("http://www.youtube.com");

   System.out.println("Made it to the promised land");

   driver.quit();

    }

}
</code>```

Edit: Also the path to FireFox itself is located here:
"C:\Program Files\Mozilla Firefox\firefox.exe"

答:
Download the latest Gecko driver V0.17.0 and this resolved my error without changing the setProperty or downgrading of Firefox browser.

Not so sure, whether this may help you.

Body:
I've been attempting to use Selenium to drive Firefox for the fist time. I used virtually identical code to drive Chrome without issue.  However, when I attempt to use the Firefox driver, the browser opens, stalls, and then, after about 60 seconds, I get an error report that reads as follows:

Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox   console output:
4474-a285-3208198ce6fd}","syncGUID":"dcskEFBTLyBH","location":"app-global","version":"48.0.1","type":"theme","internalName":"classic/1.0","updateURL":null,"updateKey":null,"optionsURL":null,"optionsType":null,"aboutURL":null,"icons":{"32":"icon.png","48":"icon.png"},"iconURL":null,"icon64URL":null,"defaultLocale":{"name":"Default","description":"The default theme.","creator":"Mozilla","homepageURL":null,"contributors":["Mozilla Contributors"]},"visible":true,"active":true,"userDisabled":false,"appDisabled":false,"descriptor":"C:\\Program Files\\Mozilla Firefox\\browser\\extensions\\{972ce4c6-7e08-4474-a285-3208198ce6fd}.xpi","installDate":1471881400240,"updateDate":1471881400240,"applyBackgroundUpdates":1,"skinnable":true,"size":21905,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":false,"hasBinaryComponents":false,"strictCompatibility":true,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"48.0.1","maxVersion":"48.0.1"}],"targetPlatforms":[],"seen":true}
1472056603181   addons.xpi  DEBUG   getModTime: Recursive scan of {972ce4c6-7e08-4474-a285-3208198ce6fd}

I've checked other guides and all they recommend is that I update my .jar files. I am using selenium-java-3.0.0-beta2 and Firefox 48.0.1 to test so my files are up to date. I would like to get this to run properly.

UPDATE: code still does not work and I've set the System property to set the geckodriver properly. However, I still cannot get the driver to function properly. It won't even launch the browser any more.

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class SimpleFireFoxDriver {

public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver","C:\\Selenium\\geckodriver.exe");

    DesiredCapabilities capabilities = DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);

   WebDriver driver = new FirefoxDriver();

   driver.get("http://www.youtube.com");

   System.out.println("Made it to the promised land");

   driver.quit();

    }

}

Edit: Also the path to FireFox itself is located here:
"C:\Program Files\Mozilla Firefox\firefox.exe"


问:
Create custom Observable
it is possible (and correct) to create a custom observable ?
For example, if i have data in my cache, i would like create custom observable before make a http request:

my request:

```<code>private device: Device;
getDeviceById(deviceId): Observable<Device> {
    if(this.device._id == deviceId) {
        let myObservable = new Observable('with my device');
        return myObservable;
    } else return this.http.get('/api/device/get/'+deviceId)
                .map(res => res.json())
                .catch(this.handleError);
}
</code>```

Thank's

答:
you can do something like this:

```<code>var button = document.querySelector('button');

var subscription = Rx.Observable.create(function(obs) {
  button.onclick = function(event) {
  obs.next(event);
}
.subscribe(function(value) {
   console.log(value);
},);
</code>```

see more in that link: http://reactivex.io/documentation/operators/create.html

Title: Create custom Observable

Body:
it is possible (and correct) to create a custom observable ?
For example, if i have data in my cache, i would like create custom observable before make a http request:

my request:

private device: Device;
getDeviceById(deviceId): Observable<Device> {
    if(this.device._id == deviceId) {
        let myObservable = new Observable('with my device');
        return myObservable;
    } else return this.http.get('/api/device/get/'+deviceId)
                .map(res => res.json())
                .catch(this.handleError);
}

Thank's

Body:
you can do something like this:

var button = document.querySelector('button');

var subscription = Rx.Observable.create(function(obs) {
  button.onclick = function(event) {
  obs.next(event);
}
.subscribe(function(value) {
   console.log(value);
},);

see more in that link: http://reactivex.io/documentation/operators/create.html


问:
What are best practices for dealing with out of memory errors?
I'm wondering, what are good practices for dealing with out of memory errors.

```<code>void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}
</code>```

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.

答:
Since it runs as a service, it's best to let it crash but make it do so in a controlled manner first by logging the error state and then aborting or self-terminating.  The service control manager can be configured to restart the service when it stops out of its control.

If possible you can go further by forcing a controlled dump of itself, which will make it possible to find the cause of the problem.

Your instincts are correct to let it die, because what else is the process to do?  Once it arrives in an out-of-memory state it'll never return to a healthy state.  RIP process.

Body:
I'm wondering, what are good practices for dealing with out of memory errors.

void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.


问:
Best way to pass the value in Some to a function with a default parameter value?
I have a function from a third party library as below :

```<code>def myfunction(input:String = "some constant value")
</code>```

I have a

```<code>myinput:Option[String]
</code>```

with me and I need to pass the function. Right now I am doing this:

```<code>myfunction(myinput.getOrElse("some constant value"))
</code>```

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

答:
There are many ways to achieve this but my favorite one is using pattern matching. This code is also much readable.</p>

```<code>myinput match {
     case Some(str) => myfunction(str)
     case _ => myfunction()
}
</code>```

Body:
I have a function from a third party library as below :

def myfunction(input:String = "some constant value")

I have a

myinput:Option[String]

with me and I need to pass the function. Right now I am doing this:

myfunction(myinput.getOrElse("some constant value"))

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

Body:
There are many ways to achieve this but my favorite one is using pattern matching. This code is also much readable.

myinput match {
     case Some(str) => myfunction(str)
     case _ => myfunction()
}


问:
UITableView not scrolling to bottom
Hi I'm going to link you a video showcasing my problem as it's somewhat hard to convey with words.
UITableView not scrolling to bottom
In the video I'm hitting a button which adds items to the list. Note that I am not stopping at Item 16, and that I am still adding more items to the list that don't get displayed. Eventually, upon added new items, the list will automatically scroll up via

```<code>[_items addObject:[NSString stringWithFormat:@"Trawl %d", count]];

[self.tbl reloadData];

[self.tbl scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.items.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
</code>```

The main issue is towards the end of the video, where I scroll towards the last few items, but I cannot select them. Apparently the issue has to deal with the height of the UITableView. I've tried changing this in the storyboard editor but it didn't do anything. Any ideas? Thanks in advance!

答:
Seems most of you are wrong.

It should be like this:

```<code>[self.tbl scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.items.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
</code>```

That is, should be UITableViewScrollPositionTop, not UITableViewScrollPositionBottom. Here atScrollPosition:UITableViewScrollPositionTop is the origin of change, not the destination.

Title: UITableView not scrolling to bottom

Body:
Hi I'm going to link you a video showcasing my problem as it's somewhat hard to convey with words.
UITableView not scrolling to bottom
In the video I'm hitting a button which adds items to the list. Note that I am not stopping at Item 16, and that I am still adding more items to the list that don't get displayed. Eventually, upon added new items, the list will automatically scroll up via

[_items addObject:[NSString stringWithFormat:@"Trawl %d", count]];

[self.tbl reloadData];

[self.tbl scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.items.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

The main issue is towards the end of the video, where I scroll towards the last few items, but I cannot select them. Apparently the issue has to deal with the height of the UITableView. I've tried changing this in the storyboard editor but it didn't do anything. Any ideas? Thanks in advance!

Body:
Seems most of you are wrong.

It should be like this:

[self.tbl scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.items.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

That is, should be UITableViewScrollPositionTop, not UITableViewScrollPositionBottom. Here atScrollPosition:UITableViewScrollPositionTop is the origin of change, not the destination.


问:
Detecting and intercepting video playback in SFSafariViewController
I am using SFSafariViewController in my app. When the user plays a video I have to show a pop up asking whether the user wants to download the videos. I have done this with UIWebView and AVPlayerItemBecameCurrentNotification. But this is not working in SFSafariViewController. Can someone give me a solution to this?

Here is the code of adding observer to SFSafariViewController

```<code>NotificationCenter.default.addObserver(self.safariViewController!, selector: #selector(self.playerItemBecameCurrent), name: NSNotification.Name(rawValue: "AVPlayerItemBecameCurrentNotification"), object: nil)
</code>```

Thanks

答:
To be honest, this would not be possible in SFSafariViewController.

SFSafariViewController isn't open for inspection/interception like UIWebView and WKWebView. Given the control interfaces with the devices KeyChain it makes sense from a security standpoint too.

You very much can only give it a URL and a set of 2 customisable options.

Revert to a WKWebView or at worst, UIWebView.

Appreciate my answer is late, I hope you found it useful

Body:
I am using SFSafariViewController in my app. When the user plays a video I have to show a pop up asking whether the user wants to download the videos. I have done this with UIWebView and AVPlayerItemBecameCurrentNotification. But this is not working in SFSafariViewController. Can someone give me a solution to this?

Here is the code of adding observer to SFSafariViewController

NotificationCenter.default.addObserver(self.safariViewController!, selector: #selector(self.playerItemBecameCurrent), name: NSNotification.Name(rawValue: "AVPlayerItemBecameCurrentNotification"), object: nil)

Thanks