问:
Adding a custom iterator to a javascript class
I'm trying to figure out how to add an itertor to a javascript class such that the class could be used in a for...in loop. Following the instructions from Mozilla doesn't produce the results they claim it will.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
Jsfiddle of given example: http://jsfiddle.net/KQayW/

```<code>function Range(low, high){
  this.low = low;
  this.high = high;
  this.current = low;
  this.next = function() {
    if (this.current > this.range.high)
      throw StopIteration;
    else
      return this.current++;
  }
}
function RangeIterator(range){
  this.range = range;
  this.current = this.range.low;
}
RangeIterator.prototype.next = function(){
  if (this.current > this.range.high)
    throw StopIteration;
  else
    return this.current++;
};
Range.prototype.__iterator__ = function(){
  return new RangeIterator(this);
};
var range = new Range(3, 5);
for (var i in range)
  document.getElementById("test").innerHTML = i+"</br>"; // prints 3, then 4, then 5 in sequence
</code>```

It doesn't print out the numbers in the range, it prints out "__iterator__"!

Does anyone know how to get this to work?

答:
With ES2015 it can be even more simple

const Range = (start, end) => ({
  *[Symbol.iterator]() {
    while (start < end)
        yield start++;
  }
})

for (var x of Range(1, 10)) {
  console.log(x)
}```

Body:
I'm trying to figure out how to add an itertor to a javascript class such that the class could be used in a for...in loop. Following the instructions from Mozilla doesn't produce the results they claim it will.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
Jsfiddle of given example: http://jsfiddle.net/KQayW/

function Range(low, high){
  this.low = low;
  this.high = high;
  this.current = low;
  this.next = function() {
    if (this.current > this.range.high)
      throw StopIteration;
    else
      return this.current++;
  }
}
function RangeIterator(range){
  this.range = range;
  this.current = this.range.low;
}
RangeIterator.prototype.next = function(){
  if (this.current > this.range.high)
    throw StopIteration;
  else
    return this.current++;
};
Range.prototype.__iterator__ = function(){
  return new RangeIterator(this);
};
var range = new Range(3, 5);
for (var i in range)
  document.getElementById("test").innerHTML = i+"
"; // prints 3, then 4, then 5 in sequence

It doesn't print out the numbers in the range, it prints out "__iterator__"!

Does anyone know how to get this to work?


来源: stackexchange

问:
find duplicate addresses in database, stop users entering them early?
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

```<code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code>```

I'm talking German addresses...
Thanks!

答:
As google fetch suggesions for search you can search database address fields

First, let’s create an index.htm(l) file:

```<code>    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta http-equiv="Content-Language" content="en-us">
        <title>Address Autocomplete</title>
        <meta charset="utf-8">
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
        <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
        <style>
            h1 {
                font-size: 20px;
                color: #111;
            }

            .content {
                width: 80%;
                margin: 0 auto;
                margin-top: 50px;
            }

            .tt-hint,
            .city {
                border: 2px solid #CCCCCC;
                border-radius: 8px 8px 8px 8px;
                font-size: 24px;
                height: 45px;
                line-height: 30px;
                outline: medium none;
                padding: 8px 12px;
                width: 400px;
            }

            .tt-dropdown-menu {
                width: 400px;
                margin-top: 5px;
                padding: 8px 12px;
                background-color: #fff;
                border: 1px solid #ccc;
                border: 1px solid rgba(0, 0, 0, 0.2);
                border-radius: 8px 8px 8px 8px;
                font-size: 18px;
                color: #111;
                background-color: #F1F1F1;
            }
        </style>
        <script>
            $(document).ready(function() {

                $('input.city').typeahead({
                    name: 'city',
                    remote: 'city.php?query=%QUERY'

                });

            })
        </script>

    <script>
            function register_address()
            {
                $.ajax({
                    type: "POST",
                    data: {
                        City: $('#city').val(),
                    },
                    url: "addressexists.php",
                    success: function(data)
                    {
                        if(data === 'ADDRESS_EXISTS')
                        {
                            $('#address')
                                .css('color', 'red')
                                .html("This address already exists!");
                        }

                    }
                })
            }
        </script>
    </head>

    <body>
        <div class="content">

            <form>
                <h1>Try it yourself</h1>
                <input type="text" name="city" size="30" id="city" class="city" placeholder="Please Enter City or ZIP code">
<span id="address"></span>
            </form>
        </div>
    </body>
</html>
</code>```

Now we will create a city.php file which will aggregate our query to MySQL DB and give response as JSON. Here is the code:

```<code><?php

//CREDENTIALS FOR DB
define ('DBSERVER', 'localhost');
define ('DBUSER', 'user');
define ('DBPASS','password');
define ('DBNAME','dbname');

//LET'S INITIATE CONNECT TO DB
$connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,"DBNAME") or die("Can't connect to server. Please check credentials and try again");

//CREATE QUERY TO DB AND PUT RECEIVED DATA INTO ASSOCIATIVE ARRAY
if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysqli_query ($connection ,"SELECT zip, city FROM zips WHERE city LIKE '%{$query}%' OR zip LIKE '%{$query}%'");
    $array = array();
    while ($row = mysqli_fetch_array($sql,MYSQLI_NUM)) {
        $array[] = array (
            'label' => $row['city'].', '.$row['zip'],
            'value' => $row['city'],
        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array);
}

?>
</code>```

and then prevent saving them into database if found duplicate in table column

And for your addressexists.php code:

```<code><?php//CREDENTIALS FOR DB
    define ('DBSERVER', 'localhost');
    define ('DBUSER', 'user');
    define ('DBPASS','password');
    define ('DBNAME','dbname');

    //LET'S INITIATE CONNECT TO DB
    $connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,"DBNAME") or die("Can't connect to server. Please check credentials and try again");

    $city= mysqli_real_escape_string($_POST['city']); // $_POST is an array (not a function)
    // mysqli_real_escape_string is to prevent sql injection

    $sql = "SELECT username FROM ".TABLENAME." WHERE city='".$city."'"; // City must enclosed in two quotations

    $query = mysqli_query($connection,$sql);

    if(mysqli_num_rows($query) != 0)

    {
        echo('ADDRESS_EXISTS');
    }
?>
</code>```

OwnerDisplayName: Johannes

ContentLicense: CC BY-SA 2.5

Body:
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

Quellenstrasse 66/11
Quellenstr. 66a-11

I'm talking German addresses...
Thanks!

LastEditorDisplayName: Remou

Body:
As google fetch suggesions for search you can search database address fields

First, let’s create an index.htm(l) file:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta http-equiv="Content-Language" content="en-us">
        <title>Address Autocomplete</title>
        <meta charset="utf-8">
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
        <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
        <style>
            h1 {
                font-size: 20px;
                color: #111;
            }

            .content {
                width: 80%;
                margin: 0 auto;
                margin-top: 50px;
            }

            .tt-hint,
            .city {
                border: 2px solid #CCCCCC;
                border-radius: 8px 8px 8px 8px;
                font-size: 24px;
                height: 45px;
                line-height: 30px;
                outline: medium none;
                padding: 8px 12px;
                width: 400px;
            }

            .tt-dropdown-menu {
                width: 400px;
                margin-top: 5px;
                padding: 8px 12px;
                background-color: #fff;
                border: 1px solid #ccc;
                border: 1px solid rgba(0, 0, 0, 0.2);
                border-radius: 8px 8px 8px 8px;
                font-size: 18px;
                color: #111;
                background-color: #F1F1F1;
            }
        </style>
        <script>
            $(document).ready(function() {

                $('input.city').typeahead({
                    name: 'city',
                    remote: 'city.php?query=%QUERY'

                });

            })
        </script>

    <script>
            function register_address()
            {
                $.ajax({
                    type: "POST",
                    data: {
                        City: $('#city').val(),
                    },
                    url: "addressexists.php",
                    success: function(data)
                    {
                        if(data === 'ADDRESS_EXISTS')
                        {
                            $('#address')
                                .css('color', 'red')
                                .html("This address already exists!");
                        }

                    }
                })
            }
        </script>
    </head>

    <body>
        <div class="content">

            <form>
                <h1>Try it yourself</h1>
                <input type="text" name="city" size="30" id="city" class="city" placeholder="Please Enter City or ZIP code">
<span id="address"></span>
            </form>
        </div>
    </body>
</html>

Now we will create a city.php file which will aggregate our query to MySQL DB and give response as JSON. Here is the code:

<?php

//CREDENTIALS FOR DB
define ('DBSERVER', 'localhost');
define ('DBUSER', 'user');
define ('DBPASS','password');
define ('DBNAME','dbname');

//LET'S INITIATE CONNECT TO DB
$connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,"DBNAME") or die("Can't connect to server. Please check credentials and try again");

//CREATE QUERY TO DB AND PUT RECEIVED DATA INTO ASSOCIATIVE ARRAY
if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysqli_query ($connection ,"SELECT zip, city FROM zips WHERE city LIKE '%{$query}%' OR zip LIKE '%{$query}%'");
    $array = array();
    while ($row = mysqli_fetch_array($sql,MYSQLI_NUM)) {
        $array[] = array (
            'label' => $row['city'].', '.$row['zip'],
            'value' => $row['city'],
        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array);
}

?>

and then prevent saving them into database if found duplicate in table column

And for your addressexists.php code:

<?php//CREDENTIALS FOR DB
    define ('DBSERVER', 'localhost');
    define ('DBUSER', 'user');
    define ('DBPASS','password');
    define ('DBNAME','dbname');

    //LET'S INITIATE CONNECT TO DB
    $connection = mysqli_connect(DBSERVER, DBUSER, DBPASS,"DBNAME") or die("Can't connect to server. Please check credentials and try again");

    $city= mysqli_real_escape_string($_POST['city']); // $_POST is an array (not a function)
    // mysqli_real_escape_string is to prevent sql injection

    $sql = "SELECT username FROM ".TABLENAME." WHERE city='".$city."'"; // City must enclosed in two quotations

    $query = mysqli_query($connection,$sql);

    if(mysqli_num_rows($query) != 0)

    {
        echo('ADDRESS_EXISTS');
    }
?>

ContentLicense: CC BY-SA 3.0


问:
codeigniter An uncaught Exception was encountered Type: RuntimeException not working in Linux server
Am creating a website using codeigniter. All the codes are working in localhost(XAMPP).

But same code not working in Linuxserver showing error like

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: Admin_user

Filename: /home/capitalw/public_html/domain/system/core/Loader.php

Line Number: 344

Backtrace:

File: /home/capitalw/public_html/domain/application/controllers/Admin.php
  Line: 10
  Function: model

File: /home/capitalw/public_html/domain/index.php
  Line: 315
  Function: require_once

Here my codes are

application/controller/Admin.php

```<code>class Admin extends CI_Controller {

    public function __construct(){
        parent::__construct();
        //$this->load->library('common');
        $this->load->library('form_validation');
        $this->load->model('admin_user');

    }
}
</code>```

application/models/admin_user.php

```<code>class Admin_user extends CI_Model {

    function __construct()
    {
        parent::__construct();

    }
//some inser update codes here

}
</code>```

答:
Change file name

```<code>admin_model.php
</code>```

to

```<code>Admin_model.php
</code>```

Linux' file system is case sensitive.

Body:
Am creating a website using codeigniter. All the codes are working in localhost(XAMPP).

But same code not working in Linuxserver showing error like

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: Admin_user

Filename: /home/capitalw/public_html/domain/system/core/Loader.php

Line Number: 344

Backtrace:

File: /home/capitalw/public_html/domain/application/controllers/Admin.php
  Line: 10
  Function: model

File: /home/capitalw/public_html/domain/index.php
  Line: 315
  Function: require_once

Here my codes are

application/controller/Admin.php

class Admin extends CI_Controller {

    public function __construct(){
        parent::__construct();
        //$this->load->library('common');
        $this->load->library('form_validation');
        $this->load->model('admin_user');

    }
}

application/models/admin_user.php

class Admin_user extends CI_Model {

    function __construct()
    {
        parent::__construct();

    }
//some inser update codes here

}

Body:
Change file name

admin_model.php

to

Admin_model.php

Linux' file system is case sensitive.


问:
get result of two query with one query - mysql
```<code>$sql ="select * from user limit 5";
</code>```

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

```<code>query 1 : select count(*) from user
query 2 : select * from user LIMIT 5
</code>```

is that possible without any sub query?

答:
How about something like

```<code>select  *,
        (select count(*) from user) TotalUsers
from    user
LIMIT 5
</code>```

Or maybe

```<code>select  user.*,
        TotalUsers.TotalCnt
from    user,
        (select count(*) TotalCnt from user) TotalUsers
LIMIT 5
</code>```

Body:
$sql ="select * from user limit 5";

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

query 1 : select count(*) from user
query 2 : select * from user LIMIT 5

is that possible without any sub query?

Body:
How about something like

select  *,
        (select count(*) from user) TotalUsers
from    user
LIMIT 5

Or maybe

select  user.*,
        TotalUsers.TotalCnt
from    user,
        (select count(*) TotalCnt from user) TotalUsers
LIMIT 5


问:
A file downloaded from DB is 'Read-Only' (cannot modify)
I have a following Class:

```<code>    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Data { get; set; }
</code>```

I upload .docx file to server using this methods:

```<code>        internal void AddDraft(OpenFileDialog openFileDialog, string description)
    {
        FileInfo fi = new FileInfo(openFileDialog.FileName);
        Draft draft = new Draft();
        draft.Description = description;
        draft.Name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
        draft.Data = getDataFromDraft(openFileDialog);

        RestRequest request = new RestRequest("api/draft", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(draft);

        restClient.Execute(request);
    }
</code>```

And convert file to Base64 using this:

```<code>        private string getDataFromDraft(OpenFileDialog openFileDialog)
    {
        byte[] bytes = null;

        using (FileStream stream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BinaryReader br = new BinaryReader(new BufferedStream(stream)))
        {
            bytes = br.ReadBytes((Int32)stream.Length);
        }

        var tmp = Convert.ToBase64String(bytes);

        return Convert.ToBase64String(bytes);
    }
</code>```

On the server side, base64 data is converted to byte[] and saved in a table.

Afterward, I use the following method to download it (in a WPF application)

```<code>        internal void SaveDraft(SaveFileDialog saveFileDialog, Draft draft)
    {
        byte[] bytes = Convert.FromBase64String(draft.Data);
        using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        using (BinaryWriter bw = new BinaryWriter(new BufferedStream(fs)))
        {
            bw.Write(bytes);
            bw.Flush();
        }
    }
</code>```

Here is my problem:

All the downloaded files are read-only, but I'd like to modify and save the downloaded file.

Any suggestions?

答:
Ok I found where was the problem. All time i try to save dowloaded file in C:/.
When i save it on another location everything was OK.</p>

Body:
I have a following Class:

    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Data { get; set; }

I upload .docx file to server using this methods:

        internal void AddDraft(OpenFileDialog openFileDialog, string description)
    {
        FileInfo fi = new FileInfo(openFileDialog.FileName);
        Draft draft = new Draft();
        draft.Description = description;
        draft.Name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
        draft.Data = getDataFromDraft(openFileDialog);

        RestRequest request = new RestRequest("api/draft", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(draft);

        restClient.Execute(request);
    }

And convert file to Base64 using this:

        private string getDataFromDraft(OpenFileDialog openFileDialog)
    {
        byte[] bytes = null;

        using (FileStream stream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BinaryReader br = new BinaryReader(new BufferedStream(stream)))
        {
            bytes = br.ReadBytes((Int32)stream.Length);
        }

        var tmp = Convert.ToBase64String(bytes);

        return Convert.ToBase64String(bytes);
    }

On the server side, base64 data is converted to byte[] and saved in a table.

Afterward, I use the following method to download it (in a WPF application)

        internal void SaveDraft(SaveFileDialog saveFileDialog, Draft draft)
    {
        byte[] bytes = Convert.FromBase64String(draft.Data);
        using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        using (BinaryWriter bw = new BinaryWriter(new BufferedStream(fs)))
        {
            bw.Write(bytes);
            bw.Flush();
        }
    }

Here is my problem:

All the downloaded files are read-only, but I'd like to modify and save the downloaded file.

Any suggestions?


问:
"The selected directory is not a valid home for Android SDK" IntelliJ 2017
I am trying to perform a clean installation of the latest Android SDK and  IntelliJ 2017 CE.

I have done things in this order:

Install IntelliJ 2017 CE

Install JDK 1.8.x

Install Android SDK using latest homebrew instructions

Set JDK location in IntelliJ

Attempt to set Android SDK location in IntelliJ.

The last step gives me the error mentioned in the title. The SDK is located at /usr/local/share/android-sdk which is a symlink to /usr/local/Caskroom/android-sdk/3859397. This SDK folder contains these files:

I have searched extensively for a solution, including other questions on SO. Here is a rough list of things I have tried:

chowned the SDK folder (and symlink) as my local user and also as root

Ran IntelliJ as root and tried to add Android SDK

Tried adding both the symlink and destination directory as the SDK directory

Reinstalling android-sdk via homebrew multiple times, restarting IntelliJ, restarting my computer

Even though there are seemingly identical questions here on SO, none of them seem to address my situation (2017 Android SDK and IntelliJ, Mac OS).

I would like to avoid giving up on the homebrew Android SDK installation, and resorting to a manual SDK installation, as it seems like it would just give me the exact same files, placed in a different location. I would also like to avoid installing Android Studio in parallel with my IntelliJ installation (kind of like using a sledgehammer to solve the problem).

Thank you for any help. I am not trying to do anything fancy - I just want a basic setup for developing Android apps using IntelliJ.

答:
IntelliJ Idea can't detect the Android-SDK because there is no "Platforms" folder

It can be created by running below commands

List installed and available packages :
sdkmanager --list

Install packages :
sdkmanager "platforms;android-26"

Then reference the "/usr/local/Caskroom/android-sdk/3859397" it will work

Reference link : https://developer.android.com/studio/command-line/sdkmanager.html


问:
Batch File Online Updater
Don't have any other name for this subject. Is there a way to make a batch file look for a file on a online storage site (EXAMPLE: Dropbox) and update.

here's an example: I am making a mod for a game that i want a batch file for updating and installing. the version of the mod is 1.0.0 and the online storage contains version 1.0.1. when you run the batch file, it'll say that there's an update available (it'll say you have latest update if you have latest version downloaded).

Anyway to do something like this or similar?

答: Unfortunately this is not an option with Windows. Dropbox has options to access your files from the command line on Linux but not on Windows. It seems there is not enough demand for this feature although I would love to see it.</p>

Title: Batch File Online Updater


问:
Incorrect syntax near the keyword 'JOIN'. using asp.net
Kindly help me on identifying the cause of this error

Incorrect syntax near the keyword 'JOIN'

Here is the code:

```<code>Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");

string queryGuitarItems = "DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)";

using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();
    }
}
</code>```

答:
change this:

```<code>DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)
</code>```

to this:

```<code>DELETE FROM stringInstrumentItem
FROM stringInstrumentItem t1 JOIN brand t2 ON t1brandId = t2.brandId WHERE t1.brandId IN(SELECT t3.brandId FROM brand t3 WHERE name = @brand)
</code>```

Hope I help you :)

Body:
Kindly help me on identifying the cause of this error

Incorrect syntax near the keyword 'JOIN'

Here is the code:

Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");

string queryGuitarItems = "DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)";

using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();
    }
}

Body:
change this:

DELETE FROM stringInstrumentItem JOIN brand ON stringInstrumentItem.brandId = brand.brandId WHERE stringInstrumentItem.brandId IN(SELECT brand.brandId FROM brand WHERE name = @brand)

to this:

DELETE FROM stringInstrumentItem
FROM stringInstrumentItem t1 JOIN brand t2 ON t1brandId = t2.brandId WHERE t1.brandId IN(SELECT t3.brandId FROM brand t3 WHERE name = @brand)

Hope I help you :)


问:
Angular 2 - NgForm null when submit a form
Hi everyone i am doing a "dinamic" form with Angular and i am having some problems to get the values that input in form, my code is:

HTML

```<code><form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>
  <div class="form-group" *ngIf = "con.type != 'submit'">
    <label for="{{con.id}}">{{con.label}}</label>
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">
 </div>
 <input  *ngIf = "con.type == 'submit'"  type="submit" class="{{con.class}}" value={{con.label}}>
</form>
</code>```

Component:

```<code>import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'form-tag',
  templateUrl: './form.html',
})

export class FormComponent {
    @Input() controls: any[];

    onSubmit(sub: NgForm)
    {
        console.log(sub.email);
    }
}
</code>```

the problem is that when i submit the form console.log(sub.email); return an empty object

答:
Since you use ngForm, it's a template driven form and not a reactive one. In template driven forms you need to pass myForm.value to onSubmit():

```<code>onSubmit(myForm.value)
</code>```

Also, from your code sample, it's not clear what's con.

Body:
Hi everyone i am doing a "dinamic" form with Angular and i am having some problems to get the values that input in form, my code is:

HTML

<form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>

    {{con.label}}
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">

 <input  *ngIf = "con.type == 'submit'"  type="submit" class="{{con.class}}" value={{con.label}}>
</form>

Component:

import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'form-tag',
  templateUrl: './form.html',
})

export class FormComponent {
    @Input() controls: any[];

    onSubmit(sub: NgForm)
    {
        console.log(sub.email);
    }
}

the problem is that when i submit the form console.log(sub.email); return an empty object

Body:
Since you use ngForm, it's a template driven form and not a reactive one. In template driven forms you need to pass myForm.value to onSubmit():

onSubmit(myForm.value)

Also, from your code sample, it's not clear what's con.


问:
how to save the correct rotation of the Bitmap
I've this problem: when I load the photo that I've get from camera or, gallery, with this code:

```<code>if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO)
        //dalla fotocamera
        {
            if (data != null)mMediaUri = data.getData();

            Glide.with(this).load(mMediaUri).bitmapTransform(new CenterCrop(context), new RoundCornerTransformation(context, 15, 2)).into(photo);
        }
}
</code>```

the picture is shown in the correct way in the imageView.
Otherwise, I need to compress the bitmap so I've made this code to do the compression:

```<code> fun compressBitmapInBackgroundtoByteArray(uri: Uri?,context: Context, callback: OnFinishedCallback) {

    Observable.create<ByteArray> { s ->

        var imageStream: InputStream? = null
        try {
            imageStream = context.getContentResolver().openInputStream(uri)
        } catch (e: FileNotFoundException) {
            s.onError(e)
        }

        val bmp = BitmapFactory.decodeStream(imageStream)

        var stream: ByteArrayOutputStream? = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.JPEG, 0, stream)
        bmp.recycle()
        val compressed:ByteArray? =(stream?.toByteArray())

        try {
            stream?.close()

        } catch (e: IOException) {
            s.onError(e)
        }

        s.onNext(compressed!!)
        s.onComplete()

    }.subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy (
                    onNext = { compress -> callback.onNext(compress) },
                    onError =  { error-> callback.onError(error.message) },
                    onComplete = { callback.onCompleted() }
            )

}
</code>```

and this loose the correct orientation. In fact, when I try to load the byteArray I've given, with this code:

```<code>  if(user.getPicUrl() != null) {
        Glide.with(this).load(user.getPicture()).bitmapTransform(new CenterCrop(context), new RoundCornerTransformation(context, 15, 2)).into(photo);
        PICTURE_INSERTED = true;
    }
</code>```

the picture has the rotation of 90 degrees.
I've read that Glide supports Exif rotation, but in this case it doesn't work. Why? There is a way to "store" the correct orientation to save in the server? Thanks

答:
You must copy the EXIF data from the original image to the final resized image.You can use ExifInterface for this.

https://developer.android.com/reference/android/media/ExifInterface.html#ExifInterface

For example;

```<code>val oldExif = ExifInterface(oldImagePath)
val exifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION)

if (exifOrientation != null) {
 val newExif = ExifInterface(imagePath)
 newExif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation)
 newExif.saveAttributes()
}
</code>```

Body:
I've this problem: when I load the photo that I've get from camera or, gallery, with this code:

if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO)
        //dalla fotocamera
        {
            if (data != null)mMediaUri = data.getData();

            Glide.with(this).load(mMediaUri).bitmapTransform(new CenterCrop(context), new RoundCornerTransformation(context, 15, 2)).into(photo);
        }
}

the picture is shown in the correct way in the imageView.
Otherwise, I need to compress the bitmap so I've made this code to do the compression:

 fun compressBitmapInBackgroundtoByteArray(uri: Uri?,context: Context, callback: OnFinishedCallback) {

    Observable.create<ByteArray> { s ->

        var imageStream: InputStream? = null
        try {
            imageStream = context.getContentResolver().openInputStream(uri)
        } catch (e: FileNotFoundException) {
            s.onError(e)
        }

        val bmp = BitmapFactory.decodeStream(imageStream)

        var stream: ByteArrayOutputStream? = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.JPEG, 0, stream)
        bmp.recycle()
        val compressed:ByteArray? =(stream?.toByteArray())

        try {
            stream?.close()

        } catch (e: IOException) {
            s.onError(e)
        }

        s.onNext(compressed!!)
        s.onComplete()

    }.subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy (
                    onNext = { compress -> callback.onNext(compress) },
                    onError =  { error-> callback.onError(error.message) },
                    onComplete = { callback.onCompleted() }
            )

}

and this loose the correct orientation. In fact, when I try to load the byteArray I've given, with this code:

  if(user.getPicUrl() != null) {
        Glide.with(this).load(user.getPicture()).bitmapTransform(new CenterCrop(context), new RoundCornerTransformation(context, 15, 2)).into(photo);
        PICTURE_INSERTED = true;
    }

the picture has the rotation of 90 degrees.
I've read that Glide supports Exif rotation, but in this case it doesn't work. Why? There is a way to "store" the correct orientation to save in the server? Thanks

Body:
You must copy the EXIF data from the original image to the final resized image.You can use ExifInterface for this.

https://developer.android.com/reference/android/media/ExifInterface.html#ExifInterface

For example;

val oldExif = ExifInterface(oldImagePath)
val exifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION)

if (exifOrientation != null) {
 val newExif = ExifInterface(imagePath)
 newExif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation)
 newExif.saveAttributes()
}


问:
How to group SQL Value if the column is same value
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

```<code>CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);
</code>```

After Insert VALUES

```<code>SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much
</code>```

What I've been trying to do is to

```<code>Select * FROM DATA WHERE Sender = 'SEND1'
</code>```

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

答:
As per comments in question, considering you have an identity column to find the order of records. Use ROW_NUMBER window function to find the latest Sender/Receiver message.

```<code>Select * from
(
Select Row_Number()Over(Partition by Sender,Receiver order by Num desc) Rn,*
From yourtable
) A
Where Rn = 1
</code>```

Body:
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);

After Insert VALUES

SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much

What I've been trying to do is to

Select * FROM DATA WHERE Sender = 'SEND1'

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

Body:
As per comments in question, considering you have an identity column to find the order of records. Use ROW_NUMBER window function to find the latest Sender/Receiver message.

Select * from
(
Select Row_Number()Over(Partition by Sender,Receiver order by Num desc) Rn,*
From yourtable
) A
Where Rn = 1


问:
Submit a List from a form generated with JavaScript with a Spring controller
I'm building an app with Spring Boot, the MVC pattern, and Thymeleaf as template engine. I have a form that generates a list with JavaScript, and a controller with a @ModelAttribute expecting a list, to be saved into the database.

At the JavaScript side I collect the items with this array:

```<code>groupList = [];
groupList.push(inputValue);

function getGroupList(){
return groupList;
}
</code>```

In the html I'm trying to assign the array value to a hidden input field:

```<code><input type="hidden" class="invisible" id="groupList" th:field="*{groupList}"/>
</code>```

With this inline function:

```<code><script th:inline="javascript" type="text/javascript">
      $(function() {
            var groupListCollected = getGroupList();
            $("#groupList").val(groupListCollected);
       });
</script>
</code>```

My problem at this point, is that I don't find the way to collect the array,  and pass it to the Controller as a list.

This is the value that the console shows, for the input field:

```<code><input type="hidden" class="invisible" id="groupList" name="groupList"
       value="[object HTMLInputElement]">
</code>```

Any advice to face this issue, would be much appreciated. Thanks in advance.

答:
You can proceed like this :
Create a Model, for exemple:

```<code>public class User {
    private String username;
    public User() {
    }
    public User(String username) {
        this.username = username;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}
</code>```

Create a FormModel:

```<code>public class FormUsers {

        private List<User> listUsers;

        public FormUsers(List<User> listUsers) {
            this.listUsers = listUsers;
        }

        public FormUsers() {
        }

        public List<User> getListUsers() {
            return listUsers;
        }

        public void setListUsers(List<User> listUsers) {
            this.listUsers = listUsers;
        }

        @Override
        public String toString() {
            return "FormUsers{" + "listUsers=" + listUsers + '}';
        }
    }
</code>```

in your controller (Get and Post) :

```<code>@RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(ModelMap model) {
        FormUsers formUsers = new FormUsers();
        List<User> list = new ArrayList<>();
        list.add(new User("Wassim"));
        formUsers.setListUsers(list);
        logger.debug("--> " + formUsers.toString());
        model.addAttribute("formUsers", formUsers);
        return "hello";
    }

   @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String helloPost(@ModelAttribute FormUsers formUsers, ModelMap model) {
        logger.debug("Get List of new users -->  " + formUsers.toString());
        return "hello";
    }
</code>```

In my view (hello.html) : for listing all users :

```<code>  <button id="addAction">ADD</button>
            <form action="#" th:action="@{/hello}" th:object="${formUsers}" method="post">
                <ul id="myUl">
                    <input type="text" th:field="*{listUsers[0].username}" />
                </ul>
                <input type="submit" value="Submit" />
            </form>
</code>```

Now if I want to add another user with javascript when I clic in the button 'ADD, I will append() a new 'li' element containing the new user :

```<code><script type="text/javascript">
                $(document).ready(function () {
                    console.log("ready!");
                    $("#addAction").click(function () {
                        console.log("FUNCTION");
                        $("#myUl").append('<li><input id="listUsers1.username" name="listUsers[1].username" value="Rafik" type="text"/></li>');
                    });
                });
            </script>
</code>```

When I Submit, I will get a list with 2 User : 'Wassim' & 'Rafik'.
You can manage this exemple (also the index of the list must managed properly) to append your list with the needed DATA.

ContentLicense: CC BY-SA 4.0

Body:
I'm building an app with Spring Boot, the MVC pattern, and Thymeleaf as template engine. I have a form that generates a list with JavaScript, and a controller with a @ModelAttribute expecting a list, to be saved into the database.

At the JavaScript side I collect the items with this array:

groupList = [];
groupList.push(inputValue);

function getGroupList(){
return groupList;
}

In the html I'm trying to assign the array value to a hidden input field:

<input type="hidden" class="invisible" id="groupList" th:field="*{groupList}"/>

With this inline function:

My problem at this point, is that I don't find the way to collect the array,  and pass it to the Controller as a list.

This is the value that the console shows, for the input field:

<input type="hidden" class="invisible" id="groupList" name="groupList"
       value="[object HTMLInputElement]">

Any advice to face this issue, would be much appreciated. Thanks in advance.

Body:
You can proceed like this :
Create a Model, for exemple:

public class User {
    private String username;
    public User() {
    }
    public User(String username) {
        this.username = username;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

Create a FormModel:

public class FormUsers {

        private List<User> listUsers;

        public FormUsers(List<User> listUsers) {
            this.listUsers = listUsers;
        }

        public FormUsers() {
        }

        public List<User> getListUsers() {
            return listUsers;
        }

        public void setListUsers(List<User> listUsers) {
            this.listUsers = listUsers;
        }

        @Override
        public String toString() {
            return "FormUsers{" + "listUsers=" + listUsers + '}';
        }
    }

in your controller (Get and Post) :

@RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(ModelMap model) {
        FormUsers formUsers = new FormUsers();
        List<User> list = new ArrayList<>();
        list.add(new User("Wassim"));
        formUsers.setListUsers(list);
        logger.debug("--> " + formUsers.toString());
        model.addAttribute("formUsers", formUsers);
        return "hello";
    }

   @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String helloPost(@ModelAttribute FormUsers formUsers, ModelMap model) {
        logger.debug("Get List of new users -->  " + formUsers.toString());
        return "hello";
    }

In my view (hello.html) : for listing all users :

  <button id="addAction">ADD</button>
            <form action="#" th:action="@{/hello}" th:object="${formUsers}" method="post">
                <ul id="myUl">
                    <input type="text" th:field="*{listUsers[0].username}" />
                </ul>
                <input type="submit" value="Submit" />
            </form>

Now if I want to add another user with javascript when I clic in the button 'ADD, I will append() a new 'li' element containing the new user :

<script type="text/javascript">
                $(document).ready(function () {
                    console.log("ready!");
                    $("#addAction").click(function () {
                        console.log("FUNCTION");
                        $("#myUl").append('<li><input id="listUsers1.username" name="listUsers[1].username" value="Rafik" type="text"/></li>');
                    });
                });
            </script>

When I Submit, I will get a list with 2 User : 'Wassim' & 'Rafik'.
You can manage this exemple (also the index of the list must managed properly) to append your list with the needed DATA.


问:
state is not being set in componentDidMount
I want to access the refs from the render function, and set it to the state.

Here is my code:

```<code>export default class App extends Component {
    constructor(props) {
        super();
            this.arr = this.generateTimelineArray();
            this.state = {el : 'empty'};
        }
    componentDidMount() {
        this.setState({
          el: this.refs.el
        });
        console.log(this.state.el)
    }
render() {
    return (
      <div  className="timeline__container--line" ref="el" ></div>
    );
  }
</code>```

I can console.log(this.refs.el) and the value is logged. But i have to save it to constructor to pass it to another component.

Problem is that the state is not being changed.

What am i doing wrong?

Thanks in advance

答:
setState is async. Docs. If you want to see updated state use callback.

```<code>componentDidMount() {
        this.setState({
          el: this.refs.el
        }, () => console.log(this.state.el));
    }
</code>```

Body:
I want to access the refs from the render function, and set it to the state.

Here is my code:

export default class App extends Component {
    constructor(props) {
        super();
            this.arr = this.generateTimelineArray();
            this.state = {el : 'empty'};
        }
    componentDidMount() {
        this.setState({
          el: this.refs.el
        });
        console.log(this.state.el)
    }
render() {
    return (

    );
  }

I can console.log(this.refs.el) and the value is logged. But i have to save it to constructor to pass it to another component.

Problem is that the state is not being changed.

What am i doing wrong?

Thanks in advance

Body:
setState is async. Docs. If you want to see updated state use callback.

componentDidMount() {
        this.setState({
          el: this.refs.el
        }, () => console.log(this.state.el));
    }


问:
For every click different effect?
I have one problem. First - I HAVE AND I WILL HAVE JUST ONE BUTTON.
My problem is: How it can be for each button click different effect-animation.
So, when I first time click on button image goes down, then I second time click image goes from left to right, then I third time click image gone and then it repeat for fourth click image goes down(I can make animation left to right, animation down and then image gone.So I know how to do animation (effects), but I just do not know how to create for every click different effect on image)...</p>

答:
Here you go</p>

```<code>public class ButtonCycle extends JPanel {
    private int counter = 0;

    public ButtonCycle() {
        JButton btn = new JButton("Next");
        btn.addMouseListener(new MouseListener() {
            @Override
            public void mouseReleased(MouseEvent e) {}
            @Override
            public void mousePressed(MouseEvent e) {}
            @Override
            public void mouseClicked(MouseEvent e) {
                switch(counter) {
                    case 0:
                        // "Go down"-animation code here
                        System.out.println("Go down");

                        counter++;
                        break;
                    case 1:
                        // "Left->right"-animation code here
                        System.out.println("Left->right");

                        counter++;
                        break;
                    case 2:
                        // "Disappearing"-animation code here
                        System.out.println("*poof*, now I'm gone");

                        counter = 0;
                        break;
                }
            }
            @Override
            public void mouseExited(MouseEvent e) {}
            @Override
            public void mouseEntered(MouseEvent e) {}
        });

        add(btn);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Button cycling through animations");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setPreferredSize(new Dimension(250,250));
                f.setContentPane(new ButtonCycle());
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}
</code>```

Title: For every click different effect?

Body:
Here you go

public class ButtonCycle extends JPanel {
    private int counter = 0;

    public ButtonCycle() {
        JButton btn = new JButton("Next");
        btn.addMouseListener(new MouseListener() {
            @Override
            public void mouseReleased(MouseEvent e) {}
            @Override
            public void mousePressed(MouseEvent e) {}
            @Override
            public void mouseClicked(MouseEvent e) {
                switch(counter) {
                    case 0:
                        // "Go down"-animation code here
                        System.out.println("Go down");

                        counter++;
                        break;
                    case 1:
                        // "Left->right"-animation code here
                        System.out.println("Left->right");

                        counter++;
                        break;
                    case 2:
                        // "Disappearing"-animation code here
                        System.out.println("*poof*, now I'm gone");

                        counter = 0;
                        break;
                }
            }
            @Override
            public void mouseExited(MouseEvent e) {}
            @Override
            public void mouseEntered(MouseEvent e) {}
        });

        add(btn);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Button cycling through animations");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setPreferredSize(new Dimension(250,250));
                f.setContentPane(new ButtonCycle());
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}


答:
You could utilize the java.util.Random class along with the Random.nextInt() method against values from 1 to 4 within the ActionPerformed event of your Button. Then, depending upon which value is randomly produced run a specific animation method, perhaps through a switch/case or if statements...whatever. Here is an example:

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Random rnd = new Random();
    int value = (rnd.nextInt(4) + 1);
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
            break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}
</code>```

Or if you prefer, you could use the Math.random() method., for example:

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int value = 4 + (int)(Math.random() * (((1 - 2) - 4) + 1));
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
        break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}
</code>```

Of course there will be times when the random number generated will be the very much the same as the number generated previously but then again you could use a class field to hold the previous random value and if the currently generated value is the same as the previously generated value then you can generate another within perhaps a do/while loop, for example:

```<code>private int previousValue = 0;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int value = 0;
    Random rnd = new Random();
    do {
        value = (rnd.nextInt(4) + 1);
    } while (previousValue == value);
    previousValue = value;
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
            break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}
</code>```

Title: For every click different effect?

Body:
I have one problem. First - I HAVE AND I WILL HAVE JUST ONE BUTTON.
My problem is: How it can be for each button click different effect-animation.
So, when I first time click on button image goes down, then I second time click image goes from left to right, then I third time click image gone and then it repeat for fourth click image goes down(I can make animation left to right, animation down and then image gone.So I know how to do animation (effects), but I just do not know how to create for every click different effect on image)...

Body:
You could utilize the java.util.Random class along with the Random.nextInt() method against values from 1 to 4 within the ActionPerformed event of your Button. Then, depending upon which value is randomly produced run a specific animation method, perhaps through a switch/case or if statements...whatever. Here is an example:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Random rnd = new Random();
    int value = (rnd.nextInt(4) + 1);
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
            break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}

Or if you prefer, you could use the Math.random() method., for example:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int value = 4 + (int)(Math.random() * (((1 - 2) - 4) + 1));
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
        break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}

Of course there will be times when the random number generated will be the very much the same as the number generated previously but then again you could use a class field to hold the previous random value and if the currently generated value is the same as the previously generated value then you can generate another within perhaps a do/while loop, for example:

private int previousValue = 0;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int value = 0;
    Random rnd = new Random();
    do {
        value = (rnd.nextInt(4) + 1);
    } while (previousValue == value);
    previousValue = value;
    switch (value) {
        case 1:
            imageDown();
            break;
        case 2:
            imageLeftRight();
            break;
        case 3:
            imageGone();
            break;
        case 4:
            imageUp();
            break;
    }
}


问:
How to save UserData in Android FireBase DB?
I'm trying to Save UserDate in Android FireBase DB.

I have Email, name, age, province data(String Type).

I want to write UserDate like this.

```<code> "users": {
"Bart@gmail.com": {
  "name": "Bart",
  "age": "10",
  "province" : "Springfield"
  },
"Lisa@gmail.com": { ... },
}
</code>```

How should I write code to save userdata like this templates?

Thank you!

答:
The easiest way is to use a json java library like Gson.

Gson is a Java library that can be used to convert Java Objects into
  their JSON representation. (...) Provide simple toJson() and
  fromJson() methods to convert Java objects to JSON and vice-versa

Body:
I'm trying to Save UserDate in Android FireBase DB.

I have Email, name, age, province data(String Type).

I want to write UserDate like this.

 "users": {
"Bart@gmail.com": {
  "name": "Bart",
  "age": "10",
  "province" : "Springfield"
  },
"Lisa@gmail.com": { ... },
}

How should I write code to save userdata like this templates?

Thank you!


问:
Select count, inner joins and where statements
This is erp.orders:

```<code>userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01
</code>```

This is prod.referral_order_delivered

```<code>user_id
1
2
</code>```

This request :

```<code>select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"
</code>```

will give me this result:

```<code>userId  count
1       2
2       1
</code>```

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

```<code>userId  count
1       2
2       4
</code>```

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

答:
How about:</p>

```<code>     SELECT erp.orders."userId"
           ,count(erp.orders."paidAt")
       FROM erp.orders
 INNER JOIN prod.referral_order_delivered
         ON erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
        AND erp.orders."paidAt"::date >= '2017-06-07'
        AND erp.orders."paidAt"::date <= '2017-07-07'
   GROUP BY erp.orders."userId"
</code>```

Body:
This is erp.orders:

userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01

This is prod.referral_order_delivered

user_id
1
2

This request :

select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"

will give me this result:

userId  count
1       2
2       1

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

userId  count
1       2
2       4

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

Body:
How about:

     SELECT erp.orders."userId"
           ,count(erp.orders."paidAt")
       FROM erp.orders
 INNER JOIN prod.referral_order_delivered
         ON erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
        AND erp.orders."paidAt"::date >= '2017-06-07'
        AND erp.orders."paidAt"::date <= '2017-07-07'
   GROUP BY erp.orders."userId"


问:
Auto logout using sessions in Django (outside views)
I'm trying to build a auto-logout function in a Django application.

Basically, with each request to the site I want to set the current timestamp in the session (if not set), and then checking that value with the current time. If the difference is too great, it should redirect to logout.

Is there a easy way to set the session on each request without adding a function to each of my views?
I know it's possible to use sessions outside views, but then I have to supply the session_key, and I'm not sure where I should get it from, or generate it myself.

答:
I'm not sure what timestamp you are comparing with what here, or why.

The usual way to manage auto-logout is to simply set a short expiry on the session cookie, via the SESSION_COOKIE_AGE setting. If the cookie expires, the user will automatically be redirected to the login page if they try and access a page that requires authentication.


问:
store multiple image through two input types in codeigniter

I want to store multiple image through two input type,but one input type post has store and another input post value not stored.

my view

```<code><span class="btn btn-round" title="Upload Photo">
<input type="file" name="photo[]" multiple="">
</span>
<span class="btn btn-round" title="Upload Photo">
<input type="file" name="doc[]" multiple="">
</span>
</code>```

my controller

```<code>             if (!empty($_FILES['photo']['name'])) {
            $filesCount = count($_FILES['photo']['name']);
            for ($i = 0; $i < $filesCount; $i++) {
                $_FILES['userFile']['name'] = $_FILES['photo']['name'][$i];
                $_FILES['userFile']['type'] = $_FILES['photo']['type'][$i];
                $_FILES['userFile']['tmp_name'] = $_FILES['photo']
                           ['tmp_name'][$i];
                $_FILES['userFile']['error'] = $_FILES['photo']['error']
                                         [$i];
                $_FILES['userFile']['size'] = $_FILES['photo']['size'][$i];

                $uploadPath = 'assets/uploads/';
                $type = 'photo';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'gif|png|jpg|jpeg';

                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('userFile')) {
                    $getdata = $this->upload->data();
                    $uploadData[$i] = $getdata['file_name'];
                }
            }
        }
        if(!empty($_FILES['doc']['name'])){
            $filesCounts = count($_FILES['doc']['name']);echo $filesCounts;
            for ($j = 0; $j < $filesCounts; $j++) {
                $_FILES['userFile']['name'] = $_FILES['doc']['name'][$j];
                $_FILES['userFile']['type'] = $_FILES['doc']['type'][$j];
                $_FILES['userFile']['tmp_name'] = $_FILES['doc']['tmp_name']
                                                                  [$j];
                $_FILES['userFile']['error'] = $_FILES['doc']['error'][$j];
                $_FILES['userFile']['size'] = $_FILES['doc']['size'][$j];

                $uploadPaths = 'assets/uploads/';
                $type1 = 'document';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] =
                   'gif|png|jpg|jpeg|pdf|xls|docx|xlsx';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('userFile')) {
                    $getdata = $this->upload->data();
                    $uploadDocument[$j] = $getdata['file_name'];
                }
            }
        }
              for ($r = 0; $r < count($uploadData); $r++) {
                $data3 = array('event_id' => $last_id, 'file_name' =>
              $uploadData[$r], 'file_path' => $uploadPath, 'content_type' =>
              $type);
              if ($data3['file_name'] != "") {
              $this->admin_model->insert_activity_photo($data3);
              }
              }
              for ($a = 0; $a < count($uploadDocument); $a++) {
            $data5 = array('event_id' => $last_id, 'file_name' =>
         $uploadDocument[$a], 'file_path' => $uploadPaths, 'content_type' =>
         $type1);
        if ($data5['file_name'] != "") {
            $this->admin_model->insert_activity_photo($data5);
        }
        }
</code>```

my model

```<code>function insert_activity_photo($data3 = array()){
    $this->db->insert('t_attachment',$data3);
}
function insert_activity_photos($data5 = array()){
    $this->db->insert('t_attachment',$data5);
}
</code>```

when i try to store multiple image from this two input types only first input type value has posted second input type value not posted.

答:
Hi the both image starting position is 0($I=0 and $j=0) so the file is replace you should change the key kindly check my code
$uploadDocument[$k]</p>

```<code> if (!empty($_FILES['photo']['name'])) {
        $filesCount = count($_FILES['photo']['name']);
         $k=0;
        for ($i = 0; $i < $filesCount; $i++) {

            $_FILES['userFile']['name'] = $_FILES['photo']['name'][$i];
            $_FILES['userFile']['type'] = $_FILES['photo']['type'][$i];
            $_FILES['userFile']['tmp_name'] = $_FILES['photo']
                       ['tmp_name'][$i];
            $_FILES['userFile']['error'] = $_FILES['photo']['error']
                                     [$i];
            $_FILES['userFile']['size'] = $_FILES['photo']['size'][$i];

            $uploadPath = 'assets/uploads/';
            $type = 'photo';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] = 'gif|png|jpg|jpeg';

            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            if ($this->upload->do_upload('userFile')) {
                $getdata = $this->upload->data();
                $uploadData[$k] = $getdata['file_name'];
            }
          $k++;
        }
    }
    if(!empty($_FILES['doc']['name'])){
        $filesCounts = count($_FILES['doc']['name']);echo $filesCounts;
        for ($j = 0; $j < $filesCounts; $j++) {
            $_FILES['userFile']['name'] = $_FILES['doc']['name'][$j];
            $_FILES['userFile']['type'] = $_FILES['doc']['type'][$j];
            $_FILES['userFile']['tmp_name'] = $_FILES['doc']['tmp_name']
                                                              [$j];
            $_FILES['userFile']['error'] = $_FILES['doc']['error'][$j];
            $_FILES['userFile']['size'] = $_FILES['doc']['size'][$j];

            $uploadPaths = 'assets/uploads/';
            $type1 = 'document';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] =
               'gif|png|jpg|jpeg|pdf|xls|docx|xlsx';
            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            if ($this->upload->do_upload('userFile')) {
                $getdata = $this->upload->data();
                $uploadDocument[$k] = $getdata['file_name'];
            }
           $k++;
        }
    }
          for ($r = 0; $r < count($uploadData); $r++) {
            $data3 = array('event_id' => $last_id, 'file_name' =>
          $uploadData[$r], 'file_path' => $uploadPath, 'content_type' =>
          $type);
          if ($data3['file_name'] != "") {
          $this->admin_model->insert_activity_photo($data3);
          }
          }
          for ($a = 0; $a < count($uploadDocument); $a++) {
              $data5 = array('event_id' => $last_id, 'file_name' =>
              $uploadDocument[$a], 'file_path' => $uploadPaths, 'content_type' => $type1);
             if ($data5['file_name'] != "") {
                 $this->admin_model->insert_activity_photo($data5);
             }
    }
</code>```

Body:
I want to store multiple image through two input type,but one input type post has store and another input post value not stored.

my view

<input type="file" name="photo[]" multiple="">

<input type="file" name="doc[]" multiple="">

my controller

             if (!empty($_FILES['photo']['name'])) {
            $filesCount = count($_FILES['photo']['name']);
            for ($i = 0; $i < $filesCount; $i++) {
                $_FILES['userFile']['name'] = $_FILES['photo']['name'][$i];
                $_FILES['userFile']['type'] = $_FILES['photo']['type'][$i];
                $_FILES['userFile']['tmp_name'] = $_FILES['photo']
                           ['tmp_name'][$i];
                $_FILES['userFile']['error'] = $_FILES['photo']['error']
                                         [$i];
                $_FILES['userFile']['size'] = $_FILES['photo']['size'][$i];

                $uploadPath = 'assets/uploads/';
                $type = 'photo';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] = 'gif|png|jpg|jpeg';

                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('userFile')) {
                    $getdata = $this->upload->data();
                    $uploadData[$i] = $getdata['file_name'];
                }
            }
        }
        if(!empty($_FILES['doc']['name'])){
            $filesCounts = count($_FILES['doc']['name']);echo $filesCounts;
            for ($j = 0; $j < $filesCounts; $j++) {
                $_FILES['userFile']['name'] = $_FILES['doc']['name'][$j];
                $_FILES['userFile']['type'] = $_FILES['doc']['type'][$j];
                $_FILES['userFile']['tmp_name'] = $_FILES['doc']['tmp_name']
                                                                  [$j];
                $_FILES['userFile']['error'] = $_FILES['doc']['error'][$j];
                $_FILES['userFile']['size'] = $_FILES['doc']['size'][$j];

                $uploadPaths = 'assets/uploads/';
                $type1 = 'document';
                $config['upload_path'] = $uploadPath;
                $config['allowed_types'] =
                   'gif|png|jpg|jpeg|pdf|xls|docx|xlsx';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('userFile')) {
                    $getdata = $this->upload->data();
                    $uploadDocument[$j] = $getdata['file_name'];
                }
            }
        }
              for ($r = 0; $r < count($uploadData); $r++) {
                $data3 = array('event_id' => $last_id, 'file_name' =>
              $uploadData[$r], 'file_path' => $uploadPath, 'content_type' =>
              $type);
              if ($data3['file_name'] != "") {
              $this->admin_model->insert_activity_photo($data3);
              }
              }
              for ($a = 0; $a < count($uploadDocument); $a++) {
            $data5 = array('event_id' => $last_id, 'file_name' =>
         $uploadDocument[$a], 'file_path' => $uploadPaths, 'content_type' =>
         $type1);
        if ($data5['file_name'] != "") {
            $this->admin_model->insert_activity_photo($data5);
        }
        }

my model

function insert_activity_photo($data3 = array()){
    $this->db->insert('t_attachment',$data3);
}
function insert_activity_photos($data5 = array()){
    $this->db->insert('t_attachment',$data5);
}

when i try to store multiple image from this two input types only first input type value has posted second input type value not posted.

Body:
Hi the both image starting position is 0($I=0 and $j=0) so the file is replace you should change the key kindly check my code
$uploadDocument[$k]

 if (!empty($_FILES['photo']['name'])) {
        $filesCount = count($_FILES['photo']['name']);
         $k=0;
        for ($i = 0; $i < $filesCount; $i++) {

            $_FILES['userFile']['name'] = $_FILES['photo']['name'][$i];
            $_FILES['userFile']['type'] = $_FILES['photo']['type'][$i];
            $_FILES['userFile']['tmp_name'] = $_FILES['photo']
                       ['tmp_name'][$i];
            $_FILES['userFile']['error'] = $_FILES['photo']['error']
                                     [$i];
            $_FILES['userFile']['size'] = $_FILES['photo']['size'][$i];

            $uploadPath = 'assets/uploads/';
            $type = 'photo';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] = 'gif|png|jpg|jpeg';

            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            if ($this->upload->do_upload('userFile')) {
                $getdata = $this->upload->data();
                $uploadData[$k] = $getdata['file_name'];
            }
          $k++;
        }
    }
    if(!empty($_FILES['doc']['name'])){
        $filesCounts = count($_FILES['doc']['name']);echo $filesCounts;
        for ($j = 0; $j < $filesCounts; $j++) {
            $_FILES['userFile']['name'] = $_FILES['doc']['name'][$j];
            $_FILES['userFile']['type'] = $_FILES['doc']['type'][$j];
            $_FILES['userFile']['tmp_name'] = $_FILES['doc']['tmp_name']
                                                              [$j];
            $_FILES['userFile']['error'] = $_FILES['doc']['error'][$j];
            $_FILES['userFile']['size'] = $_FILES['doc']['size'][$j];

            $uploadPaths = 'assets/uploads/';
            $type1 = 'document';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] =
               'gif|png|jpg|jpeg|pdf|xls|docx|xlsx';
            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            if ($this->upload->do_upload('userFile')) {
                $getdata = $this->upload->data();
                $uploadDocument[$k] = $getdata['file_name'];
            }
           $k++;
        }
    }
          for ($r = 0; $r < count($uploadData); $r++) {
            $data3 = array('event_id' => $last_id, 'file_name' =>
          $uploadData[$r], 'file_path' => $uploadPath, 'content_type' =>
          $type);
          if ($data3['file_name'] != "") {
          $this->admin_model->insert_activity_photo($data3);
          }
          }
          for ($a = 0; $a < count($uploadDocument); $a++) {
              $data5 = array('event_id' => $last_id, 'file_name' =>
              $uploadDocument[$a], 'file_path' => $uploadPaths, 'content_type' => $type1);
             if ($data5['file_name'] != "") {
                 $this->admin_model->insert_activity_photo($data5);
             }
    }


问:
How to make a dialog slide from bottom to middle of screen in android
I want to show a dialog on my activity with animation. My dialog will slide from bottom of activity to middle of activity.

/****Edit****/

I'm sorry for my question is unclear. I mean that my dialog will be slide from bottom to middle but the bottom side of dialog is placed on bottom side of activity , like this following picture

答:
I tried all the answers in here and it don't work for me. I know all that answers are written long time ago. So let me show how I get it to work.
 I followed this article.

In short :
create res/anim/slide_up.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
      android:duration="@android:integer/config_mediumAnimTime"
      android:fromYDelta="100%"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:toYDelta="0">
    </translate>
</set>
</code>```

then, create res/anim/slide_bottom.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="0%p"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="100%p">
    </translate>
</set>
</code>```

Then add a style in res/values/styles.xml

```<code><style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up_dialog</item>
    <item name="android:windowExitAnimation">@anim/slide_out_down</item>
</style>
</code>```

Now you can set this animation style to your dialog or alertdialog box like below.

```<code>Dialog dialog = new Dialog(this);
dialog.getWindow().getAttributes().windowAnimations = animationSource;
</code>```

Or,

```<code>Dialog dialog = new Dialog(this);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.BOTTOM;
lp.windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setAttributes(lp);
</code>```

I showed example only for dialog boxes, but as I said before you can use this method for alert dialog boxes too.

Body:
I tried all the answers in here and it don't work for me. I know all that answers are written long time ago. So let me show how I get it to work.
 I followed this article.

In short :
create res/anim/slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
      android:duration="@android:integer/config_mediumAnimTime"
      android:fromYDelta="100%"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:toYDelta="0">
    </translate>
</set>

then, create res/anim/slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="0%p"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="100%p">
    </translate>
</set>

Then add a style in res/values/styles.xml

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up_dialog</item>
    <item name="android:windowExitAnimation">@anim/slide_out_down</item>
</style>

Now you can set this animation style to your dialog or alertdialog box like below.

Dialog dialog = new Dialog(this);
dialog.getWindow().getAttributes().windowAnimations = animationSource;

Or,

Dialog dialog = new Dialog(this);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.BOTTOM;
lp.windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setAttributes(lp);

I showed example only for dialog boxes, but as I said before you can use this method for alert dialog boxes too.


问:
java.sql.Date set timestamp
How I can set current time for java.sql.Date?

I'm using this Hibernate code for Date object:

```<code>@Column
@Type(type = "date")
@Temporal(TemporalType.DATE)
private Date added;
</code>```

答:
Use the java.sql.Date(long date) constructor and System.currentTimeMillis():

```<code>java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
System.out.println(sqlDate);
</code>```

Title: java.sql.Date set timestamp

Body:
How I can set current time for java.sql.Date?

I'm using this Hibernate code for Date object:

@Column
@Type(type = "date")
@Temporal(TemporalType.DATE)
private Date added;

Body:
Use the java.sql.Date(long date) constructor and System.currentTimeMillis():

java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
System.out.println(sqlDate);


问:
Retrieve URL for Action from Controller
I am calling a Controller Action from a view, within that controller I need to invoke another Action which I will invoke to save the view to a network location as either HTML or Image.

How do I retrieve the URL to an Action from within a Controller. Please note I need the actual URL, this means RedirectionToAction or View() wont work.

Why? I need to pass in a URL which will contain a call to a View. This view will be used to generate an image or HTML document using the System.Windows.Forms.WebBrowser.

.NET 3.5; C#; MVC 1;

I could do something like this, but its dirty ... well it leaves me with that dirty feeling.

```<code>using(Html.BeginForm("Action", "MyWorkflowController",
new {
   MyId = "bla",
   URLToGenerateImage = Url.Action("GenerateImage", "MyWorkflowController")
}))
</code>```

答:
How about ContentResult - Represents a text result, so you could have

/Controller/GetUrl/id

```<code>Public ActionResult GetUrl(int id)
{
   // builds url to view (Controller/Image/id || Controller/Html/id)
   var url = BuildImageUrl(id);
   return ContentResult(url);
}
</code>```

in view you could have:

```<code><a href="<% Html.RenderAction("GetUrl", "Controller", new { id = idSource } ); %>">GenerateImage</a>
</code>```

Title: Retrieve URL for Action from Controller

Body:
I am calling a Controller Action from a view, within that controller I need to invoke another Action which I will invoke to save the view to a network location as either HTML or Image.

How do I retrieve the URL to an Action from within a Controller. Please note I need the actual URL, this means RedirectionToAction or View() wont work.

Why? I need to pass in a URL which will contain a call to a View. This view will be used to generate an image or HTML document using the System.Windows.Forms.WebBrowser.

.NET 3.5; C#; MVC 1;

I could do something like this, but its dirty ... well it leaves me with that dirty feeling.

using(Html.BeginForm("Action", "MyWorkflowController",
new {
   MyId = "bla",
   URLToGenerateImage = Url.Action("GenerateImage", "MyWorkflowController")
}))

Body:
How about ContentResult - Represents a text result, so you could have

/Controller/GetUrl/id

Public ActionResult GetUrl(int id)
{
   // builds url to view (Controller/Image/id || Controller/Html/id)
   var url = BuildImageUrl(id);
   return ContentResult(url);
}

in view you could have:

<a href="<% Html.RenderAction("GetUrl", "Controller", new { id = idSource } ); %>">GenerateImage</a>


问:
How to save data from text box to mysql database using asp.net (vb.net)
I want to save data from textbox1 and textbox2 to database, but i get this error and the error do not mention which line that the error occur. This is the error:

Object reference not set to an instance of an object.

```<code> Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" And TextBox2.Text = "" Then Exit Sub

    Try
        conn = New MySqlConnection
        conn.ConnectionString = connstr
        conn.Open()

        strsql = "INSERT INTO supplier "
        strsql += "(SupplierName,SupplierID) VALUES "
        strsql += "(@Name, @ID);"

        cmd.Connection = conn
        cmd.CommandText = strsql
        cmd.Parameters.AddWithValue("@Name", TextBox1.Text)
        cmd.Parameters.AddWithValue("@ID", TextBox2.Text)
        cmd.ExecuteNonQuery()
        cmd.Parameters.Clear()
        cmd.Dispose()

        conn.Close()
    Catch ex As Exception
        Response.Write(ex.Message)
    End Try
End Sub
</code>```

答: To get the error line simply remove (temporarily) the try / catch block</p>

Body:
I want to save data from textbox1 and textbox2 to database, but i get this error and the error do not mention which line that the error occur. This is the error:

Object reference not set to an instance of an object.

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" And TextBox2.Text = "" Then Exit Sub

    Try
        conn = New MySqlConnection
        conn.ConnectionString = connstr
        conn.Open()

        strsql = "INSERT INTO supplier "
        strsql += "(SupplierName,SupplierID) VALUES "
        strsql += "(@Name, @ID);"

        cmd.Connection = conn
        cmd.CommandText = strsql
        cmd.Parameters.AddWithValue("@Name", TextBox1.Text)
        cmd.Parameters.AddWithValue("@ID", TextBox2.Text)
        cmd.ExecuteNonQuery()
        cmd.Parameters.Clear()
        cmd.Dispose()

        conn.Close()
    Catch ex As Exception
        Response.Write(ex.Message)
    End Try
End Sub