问:
How to upload a file to a local folder with React.js and Node.js?
I have tried this php and html file upload:
https://www.w3schools.com/php/php_file_upload.asp

and I was wondering If the same could be done using React.js/Nodes.js.
I'm not really used to coding and have never worked with React.js before.

答:
If you are wondering about the complexity of handling this process, here is a snippet of code that uses the formidable package to handle a file upload in Node.JS

```<code>  /** UPLOAD a file **/
  app.post('/upload', isLoggedIn, (req, res) => {
    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    form.uploadDir = path.join(__dirname, '../../uploads');

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function(field, file) {
      logger.info(`Uploaded: "${file.name}"`);
      fs.rename(file.path, path.join(form.uploadDir, file.name));
    });

    // log any errors that occur
    form.on('error', function(err) {
      errorLogger.error('During file upload: ' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
      res.end('success');
    });

    // parse the incoming request containing the form data
    form.parse(req);
  });
</code>```

My particular client-side implementation didn't use React, just a plain HTML/Javascript page using the jQuery Dropzone plugin but I see that React has uploader packages as well like 'react-dropzone'.

Here is the link back to the complete example repository that accomplishes file uploads in node.js  Checkout the upload.js file to view how the client-side file streaming is done to the node server.

Body:
If you are wondering about the complexity of handling this process, here is a snippet of code that uses the formidable package to handle a file upload in Node.JS

  /** UPLOAD a file **/
  app.post('/upload', isLoggedIn, (req, res) => {
    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    form.uploadDir = path.join(__dirname, '../../uploads');

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function(field, file) {
      logger.info(`Uploaded: "${file.name}"`);
      fs.rename(file.path, path.join(form.uploadDir, file.name));
    });

    // log any errors that occur
    form.on('error', function(err) {
      errorLogger.error('During file upload: ' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
      res.end('success');
    });

    // parse the incoming request containing the form data
    form.parse(req);
  });

My particular client-side implementation didn't use React, just a plain HTML/Javascript page using the jQuery Dropzone plugin but I see that React has uploader packages as well like 'react-dropzone'.

Here is the link back to the complete example repository that accomplishes file uploads in node.js  Checkout the upload.js file to view how the client-side file streaming is done to the node server.


来源: stackexchange

问:
regular expression allow value within range
I am facing an issue of matching expected values using regular expression.My expected minimum values is -40500.00 and maximum value is 99,999.99.

Tried
       ^$|[-][0-9]{0,5}[0-5]{0,3}[0-4]{0,1}|[0-9]{0,5}[.][0-9]{0,2}$";

ContentLicense: CC BY-SA 3.0

Body:
I just added a second structure without the decimals

(^$|[-][0-9]{0,5}[0-5]{0,3}[0-4]{0,1}|[0-9]{0,5}[.][0-9]{0,2}$)|(^$|[-][0-9]{0,5}[0-5]{0,3}[0-4]{0,1}|[0-9]{0,5})

https://regex101.com/r/bXdE9a/1


问:
How to get access to webpack-dev-server with external IP
I've got my simple login website fully coded and functional on the webpack dev server. how can i display it with my external IP? I've already port forwarded my router on port 9000 but when i tried www.myIp:portnumber its not working.
Below is my webpack config for the webpack dev server.</p>

```<code>//Webpack config
module.exports = {
  entry: './app/main.js',
  output: {
    path: './app',
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './app',
    port: 9000
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  }
}
</code>```

答:
Set the host property:

```<code>devServer: {
    inline: true,
    contentBase: './app',
    port: 9000,
    host: '0.0.0.0'
  }
</code>```

https://webpack.js.org/configuration/dev-server/#devserver-host-cli-only

Body:
I've got my simple login website fully coded and functional on the webpack dev server. how can i display it with my external IP? I've already port forwarded my router on port 9000 but when i tried www.myIp:portnumber its not working.
Below is my webpack config for the webpack dev server.

//Webpack config
module.exports = {
  entry: './app/main.js',
  output: {
    path: './app',
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './app',
    port: 9000
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  }
}

Body:
Set the host property:

devServer: {
    inline: true,
    contentBase: './app',
    port: 9000,
    host: '0.0.0.0'
  }

https://webpack.js.org/configuration/dev-server/#devserver-host-cli-only


问:
MpAndroidChart obtain zero value line in barchart
I'm using MPAndroidChart for a barchart.
Actually i have this situation:

For the first 2 value i have 0.0 but i want the blue line to be drawn also for the zero value, like this:

I obtained this result by getting a very low percentage of the max value but i want to display the line in 0.0 and not showing 0.5.
If the value is 0.0 i don't want to change it to show the line. Is there a way? Some ideas?

This is the settings of my barchart:

```<code>   YAxis leftAxis = barChart.getAxisLeft();
  leftAxis.setAxisMinimum(0f);

    barChart.setDrawBarShadow(false);
    barChart.getDescription().setEnabled(false);
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(false);
    barChart.setScaleEnabled(false);
    barChart.getLegend().setEnabled(false);
    barChart.getXAxis().setDrawAxisLine(false);
    barChart.getXAxis().setDrawGridLines(false);
    barChart.getAxis(YAxis.AxisDependency.LEFT).setEnabled(true);
 barChart.getAxis(YAxis.AxisDependency.LEFT).setDrawGridLines(false);
    barChart.getAxis(YAxis.AxisDependency.LEFT).setDrawLabels(false);
    barChart.getAxis(YAxis.AxisDependency.RIGHT).setEnabled(false);
    barChart.getXAxis().setDrawLabels(false);
    barChart.setDrawValueAboveBar(true);
</code>```

Thanks

答:
You could fix this by writing a custom IValueFormatter that would floor y-values less than a given amount down to zero. Then the y-values would render at 0.5f but be labeled 0.0.

Here is a very rough example adapted from the DefaultValueFormatter in the project:

```<code>import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;

public class FlooringValueFormatter implements IValueFormatter
{

    protected DecimalFormat mFormat;

    protected int mDecimalDigits;
    protected float mMinimum;

    public FlooringValueFormatter(int digits, float minimum) {
        setup(digits);
        this.mMinimum = minimum;
    }

    public void setup(int digits) {

        this.mDecimalDigits = digits;

        StringBuffer b = new StringBuffer();
        for (int i = 0; i < digits; i++) {
            if (i == 0)
                b.append(".");
            b.append("0");
        }

        mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        if (value < mMinimum) {
            return mFormat.format(0);
        }

        return mFormat.format(value);
    }

    public int getDecimalDigits() {
        return mDecimalDigits;
    }
}
</code>```

Consume it like this:

```<code>barData.setValueFormatter(new FlooringValueFormatter(2, 0.5f));
</code>```

Body:
I'm using MPAndroidChart for a barchart.
Actually i have this situation:

For the first 2 value i have 0.0 but i want the blue line to be drawn also for the zero value, like this:

I obtained this result by getting a very low percentage of the max value but i want to display the line in 0.0 and not showing 0.5.
If the value is 0.0 i don't want to change it to show the line. Is there a way? Some ideas?

This is the settings of my barchart:

   YAxis leftAxis = barChart.getAxisLeft();
  leftAxis.setAxisMinimum(0f);

    barChart.setDrawBarShadow(false);
    barChart.getDescription().setEnabled(false);
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(false);
    barChart.setScaleEnabled(false);
    barChart.getLegend().setEnabled(false);
    barChart.getXAxis().setDrawAxisLine(false);
    barChart.getXAxis().setDrawGridLines(false);
    barChart.getAxis(YAxis.AxisDependency.LEFT).setEnabled(true);
 barChart.getAxis(YAxis.AxisDependency.LEFT).setDrawGridLines(false);
    barChart.getAxis(YAxis.AxisDependency.LEFT).setDrawLabels(false);
    barChart.getAxis(YAxis.AxisDependency.RIGHT).setEnabled(false);
    barChart.getXAxis().setDrawLabels(false);
    barChart.setDrawValueAboveBar(true);

Thanks

Body:
You could fix this by writing a custom IValueFormatter that would floor y-values less than a given amount down to zero. Then the y-values would render at 0.5f but be labeled 0.0.

Here is a very rough example adapted from the DefaultValueFormatter in the project:

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;

public class FlooringValueFormatter implements IValueFormatter
{

    protected DecimalFormat mFormat;

    protected int mDecimalDigits;
    protected float mMinimum;

    public FlooringValueFormatter(int digits, float minimum) {
        setup(digits);
        this.mMinimum = minimum;
    }

    public void setup(int digits) {

        this.mDecimalDigits = digits;

        StringBuffer b = new StringBuffer();
        for (int i = 0; i < digits; i++) {
            if (i == 0)
                b.append(".");
            b.append("0");
        }

        mFormat = new DecimalFormat("###,###,###,##0" + b.toString());
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        if (value < mMinimum) {
            return mFormat.format(0);
        }

        return mFormat.format(value);
    }

    public int getDecimalDigits() {
        return mDecimalDigits;
    }
}

Consume it like this:

barData.setValueFormatter(new FlooringValueFormatter(2, 0.5f));


问:
getting this error even after putting different keys in facial recognition door sample
even after entering the key I have been subscribed to a standard plan of the face api service but getting this error constantly.! Tried changing the end points and creating s0 tier API to but getting same error .</p>

答: The project is old, and does not allow for specifying the API endpoint.  I've made a fix in a fork and a pull request to the main project.  Cognitive Service API keys are valid in only one region (i.e. you cannot use a westeurope key in westus, etc.)</p>


问:
Scale SVG from center
I have an svg as a background image in css, and I want to flip it. (scale(-1, 1))

When I try normal transformation, it dose not go about center, and looks weird.

Is there a way to flip an entire SVG around center, without JS?

Here is a demo using HTML, not CSS background image:
https://codepen.io/anon/pen/bRVqwz

```<code><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z'/></svg><br />
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="scale(-1, 1)"/></svg>

svg {
  width: 50px;
  height: 50px;
}
</code>```

答:
You can try transform rotate with x and y transform="rotate(180 5 10)"

```<code><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="rotate(180 5 10)"/></svg>
</code>```

Documentation
https://www.w3.org/TR/SVG/coords.html#TransformAttribute

Title: Scale SVG from center

Body:
I have an svg as a background image in css, and I want to flip it. (scale(-1, 1))

When I try normal transformation, it dose not go about center, and looks weird.

Is there a way to flip an entire SVG around center, without JS?

Here is a demo using HTML, not CSS background image:
https://codepen.io/anon/pen/bRVqwz

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z'/></svg>

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="scale(-1, 1)"/></svg>

svg {
  width: 50px;
  height: 50px;
}

Body:
You can try transform rotate with x and y transform="rotate(180 5 10)"

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'><path d='M2,20l-2-2l8-8L0,2l2-2l10,10L2,20z' transform="rotate(180 5 10)"/></svg>

Documentation
https://www.w3.org/TR/SVG/coords.html#TransformAttribute


问:
Where can I find some sample WPF animations?
As I am a programmer,and not an artist or animator and I am failing at showing off the best features of WPF in my application.  Although I have samples for simple animations for buttons like growing, or having the color fade into something brighter on click but what I am looking for is some showcase button animations and some showcase panel change animations to show off the best features of WPF.  Normally I would go for the more subtle changes, but in a couple of cases I need something to really show off the advantages of using WPF over WinForms technology.

Can anyone point me at some button samples and/or panel changing (switching from one panel to the next in a navigation) that really shows of WPF and has that wow factor.

EDIT

Please don't point to http://codeproject.com or the microsoft samples, as I have already perused those at great detail.  In fact here are the list of WPF sites in my rss reader (Suggestions for other blogs welcome):

Lester's WPF blog,  Ask Dr. WPF, Expression Blend and Design, WPF Wonderland, nerdplusart, Karl On WPF, Windows Presentation Foundation SDK, Josh Smith on WPF, Rob Relyea - Xamlified, The Moth.

I want specific examples, thanks...

答: How about Cool Control Template for WPF Button?</p>

OwnerDisplayName: Kris Erickson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kris Erickson


问:
converting this hierachy into xml? confused
i havent really worked with xml before, but i was wondering how could turn this hierachy into an xml format, if that makes sense :)) thanks</p>

```<code>agent
       agentname
       email
       allproperty
         aproperty
               postcode
               price
               imagefilename
               visits
        aproperty
               postcode
               price
               imagefilename
               visits
       aproperty
               postcode
               price
              imagefilename
              visits
</code>```

答:
```<code><agent>
   <agentname></agentname>
   <email></email>
   <allproperty>
      <aproperty>
           <postcode></postcode>
           <price></price>
           <imagefilename></imagefilename>
           <visits></visits>
      </aproperty>
      <aproperty>
           <postcode></postcode>
           <price></price>
           <imagefilename></imagefilename>
           <visits></visits>
      </aproperty>
      <aproperty>
           <postcode></postcode>
           <price></price>
           <imagefilename></imagefilename>
           <visits></visits>
      </aproperty>
  </allproperty>
</agent>
</code>```

Body:
i havent really worked with xml before, but i was wondering how could turn this hierachy into an xml format, if that makes sense :)) thanks

agent
       agentname
       email
       allproperty
         aproperty
               postcode
               price
               imagefilename
               visits
        aproperty
               postcode
               price
               imagefilename
               visits
       aproperty
               postcode
               price
              imagefilename
              visits


问:
Error installing Visual Studio for mac
I have a MacBook Air with macOS Sierra 10.12.5. I'm getting the following error trying to install Visual Studio for Mac:

Initial task interrupted by exception
Access to the path "/Users/username/.config/xbuild" is denied.
Exception type: System.UnauthorizedAccessException
Message: Access to the path "/Users/username/.config/xbuild" is denied.
at Xamarin.Web.Installer.TasksManager.DetectComponents () [0x000a1] in /Users/builder/data/lanes/4852/1d420fd9/source/installer/Xamarin.Web.Installer/TasksManager.cs:306

Thanks for your help.

答:
Can you try installing this version.

https://dl.xamarin.com/VsMac/VisualStudioForMac-Preview1-7.0.0.347.dmg

Seems the store version might have issues on your version of mac.

Title: Error installing Visual Studio for mac


问:
How to add to Login PHP script USERNAME and PASSWORD from MYSQL
i'd love to ask you for help i am making a simple Login using Switch Case

Here is my code of my current Login function that works but datas are from config.php .

```<code>function login() {
  if ( isset( $_POST['login'] ) ) {
    if ($_POST['username'] == ADMIN_USERNAME && $_POST['password'] == ADMIN_PASSWORD) {
      $_SESSION['username'] = $_POST["username"];
      header( "Location: admin.php" );
    } else {
      $results['errorMessage'] = "Wrong PW or ID";
      require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
  } else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
  }
}
?>
</code>```

So i made this method

```<code>public function login($username,$password) {
        $this->result = Database::ask('SELECT * FROM '.$this->table2.' where username = ? AND password = ?', array($username, $password));
        $this->print = $this->result->fetch(PDO::FETCH_ASSOC);
        return $this->print;
    }
</code>```

Database class

```<code>class Database {

    private static $connect;

    private static $set = Array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
    );

    public static function connectDB() {
        if (!isset(self::$connect)) {
            self::$connect = @new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
                self::$set;

        }
        return self::$connect;
    }

    public static function ask($sql, $params= array()) {
        $ask = self::$connect->prepare($sql);
        $ask->execute($params);
        return $ask;
    }

}
</code>```

So i ended up with

```<code>    function login() {
    if(isset($_POST['login'])){

        $row = new AdministrationDatabaze();
        $loginArray = $row->login($_POST['username'], $_POST['password']);

        if(!empty($loginArray['username']) AND !empty($loginArray['password'])){
            $_SESSION['username'] = $loginArray['username'];
            header( "Location: admin.php" );
        }
        else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
  }else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
}
</code>```

But i get -> Fatal error: Call to a member function prepare() on null in classes/Databaze.php on line 26

Line 26:

```<code>$ask = self::$connect->prepare($sql);
</code>```

I'd love to know where is the problem.

Thanks in advance.

M.

答:
Use a try/catch block to detect if the connection failed.

```<code>public static function connectDB() {
    if ( empty(self::$connect) ) {
        try {
            self::$connect = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

        } catch (PDOException $e) {
            return null;
        }
    }
    return self::$connect;
}
</code>```

Call the connectDB function.

```<code>public function login($username,$password) {
    if ( ! Database::connectDB() ) return null;
    $this->result = Database::ask('SELECT * FROM '.$this->table2.' where username = ? AND password = ?', array($username, $password));
    $this->print = $this->result->fetch(PDO::FETCH_ASSOC);
    return $this->print;
}
</code>```

Change the ask function as follows:

```<code>public static function ask($sql, $params= array()) {
    if ( empty(self::$connect) ) return null;
    $ask = self::$connect->prepare($sql);
    $ask->execute($params);
    return $ask;
}
</code>```

Modify the login function.

```<code>function login() {
    if ( isset($_POST['login']) ) {
        $row = new AdministrationDatabaze();
        $loginArray = $row->login($_POST['username'], $_POST['password']);
        if ( ! $loginArray ) {
            // If there is no login info
            // Maybe you should tell the user that something went wrong.
            require( TEMPLATE_PATH . "/admin/loginForm.php" );
        }
        elseif ( ! empty($loginArray['username']) AND ! empty($loginArray['password']) ) {
            $_SESSION['username'] = $loginArray['username'];
            header( "Location: admin.php" );
        }
        else {
            require( TEMPLATE_PATH . "/admin/loginForm.php" );
        }
    } else {
        require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
}
</code>```

Body:
i'd love to ask you for help i am making a simple Login using Switch Case

Here is my code of my current Login function that works but datas are from config.php .

function login() {
  if ( isset( $_POST['login'] ) ) {
    if ($_POST['username'] == ADMIN_USERNAME && $_POST['password'] == ADMIN_PASSWORD) {
      $_SESSION['username'] = $_POST["username"];
      header( "Location: admin.php" );
    } else {
      $results['errorMessage'] = "Wrong PW or ID";
      require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
  } else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
  }
}
?>

So i made this method

public function login($username,$password) {
        $this->result = Database::ask('SELECT * FROM '.$this->table2.' where username = ? AND password = ?', array($username, $password));
        $this->print = $this->result->fetch(PDO::FETCH_ASSOC);
        return $this->print;
    }

Database class

class Database {

    private static $connect;

    private static $set = Array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
    );

    public static function connectDB() {
        if (!isset(self::$connect)) {
            self::$connect = @new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
                self::$set;

        }
        return self::$connect;
    }

    public static function ask($sql, $params= array()) {
        $ask = self::$connect->prepare($sql);
        $ask->execute($params);
        return $ask;
    }

}

So i ended up with

    function login() {
    if(isset($_POST['login'])){

        $row = new AdministrationDatabaze();
        $loginArray = $row->login($_POST['username'], $_POST['password']);

        if(!empty($loginArray['username']) AND !empty($loginArray['password'])){
            $_SESSION['username'] = $loginArray['username'];
            header( "Location: admin.php" );
        }
        else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
  }else {
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
}

But i get -> Fatal error: Call to a member function prepare() on null in classes/Databaze.php on line 26

Line 26:

$ask = self::$connect->prepare($sql);

I'd love to know where is the problem.

Thanks in advance.

M.

Body:
Use a try/catch block to detect if the connection failed.

public static function connectDB() {
    if ( empty(self::$connect) ) {
        try {
            self::$connect = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

        } catch (PDOException $e) {
            return null;
        }
    }
    return self::$connect;
}

Call the connectDB function.

public function login($username,$password) {
    if ( ! Database::connectDB() ) return null;
    $this->result = Database::ask('SELECT * FROM '.$this->table2.' where username = ? AND password = ?', array($username, $password));
    $this->print = $this->result->fetch(PDO::FETCH_ASSOC);
    return $this->print;
}

Change the ask function as follows:

public static function ask($sql, $params= array()) {
    if ( empty(self::$connect) ) return null;
    $ask = self::$connect->prepare($sql);
    $ask->execute($params);
    return $ask;
}

Modify the login function.

function login() {
    if ( isset($_POST['login']) ) {
        $row = new AdministrationDatabaze();
        $loginArray = $row->login($_POST['username'], $_POST['password']);
        if ( ! $loginArray ) {
            // If there is no login info
            // Maybe you should tell the user that something went wrong.
            require( TEMPLATE_PATH . "/admin/loginForm.php" );
        }
        elseif ( ! empty($loginArray['username']) AND ! empty($loginArray['password']) ) {
            $_SESSION['username'] = $loginArray['username'];
            header( "Location: admin.php" );
        }
        else {
            require( TEMPLATE_PATH . "/admin/loginForm.php" );
        }
    } else {
        require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }
}


问:
How to know when a View has scrolled into view
We are currently developing an app that displays large data sets in "registers" and in rows. We are using a TableLayout as the base view and then adding table rows for every item (with a LinearLayout in each row).

I have noticed that once the amount of records get beyond a certain point (1000+ records), the device slows down tremendously. I am sure that this is a simple memory issue(maybe rendering too?) and have devised a plan that could increase the speed.

We have implemented continuous paging on a lot of silverlight projects, and I figure that this is the best approach to take in Android?

The only problem I have now is to recognize when a specific view (say row 100) has been scrolled into view, so that I can start to render the next couple of lines.

Does anyone know how to do this, or of a better way to implement/handle large data sets?

Regards

答:
Instead of using table Layout use CustomListView ,which has the capability of reusing the row.

you can the find how to use Custom list view here.

```<code>[Custom ListView][1]
</code>```

Body:
Instead of using table Layout use CustomListView ,which has the capability of reusing the row.

you can the find how to use Custom list view here.

[Custom ListView][1]


问:
change AutoNumber values when inserting rows with UCanAccess
When using the executeUpdate method of UCanAccess, the system always chooses the row number for me. However, after I delete my rows and add new ones, the rows do not start from the beginning (e.g., I deleted 3 rows, then it marks the next 3 rows as 4, 5, and 6). Is there a way I can fix this or name the rows myself? Here is my code:

```<code>statement.executeUpdate("INSERT INTO myDB2"+ " ( columnRows,  columnA, columnB)"
    + " VALUES ( "+rows+", "+a+", "+b+")");`
</code>```

答:
Resetting the next AutoNumber value

After deleting rows you can reset the AutoNumber seed values by opening the database in Access and performing a "Compact and Repair Database" operation. UCanAccess is currently unable to reset the seed value itself.

Inserting arbitrary values into an AutoNumber column

Starting with version 4.0.2, UCanAccess is able to insert arbitrary positive values into an AutoNumber (Long Integer, Increment) column. For example, with a table named [Client]:

ClientID - AutoNumber

FirstName - Text(50)

we can do

Statement st = conn.createStatement();
st.execute("DISABLE AUTOINCREMENT ON Client");
st.execute("INSERT INTO Client (ClientID, FirstName) VALUES (123, 'Gord')");
```

For more details, see the blog post here.

Version 4.0.3 (not yet released) extends that capability to allow inserting arbitrary values that are less than or equal to zero.

Body:
When using the executeUpdate method of UCanAccess, the system always chooses the row number for me. However, after I delete my rows and add new ones, the rows do not start from the beginning (e.g., I deleted 3 rows, then it marks the next 3 rows as 4, 5, and 6). Is there a way I can fix this or name the rows myself? Here is my code:

statement.executeUpdate("INSERT INTO myDB2"+ " ( columnRows,  columnA, columnB)"
    + " VALUES ( "+rows+", "+a+", "+b+")");`

Body:
Resetting the next AutoNumber value

After deleting rows you can reset the AutoNumber seed values by opening the database in Access and performing a "Compact and Repair Database" operation. UCanAccess is currently unable to reset the seed value itself.

Inserting arbitrary values into an AutoNumber column

Starting with version 4.0.2, UCanAccess is able to insert arbitrary positive values into an AutoNumber (Long Integer, Increment) column. For example, with a table named [Client]:

ClientID - AutoNumber

FirstName - Text(50)

we can do

Statement st = conn.createStatement();
st.execute("DISABLE AUTOINCREMENT ON Client");
st.execute("INSERT INTO Client (ClientID, FirstName) VALUES (123, 'Gord')");

For more details, see the blog post here.

Version 4.0.3 (not yet released) extends that capability to allow inserting arbitrary values that are less than or equal to zero.


问:
Unable to install gulp-jshint through npm
while installing gulp-jshint using node npm following error is showing "gulp-jshint@2.0.4 requires a peer of jshint@2.x but none was installed-UNMET peer dependency". Can anyone help to solve this problem. I am using windows 7 OS.</p>

答:
As of version 2.0 of gulp-jshint module, jshint must be installed with gulp-jshint. https://github.com/spalger/gulp-jshint</p>

```<code>npm install jshint gulp-jshint --save-dev
</code>```

Body:
As of version 2.0 of gulp-jshint module, jshint must be installed with gulp-jshint. https://github.com/spalger/gulp-jshint

npm install jshint gulp-jshint --save-dev


问:
StyleCopTask couldn't be load on Hudson Server
I'm trying to set up our Hundson Server for CI our new project.
Everything runs fine, building the project, unit testing and FxCop checks runs.
But when I try to check the code with StyleCop an error occurs.
First: We develop in C# with MS VS 2010 and on the Hudson Server there is the
.Net 4.0 and the Windows SDK 7.1 installed.

Now I've added the StyleCop.Targets to my SVN and linked the .cproj files to the
file. If I build in VS2010 everythin went fine, except of the StyleCop warnings,
but if the Hundson Server tries to build the project this error occurs:

```<code>error MSB4062: The "StyleCopTask" task could not be loaded from the assembly
C:\Program Files (x86)\MSBuild\..\StyleCop 4.7\StyleCop.dll. Could not load file or
assembly 'Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot
find the file specified. Confirm that the <UsingTask> declaration is correct,
that the assembly and all its dependencies are available, and that the task
contains a public class that implements Microsoft.Build.Framework.ITask.
</code>```

The StyleCop.dll is in the path on the Hundson Server, can someone tell me what I've done wrong?

答:
Go to Control Panel\Programs\Programs and Features

Select Turn Windows features on or off

Click the .NET Framework 3.5 (includes .NET 2.0 and 3.0)

Click OK and wait

Restart Visual Studio

That should fix it

Body:
I'm trying to set up our Hundson Server for CI our new project.
Everything runs fine, building the project, unit testing and FxCop checks runs.
But when I try to check the code with StyleCop an error occurs.
First: We develop in C# with MS VS 2010 and on the Hudson Server there is the
.Net 4.0 and the Windows SDK 7.1 installed.

Now I've added the StyleCop.Targets to my SVN and linked the .cproj files to the
file. If I build in VS2010 everythin went fine, except of the StyleCop warnings,
but if the Hundson Server tries to build the project this error occurs:

error MSB4062: The "StyleCopTask" task could not be loaded from the assembly
C:\Program Files (x86)\MSBuild\..\StyleCop 4.7\StyleCop.dll. Could not load file or
assembly 'Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot
find the file specified. Confirm that the <UsingTask> declaration is correct,
that the assembly and all its dependencies are available, and that the task
contains a public class that implements Microsoft.Build.Framework.ITask.

The StyleCop.dll is in the path on the Hundson Server, can someone tell me what I've done wrong?


问:
Extract text in front of a character in certain position
If I have the following string:
100456,3456,1235,0,0,100,500

I need to be able to extract specific values such as 100456, 1235 and 100. I am having trouble writing code to extract text in front of a comma in a certain position.

Basically extract text in front of the 1st comma, extract text in front of the 3rd comma, etc.

```<code> Dim fields() As String = Split(TextLine, ",")
            For i = 0 To UBound(fields)
                If i = 0 Then
                    Value1 = fields(i)
                End If
                If i = 3 Then
                    Value2 = fields(i)
                End If
            Next
</code>```

I've tried this, but the loop seems to run more times than it should.

答:
```<code> Dim fields() As String = Split(TextLine, ",")
 Dim Value1 as String = fields(0)
 Dim Value2 as String = fields(2) 'the field in front of 3rd comma is index 2
</code>```

Body:
If I have the following string:
100456,3456,1235,0,0,100,500

I need to be able to extract specific values such as 100456, 1235 and 100. I am having trouble writing code to extract text in front of a comma in a certain position.

Basically extract text in front of the 1st comma, extract text in front of the 3rd comma, etc.

 Dim fields() As String = Split(TextLine, ",")
            For i = 0 To UBound(fields)
                If i = 0 Then
                    Value1 = fields(i)
                End If
                If i = 3 Then
                    Value2 = fields(i)
                End If
            Next

I've tried this, but the loop seems to run more times than it should.


问:
ACF PRO taxonomy term field in WordPress submenu
I have a question that I can't seem to find the right approach to.

I'm currently developing a WordPress site whereby a custom submenu is required. In said submenu, a list of category terms is displayed (incidentally, a list of years – 2003-2017). For each of these years, I have created an image field using the brilliant Advanced Custom Fields PRO plugin. The idea is that an image can be uploaded for a year in the “Edit Category” page. So far, so good. This image would then be shown in the submenu alongside the year, and here's where I am stumped.

What I am having trouble with is figuring out how I am going to check for that field in the submenu and fetch it.

I'll include the code for the custom nav walker below. Any help would be greatly appreciated!

```<code>class Nav_Header_Walker extends Walker_Nav_Menu {

    public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
        if ( ! $element ) {
            return;
        }

        $id_field = $this->db_fields['id'];
        $id = $element->$id_field;

        // Display this element.
        $this->has_children = ! empty( $children_elements[ $id ] );
        if ( isset( $args[0] ) && is_array( $args[0] ) ) {
            $args[0]['has_children'] = $this->has_children; // Backwards compatibility.
        }

        $cb_args = array_merge( array( &$output, $element, $depth ), $args );
        call_user_func_array( array( $this, 'start_el' ), $cb_args );

        // Descend only when the depth is right and there are children for this element.
        if ( ( 0 === $max_depth || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {

            foreach ( $children_elements[ $id ] as $child ) {

                if ( ! isset( $newlevel ) ) {
                    $newlevel = true;
                    // Start the child delimiter.
                    $cb_args = array_merge( array( &$output, $depth ), $args );

                    /** Additional check for custom addition of id to sub-level */
                    if ( $element->post_name = 'Megatron' ) {
                        $cb_args['sub_menu_id'] = 'megatron';
                    }
                    /** End custom check */

                    call_user_func_array( array( $this, 'start_lvl' ), $cb_args );
                }
                $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
            }
            unset( $children_elements[ $id ] );
        }

        if ( isset( $newlevel ) && $newlevel ) {
            // End the child delimiter.
            $cb_args = array_merge( array( &$output, $depth ), $args );
            call_user_func_array( array( $this, 'end_lvl' ), $cb_args );
        }

        // End this element.
        $cb_args = array_merge( array( &$output, $element, $depth ), $args );
        call_user_func_array( array( $this, 'end_el' ), $cb_args );
    }

    public function start_lvl( &$output, $depth = 0, $args = array(), $sub_menu_div = null ) {
        $indent = str_repeat( "\t", $depth );
        if ( $sub_menu_div ) {
            $output .= "\n$indent<div id=\"$sub_menu_div\"><ul class=\"sub-menu\">\n";
        } else {
            $output .= "\n$indent<ul class=\"sub-menu\">\n";
        }
    }

    function end_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat( "\t", $depth );
        $output .= "$indent</ul></div>\n";
    }
}
</code>```

答:
In case anybody ever comes across this rather niche issue in the future, I figured out what I approach I needed.

Adding the following block of code to the end of what I included in my original question did the trick.

Pay close attention to how I retrieve the ACF image field (standard way to get a taxonomy field, if you're not familiar with it), using $item->object and $item->object_id.

It’s then just a case of altering the output to include the background image for each menu item, using the conditional to check whether said item is a category link and is the correct depth (i.e. if it is a submenu item). If it isn't both of those, it doesn't bother with the background image.

```<code>function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    if ( in_array( 'menu-item-object-category', $item->classes ) && $depth > 0 ) {

        // Get the ACF PRO image field (I have replaced my field with 'field_name', change this to your field)
        $thumb = get_field( 'field_name', $item->object . '_' . $item->object_id );

        $before = '<li class="' . implode( ' ', $item->classes ) . '">';
        $after = '</li>';

        // Attributes
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url ) .'"' : '';
        $attributes .= ' style="background-image: url(' . $thumb['url']  . ')"';

        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
            $before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $args->link_after,
            $after
        );

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

    } else {

        $before = '<li class="' . implode( ' ', $item->classes ) . '">';

        // link attributes
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url ) .'"' : '';

        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
            $before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $args->link_after,
            $args->after
        );

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

    }

}

function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
}
</code>```

Body:
I have a question that I can't seem to find the right approach to.

I'm currently developing a WordPress site whereby a custom submenu is required. In said submenu, a list of category terms is displayed (incidentally, a list of years – 2003-2017). For each of these years, I have created an image field using the brilliant Advanced Custom Fields PRO plugin. The idea is that an image can be uploaded for a year in the “Edit Category” page. So far, so good. This image would then be shown in the submenu alongside the year, and here's where I am stumped.

What I am having trouble with is figuring out how I am going to check for that field in the submenu and fetch it.

I'll include the code for the custom nav walker below. Any help would be greatly appreciated!

class Nav_Header_Walker extends Walker_Nav_Menu {

    public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
        if ( ! $element ) {
            return;
        }

        $id_field = $this->db_fields['id'];
        $id = $element->$id_field;

        // Display this element.
        $this->has_children = ! empty( $children_elements[ $id ] );
        if ( isset( $args[0] ) && is_array( $args[0] ) ) {
            $args[0]['has_children'] = $this->has_children; // Backwards compatibility.
        }

        $cb_args = array_merge( array( &$output, $element, $depth ), $args );
        call_user_func_array( array( $this, 'start_el' ), $cb_args );

        // Descend only when the depth is right and there are children for this element.
        if ( ( 0 === $max_depth || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) {

            foreach ( $children_elements[ $id ] as $child ) {

                if ( ! isset( $newlevel ) ) {
                    $newlevel = true;
                    // Start the child delimiter.
                    $cb_args = array_merge( array( &$output, $depth ), $args );

                    /** Additional check for custom addition of id to sub-level */
                    if ( $element->post_name = 'Megatron' ) {
                        $cb_args['sub_menu_id'] = 'megatron';
                    }
                    /** End custom check */

                    call_user_func_array( array( $this, 'start_lvl' ), $cb_args );
                }
                $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
            }
            unset( $children_elements[ $id ] );
        }

        if ( isset( $newlevel ) && $newlevel ) {
            // End the child delimiter.
            $cb_args = array_merge( array( &$output, $depth ), $args );
            call_user_func_array( array( $this, 'end_lvl' ), $cb_args );
        }

        // End this element.
        $cb_args = array_merge( array( &$output, $element, $depth ), $args );
        call_user_func_array( array( $this, 'end_el' ), $cb_args );
    }

    public function start_lvl( &$output, $depth = 0, $args = array(), $sub_menu_div = null ) {
        $indent = str_repeat( "\t", $depth );
        if ( $sub_menu_div ) {
            $output .= "\n$indent

\n";
        } else {
            $output .= "\n$indent
\n";
        }
    }

    function end_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat( "\t", $depth );
        $output .= "$indent

\n";
    }
}

Body:
In case anybody ever comes across this rather niche issue in the future, I figured out what I approach I needed.

Adding the following block of code to the end of what I included in my original question did the trick.

Pay close attention to how I retrieve the ACF image field (standard way to get a taxonomy field, if you're not familiar with it), using $item->object and $item->object_id.

It’s then just a case of altering the output to include the background image for each menu item, using the conditional to check whether said item is a category link and is the correct depth (i.e. if it is a submenu item). If it isn't both of those, it doesn't bother with the background image.

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    if ( in_array( 'menu-item-object-category', $item->classes ) && $depth > 0 ) {

        // Get the ACF PRO image field (I have replaced my field with 'field_name', change this to your field)
        $thumb = get_field( 'field_name', $item->object . '_' . $item->object_id );

        $before = '<li class="' . implode( ' ', $item->classes ) . '">';
        $after = '</li>';

        // Attributes
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url ) .'"' : '';
        $attributes .= ' style="background-image: url(' . $thumb['url']  . ')"';

        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
            $before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $args->link_after,
            $after
        );

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

    } else {

        $before = '<li class="' . implode( ' ', $item->classes ) . '">';

        // link attributes
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url ) .'"' : '';

        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
            $before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $args->link_after,
            $args->after
        );

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

    }

}

function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
}


问:
ImageView does not display image taken from phone camera or photo gallery
I am currently designing an android app that requires at a certain point for the user to select a picture either from the camera or from the phone's gallery. After that I need to display said picture in the activity's image view.

I think the code section that gets the picture is ok, as I can effectively pick the photo from both options. But after that, besides having no picture shown, the src logo of the image view dissapears. I do not understand if I'm doing anything wrong or if there is something missing here, as it is a non-fatal error and the app continues to perform.

So here is my XML layout of the activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/Widget.Design.CoordinatorLayout"
android:orientation="vertical"

tools:context="pt.unl.fct.di.www.myapplication.ReportActivity">

<ScrollView
    android:id="@+id/report_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/submit_report_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/type_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="30dp"
            android:text="@string/select_report_type"
            android:visibility="visible" />
        <Spinner
            android:id="@+id/report_type_spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:layout_marginBottom="30dp"/>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Description"
                android:inputType="textMultiLine"
                android:selectAllOnFocus="false"
                android:layout_marginBottom="30dp"/>

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Location"
                android:layout_marginBottom="30dp"/>

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Map"
                android:layout_marginBottom="30dp"/>
        </android.support.design.widget.TextInputLayout>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@android:drawable/ic_menu_camera"
            android:adjustViewBounds="true"
             />

        <Button
            android:id="@+id/camera_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add Picture" />

        <Button
            android:id="@+id/submit_report_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/action_submit_report"
            android:textStyle="bold"
            android:layout_weight="0.68" />

    </LinearLayout>
</ScrollView>
</code>```

And the Activity's java(important stuff):

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_report);
    Spinner spinner = (Spinner) findViewById(R.id.report_type_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.report_types, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
    spinner.setAdapter(adapter);
    mReportType = spinner.getItemAtPosition(0).toString();
    spinner.setOnItemSelectedListener(this);
    mDescription = (EditText)findViewById(R.id.description);
    mImageLocationView =(ImageView) findViewById(R.id.imageView);
    Button cameraButton = (Button)findViewById(R.id.camera_button);
    cameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.choose_photo_from)
                    .setItems(R.array.picture_types, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // The 'which' argument contains the index position
                            // of the selected item
                            switch(which){
                                case 0: //fotografia
                                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(takePicture, 0);
                                    onPause();
                                    //zero can be replaced with any action code
                                    break;
                                case 1:
                                    //galeria
                                    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                    startActivityForResult(pickPhoto , 1);
                                    //one can be replaced with any action code
                                    break;
                            }

                        }
                    });
            builder.create().show();
        }
    });

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    BitmapFactory.Options o = new BitmapFactory.Options();
    mImageLocationView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
                mImageLocationView.setImageBitmap(photo);

            }

            break;
        case 1:
            if(resultCode == RESULT_OK){
                Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
                mImageLocationView.setImageBitmap(photo);
            }
            break;
    }

}
</code>```

I must say, this is my very first android project so I am kind of overwhelmed by so much information and APIS, and also doing a lot of experimenting.

答:
Simply you can add the following code in `         </p>

```<code>if(resultCode == RESULT_OK){
    // the new code
     Uri imageUri = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(imageUri, filePath, null, null, null);
            cursor.moveToFirst();
            String path = cursor.getString(cursor.getColumnIndex(filePath[0]));
            cursor.close();

            //refresh Image view
            updateImageView(path);
        }
// the update image method
    public void updateImageView(String completePath) {
         Picasso picasoo = Picasso.with(getActivity());
          String path = "file://" + completePath;
          Long tsLong = System.currentTimeMillis();
         String ts = tsLong.toString();
          picasoo.load(path+"?time="+ts).fit().centerCrop().networkPolicy(OFFLINE).into(imgUserProfile);
</code>```

<p>}`
Picasso is an image management library that make your life easy with lazy loading the image.</p>

Body:
I am currently designing an android app that requires at a certain point for the user to select a picture either from the camera or from the phone's gallery. After that I need to display said picture in the activity's image view.

I think the code section that gets the picture is ok, as I can effectively pick the photo from both options. But after that, besides having no picture shown, the src logo of the image view dissapears. I do not understand if I'm doing anything wrong or if there is something missing here, as it is a non-fatal error and the app continues to perform.

So here is my XML layout of the activity:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/Widget.Design.CoordinatorLayout"
android:orientation="vertical"

tools:context="pt.unl.fct.di.www.myapplication.ReportActivity">

<ScrollView
    android:id="@+id/report_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/submit_report_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/type_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="30dp"
            android:text="@string/select_report_type"
            android:visibility="visible" />
        <Spinner
            android:id="@+id/report_type_spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:layout_marginBottom="30dp"/>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:hint="Description"
                android:inputType="textMultiLine"
                android:selectAllOnFocus="false"
                android:layout_marginBottom="30dp"/>

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Location"
                android:layout_marginBottom="30dp"/>

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Map"
                android:layout_marginBottom="30dp"/>
        </android.support.design.widget.TextInputLayout>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@android:drawable/ic_menu_camera"
            android:adjustViewBounds="true"
             />

        <Button
            android:id="@+id/camera_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add Picture" />

        <Button
            android:id="@+id/submit_report_button"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="@string/action_submit_report"
            android:textStyle="bold"
            android:layout_weight="0.68" />

    </LinearLayout>
</ScrollView>

And the Activity's java(important stuff):

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_report);
    Spinner spinner = (Spinner) findViewById(R.id.report_type_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.report_types, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
    spinner.setAdapter(adapter);
    mReportType = spinner.getItemAtPosition(0).toString();
    spinner.setOnItemSelectedListener(this);
    mDescription = (EditText)findViewById(R.id.description);
    mImageLocationView =(ImageView) findViewById(R.id.imageView);
    Button cameraButton = (Button)findViewById(R.id.camera_button);
    cameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.choose_photo_from)
                    .setItems(R.array.picture_types, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // The 'which' argument contains the index position
                            // of the selected item
                            switch(which){
                                case 0: //fotografia
                                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(takePicture, 0);
                                    onPause();
                                    //zero can be replaced with any action code
                                    break;
                                case 1:
                                    //galeria
                                    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                    startActivityForResult(pickPhoto , 1);
                                    //one can be replaced with any action code
                                    break;
                            }

                        }
                    });
            builder.create().show();
        }
    });

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    BitmapFactory.Options o = new BitmapFactory.Options();
    mImageLocationView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
                mImageLocationView.setImageBitmap(photo);

            }

            break;
        case 1:
            if(resultCode == RESULT_OK){
                Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
                mImageLocationView.setImageBitmap(photo);
            }
            break;
    }

}

I must say, this is my very first android project so I am kind of overwhelmed by so much information and APIS, and also doing a lot of experimenting.

Body:
Simply you can add the following code in `

if(resultCode == RESULT_OK){
    // the new code
     Uri imageUri = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(imageUri, filePath, null, null, null);
            cursor.moveToFirst();
            String path = cursor.getString(cursor.getColumnIndex(filePath[0]));
            cursor.close();

            //refresh Image view
            updateImageView(path);
        }
// the update image method
    public void updateImageView(String completePath) {
         Picasso picasoo = Picasso.with(getActivity());
          String path = "file://" + completePath;
          Long tsLong = System.currentTimeMillis();
         String ts = tsLong.toString();
          picasoo.load(path+"?time="+ts).fit().centerCrop().networkPolicy(OFFLINE).into(imgUserProfile);

}`
Picasso is an image management library that make your life easy with lazy loading the image.


问:
Nodejs : Cannot get route when using add.post
I am a beginner to Node and I am trying to create a multipage application with Mongo(mlab), express and nodejs. I am trying to navigate to a page addUser that takes POST requests. But I keep getting the error

Cannot GET /addUser

when I use add.post on it. However, it does work when I use add.get

Here is app.js

```<code>var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

var urlencodedParser = bodyParser.urlencoded({ extended:false });

app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.post('/addUser', urlencodedParser, function(req, res) {
    res.render('addUser');
    // db.collection('users').save(req.body, function(err, result) {
    //  if (err) return console.log(err);
    //  console.log('saved to database');
    //  res.redirect('/');
    // })
    // console.log(req.body);
});
</code>```

Not sure what I am doing wrong.

Here is addUser.ejs:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
    <form action="/addUser" method="POST" >
    <input type="text" placeholder="username" name="username">
    <input type="text" placeholder="specialty" name="specialty">
    <input type="text" placeholder="address" name="address">
    <!-- <input type="file" name="picture"> -->
    <button type="submit">Submit</button>
    </form>
</body>
</code>```

答:
You're gonna need to add a get for addUser:</p>

```<code>app.get('/addUser', function(req, res) {
    res.render('addUser');
});
</code>```

Body:
I am a beginner to Node and I am trying to create a multipage application with Mongo(mlab), express and nodejs. I am trying to navigate to a page addUser that takes POST requests. But I keep getting the error

Cannot GET /addUser

when I use add.post on it. However, it does work when I use add.get

Here is app.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

var urlencodedParser = bodyParser.urlencoded({ extended:false });

app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.post('/addUser', urlencodedParser, function(req, res) {
    res.render('addUser');
    // db.collection('users').save(req.body, function(err, result) {
    //  if (err) return console.log(err);
    //  console.log('saved to database');
    //  res.redirect('/');
    // })
    // console.log(req.body);
});

Not sure what I am doing wrong.

Here is addUser.ejs:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>MY APP</title>

    <form action="/addUser" method="POST" >
    <input type="text" placeholder="username" name="username">
    <input type="text" placeholder="specialty" name="specialty">
    <input type="text" placeholder="address" name="address">

    <button type="submit">Submit</button>
    </form>

Body:
You're gonna need to add a get for addUser:

app.get('/addUser', function(req, res) {
    res.render('addUser');
});


问:
How to select a driver in Behat?
I have both Goutte and Sahi installed. How do I know what driver I am using by default?

Also how do I change from one driver to the other?

Thank You

```<code> public function iAmOnHomepage()
    {

      // $this->getSession()->visit("/");
   //     $driver = new \Behat\Mink\Driver\GoutteDriver();
    //    $session = new \Behat\Mink\Session($driver);

        // start session:
      //  $session->start();

     //   $this->getSession($session);
        $session = $this->getSession();
        $session->visit($this->locatePath('/'));

        $link = $session->getPage()->findLink('I am a Physician');

       if (null === $link) {
          throw new \LogicException("Home Page Not Loaded:\n");
       }
    }
</code>```

My behat.yml file:

```<code>default:
  formatter:
    name: progress
  extensions:
    Behat\Symfony2Extension\Extension:
      mink_driver: true
      kernel:
        env: test
        debug: true
    Behat\MinkExtension\Extension:
      sahi: ~
      goutte: ~
      base_url: 'http://local.referral.com'
      default_session: symfony2
</code>```

答:
I wanted to be able to switch between methods from the CLI when developing.

Assume goutte most of the time (unless the test itself was tagged to
prefer @javascript)

BUT to see where problems were, I wanted to see even the non-js ones in action on my screen.

My behat.yml:

```<code>default:
  suites:
    default:
      paths:
        - %paths.base%/features
      contexts:
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      selenium2: ~

chrome:
  extensions:
    Behat\MinkExtension:
      browser_name: chrome
      default_session: 'selenium2'
</code>```

Now, running 'behat' will use goutte mostly, but if I choose to run

```<code>behat -p chrome
</code>```

I get the browser version of the same things running.

behat version 3.1.0
(I saw many docs saying it was "Behat\MinkExtension\Extension" - but I found it was "Behat\MinkExtension" - this may be a version thing.)

Title: How to select a driver in Behat?

Body:
I have both Goutte and Sahi installed. How do I know what driver I am using by default?

Also how do I change from one driver to the other?

Thank You

 public function iAmOnHomepage()
    {

      // $this->getSession()->visit("/");
   //     $driver = new \Behat\Mink\Driver\GoutteDriver();
    //    $session = new \Behat\Mink\Session($driver);

        // start session:
      //  $session->start();

     //   $this->getSession($session);
        $session = $this->getSession();
        $session->visit($this->locatePath('/'));

        $link = $session->getPage()->findLink('I am a Physician');

       if (null === $link) {
          throw new \LogicException("Home Page Not Loaded:\n");
       }
    }

My behat.yml file:

default:
  formatter:
    name: progress
  extensions:
    Behat\Symfony2Extension\Extension:
      mink_driver: true
      kernel:
        env: test
        debug: true
    Behat\MinkExtension\Extension:
      sahi: ~
      goutte: ~
      base_url: 'http://local.referral.com'
      default_session: symfony2

Body:
I wanted to be able to switch between methods from the CLI when developing.

Assume goutte most of the time (unless the test itself was tagged to
prefer @javascript)

BUT to see where problems were, I wanted to see even the non-js ones in action on my screen.

My behat.yml:

default:
  suites:
    default:
      paths:
        - %paths.base%/features
      contexts:
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      selenium2: ~

chrome:
  extensions:
    Behat\MinkExtension:
      browser_name: chrome
      default_session: 'selenium2'

Now, running 'behat' will use goutte mostly, but if I choose to run

behat -p chrome

I get the browser version of the same things running.

behat version 3.1.0
(I saw many docs saying it was "Behat\MinkExtension\Extension" - but I found it was "Behat\MinkExtension" - this may be a version thing.)


问:
DevOpts tools for WMQ
I need a devOpts deployments tool that can do the following tasks:

Creating a project that can contain different queues or artifacts within a GUI application

Create Queues and artifacts via a GUI accessible to non WMQ experts within the DEV environment only (without relying on a script)

Once tested properly, having the tool deploy the project (more specifically the queues contained in the project) from DEV to INT via a GUI that is only accessible by the Deployment team

Does anyone have any suggestions of tools that can perform this other than using scripts

(I have heard mixed reviews about IBM uDeploy, that configurations can not be reused, etc)

答: There are lots of 3rd party MQ Administration/Configuration tools available for IBM MQ.  You can find a list of them here.

Title: DevOpts tools for WMQ


问:
Unexpected token < in JSON at position Ionic
I'm working on a project using Ionic 2 framework, but I'm getting an error of Unexpected token < in JSON at position 0 home.ts:37, whenever I submit a form input into my  MySQL database. I have checked my ports, all working fine. What could be causing the issue?

full error

```<code>SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (service.ts:28)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
</code>```

launch.json

```<code>    {

    "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${file}",
            "outFiles": [
                "${workspaceRoot}/out/**/*.js"
            ]
        }
    ]
}
</code>```

Here's my code:

home.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Agregar producto
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="insertar" (ngSubmit)="InsertarProducto()">
            <ion-list>
                  <ion-item>
                        <ion-label floating>nombre</ion-label>
                        <ion-input type="text" name="nombre" formControlName="nombre" ></ion-input>
                  </ion-item>
                  <ion-item>
                        <ion-label floating>stock</ion-label>
                        <ion-input type="text" name="stock" formControlName="stock" ></ion-input>
                  </ion-item>
                      <button  [disabled]="insertar.invalid" ion-button full block color="secondary">Enviar</button>
            </ion-list>
  </form>

</ion-content>
</code>```

home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  insertar : any = {};

  constructor(public navCtrl: NavController , public service : ServiceProvider, public formB : FormBuilder,  public toastCtrl: ToastController)
  {

            this.insertar = this.formB.group({
             nombre:['', Validators.required],
             stock:['', Validators.required]
            });
   }

   InsertarProducto(){

      /*let toast = this.toastCtrl.create({
      message: 'Usuario agregado correctamente',
      duration: 3000
    });*/

    this.service.InsertarProd(this.insertar.value)
    .subscribe(
      data=> console.log(data.mensage), //toast.present()
      err=> console.log(err));
  }

}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http , Headers, Response} from '@angular/http';
//import { Observable } from "rxjs/Observable";

/*
  Generated class for the ServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiceProvider {

    api : string = 'http://localhost:8080/ING/';

  constructor(public http: Http) {
    console.log('Hello ServiceProvider Provider');
  }

   InsertarProd(params){
             let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
           return this.http.post(this.api + 'insertarprod.php' , params,{
           headers:headers,
           method:"POST",
         }).map(
           (res:Response)=>{return res.json();}
         )
  }

}
</code>```

insertarprod.php

```<code><?php

header("Access-Control-Allow-Origin:http://localhost:8100");
header("Content-Type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    $nombre = $objData->nombre;
    $stock = $objData->stock;

    $nombre = stripslashes($nombre);
    $stock = stripslashes($stock);

    $nombre = trim($nombre);
    $stock = trim($stock);

    $datos;

    @$db = new PDO("mysql:host=localhost;dbname=aula", "root", "");

    $prueba = array('mensaje2' => "conexion correcta");
    echo json_encode($prueba);

    if($db){
        $sql = " insert into productos values(NULL,'".$nombre."','".$stock."')";
        $query = $db->prepare($sql);
        $query ->execute();
        if(!$query){
                   $datos = array('mensage' => "no fue posible insertar datos");
                   echo json_encode($datos);
         }
        else{
                   $datos = array('mensage' => "Datos ingresados correctamente");
                  echo json_encode($datos);
         };
    }
   else{
          $datos = array('mensage' => "No es posible insertar datos.");
          echo json_encode($datos);
    };

    ?>
</code>```

答:
Copy/paste your JSON into a validator, like this one: https://jsonformatter.curiousconcept.com/

If you're still unable to find it, share the JSON with us in the question.

Body:
I'm working on a project using Ionic 2 framework, but I'm getting an error of Unexpected token < in JSON at position 0 home.ts:37, whenever I submit a form input into my  MySQL database. I have checked my ports, all working fine. What could be causing the issue?

full error

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (service.ts:28)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)

launch.json

    {

    "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${file}",
            "outFiles": [
                "${workspaceRoot}/out/**/*.js"
            ]
        }
    ]
}

Here's my code:

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Agregar producto
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="insertar" (ngSubmit)="InsertarProducto()">
            <ion-list>
                  <ion-item>
                        <ion-label floating>nombre</ion-label>
                        <ion-input type="text" name="nombre" formControlName="nombre" ></ion-input>
                  </ion-item>
                  <ion-item>
                        <ion-label floating>stock</ion-label>
                        <ion-input type="text" name="stock" formControlName="stock" ></ion-input>
                  </ion-item>
                      <button  [disabled]="insertar.invalid" ion-button full block color="secondary">Enviar</button>
            </ion-list>
  </form>

</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToastController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  insertar : any = {};

  constructor(public navCtrl: NavController , public service : ServiceProvider, public formB : FormBuilder,  public toastCtrl: ToastController)
  {

            this.insertar = this.formB.group({
             nombre:['', Validators.required],
             stock:['', Validators.required]
            });
   }

   InsertarProducto(){

      /*let toast = this.toastCtrl.create({
      message: 'Usuario agregado correctamente',
      duration: 3000
    });*/

    this.service.InsertarProd(this.insertar.value)
    .subscribe(
      data=> console.log(data.mensage), //toast.present()
      err=> console.log(err));
  }

}

service.ts

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http , Headers, Response} from '@angular/http';
//import { Observable } from "rxjs/Observable";

/*
  Generated class for the ServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiceProvider {

    api : string = 'http://localhost:8080/ING/';

  constructor(public http: Http) {
    console.log('Hello ServiceProvider Provider');
  }

   InsertarProd(params){
             let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
           return this.http.post(this.api + 'insertarprod.php' , params,{
           headers:headers,
           method:"POST",
         }).map(
           (res:Response)=>{return res.json();}
         )
  }

}

insertarprod.php

<?php

header("Access-Control-Allow-Origin:http://localhost:8100");
header("Content-Type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    $nombre = $objData->nombre;
    $stock = $objData->stock;

    $nombre = stripslashes($nombre);
    $stock = stripslashes($stock);

    $nombre = trim($nombre);
    $stock = trim($stock);

    $datos;

    @$db = new PDO("mysql:host=localhost;dbname=aula", "root", "");

    $prueba = array('mensaje2' => "conexion correcta");
    echo json_encode($prueba);

    if($db){
        $sql = " insert into productos values(NULL,'".$nombre."','".$stock."')";
        $query = $db->prepare($sql);
        $query ->execute();
        if(!$query){
                   $datos = array('mensage' => "no fue posible insertar datos");
                   echo json_encode($datos);
         }
        else{
                   $datos = array('mensage' => "Datos ingresados correctamente");
                  echo json_encode($datos);
         };
    }
   else{
          $datos = array('mensage' => "No es posible insertar datos.");
          echo json_encode($datos);
    };

    ?>


问:
Delayed_job not working in Ruby on Rails app
I'm simply trying to get a function to run at a specific time, but I'm not having much luck. Let me just run through the basics of what I've done

```<code>#Gemfile

gem 'delayed_job_active_record'
</code>```

```<code>#config/application.rb

module SampleApp
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.active_job.queue_adapter = :delayed_job
  end
end
</code>```

```<code>#Ran from command line

[06.07.2017/15:38:02] user@ubuntu $ rails g delayed_job:active_record
Running via Spring preloader in process 72879
   identical  bin/delayed_job
       chmod  bin/delayed_job
      create  db/migrate/20170607203821_create_delayed_jobs.rb
[06.07.2017/15:38:21] user@ubuntu $ rake db:migrate
== 20170607203821 CreateDelayedJobs: migrating ================================
-- create_table(:delayed_jobs, {:force=>true})
   -> 0.0088s
-- add_index(:delayed_jobs, [:priority, :run_at], {:name=>"delayed_jobs_priority"})
   -> 0.0051s
== 20170607203821 CreateDelayedJobs: migrated (0.0142s) =======================
</code>```

So I basically have a button on my view that calls post_now, which then calls a function within a custom model that I have. Here's an example of what I have:

```<code>#posts_controller.rb
  def post_now
    set_post
    submit_post = SchedulePost.delay(run_at: 1.minute.from_now).schedule_post(@post)
    redirect_to posts_path, flash: {success: submit_post[1] }
  end
</code>```

and then here's the SchedulePost class, which is simply writing a text file (for now)

```<code>#models/schedule_post.rb
class SchedulePost < ActiveRecord::Base
    def self.schedule_post(post)
        command = "touch #{Rails.root}/public/test.txt"
        system(command)
        return
    end
end
</code>```

So what I'm expecting to happen is that when post_now is called, it's supposed to run the schedule_post function 1 minute from now, which is simply supposed to write a text file. If I remove the .delay(run_at: 1.minute.from_now) block and just leave schedule_post there, then it works fine. So I'm definitely doing something wrong here with the delay function.

答:
You need to start the delayed_job worker to perform delayed tasks...in your terminal from app root directory do</p>

```<code>rake jobs:work
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm simply trying to get a function to run at a specific time, but I'm not having much luck. Let me just run through the basics of what I've done

#Gemfile

gem 'delayed_job_active_record'

#config/application.rb

module SampleApp
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.active_job.queue_adapter = :delayed_job
  end
end

#Ran from command line

[06.07.2017/15:38:02] user@ubuntu $ rails g delayed_job:active_record
Running via Spring preloader in process 72879
   identical  bin/delayed_job
       chmod  bin/delayed_job
      create  db/migrate/20170607203821_create_delayed_jobs.rb
[06.07.2017/15:38:21] user@ubuntu $ rake db:migrate
== 20170607203821 CreateDelayedJobs: migrating ================================
-- create_table(:delayed_jobs, {:force=>true})
   -> 0.0088s
-- add_index(:delayed_jobs, [:priority, :run_at], {:name=>"delayed_jobs_priority"})
   -> 0.0051s
== 20170607203821 CreateDelayedJobs: migrated (0.0142s) =======================

So I basically have a button on my view that calls post_now, which then calls a function within a custom model that I have. Here's an example of what I have:

#posts_controller.rb
  def post_now
    set_post
    submit_post = SchedulePost.delay(run_at: 1.minute.from_now).schedule_post(@post)
    redirect_to posts_path, flash: {success: submit_post[1] }
  end

and then here's the SchedulePost class, which is simply writing a text file (for now)

#models/schedule_post.rb
class SchedulePost < ActiveRecord::Base
    def self.schedule_post(post)
        command = "touch #{Rails.root}/public/test.txt"
        system(command)
        return
    end
end

So what I'm expecting to happen is that when post_now is called, it's supposed to run the schedule_post function 1 minute from now, which is simply supposed to write a text file. If I remove the .delay(run_at: 1.minute.from_now) block and just leave schedule_post there, then it works fine. So I'm definitely doing something wrong here with the delay function.

Body:
You need to start the delayed_job worker to perform delayed tasks...in your terminal from app root directory do

rake jobs:work


问:
How to use subclass parameters in superclass method?
I have a superclass called Player, and I have 3 subclasses that are Young Hustler, Student and The Herbalist.

In every subclass I have private parameters money, stashSize and connections.

And I want to create a method in Player class called sellWeed() which removes 1 from stashSize and adds 10 to money, so that I could apply that method to all of the subclasses when calling them in the main method. But how do I get the private parameters from subclasses into the superclass?

I can't declare them in superclass because each subclass has it's own default starting parameters which should progress during the game.

答:
Something like this should work:

```<code>class Player {
  protected int money;
  protected int stashSize;
  // and the connections parameter too...
  public Player(int money, int stashSize) {
    this.money = money;
    this.stashSize = stashSize;
  }
  public void sellWeed() {
    // work with money and stashSize here
  }
}

class Student extends Player {
  public Student() {
    super(0, 10); // no money and stashSize 10 for student
  }
}
</code>```

The idea is to move the private parameters to the super class. Then you can initialize them by passing the values to the super constructor (super()).

Body:
Something like this should work:

class Player {
  protected int money;
  protected int stashSize;
  // and the connections parameter too...
  public Player(int money, int stashSize) {
    this.money = money;
    this.stashSize = stashSize;
  }
  public void sellWeed() {
    // work with money and stashSize here
  }
}

class Student extends Player {
  public Student() {
    super(0, 10); // no money and stashSize 10 for student
  }
}

The idea is to move the private parameters to the super class. Then you can initialize them by passing the values to the super constructor (super()).


问:
Python call class with inputs from list
I have a class called Interval for which I want to create multiple interval objects from a list of intervals. How do I do it with map ?

```<code>class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
</code>```

I tried to do:

```<code>objs = map(Interval, intervals)
</code>```

But this sends the full interval as the first parameter rather than the inputs to the class individually.

答:
Maybe you can try also the old-school way:</p>

```<code>class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

def map_intervals(intervals):
        ret = []
        for inter in intervals:
          ret.append(Interval(inter[0],inter[1]))
        return ret
inters = [[1,2],[3,5],[6,7],[8,10],[12,16]]
</code>```

Title: Python call class with inputs from list

Body:
I have a class called Interval for which I want to create multiple interval objects from a list of intervals. How do I do it with map ?

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]

I tried to do:

objs = map(Interval, intervals)

But this sends the full interval as the first parameter rather than the inputs to the class individually.

Body:
Maybe you can try also the old-school way:

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

def map_intervals(intervals):
        ret = []
        for inter in intervals:
          ret.append(Interval(inter[0],inter[1]))
        return ret
inters = [[1,2],[3,5],[6,7],[8,10],[12,16]]


答:
This worked for me.</p>

```<code>>>> objs = []
>>> for interval in intervals:
...     objs.append(Interval(*interval))
...
>>> objs
[<__main__.Interval object at 0x013E67D0>, <__main__.Interval object at 0x013E6910>, <__main__.Interval object at 0x013E68F0>, <__main__.Interval object at 0x013E6870>, <__main__.Interval object at 0x013E6950>]
>>> objs[0]
<__main__.Interval object at 0x013E67D0>
>>> objs[0].start
1
>>> objs[0].end
2
>>>
</code>```

Title: Python call class with inputs from list

Body:
This worked for me.

>>> objs = []
>>> for interval in intervals:
...     objs.append(Interval(*interval))
...
>>> objs
[<__main__.Interval object at 0x013E67D0>, <__main__.Interval object at 0x013E6910>, <__main__.Interval object at 0x013E68F0>, <__main__.Interval object at 0x013E6870>, <__main__.Interval object at 0x013E6950>]
>>> objs[0]
<__main__.Interval object at 0x013E67D0>
>>> objs[0].start
1
>>> objs[0].end
2
>>>


问:
An intelligent Javascript back button that doesnt use history()
Im developing on a platform that has some limitations on how i can implement a proper back button.

So i need to create a button that does more then just "javascript:history.back()"

Let me explain:

page1...clicks through to...

page2...fill in the fields and submit to itself...

page2?something=else... here is where the back button is needed

on page2?something=else i want the back button to take the user back to page1

page1 = could be any page (so cant link directly)

is there a function that will know changes in the URL as well as remember the  URL when the page is submitted?

Please lety me know if you would like more info.

Thanks

答:
One way you could achieve this is during the form submission on page2.  Where it would normally submit a form to itself, your script would intercept the submit action and replace the current item in the history instead.  In order to do this, you would need to reconstruct the query string values:

```<code>myForm.onsubmit = function () {
    var url = this.action,   // The URL where the form is submitted
        els = this.elements, // A list of all the input elements
        qs  = "?",           // The query string we're constructing
        enc = function (s) { // Function for encoding
            return encodeURIComponent(s).replace(/%20/g, "+");
        };

    for (var i=0, max = els.length; i < max; i++) {
        if (els[i].disabled || !els[i].name)
            continue;

        qs += enc(els[i].name) + "=" + enc(els[i].value) + "&";
    }

    // chop off the final ampersand
    qs = qs.slice(0, -1);

    // Replace the current entry in the history
    window.location.replace(action + qs);

    // Cancel the default form submission
    return false;
}
</code>```

It will probably need a little refinement to suit your needs but you get the general idea.  Now both the browser's back button and your own back button should return to page1.  This approach won't work for POST submissions, however.

Body:
One way you could achieve this is during the form submission on page2.  Where it would normally submit a form to itself, your script would intercept the submit action and replace the current item in the history instead.  In order to do this, you would need to reconstruct the query string values:

myForm.onsubmit = function () {
    var url = this.action,   // The URL where the form is submitted
        els = this.elements, // A list of all the input elements
        qs  = "?",           // The query string we're constructing
        enc = function (s) { // Function for encoding
            return encodeURIComponent(s).replace(/%20/g, "+");
        };

    for (var i=0, max = els.length; i < max; i++) {
        if (els[i].disabled || !els[i].name)
            continue;

        qs += enc(els[i].name) + "=" + enc(els[i].value) + "&";
    }

    // chop off the final ampersand
    qs = qs.slice(0, -1);

    // Replace the current entry in the history
    window.location.replace(action + qs);

    // Cancel the default form submission
    return false;
}

It will probably need a little refinement to suit your needs but you get the general idea.  Now both the browser's back button and your own back button should return to page1.  This approach won't work for POST submissions, however.


问:
Bootstrap fixed navbar inside div
In bootstrap documentation they're able to "trap" a .navbar-fixed-top inside their .bs-docs-example div:

```<code><div class="bs-docs-example bs-navbar-top-example">
    <div class="navbar navbar-fixed-top" style="position: absolute;">
        <div class="navbar-inner">
        [...]
</code>```

But if I do the same in my test page the navbar "escapes" the div and get fixed in the top of the body, not the top of the div. How it's the trick achieved?

答:
```<code><div class="container-fluid">
    <div class="container">
        <nav class="navbar">...</nav>
    </div>
</div>
</code>```

That works with built-in Bootstrap's CSS.

Title: Bootstrap fixed navbar inside div

Body:
In bootstrap documentation they're able to "trap" a .navbar-fixed-top inside their .bs-docs-example div:

        [...]

But if I do the same in my test page the navbar "escapes" the div and get fixed in the top of the body, not the top of the div. How it's the trick achieved?

Body:
<div class="container-fluid">
    <div class="container">
        <nav class="navbar">...</nav>
    </div>
</div>

That works with built-in Bootstrap's CSS.