问:
How to skip wrapping to Try if the argument is already a Try-instance?
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

```<code>def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
</code>```

but that does not compile due to type erasure with the compilation error

```<code>Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^
</code>```

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

```<code>object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}
</code>```

But that does not compile due to ambiguity with the following compiler error:

```<code>Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^
</code>```

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

```<code>class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }
</code>```

This allows me to write tests like the following one:

```<code>"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }
</code>```

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

答:
The standard solution for such overloading is

```<code>def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T])(implicit d: DummyImplicit):Try[T] = arg
</code>```

Note there is a caveat: the second version will only be called if arg is known to by a Try at compile-time. E.g.

```<code>def foo(arg: Any) = wrapToTry(arg)

foo(Try(1))
</code>```

will produce Success(Success(1)). But this will likely be shared by all reasonable solutions (I am not counting your initial version as reasonable).

Body:
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg

but that does not compile due to type erasure with the compilation error

Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}

But that does not compile due to ambiguity with the following compiler error:

Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }

This allows me to write tests like the following one:

"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

Body:
The standard solution for such overloading is

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T])(implicit d: DummyImplicit):Try[T] = arg

Note there is a caveat: the second version will only be called if arg is known to by a Try at compile-time. E.g.

def foo(arg: Any) = wrapToTry(arg)

foo(Try(1))

will produce Success(Success(1)). But this will likely be shared by all reasonable solutions (I am not counting your initial version as reasonable).


来源: stackexchange

问:
grabbing form with jquery not working
I am using JQuery 3.2.1 to grab input forms. the problem is that I don't get anything out, empty object or empty string. I tried with serialize, serialize array, code from SO to get the fields and transform to json, nothing did work.

I am sure that I wrote correctly the form id because the subscription of the function is successful.

here are part of the html:

```<code><form role="form" id="organisationform">
    <div class="row col-sm-offset-1">
        <div class="form-group col-sm-5">
            <label for="name" class="h4">Nom Organisation</label>
            <input type="text" class="form-control" id="nomOrg" placeholder="Nom de l'organisation" required>
        </div>
        <div class="form-group col-sm-5">
            <label for="lastname" class="h4">Identificateur </label>
            <input type="text" class="form-control" id="idOrg" placeholder="Entrer IDentificateur" required>
        </div>
    </div>
...
</form>
</code>```

and here is the js code:

```<code>onSubmit('form#organisationform', function() {
    send('http://localhost:8080/organisation/ajouter', 'form#organisationform');
});
</code>```

in an other file:

```<code>function grabForm(formId) {
var data = {};
 $(this).serializeArray().map(function(x){data[x.name] = x.value;});
return data;
}

function send(url, formId) {

var data = grabForm(formId);

$.ajax({
    url: url,
    ...
});
}

function onSubmit(idform, fn) {
$(idform).submit(function(event) {
event.preventDefault();
fn();
});
}
</code>```

the problem is on the grab thing function it's returns an empty object, but before this form it was serialize function.

in an other test, I just Copy-Paste code from SO:

```<code>    $('#organisationform').submit(function () {
  var $inputs = $('#organisationform :input');

// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
    values[this.name] = $(this).val();
});

 alert(values);
  //Do stuff with view object here (e.g. JSON.stringify?)
});
</code>```

same problem.

SO how can I fix this? or how can I do it?

答:
Seems like you are wrapping the jQuery functions in a load of your own functions which don't actually seem to add any value, but are overcomplicating things, in particular making the scope uncertain and making the flow of control hard to follow.

This should be sufficient to submit the form via ajax:

```<code>$("form#organisationform").submit(function(event) {
  event.preventDefault();
  $.ajax({
    url: "http://localhost:8080/organisation/ajouter",
    data: $(this).serialize(), //serialise the form, which due to the scope can be fetched via 'this',
    method: "POST", //assuming it's a POST, but set it to whatever is right for your server
    success: function(data) {
      console.log(data); //receive any response from the server
    },
    error: function(jQXHR, textStatus, errorThrown) {
      console.log(errorThrown + " " + textStatus); //log any HTTP errors encountered
    }
    //...etc
  });
});
</code>```

You may need to tweak things depending on what exactly the server expects to receive.

ContentLicense: CC BY-SA 3.0

Title: grabbing form with jquery not working

Body:
I am using JQuery 3.2.1 to grab input forms. the problem is that I don't get anything out, empty object or empty string. I tried with serialize, serialize array, code from SO to get the fields and transform to json, nothing did work.

I am sure that I wrote correctly the form id because the subscription of the function is successful.

here are part of the html:

<form role="form" id="organisationform">

            Nom Organisation
            <input type="text" class="form-control" id="nomOrg" placeholder="Nom de l'organisation" required>

            Identificateur
            <input type="text" class="form-control" id="idOrg" placeholder="Entrer IDentificateur" required>

...
</form>

and here is the js code:

onSubmit('form#organisationform', function() {
    send('http://localhost:8080/organisation/ajouter', 'form#organisationform');
});

in an other file:

function grabForm(formId) {
var data = {};
 $(this).serializeArray().map(function(x){data[x.name] = x.value;});
return data;
}

function send(url, formId) {

var data = grabForm(formId);

$.ajax({
    url: url,
    ...
});
}

function onSubmit(idform, fn) {
$(idform).submit(function(event) {
event.preventDefault();
fn();
});
}

the problem is on the grab thing function it's returns an empty object, but before this form it was serialize function.

in an other test, I just Copy-Paste code from SO:

    $('#organisationform').submit(function () {
  var $inputs = $('#organisationform :input');

// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
    values[this.name] = $(this).val();
});

 alert(values);
  //Do stuff with view object here (e.g. JSON.stringify?)
});

same problem.

SO how can I fix this? or how can I do it?

Body:
Seems like you are wrapping the jQuery functions in a load of your own functions which don't actually seem to add any value, but are overcomplicating things, in particular making the scope uncertain and making the flow of control hard to follow.

This should be sufficient to submit the form via ajax:

$("form#organisationform").submit(function(event) {
  event.preventDefault();
  $.ajax({
    url: "http://localhost:8080/organisation/ajouter",
    data: $(this).serialize(), //serialise the form, which due to the scope can be fetched via 'this',
    method: "POST", //assuming it's a POST, but set it to whatever is right for your server
    success: function(data) {
      console.log(data); //receive any response from the server
    },
    error: function(jQXHR, textStatus, errorThrown) {
      console.log(errorThrown + " " + textStatus); //log any HTTP errors encountered
    }
    //...etc
  });
});

You may need to tweak things depending on what exactly the server expects to receive.


问:
How to take the actionscript from an as3 package and use it in .fla
This morning i stumbled upon this source code for a miner game : http://www.emanueleferonato.com/2010/10/22/create-a-flash-game-like-gold-miner-as3-version/

The problem is that I never used packages and classes before ( I only worked with as2 ) .

I need the code from the AS files to be in the timeline AS but cant figure out a way to have it there and working .

If anybody knows how please tell me .

I tried copy/pasting the code , removing the package,class and private text and it still doesn't work .

Any help is apreciated.

Chris

答:
I assume that AS3 package lookups work pretty much like AS2 classes in that they're relative to root directories pointed to by your Flash movie.

For example, the package i.am.a.test{}, would exist at:

i/am/a/test

(Of course, the path above would be relative either to the .fla using it, or to another directory specified in your movie settings.)

...And with a class definition would be something like:

```<code>package i.am.a.test
{
    class ReallyATest
    {
    }
}
</code>```

So, what you need to do is ensure all classes used in the .fla exist in the path relative to the .fla you're working on. Here's a little more info you can use to read up on working with packages: creating a package

ContentLicense: CC BY-SA 2.5

Body:
I assume that AS3 package lookups work pretty much like AS2 classes in that they're relative to root directories pointed to by your Flash movie.

For example, the package i.am.a.test{}, would exist at:

i/am/a/test

(Of course, the path above would be relative either to the .fla using it, or to another directory specified in your movie settings.)

...And with a class definition would be something like:

package i.am.a.test
{
    class ReallyATest
    {
    }
}

So, what you need to do is ensure all classes used in the .fla exist in the path relative to the .fla you're working on. Here's a little more info you can use to read up on working with packages: creating a package


问:
How do I access my viewmodel commands on a Xamarin Forms button?
I have written out some commands for my interface within my viewmodel for my Xamarin Forms project.  I need to access these commands on my buttons so that they perform a task however I'm not sure how to do that.

My ViewModel

TheDemo/ViewModel/MenupageViewModel.cs

```<code>using System;
using System.Windows.Input;
using Xamarin.Forms;

namespace TheDemo
{
    public class MenuPageViewModel
    {
        public ICommand GoDashboardCommand { get; set; }
        public ICommand GoRequirementsCommand { get; set; }
        public ICommand GoFixturesCommand { get; set; }
        public ICommand GoVesselsCommand { get; set; }
        public ICommand GoDutyBrokerCommand { get; set; }
        public ICommand GoSettingsCommand { get; set; }
        public ICommand GoInfoCommand { get; set; }

        public MenuPageViewModel()
        {
            GoDashboardCommand = new Command(GoDashboard);
            GoRequirementsCommand = new Command(GoRequirements);
            GoFixturesCommand = new Command(GoFixtures);
            GoVesselsCommand = new Command(GoVessels);
            GoDutyBrokerCommand = new Command(GoBroker);
            GoSettingsCommand = new Command(GoSettings);
            GoInfoCommand = new Command(GoInfo);
        }

        void GoDashboard(object obj) {
            App.NavigationPage.Navigation.PopToRootAsync();
            App.MenuIsPresented = false;
        }
        void GoRequirements(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Requirements());
            App.MenuIsPresented = false;
        }
        void GoFixtures(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Fixtures());
            App.MenuIsPresented = false;
        }
        void GoVessels(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Vessels());
            App.MenuIsPresented = false;
        }
        void GoBroker(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Duty());
            App.MenuIsPresented = false;
        }
        void GoSettings(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Settings());
            App.MenuIsPresented = false;
        }
        void GoInfo(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Information());
            App.MenuIsPresented = false;
        }
    }
}
</code>```

Menu
TheDemo/Menupage.cs

```<code>using System;
using System.Collections.Generic;
using OxyPlot;
using OxyPlot.Axes;

using OxyPlot.Series;
using OxyPlot.Xamarin.Forms;
using System.Windows.Input;
using Xamarin.Forms;
namespace TheDemo
{
    public partial class MenuPage : ContentPage
    {
        public MenuPage()
        {
            InitializeComponent();
            BindingContext = new MenuPageViewModel();

            Grid grid = new Grid();

            grid.Children.Add(
                        new Button {
                            Text = "Requirements",
                            BackgroundColor = Color.Orange,
                            TextColor = Color.White,
                            Command = //How do I access my commands in my viewmmodel?
                        }, 0, 1);

        }
    }
}
</code>```

答:
First of all, map the view model to the view. To do that, add the following line to the ContentPage tag of your view in XAML like this.

The line to add

```<code>xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo"
</code>```

Example

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo">
</code>```

Then add this snippet inside the content page tag

```<code><ContentPage.BindingContext>
        <viewModels:MenuPageViewModel/>
    </ContentPage.BindingContext>
</code>```

Then add the button and use the command property, like this

```<code><Button Command="{Binding GoInfoCommand}"/>
</code>```

Update the assembly and namespace according to your application. Hope this solved your issue.

Body:
I have written out some commands for my interface within my viewmodel for my Xamarin Forms project.  I need to access these commands on my buttons so that they perform a task however I'm not sure how to do that.

My ViewModel

TheDemo/ViewModel/MenupageViewModel.cs

using System;
using System.Windows.Input;
using Xamarin.Forms;

namespace TheDemo
{
    public class MenuPageViewModel
    {
        public ICommand GoDashboardCommand { get; set; }
        public ICommand GoRequirementsCommand { get; set; }
        public ICommand GoFixturesCommand { get; set; }
        public ICommand GoVesselsCommand { get; set; }
        public ICommand GoDutyBrokerCommand { get; set; }
        public ICommand GoSettingsCommand { get; set; }
        public ICommand GoInfoCommand { get; set; }

        public MenuPageViewModel()
        {
            GoDashboardCommand = new Command(GoDashboard);
            GoRequirementsCommand = new Command(GoRequirements);
            GoFixturesCommand = new Command(GoFixtures);
            GoVesselsCommand = new Command(GoVessels);
            GoDutyBrokerCommand = new Command(GoBroker);
            GoSettingsCommand = new Command(GoSettings);
            GoInfoCommand = new Command(GoInfo);
        }

        void GoDashboard(object obj) {
            App.NavigationPage.Navigation.PopToRootAsync();
            App.MenuIsPresented = false;
        }
        void GoRequirements(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Requirements());
            App.MenuIsPresented = false;
        }
        void GoFixtures(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Fixtures());
            App.MenuIsPresented = false;
        }
        void GoVessels(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Vessels());
            App.MenuIsPresented = false;
        }
        void GoBroker(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Duty());
            App.MenuIsPresented = false;
        }
        void GoSettings(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Settings());
            App.MenuIsPresented = false;
        }
        void GoInfo(object obj) {
            App.NavigationPage.Navigation.PushAsync(new Information());
            App.MenuIsPresented = false;
        }
    }
}

Menu
TheDemo/Menupage.cs

using System;
using System.Collections.Generic;
using OxyPlot;
using OxyPlot.Axes;

using OxyPlot.Series;
using OxyPlot.Xamarin.Forms;
using System.Windows.Input;
using Xamarin.Forms;
namespace TheDemo
{
    public partial class MenuPage : ContentPage
    {
        public MenuPage()
        {
            InitializeComponent();
            BindingContext = new MenuPageViewModel();

            Grid grid = new Grid();

            grid.Children.Add(
                        new Button {
                            Text = "Requirements",
                            BackgroundColor = Color.Orange,
                            TextColor = Color.White,
                            Command = //How do I access my commands in my viewmmodel?
                        }, 0, 1);

        }
    }
}

Body:
First of all, map the view model to the view. To do that, add the following line to the ContentPage tag of your view in XAML like this.

The line to add

xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo"

Example

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo">

Then add this snippet inside the content page tag

<ContentPage.BindingContext>
        <viewModels:MenuPageViewModel/>
    </ContentPage.BindingContext>

Then add the button and use the command property, like this

<Button Command="{Binding GoInfoCommand}"/>

Update the assembly and namespace according to your application. Hope this solved your issue.


问:
How to make/configure an MPI project to run on multiple processes?
I have a small piece of code that should run on multilple processes, which is :

```<code>  #include <stdio.h>
  #include "mpi.h"

  main(int argc, char **argv)
  {
  int ierr, num_procs, my_id;

  ierr = MPI_Init(&argc, &argv);

  /* find out MY process ID, and how many processes were started. */

  ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
  ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

  printf("Hello world! I'm process %i out of %i processes\n",
     my_id, num_procs);

  ierr = MPI_Finalize();
  }
</code>```

the output is :
      Hello world! I'm process 0 out of 1 processes. although it should run on more than one process

We edited the run configurations arguments to "-np 2" so it would run on 2 processes but it always gives us 1 process no matter what the value is.

The used environment is:
Eclipse Juno on Ubuntu 12.04

Source of code: http://condor.cc.ku.edu/~grobe/docs/intro-MPI-C.shtml[^]

答:
Some small points about mpirun or mpiexec commands:

If you are trying to run you app on multiple nodes, make sure that your app is copied to all the nodes.In addition, make sure that all needed binary files (executable & libraries) could be found directly from command line. I personally, prefer to run my MPI programs within a shell script like this:

```<code>#!/bin/sh
PATH=/path/to/all/executable/files \
LD_LIBRARY_PATH=/path/to/all/libraries \
mpirun -np 4 ./my_app  arg1 arg2 arg3
</code>```

Body:
I have a small piece of code that should run on multilple processes, which is :

  #include <stdio.h>
  #include "mpi.h"

  main(int argc, char **argv)
  {
  int ierr, num_procs, my_id;

  ierr = MPI_Init(&argc, &argv);

  /* find out MY process ID, and how many processes were started. */

  ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
  ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

  printf("Hello world! I'm process %i out of %i processes\n",
     my_id, num_procs);

  ierr = MPI_Finalize();
  }

the output is :
      Hello world! I'm process 0 out of 1 processes. although it should run on more than one process

We edited the run configurations arguments to "-np 2" so it would run on 2 processes but it always gives us 1 process no matter what the value is.

The used environment is:
Eclipse Juno on Ubuntu 12.04

Source of code: http://condor.cc.ku.edu/~grobe/docs/intro-MPI-C.shtml[^]

Body:
Some small points about mpirun or mpiexec commands:

If you are trying to run you app on multiple nodes, make sure that your app is copied to all the nodes.In addition, make sure that all needed binary files (executable & libraries) could be found directly from command line. I personally, prefer to run my MPI programs within a shell script like this:

#!/bin/sh
PATH=/path/to/all/executable/files \
LD_LIBRARY_PATH=/path/to/all/libraries \
mpirun -np 4 ./my_app  arg1 arg2 arg3


问:
Provide external Bean before context start
I am developing a Java API for a service and I want to extract it to a library.
I am using spring 4.3.3

Right now there is a bean called ApiConfig which is simple pojo.

```<code>public class ApiConfig {
   private String host;
   private String username;
   private String password;
}
</code>```

and the values are read from a properties file.

I would like to be able to construct and provide this class before the context starts (several components have this class as @Autowired dependency).

For instance:

```<code>public class LoginService {

    @Autowired
    private ApiConfig apiConfig

    [...]
}
</code>```

Basically, I would like to do something like this:

```<code>public static MyApi get(ApiConfig apiConfig) {

     //Here I want to provide this apiConfig as singleton bean that would be used everywhere
    provide somehow this class as bean
    // here all beans are loaded and the it fails because it cannot resolve ApiConfig
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class);
    MyApi myApi= context.getBean(MyApi.class);
    return myApi;
}
</code>```

The method MyApi.get(AppConfig) would be used by other java applications by adding dependency in pom.xml

Is there a way I can do this? Providing the ApiConfig bean and then initialize all the application?

Basically to let Spring know that there is also this bean, before starting context with new AnnotationConfigApplicationContext(ContextConfig.class)

UPDATE

The idea would be this, in any application using this library.

```<code>public static void main(String asdas[]) {
    ApiConfig config = new ApiConfig();
    config.setUsername("BOBTHEUSER");
    //config.set etc
    MyApi api = MyApi.get(config);
    api.doOperation();
</code>```

答:
Actually @Autowire is enough. Make the ApiConfig a Bean and autowire it where it's is necessary. Spring resolves the proper order.

If you have two beans and one need the second to be initialized before creation use @DependsOn annotation

```<code>@Configuration
public class MainConfig  {
    @Autowired
    private ApiConfig apiConfig

    @Bean(name="apiConfig")
    public ApiConfig apiConfig(){
        ... init the config ...
        return apiConfigInstance;
    }

    @Bean(name="myApi")
    @DependsOn("apiConfig")
    public MyApi myApi(){
        MyApi api = new MyApi(apiConfig);
        return api;
    }
}
</code>```

Code from the example modified

Body:
I am developing a Java API for a service and I want to extract it to a library.
I am using spring 4.3.3

Right now there is a bean called ApiConfig which is simple pojo.

public class ApiConfig {
   private String host;
   private String username;
   private String password;
}

and the values are read from a properties file.

I would like to be able to construct and provide this class before the context starts (several components have this class as @Autowired dependency).

For instance:

public class LoginService {

    @Autowired
    private ApiConfig apiConfig

    [...]
}

Basically, I would like to do something like this:

public static MyApi get(ApiConfig apiConfig) {

     //Here I want to provide this apiConfig as singleton bean that would be used everywhere
    provide somehow this class as bean
    // here all beans are loaded and the it fails because it cannot resolve ApiConfig
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class);
    MyApi myApi= context.getBean(MyApi.class);
    return myApi;
}

The method MyApi.get(AppConfig) would be used by other java applications by adding dependency in pom.xml

Is there a way I can do this? Providing the ApiConfig bean and then initialize all the application?

Basically to let Spring know that there is also this bean, before starting context with new AnnotationConfigApplicationContext(ContextConfig.class)

UPDATE

The idea would be this, in any application using this library.

public static void main(String asdas[]) {
    ApiConfig config = new ApiConfig();
    config.setUsername("BOBTHEUSER");
    //config.set etc
    MyApi api = MyApi.get(config);
    api.doOperation();

Body:
Actually @Autowire is enough. Make the ApiConfig a Bean and autowire it where it's is necessary. Spring resolves the proper order.

If you have two beans and one need the second to be initialized before creation use @DependsOn annotation

@Configuration
public class MainConfig  {
    @Autowired
    private ApiConfig apiConfig

    @Bean(name="apiConfig")
    public ApiConfig apiConfig(){
        ... init the config ...
        return apiConfigInstance;
    }

    @Bean(name="myApi")
    @DependsOn("apiConfig")
    public MyApi myApi(){
        MyApi api = new MyApi(apiConfig);
        return api;
    }
}

Code from the example modified


问:
Access split form datasheet goes off screen
I have a split form and the datasheet part goes off the screen. How can I make the split form resize itself automatically so that all this blank space is not shown and only existing records show on the window?
Here is a picture of the form.
Thank you for your time.</p>

答:
You cannot do that, this is the normal behaviour of the datasheet. However, you can try this, it may fit your needs:

1) Drag and adjust the column headings to fill the white space to the right.

2) Set Gridlines to None.

3) Set Alternate Row Color to white.


问:
AFnetworking Internet reachability
Hello Currently I am working with Afnetworking network reachability

```<code> func CheckRechability() {

        AFNetworkReachabilityManager.shared().setReachabilityStatusChange {  (status: AFNetworkReachabilityStatus) in

            debugPrint(status.rawValue)

            switch (status.rawValue){

            case 0,-1:
                Print("No rechability")

                break

            case 1,2:
                Print("I have rechability")

                break
            default:

                break
            }
        }
        AFNetworkReachabilityManager.shared().startMonitoring()
    }
</code>```

It works fine, but suppose I am connected with wifi and I have no internet connectivity it will give me reachability status. So my question is how to check that I have an internet connection or not whether I am connected to wifi or mobile connection.

答:
Reachability library can't tell you about internet connectivity ,for that mostly use to ping some server
Use this
Check for internet connection with Swift</p>

Title: AFnetworking Internet reachability

Body:
Hello Currently I am working with Afnetworking network reachability

 func CheckRechability() {

        AFNetworkReachabilityManager.shared().setReachabilityStatusChange {  (status: AFNetworkReachabilityStatus) in

            debugPrint(status.rawValue)

            switch (status.rawValue){

            case 0,-1:
                Print("No rechability")

                break

            case 1,2:
                Print("I have rechability")

                break
            default:

                break
            }
        }
        AFNetworkReachabilityManager.shared().startMonitoring()
    }

It works fine, but suppose I am connected with wifi and I have no internet connectivity it will give me reachability status. So my question is how to check that I have an internet connection or not whether I am connected to wifi or mobile connection.


问:
Java Swing - jComboBox not refreshing
I have an issue with my jComboBox not reflecting the changes in the model ...

In the model I have Box class that keeps an array list of Items. I have a combo box model defined this way :

```<code>myCombo.setModel(new javax.swing.DefaultComboBoxModel(box.items().toArray()));
</code>```

(I use NetBeans 'design' mode). So as far as I understand, after setting the model this way, the combo box should reflect any changes in items list and at the start of the application, it indeed correctly shows the elements of the item list.

I also have a button Add to add a random instance of Item to the items list.

```<code>    private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {
    box.addRandomItem();
}
</code>```

The method addRandomItem() simply adds some new instance of Item to the items list. So when I click the Add button, the new random item is correctly added to the items list (I can see it printed at the console) but at the GUI level, the list in combo box is not being updated so I cannot see the newly added item in it.

答:
You should add the new item manually to the model using addElement(E element) or insertElementAt(E element, int index).

Internally, the DefaultComboBoxModel makes a copy of the items you provide as a parameter in the constructor, so there isn't any way to know that the original array has changed.

Title: Java Swing - jComboBox not refreshing

Body:
I have an issue with my jComboBox not reflecting the changes in the model ...

In the model I have Box class that keeps an array list of Items. I have a combo box model defined this way :

myCombo.setModel(new javax.swing.DefaultComboBoxModel(box.items().toArray()));

(I use NetBeans 'design' mode). So as far as I understand, after setting the model this way, the combo box should reflect any changes in items list and at the start of the application, it indeed correctly shows the elements of the item list.

I also have a button Add to add a random instance of Item to the items list.

    private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {
    box.addRandomItem();
}

The method addRandomItem() simply adds some new instance of Item to the items list. So when I click the Add button, the new random item is correctly added to the items list (I can see it printed at the console) but at the GUI level, the list in combo box is not being updated so I cannot see the newly added item in it.


问:
How to get XYPlot axis with OnTouchListener
I'm trying to get the axis of an XYPlot using a custom OnTouchListener:

```<code>mPlot.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                Log.d(TAG, touchX+":"+touchY);
                return false;
            }
        });
</code>```

The problem is that I'm getting the pixel values.

Is there any method or workaround to get the exact axis of the plot?

答:
Try this:

```<code>int touchX = (int) event.getX();
int touchY = (int) event.getY();
</code>```

For more info on how Android Screen Coordinates work : link

Body:
I'm trying to get the axis of an XYPlot using a custom OnTouchListener:

mPlot.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                Log.d(TAG, touchX+":"+touchY);
                return false;
            }
        });

The problem is that I'm getting the pixel values.

Is there any method or workaround to get the exact axis of the plot?

Body:
Try this:

int touchX = (int) event.getX();
int touchY = (int) event.getY();

For more info on how Android Screen Coordinates work : link


问:
how to add the label in both right and left in asp.net text box
I try to add label in the right side as well of the text box to include the unit of the value.I would like to have like this

and  This code gives like this.

this is my code

```<code>    <div class="form-group ">

                    @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-8">
                        @{ Html.EnableClientValidation(false); }

                        @Html.EditorFor(model => model.files, new { htmlAttributes = new { @class = "form-control " } })<span>GB</span>
                        @{ Html.EnableClientValidation(true); }
                        @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })

                    </div>
                </div>
</code>```

Thanks.

答:
The class = "col-md-8" contains position:relative.
Since this line has class="form control " and your GB doesn't have a class. It goes to its natural position. Adding a class should tell it where to go.</p>

```<code>@Html.EditorFor(model => model.files, new { htmlAttributes = new { @class = "form-control col-md-11" } })<span class="col-md-1">GB</span>
</code>```

Body:
I try to add label in the right side as well of the text box to include the unit of the value.I would like to have like this

and  This code gives like this.

this is my code

                    @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-3" })

                        @{ Html.EnableClientValidation(false); }

                        @Html.EditorFor(model => model.files, new { htmlAttributes = new { @class = "form-control " } })GB
                        @{ Html.EnableClientValidation(true); }
                        @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })

Thanks.

Body:
The class = "col-md-8" contains position:relative.
Since this line has class="form control " and your GB doesn't have a class. It goes to its natural position. Adding a class should tell it where to go.

@Html.EditorFor(model => model.files, new { htmlAttributes = new { @class = "form-control col-md-11" } })<span class="col-md-1">GB</span>


问:
Ssequelizejs, MySQL and passportjs user.findOne not a function
I'm currently migrating from mongodb to MySQL in my Node js application. I use sequelize as ORM, but I'm having some trouble migrating some passportjs code.

I have the following modal.

user.js:

```<code>"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("users", {
    username: DataTypes.STRING,
    localemail: DataTypes.STRING,
    localpassword: DataTypes.STRING,
    facebookid: DataTypes.STRING,
    facebooktoken: DataTypes.STRING,
    facebookemail: DataTypes.STRING,
    facebookname: DataTypes.STRING,
    twitterid: DataTypes.STRING,
    twittertoken: DataTypes.STRING,
    twitterdisplayname: DataTypes.STRING,
    twitterusername: DataTypes.STRING,
    googleid: DataTypes.STRING,
    googletoken: DataTypes.STRING,
    googleemail: DataTypes.STRING,
    googlename: DataTypes.STRING
  });

  return User;
};
</code>```

And the following function in my passportjs file:

...

```<code>// load all the things we need
var LocalStrategy    = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
var GoogleStrategy   = require('passport-google-oauth').OAuth2Strategy;

// load up the user model
var User       = require('../models/user');
</code>```

...

```<code>passport.use('local-login', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
    },
    function(req, email, password, done) {
        if (email)
            email = email.toLowerCase();
    // asynchronous
    process.nextTick(function() {
        User.findOne({
            where: {
                localemail: email
            }
        }).then(function(user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.'));

            if (!validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));

            // all is well, return user
            else
                return done(null, user);
        });
    });

}));
</code>```

...

The applications exits with the following error:

```<code>passport.js:100
                    User.findOne({
                         ^

TypeError: User.findOne is not a function
</code>```

I have looked at this code on github for inspiration:

https://github.com/sequelize/express-example

Any ideas to what i'm overlooking?

UPDATE:

So in my passport.js file I have done this:

```<code>var models = require('../models');
console.log("models.User:" +models.User);
</code>```

which output this:

```<code>npm start app.js
> myapp0.0.0 start /home/mathias/nodejs/myapp
> DEBUG=express-sequelize
node ./bin/www "app.js"
models.User:undefined
express-sequelize
Express server listening on port 3000 +0ms express-sequelize
Listening on port 3000 +7ms –
</code>```

This gives an [object:object] in the console:

```<code>var models  = require('../models');
console.log("models:" +models);
</code>```

An this also gives an undefined:

```<code>var models  = require('../models').User;
console.log("models:" +models);
</code>```

Update with config.json file:

```<code>{
  "development": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  }
}
</code>```

答:
The file user.js exports a function that returns the model:

```<code>module.exports = function(sequelize, DataTypes) {
  ...
  return User;
}
</code>```

So in order to get that model reference, you need to use something like this:

```<code>const Sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;

let sequelize = new Sequelize(...);

const User = require('../models/user')(sequelize, DataTypes);
</code>```

<s>However, I don't see why you'd want to pass sequelize and DataTypes around, since you can just as easily import them in the models file (which, in turn, could export the model directly):

```<code>// models/user.js
const sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;

module.exports = sequelize.define("users", { ... });
</code>```

To use:

```<code>const User = require('../models/user');
</code>```

</s>

Body:
I'm currently migrating from mongodb to MySQL in my Node js application. I use sequelize as ORM, but I'm having some trouble migrating some passportjs code.

I have the following modal.

user.js:

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("users", {
    username: DataTypes.STRING,
    localemail: DataTypes.STRING,
    localpassword: DataTypes.STRING,
    facebookid: DataTypes.STRING,
    facebooktoken: DataTypes.STRING,
    facebookemail: DataTypes.STRING,
    facebookname: DataTypes.STRING,
    twitterid: DataTypes.STRING,
    twittertoken: DataTypes.STRING,
    twitterdisplayname: DataTypes.STRING,
    twitterusername: DataTypes.STRING,
    googleid: DataTypes.STRING,
    googletoken: DataTypes.STRING,
    googleemail: DataTypes.STRING,
    googlename: DataTypes.STRING
  });

  return User;
};

And the following function in my passportjs file:

...

// load all the things we need
var LocalStrategy    = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
var GoogleStrategy   = require('passport-google-oauth').OAuth2Strategy;

// load up the user model
var User       = require('../models/user');

...

passport.use('local-login', new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true
    },
    function(req, email, password, done) {
        if (email)
            email = email.toLowerCase();
    // asynchronous
    process.nextTick(function() {
        User.findOne({
            where: {
                localemail: email
            }
        }).then(function(user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.'));

            if (!validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));

            // all is well, return user
            else
                return done(null, user);
        });
    });

}));

...

The applications exits with the following error:

passport.js:100
                    User.findOne({
                         ^

TypeError: User.findOne is not a function

I have looked at this code on github for inspiration:

https://github.com/sequelize/express-example

Any ideas to what i'm overlooking?

UPDATE:

So in my passport.js file I have done this:

var models = require('../models');
console.log("models.User:" +models.User);

which output this:

npm start app.js
> myapp0.0.0 start /home/mathias/nodejs/myapp
> DEBUG=express-sequelize
node ./bin/www "app.js"
models.User:undefined
express-sequelize
Express server listening on port 3000 +0ms express-sequelize
Listening on port 3000 +7ms –

This gives an [object:object] in the console:

var models  = require('../models');
console.log("models:" +models);

An this also gives an undefined:

var models  = require('../models').User;
console.log("models:" +models);

Update with config.json file:

{
  "development": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": "password",
    "database": "myapp",
    "host": "0.0.0.0",
    "dialect": "mysql"
  }
}

Body:
The file user.js exports a function that returns the model:

module.exports = function(sequelize, DataTypes) {
  ...
  return User;
}

So in order to get that model reference, you need to use something like this:

const Sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;

let sequelize = new Sequelize(...);

const User = require('../models/user')(sequelize, DataTypes);

<s>However, I don't see why you'd want to pass sequelize and DataTypes around, since you can just as easily import them in the models file (which, in turn, could export the model directly):

// models/user.js
const sequelize = require('sequelize');
const DataTypes = sequelize.DataTypes;

module.exports = sequelize.define("users", { ... });

To use:

const User = require('../models/user');

</s>


问:
ajax doesn't work on localhost
I have a simple Ajax calculation but it doesn't work

that's the JavaScript Code

```<code><script>

   function showFees() {
        e.preventDefault();
        var weight = ('weight').val;
        var ship_type== ('ship_type').val;
        var eol== ('eol').val;
        if (weight == 0) {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
         document.getElementById("txtHint").innerHTML =this.responseText;
                }
            };
            xmlhttp.open("GET", "sdr.php?weight=" + weight "ship_type" + ship_type + "eol" + eol, true);
            xmlhttp.send();
        }
    }
</code>```

that's my form

```<code><form>

 <label>weight:</label>

 <input type="number" name="weight" min="0" value="0">

 Ship Type:

 <select name="ship_type">

        <option value="1">Tankers of Crude Oil</option>
        <option value="2">Tankers of Petroleum Products</option>

      </select>
      Laden Or Ballast:
      <select name="eol">
                <option value="0">Ballast</option>
                <option value="1">Laden</option>
              </select>
      <input type="submit" onclick="showFees()" value="calc">
      </form>
      <p>Suggestions: <span id="txtHint"></span></p>
</code>```

and my sdr page to calculate the final result

```<code>$weight;
$i=0;
$wpt=0/*weight per ton result*/;
$ship_type;
$eol;/*empty or loaded*/
$channel_weights=array(5,5,10,20,30,50,10000);

$weight = $_REQUEST['weight'];
$ship_type = $_REQUEST['ship_type'];
$eol = $_REQUEST['eol'];
while($weight!=0){
    if($weight>=$channel_weights[$i]){
        $wpt+=$channel_weights[$i]*$ship_load_vlues[$eol][$ship_type][$i];
        $weight-=$channel_weights[$i];
    }
    else{
        $wpt+=$weight*$ship_load_vlues[$eol][$ship_type][$i];
        $weight=0;
    }

    $i++;
}

$final = $wpt*$float_sdr*1000;
echo $final === "0" ? "wrong data" : $final;
 ?>
</code>```

I think echo must return to span with ID 'txtHint' but it doesn't return any and if I tried to put alert in java script doesn't work either and I tried to add ajax library and doesn't work also

答:
You're using e.preventDefault(); but you don't have e defined at this point. Pass it as an argument on the button:

```<code> onclick="showFees(event)"
</code>```

Capture it in the function:

```<code>function showFees(e) {
</code>```

Fix the bad URL format and use encodeURIComponent on the values:

```<code>xmlhttp.open("GET", "sdr.php?weight=" + encodeURIComponent(weight) + "&ship_type" + encodeURIComponent(ship_type) + "&eol" + encodeURIComponent(eol), true);
</code>```

Fix these two lines which are nowhere near correct:

```<code>var ship_type== ('ship_type').val;
var eol== ('eol').val;
</code>```

Should be:

```<code>var ship_type = document.querySelector('select[name=ship_type]').value;
var eol = document.querySelector('select[name=eol]').value;
</code>```

Open the browser dev tools (F12) and look at the console, these issues would be producing errors which would help you to narrow the problems down.

Title: ajax doesn't work on localhost

Body:
You're using e.preventDefault(); but you don't have e defined at this point. Pass it as an argument on the button:

 onclick="showFees(event)"

Capture it in the function:

function showFees(e) {

Fix the bad URL format and use encodeURIComponent on the values:

xmlhttp.open("GET", "sdr.php?weight=" + encodeURIComponent(weight) + "&ship_type" + encodeURIComponent(ship_type) + "&eol" + encodeURIComponent(eol), true);

Fix these two lines which are nowhere near correct:

var ship_type== ('ship_type').val;
var eol== ('eol').val;

Should be:

var ship_type = document.querySelector('select[name=ship_type]').value;
var eol = document.querySelector('select[name=eol]').value;

Open the browser dev tools (F12) and look at the console, these issues would be producing errors which would help you to narrow the problems down.


问:
in 'for loops and range', although same range, two result differs. wanna know why
I'm currently learning python, and I found my self encountered some issue.

```<code>a={}
for i in range(0,10):
    for j in str(i):
        a[i]='%sth number'%(j)
b={}
for i in range(0,10):
    for j in range(0,10):
        b[i]='%sth number'%(j)

print(a)
print(b)
</code>```

anyone could tell why does this two are different?

答:
str(i) merely casts the integer i to a string. So doing for j in str(i): runs through every character in i as a string... which is only 1, in each case you've provided.

It would not run through all the numbers 0-9 as a string because you are casting each individual integer to a string as it is generated by the loop. If you put all the characters into a string first, then ran the second for loop through them, you might see the same results as the other loop.

Body:
I'm currently learning python, and I found my self encountered some issue.

a={}
for i in range(0,10):
    for j in str(i):
        a[i]='%sth number'%(j)
b={}
for i in range(0,10):
    for j in range(0,10):
        b[i]='%sth number'%(j)

print(a)
print(b)

anyone could tell why does this two are different?


问:
why following code is forwarded to next page after submit button while error is popup?
i want to prevent my first page that should not navigate to next jsp page when validation error is come .

index.jsp

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>date of birth validation</title>
<script type="text/javascript">
        function isValidDate(date, month, year)
        {
            var flagDate = new Date(year, month, date);
            if (flagDate.getFullYear() != year || flagDate.getMonth() != month || flagDate.getDate() != date)
            {
                return false;
            }
            return true;
        }

        function calculateDiffYear(date, month, year)
        {
            var cur = new Date();
            var diff = Math.floor((cur.getTime() - new Date(year, month, date)) / (60 * 60 * 24 * 1000));
                diff -= Math.floor((cur.getFullYear() - year) / 4);

            return diff / 365;
        }

        function checkBorn(sender)
        {
            var root = sender.form;
            var date = root.elements['date'].value;
            var month = root.elements['month'].value - 1;
            var year = root.elements['year'].value;

            if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18)
                {
                    alert("candidate should be grater than 18 years");
                    document.form.name1.focus();
                    return false;
                }

            return true;
        }
    </script>

</head>
<body>
<form name = "form" action="./next2.jsp" method="post">
<center>
<br><br><br><br>

<br><br><br><br>
Date of Birth :
<select name='date' id='dayddl'>
<option value='dd'>dd</option>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
<option value='23'>23</option>
<option value='24'>24</option>
<option value='25'>25</option>
<option value='26'>26</option>
<option value='27'>27</option>
<option value='28'>28</option>
<option value='29'>29</option>
<option value='30'>30</option>
<option value='31'>31</option>
</select>

<select name='month' id='monthddl'>
<option value='mm'>mm</option>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
</select>

<select name='year' id='blah'>
<option value='yyyy'>yyyy</option>

<option value='1995'>1995</option>
<option value='1996'>1996</option>
<option value='1997'>1997</option>
<option value='1998'>1998</option>
<option value='1999'>1999</option>
<option value='2000'>2000</option>
<option value='2001'>2001</option>
<option value='2002'>2002</option>
<option value='2003'>2003</option>
<option value='2004'>2004</option>
<option value='2005'>2005</option>
<option value='2006'>2006</option>
<option value='2007'>2007</option>
 <option value='2008'>2008</option>
<option value='2009'>2009</option>
<option value='2010'>2010</option>
<option value='2011'>2011</option>
<option value='2012'>2012</option>
<option value='2013'>2013</option>
<option value='2014'>2014</option>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
<option value='2017'>2017</option>
</select>

<br><br><input type ="submit" value="submit" onclick="checkBorn(this)">
</center>
</form>
</body>
</html>
</code>```

when error will come then control should not forward to next jsp page
but that is forwarded to next jsp page
why that is happening ? , what should i make a change on the code

next2.jsp is as follow :

```<code>            <html>
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Insert title here</title>
            </head>
            <body>
            <%@ page import="java.util.Date"%>
            <%@ page import="java.text.*"%>
            <%
            String day = request.getParameter("date");
            String month = request.getParameter("month");
            String year = request.getParameter("year");
            //String date = request.getParameter("dob");
            out.write(day+":"+month+":"+year);
            String date1 =year+"-"+month+"-"+day;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date dob1 = sdf.parse(date1);
            java.sql.Date dob2 = new java.sql.Date(dob1.getTime());
            out.write("<br><br>"+dob2);

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

答:
Change the type from Submit to button. Submit always trigger the form posting. Hence validate your form as follows

```<code><input type ="button" value="submit" onclick="checkBorn(this)">
</code>```

Submit your form using Javascript.

```<code>function checkBorn(sender)
    {
        var root = sender.form;
        var date = root.elements['date'].value;
        var month = root.elements['month'].value - 1;
        var year = root.elements['year'].value;

        if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18)
            {
                alert("candidate should be grater than 18 years");
                document.form.name1.focus();
                return false;
            }else{
                 //Submit your form here
            }
        //return true;
    }
</code>```

Body:
i want to prevent my first page that should not navigate to next jsp page when validation error is come .

index.jsp

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>date of birth validation</title>

<form name = "form" action="./next2.jsp" method="post">

Date of Birth :
<select name='date' id='dayddl'>
<option value='dd'>dd</option>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
<option value='23'>23</option>
<option value='24'>24</option>
<option value='25'>25</option>
<option value='26'>26</option>
<option value='27'>27</option>
<option value='28'>28</option>
<option value='29'>29</option>
<option value='30'>30</option>
<option value='31'>31</option>
</select>

<select name='month' id='monthddl'>
<option value='mm'>mm</option>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
</select>

<select name='year' id='blah'>
<option value='yyyy'>yyyy</option>

<option value='1995'>1995</option>
<option value='1996'>1996</option>
<option value='1997'>1997</option>
<option value='1998'>1998</option>
<option value='1999'>1999</option>
<option value='2000'>2000</option>
<option value='2001'>2001</option>
<option value='2002'>2002</option>
<option value='2003'>2003</option>
<option value='2004'>2004</option>
<option value='2005'>2005</option>
<option value='2006'>2006</option>
<option value='2007'>2007</option>
 <option value='2008'>2008</option>
<option value='2009'>2009</option>
<option value='2010'>2010</option>
<option value='2011'>2011</option>
<option value='2012'>2012</option>
<option value='2013'>2013</option>
<option value='2014'>2014</option>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
<option value='2017'>2017</option>
</select>

<input type ="submit" value="submit" onclick="checkBorn(this)">

</form>

when error will come then control should not forward to next jsp page
but that is forwarded to next jsp page
why that is happening ? , what should i make a change on the code

next2.jsp is as follow :

            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Insert title here</title>

            <%@ page import="java.util.Date"%>
            <%@ page import="java.text.*"%>
            <%
            String day = request.getParameter("date");
            String month = request.getParameter("month");
            String year = request.getParameter("year");
            //String date = request.getParameter("dob");
            out.write(day+":"+month+":"+year);
            String date1 =year+"-"+month+"-"+day;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date dob1 = sdf.parse(date1);
            java.sql.Date dob2 = new java.sql.Date(dob1.getTime());
            out.write("

"+dob2);

            %>

Body:
Change the type from Submit to button. Submit always trigger the form posting. Hence validate your form as follows

<input type ="button" value="submit" onclick="checkBorn(this)">

Submit your form using Javascript.

function checkBorn(sender)
    {
        var root = sender.form;
        var date = root.elements['date'].value;
        var month = root.elements['month'].value - 1;
        var year = root.elements['year'].value;

        if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18)
            {
                alert("candidate should be grater than 18 years");
                document.form.name1.focus();
                return false;
            }else{
                 //Submit your form here
            }
        //return true;
    }


问:
Sum up vector values till threshold, then start again
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

```<code>b = [1 4 4 2 3 5 6 3 5]
</code>```

Any ideas?

答:
Calculate the cumulative sum and replace the indices value obeying your condition.</p>

```<code> a = [1 3 4 2 1 5 6 3 2] ;

 b = [1 4 4 2 3 5 6 3 5] ;

 iwant = a ;
 a_sum = cumsum(a) ;
 iwant(a_sum<5) = a_sum(a_sum<5) ;
</code>```

Body:
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

b = [1 4 4 2 3 5 6 3 5]

Any ideas?

Body:
Calculate the cumulative sum and replace the indices value obeying your condition.

 a = [1 3 4 2 1 5 6 3 2] ;

 b = [1 4 4 2 3 5 6 3 5] ;

 iwant = a ;
 a_sum = cumsum(a) ;
 iwant(a_sum<5) = a_sum(a_sum<5) ;


问:
Spring: get current user through injection
Currently I am getting the user with the usual

```<code>SecurityContextHolder.getContext().getAuthentication().getPrincipal
</code>```

I wonder if it is possible to get it through the bean factory, like this

```<code>@Service
class UserProvider implements BeanFactoryAware {
    BeanFactory beanFactory;

    public Principal get(){
        return (Principal) beanFactory.getBean("Principal");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
</code>```

Does Spring store a session scoped bean containing the current authenticated user?

答:
It is possible to define session-scoped beans.

Definition

```<code>@Component
@Scope("session")
public class User {
    init
}
</code>```

Usage

```<code>@Service
public UserService {
    @Autowire
    User user;
}
</code>```

NOTE Take care of proxy if you are injecting session-scoped bean to non-scoped

```<code>@Scope(value="session", proxyMode=ScopedProxyMode.???)
</code>```

Body:
Currently I am getting the user with the usual

SecurityContextHolder.getContext().getAuthentication().getPrincipal

I wonder if it is possible to get it through the bean factory, like this

@Service
class UserProvider implements BeanFactoryAware {
    BeanFactory beanFactory;

    public Principal get(){
        return (Principal) beanFactory.getBean("Principal");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

Does Spring store a session scoped bean containing the current authenticated user?

Body:
It is possible to define session-scoped beans.

Definition

@Component
@Scope("session")
public class User {
    init
}

Usage

@Service
public UserService {
    @Autowire
    User user;
}

NOTE Take care of proxy if you are injecting session-scoped bean to non-scoped

@Scope(value="session", proxyMode=ScopedProxyMode.???)


问:
Read output from another application
I am not a developer but I have to create a small application. The scenario is
we have an existing financial application. When the application completes calculation it will pass a few parameters. My C# application needs to read these parameters(financial application output parameters).If the primary application (financial application) doesn't pass the parameter then the C# application ask to input these parameters(input in textboxes). Can anyone help me on how I can read these parameters in my C# windows form application.</p>

答:
Unless your financial application writes the output to the command line, your C# application cannot pick up these results. The financial app needs to write out the results to a file in some format and your C# can in turn read this file and process them.

UPDATE

Look into calling an application from using Process(). Check this post how to run an application using Process() and getting it's output.

Hope this helps out.

Title: Read output from another application


问:
Appending more than two child elements to an element gives a strange behaviour
I have a very strange behaviour and I don't know what causes it.

I loop through all of the id's which javascript can find within my html page. Every time when the 'id' startsWith a specific label, it goes into my if statement.

Within this if-statement I am creating several elements such as P,H1 and HR. Within my 'html'-page I've got 3 unique id's which are DIV's and should go into the if statement. This worked well(picture left [ 1]), until...

I tried to append more than two child elements to those DIV elements. The first two DIV elements are extended as expected. The last one has not been extended though. At the moment that there are more than two elements added to the parent, the 3th DIV (standardArticle3) does not pass the if statement. (picture right [2])

Hopefully the code and scenario picture can make this story clearer:

home.component.ts

```<code>var allElements = document.getElementsByTagName("*");
console.log(allElements);
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  var foundElementId = el.id;
  console.log(foundElementId);
  if (foundElementId.startsWith("standardArticle"))
  {
    var standardArticleElement = this.jsonReaderService.getStandardArticleContent(foundElementId.substring(15, foundElementId.length));

    var titleElement = document.createElement("h1");
    var titleText = document.createTextNode(standardArticleElement.title);
    titleElement.appendChild(titleText);

    var contentElement = document.createElement("p");
    contentElement.innerHTML = standardArticleElement.content;

    var thematicBreak = document.createElement("hr");
    thematicBreak.style.borderTopColor = "black";

    var thematicBreakTwo = document.createElement("hr");
    thematicBreakTwo.style.borderTopColor = "black";

    // Child elements are all being appended the right way, but the last DIV will never be extended
    el.appendChild(titleElement);
    el.appendChild(thematicBreak);
    el.appendChild(contentElement);
    el.appendChild(thematicBreakTwo);
  }
}
</code>```

home.component.html

```<code>    // other content
    <div id="standardArticle1" class="col-sm-6">
    </div>
    // other content
    <div id="standardArticle2" class="col-sm-6 pull-right">
    </div>
    // other content
    <div id="standardArticle3" class="col-sm-6">
    </div>
</code>```

Scenario's 1 and 2.

Does anybody have an idea why this is happening?

答:
document.getElementsByTagName() returns a live HTMLCollection, and your collection includes every element on the page. This means that when you append new elements, these elements get included in the collection but since you iterate up to the original length of the collection, you'll miss the last elements of the collection (the same number of elements as the number of elements you added).

It seems like a better solution to your problem would be to add a class to all elements you want to find and just get those ones with document.getElementsByClassName():

```<code>var allElements = document.getElementsByClassName("standard-article");
</code>```

... and then you add your class name to your HTML:

```<code>// other content
<div id="standardArticle1" class="standard-article col-sm-6">
</div>
// other content
<div id="standardArticle2" class="standard-article col-sm-6 pull-right">
</div>
// other content
<div id="standardArticle3" class="standard-article col-sm-6">
</div>
</code>```

With this approach you don't need your id.startsWith("standardArticle") if statement either.

Body:
I have a very strange behaviour and I don't know what causes it.

I loop through all of the id's which javascript can find within my html page. Every time when the 'id' startsWith a specific label, it goes into my if statement.

Within this if-statement I am creating several elements such as P,H1 and HR. Within my 'html'-page I've got 3 unique id's which are DIV's and should go into the if statement. This worked well(picture left [ 1]), until...

I tried to append more than two child elements to those DIV elements. The first two DIV elements are extended as expected. The last one has not been extended though. At the moment that there are more than two elements added to the parent, the 3th DIV (standardArticle3) does not pass the if statement. (picture right [2])

Hopefully the code and scenario picture can make this story clearer:

home.component.ts

var allElements = document.getElementsByTagName("*");
console.log(allElements);
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  var foundElementId = el.id;
  console.log(foundElementId);
  if (foundElementId.startsWith("standardArticle"))
  {
    var standardArticleElement = this.jsonReaderService.getStandardArticleContent(foundElementId.substring(15, foundElementId.length));

    var titleElement = document.createElement("h1");
    var titleText = document.createTextNode(standardArticleElement.title);
    titleElement.appendChild(titleText);

    var contentElement = document.createElement("p");
    contentElement.innerHTML = standardArticleElement.content;

    var thematicBreak = document.createElement("hr");
    thematicBreak.style.borderTopColor = "black";

    var thematicBreakTwo = document.createElement("hr");
    thematicBreakTwo.style.borderTopColor = "black";

    // Child elements are all being appended the right way, but the last DIV will never be extended
    el.appendChild(titleElement);
    el.appendChild(thematicBreak);
    el.appendChild(contentElement);
    el.appendChild(thematicBreakTwo);
  }
}

home.component.html

    // other content

    // other content

    // other content

Scenario's 1 and 2.

Does anybody have an idea why this is happening?

Body:
document.getElementsByTagName() returns a live HTMLCollection, and your collection includes every element on the page. This means that when you append new elements, these elements get included in the collection but since you iterate up to the original length of the collection, you'll miss the last elements of the collection (the same number of elements as the number of elements you added).

It seems like a better solution to your problem would be to add a class to all elements you want to find and just get those ones with document.getElementsByClassName():

var allElements = document.getElementsByClassName("standard-article");

... and then you add your class name to your HTML:

// other content
<div id="standardArticle1" class="standard-article col-sm-6">
</div>
// other content
<div id="standardArticle2" class="standard-article col-sm-6 pull-right">
</div>
// other content
<div id="standardArticle3" class="standard-article col-sm-6">
</div>

With this approach you don't need your id.startsWith("standardArticle") if statement either.


问:
Function being called faster
I hava made a flappy bird game and there are 2 frames. frame 1 is for playing while 2 is for death. I put a trace call on a function to see how many times is it called due to a problem. I found out that the more i die , the speedy my function call gets and the gravity is increased more times, so, my character flappy falls faster each time it dies.Please help. Here's the code:

```<code>var calls = 0;
flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
function fl_gravity(event: Event): void {
    calls++;
    if (dead) {
        if (flappy.hitTestObject(ground)) {
            gravity = 0;
        } else {
            gravity += 0.5;
        }
        upPressed = false;
    } else {
        flappy.x += 2.5;
    }
    flappy.y += gravity;
    gravity += 0.5;
    trace(calls);
}
</code>```

答: It looks like you're increasing the bird's gravity not only if it isn't dead but if it is. It lies outside of the conditional. Remove the line that increases your gravity outside of the conditional (line 16 in that excerpt) </p>

Title: Function being called faster

Body:
I hava made a flappy bird game and there are 2 frames. frame 1 is for playing while 2 is for death. I put a trace call on a function to see how many times is it called due to a problem. I found out that the more i die , the speedy my function call gets and the gravity is increased more times, so, my character flappy falls faster each time it dies.Please help. Here's the code:

var calls = 0;
flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
function fl_gravity(event: Event): void {
    calls++;
    if (dead) {
        if (flappy.hitTestObject(ground)) {
            gravity = 0;
        } else {
            gravity += 0.5;
        }
        upPressed = false;
    } else {
        flappy.x += 2.5;
    }
    flappy.y += gravity;
    gravity += 0.5;
    trace(calls);
}


问:
misalignment error in pixels
I have two cameras I have calibrated the cameras considering there position at the same point. But actually the positions of the cameras is slightly different than considered during calibration. This caused a parallax error. Now when I capture a point with these two cameras I get a misalignment in the images due to parallax Now I want to calculate this misalignment in pixels.

I tried to calculate the misalignment in m

Z(measured) = Z(calib) + (Du /tan a1 + tan a2)
Z(measured) is actual distance from cam to object in m
Z(calib) is distance from camera to calibration marker point.
Du is distance between the projected point of the object captured by two cameras on image plane in meters
tan a1 = (distance between camera position during calibration and actual camera 1 position/ distance between camera position during calibration and position of calibration marker point)

tan a2 = (distance between camera position during calibration and actual camera 2 position/ distance between camera position during calibration and position of calibration marker point)

How can I now convert this value of Du in meters to pixels

答:
If you know what the ground sample distance of your image you can use that to determine how much distance a pixel represents and use that number to convert meters to pixels.
Ground sample distance is calculated as:

```<code>GSD = D/F* PS
GSD = Ground sample distance
D = Distance to object (from camera)
F = Focal Length
PS = Pixel size (calculated using Photo dimension/Camera Sensor Dimension.
PS should be almost if not exactly the same when comparing Width and Height result.
</code>```

Having GSD you can then work backwards to determine number of pixels based on distance in meters (note this means you will want units to all be in meters).

Title: misalignment error in pixels

Body:
If you know what the ground sample distance of your image you can use that to determine how much distance a pixel represents and use that number to convert meters to pixels.
Ground sample distance is calculated as:

GSD = D/F* PS
GSD = Ground sample distance
D = Distance to object (from camera)
F = Focal Length
PS = Pixel size (calculated using Photo dimension/Camera Sensor Dimension.
PS should be almost if not exactly the same when comparing Width and Height result.

Having GSD you can then work backwards to determine number of pixels based on distance in meters (note this means you will want units to all be in meters).


问:
Should the password field be unique?
In light of the recent Gawker Media password leak, I've realized that many users share the same passwords. To help encourage stronger passwords, would it be helpful if passwords are constrained to be unique among all users?

One immediate downside I could think of (besides account creation performance?) is being able to know that someone is using a given string as a password. This knowledge, combined with a list of users, could be quite dangerous.

Is there a way to mitigate that downside while retaining the alleged benefits of not allowing repeat passwords?

It's kind of like the XKCD kick bot where you aren't allowed to repeat short, unoriginal sentences like "yah" or "lol".

Edit^2: I thought you could unique-ify against a hash, but as someone pointed out, with varying salts, this would not have the intended effect. Good eye!

答:
If password management is done correctly, the only person who should know their password is the user who created it in the first place.  In my web sites, I never store the password in any form.  I store a cryptographic hash (SHA-1 or some variant) of that password that is manipulated with some sort of unique "salt" padding.  Essentially if two people did have unique passwords, there would be no way to tell.

Most of the passwords on that link you gave are all easily guessed dictionary passwords.  Very weak, and easy to brute force.  They would all be unallowed by any system with rudimentary password checking.

Title: Should the password field be unique?


问:
Bazel Complains about Dependencies to system header files
Our Bazel build complains as

```<code>ERROR: XXX/BUILD:5:1: undeclared inclusion(s) in rule 'YYY':
this rule is missing dependency declarations for the following files included by 'ZZZ.c':
  '/usr/lib/gcc/x86_64-linux-gnu/6/include/stddef.h'
  '/usr/lib/gcc/x86_64-linux-gnu/6/include/stdint.h'.
</code>```

Why does it complain about dependencies to gcc system header files?

I'm using Ubuntu 17.04 with GCC 6.3.0.

答:
Do you use custom crosstool? If so, can you check that those directories are covered by cxx_builtin_include_directory messages?

If you use builtin Bazel autoconfiguration, can you make sure Bazel is not using some other gcc? Bazel calls cc -E -xc++ - -v to find all the builtin directories, do you expect this to work? Also, Bazel checks whether CC environment variable is set, and if yes, it will take the compiler from there.

Body:
Our Bazel build complains as

ERROR: XXX/BUILD:5:1: undeclared inclusion(s) in rule 'YYY':
this rule is missing dependency declarations for the following files included by 'ZZZ.c':
  '/usr/lib/gcc/x86_64-linux-gnu/6/include/stddef.h'
  '/usr/lib/gcc/x86_64-linux-gnu/6/include/stdint.h'.

Why does it complain about dependencies to gcc system header files?

I'm using Ubuntu 17.04 with GCC 6.3.0.


问:
How to to skip invalid XML file with incomplete closing tags in PHP
I am using PHP DOM Xpath to read XML files. In some cases tags are not properly closed like below

```<code><data>
   <name> value </name>
   <address
</code>```

I have following code to check if XML is valid

```<code>$doc = new DOMDocument();

if(!$doc->load(test.xml))
 {
      foreach (libxml_get_errors() as $error)
      {
          print_r($error);
      }
        libxml_clear_errors();
 }
 else
 {
     $valid_xml = 'y';
 }

 if($valid_xml=='y')
 // then process XML
 else
 // skip and take next file
</code>```

but I am getting below errors at line if(!$doc->load(test.xml))

```<code>Message: DOMDocument::load(): Couldn't find end of Start Tag AdjustmentsToReconcile

Message: DOMDocument::load(): Premature end of data in tag
</code>```

答:
That should helps you:

```<code>libxml_use_internal_errors(true);
$doc = new DOMDocument();

$valid_xml = true;
if(!$doc->load(test.xml))
{
    $valid_xml = (count(libxml_get_errors()) === 0);
    libxml_clear_errors();
}

if($valid_xml)
// then process XML
else
// skip and take next file
</code>```

libxml_use_internal_errors is the key.

Body:
I am using PHP DOM Xpath to read XML files. In some cases tags are not properly closed like below

<data>
   <name> value </name>
   <address

I have following code to check if XML is valid

$doc = new DOMDocument();

if(!$doc->load(test.xml))
 {
      foreach (libxml_get_errors() as $error)
      {
          print_r($error);
      }
        libxml_clear_errors();
 }
 else
 {
     $valid_xml = 'y';
 }

 if($valid_xml=='y')
 // then process XML
 else
 // skip and take next file

but I am getting below errors at line if(!$doc->load(test.xml))

Message: DOMDocument::load(): Couldn't find end of Start Tag AdjustmentsToReconcile

Message: DOMDocument::load(): Premature end of data in tag

Body:
That should helps you:

libxml_use_internal_errors(true);
$doc = new DOMDocument();

$valid_xml = true;
if(!$doc->load(test.xml))
{
    $valid_xml = (count(libxml_get_errors()) === 0);
    libxml_clear_errors();
}

if($valid_xml)
// then process XML
else
// skip and take next file

libxml_use_internal_errors is the key.


问:
How can I check if an object is an array?
I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.

So how do I check if the variable is an array?

答:
There's just one line solution for this question

```<code>x instanceof Array
</code>```

where x is the variable it will return true if x is an array and false if it is not.

ContentLicense: CC BY-SA 4.0

Body:
There's just one line solution for this question

x instanceof Array

where x is the variable it will return true if x is an array and false if it is not.


问:
String to phrase replacement python
I have a text string and I want to replace two words with a single word. E.g. if the word is artificial intelligence, I want to replace it with artificial_intelligence. This needs to be done for a list of 200 words and on a text file of size 5 mb.
I tried string.replace but it can work only for one element, not for the list.

Example

Text='Artificial intelligence is useful for us in every situation of deep learning.'

```<code>List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning
...
</code>```

Text.replace('Artificial intelligence','Artificial_intelligence') is working.
But

```<code>For I in range(len(Lista)):
 Text=Text.replace(Lista[I],List b[I])
</code>```

doesn't work.

答:
I would suggest using a dict for your replacements:

```<code>text = "Artificial intelligence is useful for us in every situation of deep learning."
replacements = {"Artificial intelligence" : "Artificial_intelligence",
                "deep learning" : "deep_learning"}
</code>```

Then your approach works (although it is case-sensitive):

```<code>>>> for rep in replacements:
        text = text.replace(rep, replacements[rep])
>>> print(text)
Artificial_intelligence is useful for us in every situation of deep_learning.
</code>```

For other approaches (like the suggested regex-approach), have a look at SO: Python replace multiple strings.

Title: String to phrase replacement python

Body:
I have a text string and I want to replace two words with a single word. E.g. if the word is artificial intelligence, I want to replace it with artificial_intelligence. This needs to be done for a list of 200 words and on a text file of size 5 mb.
I tried string.replace but it can work only for one element, not for the list.

Example

Text='Artificial intelligence is useful for us in every situation of deep learning.'

List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning
...

Text.replace('Artificial intelligence','Artificial_intelligence') is working.
But

For I in range(len(Lista)):
 Text=Text.replace(Lista[I],List b[I])

doesn't work.

Body:
I would suggest using a dict for your replacements:

text = "Artificial intelligence is useful for us in every situation of deep learning."
replacements = {"Artificial intelligence" : "Artificial_intelligence",
                "deep learning" : "deep_learning"}

Then your approach works (although it is case-sensitive):

>>> for rep in replacements:
        text = text.replace(rep, replacements[rep])
>>> print(text)
Artificial_intelligence is useful for us in every situation of deep_learning.

For other approaches (like the suggested regex-approach), have a look at SO: Python replace multiple strings.


问:
Redefine/Reset columns in flexigrid?
how to dynamically redefine columns in flexigrid?

i have tried the followings:

```<code>model = [{ .../*some new columns model*/ } ];

target.flexOptions({colModel: model});
target.flexReload();
</code>```

without any luck :/

答:
I just had this same problem.

The bes I could do was create a wrapper div for the flexigrid's div and empty the wrapper/recreate the flexigrid everytime I needed to change the colmodel. Something like:

```<code>$("#flexigridContainer").empty();
$("#flexigridContainer").append($("<div>").attr("id", "reporteFlexigrid"));

var report = $("#cmbValReports option:selected").attr("value");
var colModel;
switch(report){
    case 1: url = ""; colModel = abonosFlexigridModel(); break;
    case 2: url = ""; colModel = cgeneralFlexigridModel(); break;
    case 3: url = ""; colModel = cccostoFlexigridModel(); break;
    case 4: url = ""; colModel = prestamoFlexigridModel(); break;
}

    initFlexigrid(url, colModel);
</code>```

And the initFlexigrid was something like

```<code>function initFlexigrid(purl, pcolModel){
$("#reporteFlexigrid").flexigrid({url: purl, colModel: pcolModel, ... }); }
</code>```

It worked for me :-)

Title: Redefine/Reset columns in flexigrid?

Body:
how to dynamically redefine columns in flexigrid?

i have tried the followings:

model = [{ .../*some new columns model*/ } ];

target.flexOptions({colModel: model});
target.flexReload();

without any luck :/

Body:
I just had this same problem.

The bes I could do was create a wrapper div for the flexigrid's div and empty the wrapper/recreate the flexigrid everytime I needed to change the colmodel. Something like:

$("#flexigridContainer").empty();
$("#flexigridContainer").append($("<div>").attr("id", "reporteFlexigrid"));

var report = $("#cmbValReports option:selected").attr("value");
var colModel;
switch(report){
    case 1: url = ""; colModel = abonosFlexigridModel(); break;
    case 2: url = ""; colModel = cgeneralFlexigridModel(); break;
    case 3: url = ""; colModel = cccostoFlexigridModel(); break;
    case 4: url = ""; colModel = prestamoFlexigridModel(); break;
}

    initFlexigrid(url, colModel);

And the initFlexigrid was something like

function initFlexigrid(purl, pcolModel){
$("#reporteFlexigrid").flexigrid({url: purl, colModel: pcolModel, ... }); }

It worked for me :-)


答:
Somthing wrong with url , your forming a bad url , missing = and & for the GET request

it should look like

```<code>xmlhttp.open("GET", "sdr.php?weight=" + weight + "&ship_type=" + ship_type + "&eol=" + eol, true);
</code>```

and to get the values of inputs you should write a correct code :

if you're using jquery

```<code>var weight = $("[name='weight']").val();
var ship_type = $("[name='ship_type']").val();
var eol = $("[name='eol']").val();
</code>```

Or js :

```<code>var weight = document.querySelector('input[name=weight]').value
var ship_type =document.querySelector('select[name=ship_type]').value
var eol = document.querySelector('select[name=eol]').value
</code>```

Also as MrCode answer

e.preventDefault() will throw error because e is undefined

Title: ajax doesn't work on localhost

Body:
I have a simple Ajax calculation but it doesn't work

that's the JavaScript Code

Body:
Somthing wrong with url , your forming a bad url , missing = and & for the GET request

it should look like

xmlhttp.open("GET", "sdr.php?weight=" + weight + "&ship_type=" + ship_type + "&eol=" + eol, true);

and to get the values of inputs you should write a correct code :

if you're using jquery

var weight = $("[name='weight']").val();
var ship_type = $("[name='ship_type']").val();
var eol = $("[name='eol']").val();

Or js :

var weight = document.querySelector('input[name=weight]').value
var ship_type =document.querySelector('select[name=ship_type]').value
var eol = document.querySelector('select[name=eol]').value

Also as MrCode answer

e.preventDefault() will throw error because e is undefined


问:
How to run psutil inside a docker container?
I am trying to monitor the CPU and Memory of my docker container from within my python application . I am planning to use psutil for this job. I have read on other forums that the /proc can be changed in psutil.

```<code>import psutil
psutil.PROCFS_PATH = 'proc/self'
psutil.cpu_percent()
</code>```

This gives me the following error:

```<code> File "app.py", line 22, in <module>
 web-vote-app_1  |     r = psutil.cpu_percent()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil       /__init__.py", line 1773, in cpu_percent
 web-vote-app_1  |     _last_cpu_times = cpu_times()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/__init__.py", line 1645, in cpu_times
 web-vote-app_1  |     return _psplatform.cpu_times()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/_pslinux.py", line 544, in cpu_times
 web-vote-app_1  |     fields = [float(x) / CLOCK_TICKS for x in fields]
 web-vote-app_1  | ValueError: could not convert string to float: (python)
 web-result_1    |  * Running on http://0.0.0.0:5002/ (Press CTRL+C to quit)
 swarmmicroservicedemov1_web-vote-app_1 exited with code 1
</code>```

Can anyone tell me if its possible to get the same information about the container instead of the host, if so. how ? Thanks

答:
Why are you changing the default /proc/ path?

This just works:

```<code>import psutil
psutil.cpu_percent(interval=1)
</code>```

Each container has already mounted it's /proc information properly. So psutil can work without mounting any extra.

Edit: See it working

Dockerfile:

```<code>FROM python:2

RUN pip install psutil

CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'
</code>```

Build and run:

```<code>docker build . -t psutil-test && docker run -it psutil-test
Sending build context to Docker daemon 2.048 kB
Step 1/3 : FROM python:2
 ---> 2e9467da064d
Step 2/3 : RUN pip install psutil
 ---> Using cache
 ---> bdb07a51b12b
Step 3/3 : CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'
 ---> Using cache
 ---> 028f88f8844c
Successfully built 028f88f8844c
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
</code>```

Body:
I am trying to monitor the CPU and Memory of my docker container from within my python application . I am planning to use psutil for this job. I have read on other forums that the /proc can be changed in psutil.

import psutil
psutil.PROCFS_PATH = 'proc/self'
psutil.cpu_percent()

This gives me the following error:

 File "app.py", line 22, in <module>
 web-vote-app_1  |     r = psutil.cpu_percent()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil       /__init__.py", line 1773, in cpu_percent
 web-vote-app_1  |     _last_cpu_times = cpu_times()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/__init__.py", line 1645, in cpu_times
 web-vote-app_1  |     return _psplatform.cpu_times()
 web-vote-app_1  |   File "/usr/local/lib/python2.7/site-packages/psutil/_pslinux.py", line 544, in cpu_times
 web-vote-app_1  |     fields = [float(x) / CLOCK_TICKS for x in fields]
 web-vote-app_1  | ValueError: could not convert string to float: (python)
 web-result_1    |  * Running on http://0.0.0.0:5002/ (Press CTRL+C to quit)
 swarmmicroservicedemov1_web-vote-app_1 exited with code 1

Can anyone tell me if its possible to get the same information about the container instead of the host, if so. how ? Thanks

Body:
Why are you changing the default /proc/ path?

This just works:

import psutil
psutil.cpu_percent(interval=1)

Each container has already mounted it's /proc information properly. So psutil can work without mounting any extra.

Edit: See it working

Dockerfile:

FROM python:2

RUN pip install psutil

CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'

Build and run:

docker build . -t psutil-test && docker run -it psutil-test
Sending build context to Docker daemon 2.048 kB
Step 1/3 : FROM python:2
 ---> 2e9467da064d
Step 2/3 : RUN pip install psutil
 ---> Using cache
 ---> bdb07a51b12b
Step 3/3 : CMD sh -c 'while true; do python -c "import psutil; print psutil.cpu_percent()"; sleep 0.5; done'
 ---> Using cache
 ---> 028f88f8844c
Successfully built 028f88f8844c
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0