问:
Java JDBC thows com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException for \'Test1\' value
I have below table:
dummy_tbl

```<code>  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|
</code>```

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

```<code> select * from dummy_tbl where name like \'Test1\';
</code>```

But same query when I tried from code using JDBC statement it's throwing below error:

```<code> com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1
</code>```

Code snipped from code:

```<code>  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);
</code>```

答:
As mentioned the statement should have been

```<code>select * from dummy_tbl where name like 'Test%'
</code>```

but it was "sanitized" adding backslashes.

In that case use a PreparedStatement - which anyway is the correct manner (escaping itself, against SQL injection):

```<code>String sql = "select * from dummy_tbl where name like ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
    stmt.setString(1, "Test%");
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            ...
        }
    }
}
</code>```

Body:
I have below table:
dummy_tbl

  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

 select * from dummy_tbl where name like \'Test1\';

But same query when I tried from code using JDBC statement it's throwing below error:

 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Test1\'' at line 1

Code snipped from code:

  String sql = "SELECT * from dummy_tbl where name like \'Test1\'";
  Statement stmt= conn.createStatement();
  ResultSet rs = stmt.executeQuery(sql);

Body:
As mentioned the statement should have been

select * from dummy_tbl where name like 'Test%'

but it was "sanitized" adding backslashes.

In that case use a PreparedStatement - which anyway is the correct manner (escaping itself, against SQL injection):

String sql = "select * from dummy_tbl where name like ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
    stmt.setString(1, "Test%");
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            ...
        }
    }
}


来源: stackexchange

问:
Do Statement that isn't working correctly
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!</p>

```<code>    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}
</code>```

答:
The while statement in your code is  while (swapflag = true);
Thus your swap flag gets set to true. The inner do-while loop never terminates.
This statement should be either:

```<code>while(swapflag==true)
</code>```

or while (swapflag)

ContentLicense: CC BY-SA 3.0

Body:
I can't figure out why the second do statement is not repeating.  It appears to be exiting regardless of the while statement being true or false.  I feel like it's something small I'm missing, but any help is greatly appreciated.  Thanks!

    public void ShellSort()
{
    int gap = size/2;
    do
    {
        boolean swapflag = true;
        do
        {
            swapflag = false;
            for(int s = 0; s < (size-gap); s++)
                if (arr[s] > arr[s + gap])
                    {
                        int temp = arr[s];
                        arr[s] = arr[s + gap];
                        arr[s + gap] = temp;
                        swapflag = true;
                    }
        } while (swapflag = true);
        gap = gap/2;
    } while (gap >= 0);
}

Body:
The while statement in your code is  while (swapflag = true);
Thus your swap flag gets set to true. The inner do-while loop never terminates.
This statement should be either:

while(swapflag==true)

or while (swapflag)


问:
Why need the class Preference<T> be wrapped with object?
The following Code A is from https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/extensions/DelegatesExtensions.kt

I can use private var zipCode: Long by DelegatesExt.preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code A.

I don't understand why the author wrap class Preference(...) with object DelegatesExt

I think Code B is more simple, I can use private val zipCode: Long by Preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code B

Why need the class Preference be wrapped with object ?

Code A

```<code>object DelegatesExt {
    fun <T> notNullSingleValue() = NotNullSingleValueVar<T>()
    fun <T> preference(context: Context, name: String,
            default: T) = Preference(context, name, default)
}

class NotNullSingleValueVar<T> {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
            value ?: throw IllegalStateException("${property.name} not initialized")

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value
        else throw IllegalStateException("${property.name} already initialized")
    }
}

class Preference<T>(private val context: Context, private val name: String,
        private val default: T) {

    private val prefs: SharedPreferences by lazy {
        context.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(name: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }

        res as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(name: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can't be saved into Preferences")
        }.apply()
    }
}
</code>```

Code B

```<code>class NotNullSingleValueVar<T> {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
            value ?: throw IllegalStateException("${property.name} not initialized")

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value
        else throw IllegalStateException("${property.name} already initialized")
    }
}

class Preference<T>(private val context: Context, private val name: String,
        private val default: T) {

    private val prefs: SharedPreferences by lazy {
        context.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(name: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }

        res as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(name: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can't be saved into Preferences")
        }.apply()
    }
}
</code>```

答:
I can use private var zipCode: Long by DelegatesExt.preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code A.

I think Code B is more simple, I can use private val zipCode: Long by Preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code B

In the first case you can also import DelegatesExt.* or DelegatesExt.preference instead of DelegatesExt and write by preference.

Why need the class Preference be wrapped with object ?

It doesn't need to be (and I wouldn't do it), that's just the author's preference.

Body:
The following Code A is from https://github.com/antoniolg/Kotlin-for-Android-Developers/blob/master/app/src/main/java/com/antonioleiva/weatherapp/extensions/DelegatesExtensions.kt

I can use private var zipCode: Long by DelegatesExt.preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code A.

I don't understand why the author wrap class Preference(...) with object DelegatesExt

I think Code B is more simple, I can use private val zipCode: Long by Preference(this, ZIP_CODE, DEFAULT_ZIP) to invoke when I use Code B

Why need the class Preference be wrapped with object ?

Code A

object DelegatesExt {
    fun <T> notNullSingleValue() = NotNullSingleValueVar<T>()
    fun <T> preference(context: Context, name: String,
            default: T) = Preference(context, name, default)
}

class NotNullSingleValueVar<T> {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
            value ?: throw IllegalStateException("${property.name} not initialized")

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value
        else throw IllegalStateException("${property.name} already initialized")
    }
}

class Preference<T>(private val context: Context, private val name: String,
        private val default: T) {

    private val prefs: SharedPreferences by lazy {
        context.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(name: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }

        res as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(name: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can't be saved into Preferences")
        }.apply()
    }
}

Code B

class NotNullSingleValueVar<T> {

    private var value: T? = null

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
            value ?: throw IllegalStateException("${property.name} not initialized")

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = if (this.value == null) value
        else throw IllegalStateException("${property.name} already initialized")
    }
}

class Preference<T>(private val context: Context, private val name: String,
        private val default: T) {

    private val prefs: SharedPreferences by lazy {
        context.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(name: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }

        res as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(name: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can't be saved into Preferences")
        }.apply()
    }
}


问:
Disabled all other radio button if name and value not same
I am making one form where I need to disable all other radio button and submit button if Radio button name or Id or class name not same to each other.

ID or name or class, I am generating through dynamic way. (name=radio_1, id= radio_1).

or

if I click on Group-1 radio button then other group should be disable.

Please have a look.

```<code><label class="radio-inline">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">
</label>

<label class="radio-inline">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">
</label>
</code>```

HTML Output:

```<code><label class="radio-inline">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">
</label>

<label class="radio-inline">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">
</label>
</code>```

My Query:

```<code>$(document).ready(function() {
$("input:radio").click(function() {
    var val = $(this).val();
    var name = $(this).attr('name');
    if(val != name){
      $(this).attr("disabled", true);
    }
    else{
    $(this).attr("disabled", false);
    }
});

});
</code>```

Please guide me how can I do this.

答:
You can use the Attribute selector with != to get all other input not having the same name inside label with specific class as in below code snippet. I have selected all inputs inside class='radio-inline so that it will not effect other input tags on the page.

below is the code snippet you can use. Hope this helps you.

$(document).ready(function() {
  $("input:radio").click(function() {
    $(".radio-inline input[name!='" + $(this).val() + "']").prop('disabled', true);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="radio-inline">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">
</label>

<label class="radio-inline">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">
</label>

<label class="radio-inline">
<input type="radio" name="start_3" class="group_3" value="start_3">
<input type="radio" name="start_3" class="group_3" value="start_3">
<input type="submit" name="start_3" value="Save" class="btn sm btn-primary group_3">
</label></code>```

Body:
I am making one form where I need to disable all other radio button and submit button if Radio button name or Id or class name not same to each other.

ID or name or class, I am generating through dynamic way. (name=radio_1, id= radio_1).

or

if I click on Group-1 radio button then other group should be disable.

Please have a look.

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

HTML Output:

<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">

<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">

My Query:

$(document).ready(function() {
$("input:radio").click(function() {
    var val = $(this).val();
    var name = $(this).attr('name');
    if(val != name){
      $(this).attr("disabled", true);
    }
    else{
    $(this).attr("disabled", false);
    }
});

});

Please guide me how can I do this.

Body:
You can use the Attribute selector with != to get all other input not having the same name inside label with specific class as in below code snippet. I have selected all inputs inside class='radio-inline so that it will not effect other input tags on the page.

below is the code snippet you can use. Hope this helps you.

$(document).ready(function() {
  $("input:radio").click(function() {
    $(".radio-inline input[name!='" + $(this).val() + "']").prop('disabled', true);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="radio-inline">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">
</label>

<label class="radio-inline">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">
</label>

<label class="radio-inline">
<input type="radio" name="start_3" class="group_3" value="start_3">
<input type="radio" name="start_3" class="group_3" value="start_3">
<input type="submit" name="start_3" value="Save" class="btn sm btn-primary group_3">
</label>


问:
Connect to a MySQL server over SSH in PHP
I'd like to establish an ssh tunnel over ssh to my mysql server.

Ideally I'd return a mysqli db pointer just like I was connecting directly.

I'm on a shared host that doesn't have the SSH2 libraries but I might be able to get them installed locally using PECL.

If there's a way that uses native commands that would be great.

I was thinking something like this, but without those libraries it won't work.

```<code>$connection = ssh2_connect('SERVER IP', 22);

ssh2_auth_password($connection, 'username', 'password');

$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);

$db = new mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
                         'dbname', 3307, $tunnel)
    or die ('Fail: ' . mysql_error());
</code>```

Anyone have any ideas?  I'm running a shared CentOS linux host at liquidweb.

Any thoughts on making the tunnel persistent?  Is it possible to establish it with another script and just take advantage of it in PHP?

Thanks.

答:
I tried it by doing SSH both by root credentials and and public private key pair. It allows me to conect through command line but not through PHP code.

I also tried by creating a tunnel (by using SSH2 functions), and running shell commands from PHP code (system, exec, etc.); nothing worked.

Finally I tried SSH2 function to execute shell command and it finally worked :)

Here is my code, if it helps you:

```<code>$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
    echo "Authentication Successful!\n";
} else {
    die('Authentication Failed...');
}

$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";"  | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
    flush();
    echo $line."\n";
}
</code>```

Try this if want to use PHP functions specifically.

OwnerDisplayName: Eric Goodwin

Body:
I'd like to establish an ssh tunnel over ssh to my mysql server.

Ideally I'd return a mysqli db pointer just like I was connecting directly.

I'm on a shared host that doesn't have the SSH2 libraries but I might be able to get them installed locally using PECL.

If there's a way that uses native commands that would be great.

I was thinking something like this, but without those libraries it won't work.

$connection = ssh2_connect('SERVER IP', 22);

ssh2_auth_password($connection, 'username', 'password');

$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);

$db = new mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
                         'dbname', 3307, $tunnel)
    or die ('Fail: ' . mysql_error());

Anyone have any ideas?  I'm running a shared CentOS linux host at liquidweb.

Any thoughts on making the tunnel persistent?  Is it possible to establish it with another script and just take advantage of it in PHP?

Thanks.

Body:
I tried it by doing SSH both by root credentials and and public private key pair. It allows me to conect through command line but not through PHP code.

I also tried by creating a tunnel (by using SSH2 functions), and running shell commands from PHP code (system, exec, etc.); nothing worked.

Finally I tried SSH2 function to execute shell command and it finally worked :)

Here is my code, if it helps you:

$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
    echo "Authentication Successful!\n";
} else {
    die('Authentication Failed...');
}

$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";"  | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
    flush();
    echo $line."\n";
}

Try this if want to use PHP functions specifically.

OwnerDisplayName: spooja


问:
Version Control on Mac
I am a student and my uses of source control are mostly academic (HW assignments, 2-4 person projects and so on).

Until now I have been using Subversion hosted in google code, and used the eclipse plugin to manage my repository.

Recently I heard of git, which to my understanding needs to be synced between each two collaborates each time, and something called Mercurial.

So basically my question has 3 parts:

Which source control system is recommended and what benefits does git offer? Is it worth learning it?

Which is a good free host that will support this system?

What is the best tool to manage my repository? Is using the command line better in any way than the Eclipse plugin? or is there some other software that is recommended?

If my question is to vague please comment and I'll be glad to revise it.

答:
Git and Mercurial are distrubuted SCMs, meaning there is not central server (in practice people agree on one, but the infrastructure doesn't require it).

It is the way SCMs are going, so yes, worth learning.

For git hosting look at github, for Mercurial, look at Kiln (not free), though there are many free ones as well.

As for asking if command line is better than a plugin/GUI? It depends on how you like to work.

ContentLicense: CC BY-SA 2.5

Title: Version Control on Mac


问:
File Upload with some information
I am uploading an images for that I created template to display it before upload. Here is code for it:

```<code>   <script id="fileTemplate" type="text/x-kendo-template">
    <div class='file-wrapper'>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-description-heading'>Image Heading: <input type="text" id="headingTextbox"/></h4>
    </div>
</script>
</code>```

As you can see I am showing image name in #=name# parameter and I want some information about image therefore I am using Textbox (id: headingTextbox). Now here is my code to upload the images:

```<code>            $("#files").kendoUpload({
            multiple: true,
            async: {
                saveUrl: "SaveSectionImages",
            },
            upload: function (e) {
                e.data = {
                    hdId: $('#hdId').val(),
                    fileDesc: $('#headingTextbox').val()
                };

            },
            complete: onComplete,
            template: kendo.template($('#fileTemplate').html())
        });
</code>```

Now my problem is if I select multiple images and I get information about only one image then header information is automatically get attached to all images (Because I am using same textbox id for all images). I want pathway that how can I achieve image upload with some information with it?
Any help would be appreciable. Thank You

答:
Try this :

$("#files").kendoUpload({
      multiple: true,
      async: {
          saveUrl: "SaveSectionImages",
          autoUpload : false
      },
      complete: function(e) {
         var fileList = $("#files").data("kendoUpload").options.files;
         $.each(fileList, function(idx) {
           this.fileDesc = $('.headingTextbox')[idx].value;
         });
         console.log($("#files").data("kendoUpload").options.files);
      },
      template: kendo.template($('#fileTemplate').html())
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="fileTemplate" type="text/x-kendo-template">
    <div class='file-wrapper'>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-description-heading'>Image Heading: <input type="text" class="headingTextbox"/></h4>
    </div>
</script></code>```

Title: File Upload with some information

Body:
I am uploading an images for that I created template to display it before upload. Here is code for it:

As you can see I am showing image name in #=name# parameter and I want some information about image therefore I am using Textbox (id: headingTextbox). Now here is my code to upload the images:

            $("#files").kendoUpload({
            multiple: true,
            async: {
                saveUrl: "SaveSectionImages",
            },
            upload: function (e) {
                e.data = {
                    hdId: $('#hdId').val(),
                    fileDesc: $('#headingTextbox').val()
                };

            },
            complete: onComplete,
            template: kendo.template($('#fileTemplate').html())
        });

Now my problem is if I select multiple images and I get information about only one image then header information is automatically get attached to all images (Because I am using same textbox id for all images). I want pathway that how can I achieve image upload with some information with it?
Any help would be appreciable. Thank You

Body:
Try this :

$("#files").kendoUpload({
      multiple: true,
      async: {
          saveUrl: "SaveSectionImages",
          autoUpload : false
      },
      complete: function(e) {
         var fileList = $("#files").data("kendoUpload").options.files;
         $.each(fileList, function(idx) {
           this.fileDesc = $('.headingTextbox')[idx].value;
         });
         console.log($("#files").data("kendoUpload").options.files);
      },
      template: kendo.template($('#fileTemplate').html())
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="fileTemplate" type="text/x-kendo-template">
    <div class='file-wrapper'>
        <h4 class='file-heading file-name-heading'>Name: #=name#</h4>
        <h4 class='file-heading file-description-heading'>Image Heading: <input type="text" class="headingTextbox"/></h4>
    </div>
</script>


问:
Cannot add/remove sealed array elements
I am combining a graphql api call with an array modification.

```<code>async deletePhoto(photoId, driveId, index) {

  this.property.photos.splice(index, 1);

  await api.photos.remove(this.property.id, photoId, driveId);
},
</code>```

api call:

```<code>  const remove = async (propertyId, photoId, driveId) => {

  const mutation = gql`
    mutation photoDelete($propertyId: Int!, $photoId: String!, $driveId: String!) {
      deletePropertyPhoto(propertyId: $propertyId, photoId: $photoId, driveId: $driveId)
    }
  `;

  const result = await apolloClient.mutate({
    mutation,
    variables: {
      propertyId,
      photoId,
      driveId,
    },
  });

  console.log(result);
  return result;
};
</code>```

Problem:

```<code>Uncaught (in promise) TypeError: Cannot add/remove sealed array elements
    at Array.splice (<anonymous>)
    at VueComponent._callee3$ (http://localhost:3030/_nuxt/3.js:284:38)
    at tryCatch (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26549:40)
    at Generator.invoke [as _invoke] (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26787:22)
    at Generator.prototype.(anonymous function) [as next] (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26601:21)
    at step (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8714:30)
    at http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8732:14
    at Promise (<anonymous>)
    at F (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8036:28)
    at VueComponent.<anonymous> (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8711:12)
</code>```

What makes this error so weird? When I remove the api call, it works fine. This doesn't make any sense to me, because the api call has nothing to do with the array modification.

EDIT:
This is insane, sometimes the error appears, and sometimes the splicing works just fine. This is the most random bug I've ever encountered.

EDIT2:
When fetching the properties (and photos) I've already made an object copy of the graphql result:

```<code>async asyncData({ params }) {
    const fetchedProperty = await api.properties.findOne(params.id);
    return {
      oldProperty: fetchedProperty,
      property: Object.assign({}, fetchedProperty),
    };
  },
</code>```

答:
Another way to delete a sealed Object is using slice is

```<code>this.property.photos = this.property.photos.slice(0, idx).concat(this.property.photos.slice(idx + 1));
</code>```

In your function as:

```<code>async deletePhoto(photoId, driveId, index) {
    this.property.photos = this.property.photos.slice(0, idx).concat(this.property.photos.slice(idx + 1));
    await api.photos.remove(this.property.id, photoId, driveId);
},
</code>```

Title: Cannot add/remove sealed array elements

Body:
I am combining a graphql api call with an array modification.

async deletePhoto(photoId, driveId, index) {

  this.property.photos.splice(index, 1);

  await api.photos.remove(this.property.id, photoId, driveId);
},

api call:

  const remove = async (propertyId, photoId, driveId) => {

  const mutation = gql`
    mutation photoDelete($propertyId: Int!, $photoId: String!, $driveId: String!) {
      deletePropertyPhoto(propertyId: $propertyId, photoId: $photoId, driveId: $driveId)
    }
  `;

  const result = await apolloClient.mutate({
    mutation,
    variables: {
      propertyId,
      photoId,
      driveId,
    },
  });

  console.log(result);
  return result;
};

Problem:

Uncaught (in promise) TypeError: Cannot add/remove sealed array elements
    at Array.splice (<anonymous>)
    at VueComponent._callee3$ (http://localhost:3030/_nuxt/3.js:284:38)
    at tryCatch (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26549:40)
    at Generator.invoke [as _invoke] (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26787:22)
    at Generator.prototype.(anonymous function) [as next] (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:26601:21)
    at step (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8714:30)
    at http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8732:14
    at Promise (<anonymous>)
    at F (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8036:28)
    at VueComponent.<anonymous> (http://localhost:3030/_nuxt/vendor.bundle.5559a1f55cb4b1323e8d.js:8711:12)

What makes this error so weird? When I remove the api call, it works fine. This doesn't make any sense to me, because the api call has nothing to do with the array modification.

EDIT:
This is insane, sometimes the error appears, and sometimes the splicing works just fine. This is the most random bug I've ever encountered.

EDIT2:
When fetching the properties (and photos) I've already made an object copy of the graphql result:

async asyncData({ params }) {
    const fetchedProperty = await api.properties.findOne(params.id);
    return {
      oldProperty: fetchedProperty,
      property: Object.assign({}, fetchedProperty),
    };
  },

Body:
Another way to delete a sealed Object is using slice is

this.property.photos = this.property.photos.slice(0, idx).concat(this.property.photos.slice(idx + 1));

In your function as:

async deletePhoto(photoId, driveId, index) {
    this.property.photos = this.property.photos.slice(0, idx).concat(this.property.photos.slice(idx + 1));
    await api.photos.remove(this.property.id, photoId, driveId);
},


问:
How to check if directory exists outside of workspace from a jenkins pipeline script
Given I have a directory path, how do I check if this directory exists outside of the workspace from a jenkins pipeline script.</p>

答:
Tried a few things and turned out the answer was already in front of me.
fileExists can check for directories as well. Here's how I got around the problem.
In this example, I am creating a directory on Windows if it doesn't exist.

Step 1: dir into the directory

```<code>dir("C:/_Tests")
</code>```

Step 2: Now, use fileExists without any file name.

```<code>if(!fileExists("/"))
{
  bat "mkdir \"C:/_Tests\""
}
</code>```

Body:
Tried a few things and turned out the answer was already in front of me.
fileExists can check for directories as well. Here's how I got around the problem.
In this example, I am creating a directory on Windows if it doesn't exist.

Step 1: dir into the directory

dir("C:/_Tests")

Step 2: Now, use fileExists without any file name.

if(!fileExists("/"))
{
  bat "mkdir \"C:/_Tests\""
}


问:
selenium invalid element state: Element is not currently interactable and may not be manipulated
I have this issue with selenium; I cannot find i textinput : it always raises this exeception:

```<code>Element is not currently interactable and may not be manipulated
</code>```

in this line:

```<code>Driver.FindElement(By.Id("ctl00")).Clear();
</code>```

I try to put waiting like this:

```<code>Waiting.Until(driver =>(By.Id("ctl00")));
</code>```

and

```<code>Waiting.Until(ExpectedConditions.ElementExists(By.Id("ctl00")));
</code>```

but no luck.

答:
If the exception gets thrown on Clear(),
the element is most likely present on the page and the input in a readonly state.

Body:
I have this issue with selenium; I cannot find i textinput : it always raises this exeception:

Element is not currently interactable and may not be manipulated

in this line:

Driver.FindElement(By.Id("ctl00")).Clear();

I try to put waiting like this:

Waiting.Until(driver =>(By.Id("ctl00")));

and

Waiting.Until(ExpectedConditions.ElementExists(By.Id("ctl00")));

but no luck.


问:
Unable to perform POST request with retrofit android
While I am trying to perform the post request with retrofit, it is throwing timeout exception. While using postman the API Url is working perfectly fine. Is there any error in the code. This is my code:

```<code>ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
Call<ResponseBody> callUser = apiInterface.facebookLogin(jsonObject);
dialog.show();
callUser.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.code() == 200)
        Log.e("Token Object", response.toString());
        dialog.dismiss();
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Toast.makeText(getContext(), "Sorry! Somme Error Occured" + t.toString(), Toast.LENGTH_LONG).show();
        dialog.dismiss();
    }
});
</code>```

This is the interface:

```<code>//facebook login
@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body JSONObject jsonObject);
</code>```

This is the  Retrofit Client

```<code>public class ApiClient {
    public static final String BASE_URL = "http://192.168.100.15:8000/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100,TimeUnit.SECONDS).build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

This is the successful postman request

答:
Pass the request parameters as RequestBody as follows:

```<code>@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body RequestBody request);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
Call<ResponseBody> callUser = apiInterface.facebookLogin(requestBody);
</code>```

Body:
While I am trying to perform the post request with retrofit, it is throwing timeout exception. While using postman the API Url is working perfectly fine. Is there any error in the code. This is my code:

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
Call<ResponseBody> callUser = apiInterface.facebookLogin(jsonObject);
dialog.show();
callUser.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.code() == 200)
        Log.e("Token Object", response.toString());
        dialog.dismiss();
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Toast.makeText(getContext(), "Sorry! Somme Error Occured" + t.toString(), Toast.LENGTH_LONG).show();
        dialog.dismiss();
    }
});

This is the interface:

//facebook login
@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body JSONObject jsonObject);

This is the  Retrofit Client

public class ApiClient {
    public static final String BASE_URL = "http://192.168.100.15:8000/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100,TimeUnit.SECONDS).build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

This is the successful postman request

Body:
Pass the request parameters as RequestBody as follows:

@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body RequestBody request);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
Call<ResponseBody> callUser = apiInterface.facebookLogin(requestBody);


问:
How do you display a 3D graph of a image? On MATLab
```<code>clear all
clc
img = imread('TestImage.jpg');
frame_size = size(img);
allpixels = reshape(img, frame_size(1)*frame_size(2), frame_size(3))
[row,col] = size(allpixels);
totalPixels = 0;
count = 0;
white = 0;
black = 0;
red = 0;
green = 0;
blue = 0;
grey = 0;
purplepink = 0;
yelloworange = 0;
for row = 1:row
    count = 0;
    for col = 1:col
        if count == 0
            R = allpixels(row,col);
            count = count + 1;
        elseif count == 1
            G = allpixels(row,col);
            count = count + 1;
        elseif count == 2
            B = allpixels(row,col);
            count = count + 1;
        end
        totalPixels = totalPixels + 1;
    end
        if R > 230 && G > 230 && B > 230
            white = white + 1;
        elseif R < 70 && G < 70 && B < 70
            black = black + 1;
        elseif abs(R - G) <= 5 && abs(G - B) <= 5 && abs(R - B) <= 5
            grey = grey + 1;
        elseif R > B && R > G
            red = red + 1;
        elseif G > B && G >= R
            green = green + 1;
        elseif B >= R && B >= G
            blue = blue + 1;
        end
end

totalPixels = totalPixels/3;
totalPixels
white
black
grey
red
green
blue
white + black + grey + red + green + blue

PercentOfWhite = (white/totalPixels)* 100
A=PercentOfWhite;
PercentOfBlack = (black/totalPixels) * 100
B=PercentOfBlack;
PercentOfGrey = (grey/totalPixels)* 100
C=PercentOfGrey;
PercentOfRed = (red/totalPixels)* 100
D=PercentOfRed;
PercentOfGreen = (green/totalPixels) * 100
E=PercentOfGreen;
PercentOfBlue = (blue/totalPixels) * 100
F=PercentOfBlue;

[x,y]=meshgrid(1:15,1:15);
tri = delaunay(x,y);
z= peaks(15);
trisurf(tri,x,y,z)
</code>```

The code above displays a 3D graph. However, it does not display any useful data. For example, I inserted an image called TestImage.jpg. It was 80% red, the 3D graph showed up. I then tried another image that was 80% blue, the graph showed up and it looked just like the image I previously tested! I've come to a conclusion that my code isn't reading any image, it is just randomly displaying a 3D with no real data results. Any suggestion on how I can fix my code to display a 3D graph that ACTUALLY reads my image and displays useful data

答:
I tested your code and it looks like your last 4 lines of your script are not using any variables from above. That means whatever happens before the last 4 code lines doesn't matter for the 3D graph because it is separated.

If you replace your last 4 lines with the following code a diagram will appear and show bars representing the color percentages:

```<code>names = categorical({'PercentOfWhite' 'PercentOfBlack' 'PercentOfGrey' 'PercentOfRed' 'PercentOfGreen' 'PercentOfBlue'});
bar(names,[PercentOfWhite PercentOfBlack PercentOfGrey PercentOfRed PercentOfGreen PercentOfBlue]);
</code>```

Hope I could help.

Body:
clear all
clc
img = imread('TestImage.jpg');
frame_size = size(img);
allpixels = reshape(img, frame_size(1)*frame_size(2), frame_size(3))
[row,col] = size(allpixels);
totalPixels = 0;
count = 0;
white = 0;
black = 0;
red = 0;
green = 0;
blue = 0;
grey = 0;
purplepink = 0;
yelloworange = 0;
for row = 1:row
    count = 0;
    for col = 1:col
        if count == 0
            R = allpixels(row,col);
            count = count + 1;
        elseif count == 1
            G = allpixels(row,col);
            count = count + 1;
        elseif count == 2
            B = allpixels(row,col);
            count = count + 1;
        end
        totalPixels = totalPixels + 1;
    end
        if R > 230 && G > 230 && B > 230
            white = white + 1;
        elseif R < 70 && G < 70 && B < 70
            black = black + 1;
        elseif abs(R - G) <= 5 && abs(G - B) <= 5 && abs(R - B) <= 5
            grey = grey + 1;
        elseif R > B && R > G
            red = red + 1;
        elseif G > B && G >= R
            green = green + 1;
        elseif B >= R && B >= G
            blue = blue + 1;
        end
end

totalPixels = totalPixels/3;
totalPixels
white
black
grey
red
green
blue
white + black + grey + red + green + blue

PercentOfWhite = (white/totalPixels)* 100
A=PercentOfWhite;
PercentOfBlack = (black/totalPixels) * 100
B=PercentOfBlack;
PercentOfGrey = (grey/totalPixels)* 100
C=PercentOfGrey;
PercentOfRed = (red/totalPixels)* 100
D=PercentOfRed;
PercentOfGreen = (green/totalPixels) * 100
E=PercentOfGreen;
PercentOfBlue = (blue/totalPixels) * 100
F=PercentOfBlue;

[x,y]=meshgrid(1:15,1:15);
tri = delaunay(x,y);
z= peaks(15);
trisurf(tri,x,y,z)

The code above displays a 3D graph. However, it does not display any useful data. For example, I inserted an image called TestImage.jpg. It was 80% red, the 3D graph showed up. I then tried another image that was 80% blue, the graph showed up and it looked just like the image I previously tested! I've come to a conclusion that my code isn't reading any image, it is just randomly displaying a 3D with no real data results. Any suggestion on how I can fix my code to display a 3D graph that ACTUALLY reads my image and displays useful data

Body:
I tested your code and it looks like your last 4 lines of your script are not using any variables from above. That means whatever happens before the last 4 code lines doesn't matter for the 3D graph because it is separated.

If you replace your last 4 lines with the following code a diagram will appear and show bars representing the color percentages:

names = categorical({'PercentOfWhite' 'PercentOfBlack' 'PercentOfGrey' 'PercentOfRed' 'PercentOfGreen' 'PercentOfBlue'});
bar(names,[PercentOfWhite PercentOfBlack PercentOfGrey PercentOfRed PercentOfGreen PercentOfBlue]);

Hope I could help.


问:
Subprocedure call in VHDL
I have two nested procedures, where the "main" procedure
makes use of "subproc" to accumulates a result in variables
t0 and t1, which is then returned at the end. This should all
be computed in one clock cycle, and the circuit more or less
just consists of simple logic gates (xor, or, and). When I try
to describe the circuit as below I get the following error:

```<code>Acutal (variable t0) for formal "a" is not a signal
</code>```

That makes sense as the subprocure requires signals as input,
but I wanna pass it a variable during the main procedure. Is
there a simple way to circumvent this problem with casting for
example?

Thanks

```<code>procedure subproc
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal c : in  std_logic_vector(31 downto 0);
  signal d : in  std_logic_vector(31 downto 0);
  signal e : out std_logic_vector(31 downto 0);
  signal f : out std_logic_vector(31 downto 0)
)
is
  variable x : std_logic_vector(31 downto 0);
  variable y : std_logic_vector(31 downto 0);
begin

  x := (others => '0');
  y := (others => '0');

  for i in 0 to 31 loop
      x(i) := (a(i) xor b(i)) and (c(i) xor d(i));
      y(i) := (a(i) xor b(i)) or ((d(i) xor c(i)) xor b(i));
  end loop;

  e <= x(31 downto 0);
  f <= y(31 downto 0);

end;

procedure main
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal r : out std_logic_vector(31 downto 0)
)
is
  variable res : std_logic_vector(31 downto 0);
  variable t0, t1 : std_logic_vector(31 downto 0);
  constant c : std_logic_vector(31 downto 0) := X"fedcba90";
  constant d : std_logic_vector(31 downto 0) := X"7654321f";
begin

  t0 := (others => '0');
  t1 := (others => '0');

  for i in 0 to 31 loop
    if ( (c(i) = '0') && (d(i) = '1') ) then
       subproc( t0, t1,
                a, b, t0, t1 );
    end if;
  end loop;

  r <= t0;
end;
</code>```

答: Why don't you just define the subproc parameters as variables instead of signals?</p>

Title: Subprocedure call in VHDL

Body:
I have two nested procedures, where the "main" procedure
makes use of "subproc" to accumulates a result in variables
t0 and t1, which is then returned at the end. This should all
be computed in one clock cycle, and the circuit more or less
just consists of simple logic gates (xor, or, and). When I try
to describe the circuit as below I get the following error:

Acutal (variable t0) for formal "a" is not a signal

That makes sense as the subprocure requires signals as input,
but I wanna pass it a variable during the main procedure. Is
there a simple way to circumvent this problem with casting for
example?

Thanks

procedure subproc
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal c : in  std_logic_vector(31 downto 0);
  signal d : in  std_logic_vector(31 downto 0);
  signal e : out std_logic_vector(31 downto 0);
  signal f : out std_logic_vector(31 downto 0)
)
is
  variable x : std_logic_vector(31 downto 0);
  variable y : std_logic_vector(31 downto 0);
begin

  x := (others => '0');
  y := (others => '0');

  for i in 0 to 31 loop
      x(i) := (a(i) xor b(i)) and (c(i) xor d(i));
      y(i) := (a(i) xor b(i)) or ((d(i) xor c(i)) xor b(i));
  end loop;

  e <= x(31 downto 0);
  f <= y(31 downto 0);

end;

procedure main
(
  signal a : in  std_logic_vector(31 downto 0);
  signal b : in  std_logic_vector(31 downto 0);
  signal r : out std_logic_vector(31 downto 0)
)
is
  variable res : std_logic_vector(31 downto 0);
  variable t0, t1 : std_logic_vector(31 downto 0);
  constant c : std_logic_vector(31 downto 0) := X"fedcba90";
  constant d : std_logic_vector(31 downto 0) := X"7654321f";
begin

  t0 := (others => '0');
  t1 := (others => '0');

  for i in 0 to 31 loop
    if ( (c(i) = '0') && (d(i) = '1') ) then
       subproc( t0, t1,
                a, b, t0, t1 );
    end if;
  end loop;

  r <= t0;
end;


问:
Xamarin.android - Pass data to my fragment
i have a List with my services, and on item selected i'm passing service type to my activity ServiceDetail like this:

ServiceActivity

```<code>void item_selected(object sender, AdapterView.ItemClickEventArgs e) {
    MenuContentItem selectedItem = (MenuContentItem)item[e.Position];
    if(selectedItem.Title == "COLLO") {
        var activity_go = new Intent(this, typeof(ServiceDetailActivity));
        activity_go.PutExtra("service_type", "Collo");
        StartActivity(activity_go);
    }
    if (selectedItem.Title == "SPALLA") {
        var activity_go = new Intent(this, typeof(ServiceDetailActivity));
        activity_go.PutExtra("service_type", "Spalla");
        StartActivity(activity_go);
    }
}
</code>```

ServiceDetailActivity

```<code>protected override void OnCreate(Bundle savedInstanceState) {
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.ServiceDetail);
    //enable navigation mode to support tab layout
    this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
    AddTab("Introduzione", Resource.Mipmap.Icon, new IntroduzioneFragment());
    //intent data
    string text = Intent.GetStringExtra("service_type") ?? "Data not available";
    IntroduzioneFragment fragment = new IntroduzioneFragment();
    // set data to pass to my fragment
    Bundle bundle = new Bundle();
    bundle.PutString("text", text);
    fragment.Arguments = bundle;
}
// MY FRAGMENT - I would like "CUSTOM" my fragment "IntroduzioneFragment" like this:
class IntroduzioneFragment : Fragment {
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Menu.Tab, container, false);
        var sampleTextView = view.FindViewById<TextView>(Resource.Id.textView);
        var imageView = view.FindViewById<ImageView>(Resource.Id.image_view);
        imageView.SetImageResource(Resource.Mipmap.slide1);
        // Get type of service
        var test = Arguments.GetString("text");
        if (test == "Collo") {
            sampleTextView.Text = "is collooooo";
        } else {
            sampleTextView.Text = "is not collo";
        }
        return view;
    }
}
</code>```

I don't want create one activity for each service, i would like just have one "Service activity detail" and custom text and image by service type.

ERROR: when I select item service:

```<code>System.NullReferenceException - Object reference not set to an instance of an object. on:
var test = Arguments.GetString("text");
</code>```

答:
You have two ways of doing that.

If that is the activity that holds the fragment, you can call

```<code>this.Activity
</code>```

inside fragment and just call any method of the activity after casting

```<code>AwesomceActivty castetActivity = (AwesomeActivity)this.Activity;
castetActivity.AwesomeMethod(12);
</code>```

Or you can do that by using Delegates:

Define delegates in your Fragment class

```<code>namespace Awesome.Android {
     public class AwesomeFragment : Fragment {

       public delegate void OnAwesomePress (int number);
       public event OnAwesomePress sendOnAwesomePressEvent;
     }
}
</code>```

You can assign it when you create a Framgent

```<code>AwesomeFragment fragment = new AwesomeFragment ();
fragment.OnAwesomePress += OnAwesomePress;
</code>```

After that, you implement OnAwesomePress in your activity

```<code>private void OnAwesomePress (int number) {

}
</code>```

Now, when you call sendOnAwesomePressEvent in your Fragment, that event will be passed to Activity.

```<code>sendOnAwesomePressEvent (10);
</code>```

Body:
i have a List with my services, and on item selected i'm passing service type to my activity ServiceDetail like this:

ServiceActivity

void item_selected(object sender, AdapterView.ItemClickEventArgs e) {
    MenuContentItem selectedItem = (MenuContentItem)item[e.Position];
    if(selectedItem.Title == "COLLO") {
        var activity_go = new Intent(this, typeof(ServiceDetailActivity));
        activity_go.PutExtra("service_type", "Collo");
        StartActivity(activity_go);
    }
    if (selectedItem.Title == "SPALLA") {
        var activity_go = new Intent(this, typeof(ServiceDetailActivity));
        activity_go.PutExtra("service_type", "Spalla");
        StartActivity(activity_go);
    }
}

ServiceDetailActivity

protected override void OnCreate(Bundle savedInstanceState) {
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.ServiceDetail);
    //enable navigation mode to support tab layout
    this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
    AddTab("Introduzione", Resource.Mipmap.Icon, new IntroduzioneFragment());
    //intent data
    string text = Intent.GetStringExtra("service_type") ?? "Data not available";
    IntroduzioneFragment fragment = new IntroduzioneFragment();
    // set data to pass to my fragment
    Bundle bundle = new Bundle();
    bundle.PutString("text", text);
    fragment.Arguments = bundle;
}
// MY FRAGMENT - I would like "CUSTOM" my fragment "IntroduzioneFragment" like this:
class IntroduzioneFragment : Fragment {
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        base.OnCreateView(inflater, container, savedInstanceState);
        var view = inflater.Inflate(Resource.Menu.Tab, container, false);
        var sampleTextView = view.FindViewById<TextView>(Resource.Id.textView);
        var imageView = view.FindViewById<ImageView>(Resource.Id.image_view);
        imageView.SetImageResource(Resource.Mipmap.slide1);
        // Get type of service
        var test = Arguments.GetString("text");
        if (test == "Collo") {
            sampleTextView.Text = "is collooooo";
        } else {
            sampleTextView.Text = "is not collo";
        }
        return view;
    }
}

I don't want create one activity for each service, i would like just have one "Service activity detail" and custom text and image by service type.

ERROR: when I select item service:

System.NullReferenceException - Object reference not set to an instance of an object. on:
var test = Arguments.GetString("text");

Body:
You have two ways of doing that.

If that is the activity that holds the fragment, you can call

this.Activity

inside fragment and just call any method of the activity after casting

AwesomceActivty castetActivity = (AwesomeActivity)this.Activity;
castetActivity.AwesomeMethod(12);

Or you can do that by using Delegates:

Define delegates in your Fragment class

namespace Awesome.Android {
     public class AwesomeFragment : Fragment {

       public delegate void OnAwesomePress (int number);
       public event OnAwesomePress sendOnAwesomePressEvent;
     }
}

You can assign it when you create a Framgent

AwesomeFragment fragment = new AwesomeFragment ();
fragment.OnAwesomePress += OnAwesomePress;

After that, you implement OnAwesomePress in your activity

private void OnAwesomePress (int number) {

}

Now, when you call sendOnAwesomePressEvent in your Fragment, that event will be passed to Activity.

sendOnAwesomePressEvent (10);


问:
wildcard loading for every route in angular
I have added the wildcard route to my application in angular .
The issue is after adding the wildcard.

I'm not sure what is the issue!
 below id the routes array:

```<code>const appRoutes: Routes = [
    { path: 'login', redirectTo: '/login', pathMatch: 'full' },
    { path: 'settings', redirectTo: '/settings', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];
</code>```

Login and setting are modules and they have their own routing files.
Before adding the wildcard and default route, on start the app was redirected to login screen .

But now every url is redirected to PageNotFoundComponent .

The order of the routes in the configuration matters and this is by
  design. The router uses a first-match wins strategy when matching
  routes, so more specific routes should be placed above less specific
  routes. In the configuration above, routes with a static path are
  listed first, followed by an empty path route, that matches the
  default route. The wildcard route comes last because it matches every
  URL and should be selected only if no other routes are matched first.

Please guide!
Thanks

答:
Use it like : Make sure you have all the components created as follows

Never keep the wildcard route at first position, because it will always take wildcard path as default path.

```<code>const appRoutes: Routes = [
    { path: '', component:AppComponent},
    { path: 'login', component:LoginComponent},
    { path: 'settings', component:SettingsComponent},
    { path: '**', component: PageNotFoundComponent }
];
</code>```

Try importing  RouterModule as RouterModule.forRoot(routes, { useHash: true })

Body:
I have added the wildcard route to my application in angular .
The issue is after adding the wildcard.

I'm not sure what is the issue!
 below id the routes array:

const appRoutes: Routes = [
    { path: 'login', redirectTo: '/login', pathMatch: 'full' },
    { path: 'settings', redirectTo: '/settings', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

Login and setting are modules and they have their own routing files.
Before adding the wildcard and default route, on start the app was redirected to login screen .

But now every url is redirected to PageNotFoundComponent .

The order of the routes in the configuration matters and this is by
  design. The router uses a first-match wins strategy when matching
  routes, so more specific routes should be placed above less specific
  routes. In the configuration above, routes with a static path are
  listed first, followed by an empty path route, that matches the
  default route. The wildcard route comes last because it matches every
  URL and should be selected only if no other routes are matched first.

Please guide!
Thanks

Body:
Use it like : Make sure you have all the components created as follows

Never keep the wildcard route at first position, because it will always take wildcard path as default path.

const appRoutes: Routes = [
    { path: '', component:AppComponent},
    { path: 'login', component:LoginComponent},
    { path: 'settings', component:SettingsComponent},
    { path: '**', component: PageNotFoundComponent }
];

Try importing  RouterModule as RouterModule.forRoot(routes, { useHash: true })


问:
Android SQL Database File not Appearing
I'm working on an app for class that will be using a SQL database to keep track of distances and continually update them. I've never coded in java before or implemented a SQL database so I've run into some issues. Right now I'm trying to load my database with initial values (0) but the database file won't pop up in the device monitor, please help!

package tamu.thecaddyapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;
    DataHandler helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonDriver = (Button)findViewById(R.id.button_DRIVER);
        buttonFouriron = (Button)findViewById(R.id.button_4IRON);
        buttonFiveiron = (Button)findViewById(R.id.button_5IRON);
        buttonSixiron = (Button)findViewById(R.id.button_6IRON);
        buttonSeveniron = (Button)findViewById(R.id.button_7IRON);
        buttonEightiron = (Button)findViewById(R.id.button_8IRON);
        buttonNineiron = (Button)findViewById(R.id.button_9IRON);
        buttonPW = (Button)findViewById(R.id.button_PW);
        buttonSW = (Button)findViewById(R.id.button_SW);
        buttonFiftysix = (Button)findViewById(R.id.button_56DEG);
        buttonSixty = (Button)findViewById(R.id.button_60DEG);
    }

    public void buttonDriver(View view) {
    }

    public void buttonFouriron(View view) {
    }

    public void buttonFiveiron(View view) {
    }

    public void buttonSixiron(View view) {
    }

    public void buttonSeveniron(View view) {
    }

    public void buttonEightiron(View view) {
    }

    public void buttonNineiron(View view) {
    }

    public void buttonPW(View view) {
    }

    public void buttonSW(View view) {
    }

    public void buttonFiftysix(View view) {
    }

    public void buttonSixty(View view) {
    }
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package tamu.thecaddyapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Owner on 11/12/2017.
 */

public class DataHandler {
    public static final String _ID = "_ID";
    public static final String TABLE_NAME = "SHOT_AVERAGES";
    public static final String DATA_BASE_NAME = "thecaddyappdb";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + "TEXT NOT NULL"+ ") VALUES(150)";

    DataBaseHelper dbhelper;
    Context ctx;
    SQLiteDatabase db;

    public DataHandler(Context ctx) {
        this.ctx = ctx;
        dbhelper = new DataBaseHelper(ctx);
    }

    private static class DataBaseHelper extends SQLiteOpenHelper {
        public DataBaseHelper(Context ctx) {
            super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(TABLE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int i, int i1) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    public DataHandler open(){
        db = dbhelper.getWritableDatabase();
        return this;
    }

    public void close() {
        dbhelper.close();
    }

    public long insertData(int recalDist){
        ContentValues content = new ContentValues();
        String clubName = "Driver";
        content.put(_ID, clubName);
        content.put(_ID, recalDist);
        return db.insertOrThrow(TABLE_NAME, null, content);
    }

}</code>```

Additionally, I worked on this for awhile, so these files are a lot different than some of the stuff I've had, really just experimenting but not completely sure what's wrong, this code I was going for one column with values and will later implement the additional columns after I know a database file is being created.

Thanks

答: Regarding the SQl file not showing in Android monitor, please ensure that you have your device API 22 or below. It doesn't work properly for API's above 22.</p>

Title: Android SQL Database File not Appearing

Body:
I'm working on an app for class that will be using a SQL database to keep track of distances and continually update them. I've never coded in java before or implemented a SQL database so I've run into some issues. Right now I'm trying to load my database with initial values (0) but the database file won't pop up in the device monitor, please help!

package tamu.thecaddyapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button buttonDriver, buttonFouriron, buttonFiveiron, buttonSixiron, buttonSeveniron, buttonEightiron, buttonNineiron, buttonPW, buttonFiftysix, buttonSW, buttonSixty;
    DataHandler helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonDriver = (Button)findViewById(R.id.button_DRIVER);
        buttonFouriron = (Button)findViewById(R.id.button_4IRON);
        buttonFiveiron = (Button)findViewById(R.id.button_5IRON);
        buttonSixiron = (Button)findViewById(R.id.button_6IRON);
        buttonSeveniron = (Button)findViewById(R.id.button_7IRON);
        buttonEightiron = (Button)findViewById(R.id.button_8IRON);
        buttonNineiron = (Button)findViewById(R.id.button_9IRON);
        buttonPW = (Button)findViewById(R.id.button_PW);
        buttonSW = (Button)findViewById(R.id.button_SW);
        buttonFiftysix = (Button)findViewById(R.id.button_56DEG);
        buttonSixty = (Button)findViewById(R.id.button_60DEG);
    }

    public void buttonDriver(View view) {
    }

    public void buttonFouriron(View view) {
    }

    public void buttonFiveiron(View view) {
    }

    public void buttonSixiron(View view) {
    }

    public void buttonSeveniron(View view) {
    }

    public void buttonEightiron(View view) {
    }

    public void buttonNineiron(View view) {
    }

    public void buttonPW(View view) {
    }

    public void buttonSW(View view) {
    }

    public void buttonFiftysix(View view) {
    }

    public void buttonSixty(View view) {
    }
}

package tamu.thecaddyapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Owner on 11/12/2017.
 */

public class DataHandler {
    public static final String _ID = "_ID";
    public static final String TABLE_NAME = "SHOT_AVERAGES";
    public static final String DATA_BASE_NAME = "thecaddyappdb";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + _ID + "TEXT NOT NULL"+ ") VALUES(150)";

    DataBaseHelper dbhelper;
    Context ctx;
    SQLiteDatabase db;

    public DataHandler(Context ctx) {
        this.ctx = ctx;
        dbhelper = new DataBaseHelper(ctx);
    }

    private static class DataBaseHelper extends SQLiteOpenHelper {
        public DataBaseHelper(Context ctx) {
            super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(TABLE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int i, int i1) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    public DataHandler open(){
        db = dbhelper.getWritableDatabase();
        return this;
    }

    public void close() {
        dbhelper.close();
    }

    public long insertData(int recalDist){
        ContentValues content = new ContentValues();
        String clubName = "Driver";
        content.put(_ID, clubName);
        content.put(_ID, recalDist);
        return db.insertOrThrow(TABLE_NAME, null, content);
    }

}

Additionally, I worked on this for awhile, so these files are a lot different than some of the stuff I've had, really just experimenting but not completely sure what's wrong, this code I was going for one column with values and will later implement the additional columns after I know a database file is being created.

Thanks


答:
Try This:-</p>

```<code>$(document).ready(function() {
    $("input:radio").click(function() {

        var val = $(this).val();

        var class_name = $(this).attr('class');
        var name = $(this).attr('name');

        //disable radio by class name
        $('input:radio').each(function() {
            if ($(this).attr('class') != class_name) {
                $(this).attr("disabled", true);
            } else {
                $(this).attr("disabled", false);
            }
        });

        //disable button by  name
        $('input:submit').each(function() {

            if ($(this).attr('name') != name) {
                $(this).attr("disabled", true);
            } else {
                $(this).attr("disabled", false);
            }
        });

    });

});
</code>```

Title: Disabled all other radio button if name and value not same

Body:
I am making one form where I need to disable all other radio button and submit button if Radio button name or Id or class name not same to each other.

ID or name or class, I am generating through dynamic way. (name=radio_1, id= radio_1).

or

if I click on Group-1 radio button then other group should be disable.

Please have a look.

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="radio" name="start_<?=$value['task_id']?>" class="group_<?=$value['task_id']?>" value="start_<?=$value['task_id']?>">
<input type="submit" name="start_<?=$value['task_id']?>" value="Save" class="btn sm btn-primary group_<?=$value['task_id']?>">

HTML Output:

<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="radio" name="start_1" class="group_1" value="start_1">
<input type="submit" name="start_1" value="Save" class="btn sm btn-primary group_1">

<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="radio" name="start_2" class="group_2" value="start_2">
<input type="submit" name="start_2" value="Save" class="btn sm btn-primary group_2">

My Query:

$(document).ready(function() {
$("input:radio").click(function() {
    var val = $(this).val();
    var name = $(this).attr('name');
    if(val != name){
      $(this).attr("disabled", true);
    }
    else{
    $(this).attr("disabled", false);
    }
});

});

Please guide me how can I do this.

Body:
Try This:-

$(document).ready(function() {
    $("input:radio").click(function() {

        var val = $(this).val();

        var class_name = $(this).attr('class');
        var name = $(this).attr('name');

        //disable radio by class name
        $('input:radio').each(function() {
            if ($(this).attr('class') != class_name) {
                $(this).attr("disabled", true);
            } else {
                $(this).attr("disabled", false);
            }
        });

        //disable button by  name
        $('input:submit').each(function() {

            if ($(this).attr('name') != name) {
                $(this).attr("disabled", true);
            } else {
                $(this).attr("disabled", false);
            }
        });

    });

});


问:
User Input Date Comparison in Javascript and moment.js
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}</code>```

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

```

what is the mistake I have made?

答:
your snippet contains, jquery, simply get value like this, $("#date1").val()

use common format for date by assigning separately,

function compare() {
    $("#status").removeClass('redBg greenBg yellowBg');
    var dateFormat = "MM-DD-YYYY";
    var firstDate = moment($("#date1").val(),dateFormat);

    var secondDate = moment($("#date2").val(),dateFormat);

    var diff = firstDate.diff(secondDate, 'days');
    console.log('s',diff);
    if(7 < diff)
    {
         $("#status").addClass('redBg');
    }
    else if(4 < diff)
    {
        $("#status").addClass('greenBg');
    }
    else if(diff <= 4)
    {
        $("#status").addClass('yellowBg');
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}</code>```

<input type="text" id="date1"/>
<input type="text" id="date2"/>
<input type="text" id="status"/>
<input type="button" id="click" value="check" onclick="compare(this)">

```

Body:
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });

.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

what is the mistake I have made?

Body:
your snippet contains, jquery, simply get value like this, $("#date1").val()

use common format for date by assigning separately,

function compare() {
    $("#status").removeClass('redBg greenBg yellowBg');
    var dateFormat = "MM-DD-YYYY";
    var firstDate = moment($("#date1").val(),dateFormat);

    var secondDate = moment($("#date2").val(),dateFormat);

    var diff = firstDate.diff(secondDate, 'days');
    console.log('s',diff);
    if(7 < diff)
    {
         $("#status").addClass('redBg');
    }
    else if(4 < diff)
    {
        $("#status").addClass('greenBg');
    }
    else if(diff <= 4)
    {
        $("#status").addClass('yellowBg');
    }
}

.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<html>
<body>
<input type="text" id="date1"/>
<input type="text" id="date2"/>
<input type="text" id="status"/>
<input type="button" id="click" value="check" onclick="compare(this)">
</body>
</html>


问:
Add new rows to a gridview before submit to database
Good afternoon,

I'm developing a form to place orders online.

I get the article from a combobox and get the details of that article using a sql query. So far, so good.

I put that article to a gridview. For one article, it's all ok.

I make the selection of the article, click on insert button, and the article with the details is inserted on the gridview.

My problem is on how to add more rows. When i click the insert button, with a different article and details, i only get one row, with overwritten data.

After all rows are in the gridview, i finally can submit that rows and process the order.

What should i use to add so many rows as i need? ViewState? Session State?

I read some articles, but none of them helped me as i needed.

Thank you.

EDIT:

I use a datatable to store the data.

```<code> DataTable DT = new DataTable();

        DT.Columns.Add("Artigo");
        DT.Columns.Add("Descricao");
        DT.Columns.Add("IVA");
        DT.Columns.Add("PU");
        DT.Columns.Add("UN");
        DT.Columns.Add("Qtd");
        DT.Columns.Add("TotalLiq");

        try
        {
            int Qtd = Convert.ToInt32(Quantidade.Text);
            int PrecoUnit = glb._precolente;
            float TotalLiq = Qtd * PrecoUnit;

            string str = "SELECT TOP 1 A.Artigo as Artigo, A.Descricao as Descricao, (SELECT Taxa FROM prisalviani.dbo.Iva WHERE Iva = A.Iva)AS IVA, A.UnidadeBase as UN FROM prisalviani.dbo.ARTIGO A where A.Artigo='" + result.ToString() + "'";

            ListaLentes = Motor.Consulta(ref str);

            while (!ListaLentes.NoFim())
            {
                DT.Rows.Add(ListaLentes.Valor("Artigo"),
                            ListaLentes.Valor("Descricao"),
                            ListaLentes.Valor("IVA"),
                            PrecoUnit,
                ListaLentes.Valor("UN"),
                Qtd,
                TotalLiq
                );
                ListaLentes.Seguinte();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
</code>```

答:
the description you have given is a bit vague, what kind of data structure are you using to hold the order rows? do you want to implement something similar to a shopping basket?

you can implement your own business entities or use a dataset/datatable to hold the new records, you can the keep these objects in the Session.

does it help a bit?

Body:
Good afternoon,

I'm developing a form to place orders online.

I get the article from a combobox and get the details of that article using a sql query. So far, so good.

I put that article to a gridview. For one article, it's all ok.

I make the selection of the article, click on insert button, and the article with the details is inserted on the gridview.

My problem is on how to add more rows. When i click the insert button, with a different article and details, i only get one row, with overwritten data.

After all rows are in the gridview, i finally can submit that rows and process the order.

What should i use to add so many rows as i need? ViewState? Session State?

I read some articles, but none of them helped me as i needed.

Thank you.

EDIT:

I use a datatable to store the data.

 DataTable DT = new DataTable();

        DT.Columns.Add("Artigo");
        DT.Columns.Add("Descricao");
        DT.Columns.Add("IVA");
        DT.Columns.Add("PU");
        DT.Columns.Add("UN");
        DT.Columns.Add("Qtd");
        DT.Columns.Add("TotalLiq");

        try
        {
            int Qtd = Convert.ToInt32(Quantidade.Text);
            int PrecoUnit = glb._precolente;
            float TotalLiq = Qtd * PrecoUnit;

            string str = "SELECT TOP 1 A.Artigo as Artigo, A.Descricao as Descricao, (SELECT Taxa FROM prisalviani.dbo.Iva WHERE Iva = A.Iva)AS IVA, A.UnidadeBase as UN FROM prisalviani.dbo.ARTIGO A where A.Artigo='" + result.ToString() + "'";

            ListaLentes = Motor.Consulta(ref str);

            while (!ListaLentes.NoFim())
            {
                DT.Rows.Add(ListaLentes.Valor("Artigo"),
                            ListaLentes.Valor("Descricao"),
                            ListaLentes.Valor("IVA"),
                            PrecoUnit,
                ListaLentes.Valor("UN"),
                Qtd,
                TotalLiq
                );
                ListaLentes.Seguinte();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }


问:
CakePHP Migration Creating a new table causes duplicate column name
I created a new Migration script on CakePHP 3 using the following command

```<code>bin/cake bake migration CreateOfficialTeams id:int name:string topic_id:int
</code>```

The id field should be the primary key, and topic_id is a foreign key. The script comes out like I want, except topic_id is a string for some reason, but I manually fix that.

When I attempt to run the script I get an error stating:

```<code>Exception: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' in [/home/bradygp/workspace/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php, line 306]
2017-02-27 21:52:16 Error [PDOException] SQLSTATE[45S21]: Column already exists: 1060 Duplicate column name 'id'
</code>```

I have other tables with a column name of 'id', but this is a new table, called with the create() function,

答:
Remove ID. ID column is automatically created, so you don't need to write it.

bin/cake bake migration CreateOfficialTeams name:string topic_id:int

Body:
I created a new Migration script on CakePHP 3 using the following command

bin/cake bake migration CreateOfficialTeams id:int name:string topic_id:int

The id field should be the primary key, and topic_id is a foreign key. The script comes out like I want, except topic_id is a string for some reason, but I manually fix that.

When I attempt to run the script I get an error stating:

Exception: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' in [/home/bradygp/workspace/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php, line 306]
2017-02-27 21:52:16 Error [PDOException] SQLSTATE[45S21]: Column already exists: 1060 Duplicate column name 'id'

I have other tables with a column name of 'id', but this is a new table, called with the create() function,


问:
my own banner ads in my android app like Google banner ads
i want to add my own created ads display in my android app like google banner ads
how i can archive that.

if using image view is this this possible ? than how to add animations any lib for that?.

答:
If you want to make your own AdView, I think you will only 2 option,

You can use ImageView with X seconds of refresh rate.

If you want to make animated ImageView, it is better to have GIFView


问:
How to remove corner radius of the formsheet style UIViewController
```<code>    @IBAction func popOverRadarChart(sender: UIButton) {

    let popOverViewController = ResultTwoPopoverViewController(nibName: "ResultTwoPopoverViewController", bundle: nil)

    popOverViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
    popOverViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
    popOverViewController.preferredContentSize = CGSizeMake(540, 622)
    popOverViewController.view.layer.cornerRadius = 0.0
    popOverViewController.view.layer.masksToBounds = true
    presentViewController(popOverViewController, animated: true, completion: nil)

}
</code>```

If I could remove those four corner radius to 0.0.

答:
It works for me with this code:</p>

```<code>- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //change the cornerRadius
    self.view.superview.layer.cornerRadius = 4;
}
</code>```

Body:
    @IBAction func popOverRadarChart(sender: UIButton) {

    let popOverViewController = ResultTwoPopoverViewController(nibName: "ResultTwoPopoverViewController", bundle: nil)

    popOverViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
    popOverViewController.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
    popOverViewController.preferredContentSize = CGSizeMake(540, 622)
    popOverViewController.view.layer.cornerRadius = 0.0
    popOverViewController.view.layer.masksToBounds = true
    presentViewController(popOverViewController, animated: true, completion: nil)

}

If I could remove those four corner radius to 0.0.

Body:
It works for me with this code:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //change the cornerRadius
    self.view.superview.layer.cornerRadius = 4;
}


答:
Edit: This whole answer assumes that * is a binary operator in Julia. This is incorrect and as such the OP question is perfectly valid. See https://discourse.julialang.org/t/is-there-any-way-to-make-custom-binary-infix-operators-right-associative/3202/5 for some discussion (specifically mentioning that * is parsed as n-arry, which can be seen here). I will leave the original answer below.

Matrix-matrix multiplication takes n^3 steps (for smallish matrices). Matrix-vector multiplication takes n^2 steps.

a*b*c is the same as (a*b)*c which takes a total of n^3+n^2 operations, while a*(b*c) takes 2*n^2 operations because it contains only matrix-vector multiplications.

If you want something to automatically optimize your matrix algebra expression, you can try a library like https://github.com/Jutho/TensorOperations.jl (the first hit on google for that type of question). Another option mentioned in the comments is https://github.com/AustinPrivett/MatrixChainMultiply.jl

As to why Julia does not do this automatically: That would have to be part of the parser (precedence of operators), however you do not want the parser to be able to peek inside the runtime in order to learn what the object is. On the other hand, this is certainly achievable with a macro applied before compilation as done by the aforementioned packages. Maybe it is also feasible if you use some compile-time type information, however this will be a rather ugly special-case for only a couple of types in the otherwise elegant multiple-dispatch mechanism of Julia.

ContentLicense: CC BY-SA 4.0

Title: Why enforcing order onto Julia matrix vector multiplications has speed up?

Body:
I've tried the following.

a = randn(100,100);
b = randn(100,100);
c = randn(100,1);

@time a*b*c
@time a*(b*c)

Results

julia> @time a*b*c;
  0.000591 seconds (7 allocations: 79.234 KiB)

julia> @time a*(b*c);
  0.000101 seconds (6 allocations: 1.906 KiB)

Results are quite consistent with the above.  While it does make intuitive sense why the the second one is better (A matrix-vector multiplication twice instead of a large matrix-matrix multiplication).

I was wondering, shouldn't Julia have optimized this knowing that the dimensions of the matrices and it could've reordered the operation to have optimized it?  Or am I just being too lazy to wish for that or are there other technical issues that I don't see.

So, this is what I get when I use dump() on (a*b*c)

  head: Symbol call
  args: Array{Any}((4,))
    1: Symbol *
    2: Array{Float64}((100, 100)) [0.290788 -0.0601455 … -0.408164 1.16261; -0.539274 -1.56979 … 2.56233 0.806247; … ; 1.30981 -1.31929 … 1.38655 -1.89169; -1.58483 0.318804 … -0.0500151 2.13105]
    3: Array{Float64}((100, 100)) [-0.464882 1.60371 … -0.390234 0.605401; -1.06837 0.296049 … 0.759708 0.0124688; … ; -0.149613 -1.38653 … 0.284494 1.47524; 0.34351 0.420449 … 0.544973 1.85736]
    4: Array{Float64}((100, 1)) [1.64066; 0.593296; … ; 0.908361; 0.486164]
  typ: Any

dump(a*(b*c))

Expr
  head: Symbol call
  args: Array{Any}((3,))
    1: Symbol *
    2: Array{Float64}((100, 100)) [0.290788 -0.0601455 … -0.408164 1.16261; -0.539274 -1.56979 … 2.56233 0.806247; … ; 1.30981 -1.31929 … 1.38655 -1.89169; -1.58483 0.318804 … -0.0500151 2.13105]
    3: Expr
      head: Symbol call
      args: Array{Any}((3,))
        1: Symbol *
        2: Array{Float64}((100, 100)) [-0.464882 1.60371 … -0.390234 0.605401; -1.06837 0.296049 … 0.759708 0.0124688; … ; -0.149613 -1.38653 … 0.284494 1.47524; 0.34351 0.420449 … 0.544973 1.85736]
        3: Array{Float64}((100, 1)) [1.64066; 0.593296; … ; 0.908361; 0.486164]
      typ: Any
  typ: Any

So, is there an issue trying to optimize on this assuming operators are associative?  Does it become very complex or intractable otherwise?


问:
CKEditor and asp.net
I am using CKEditor on my page. It is working fine except when I post back. I am getting this error:

A potentially dangerous Request.Form value was detected from the client (ctl00$MainContent$txtDesc="

I am using this code to put CKEditor value into textbox on OnClientClick event of submit button:

```<code>function getEditorValue(){
    var editor=$("#<%= txtDesc.ClientID%>").ckeditorGet();
    editor.updateElement();
    return true;
}
</code>```

答:
Have you tried setting the htmlEncodeOutput property?

```<code>> CKEDITOR.replace('#<%= txtDesc.ClientID%>', {
>  htmlEncodeOutput: true });
</code>```

This should encode the output and you should be able to avoid setting the requestValidationMode.

Documentation for it is here: ckEditor documentation

Title: CKEditor and asp.net

Body:
I am using CKEditor on my page. It is working fine except when I post back. I am getting this error:

A potentially dangerous Request.Form value was detected from the client (ctl00$MainContent$txtDesc="

I am using this code to put CKEditor value into textbox on OnClientClick event of submit button:

function getEditorValue(){
    var editor=$("#<%= txtDesc.ClientID%>").ckeditorGet();
    editor.updateElement();
    return true;
}

Body:
Have you tried setting the htmlEncodeOutput property?

> CKEDITOR.replace('#<%= txtDesc.ClientID%>', {
>  htmlEncodeOutput: true });

This should encode the output and you should be able to avoid setting the requestValidationMode.

Documentation for it is here: ckEditor documentation


问:
i want the link style like in the picture
html code:

```<code> <ul class="info-link">
   <li><a href="#"><i class="fa fa-map-marker"></i>  3588 N Stelling road, Brooklyn, NYC, United State.</a> </li>
   <li><a href="#"><i class="fa fa-phone"></i>  1900-167-168-99 EXT: 001</a></li>
   <li><a href="#"><i class="fa fa-mobile"></i>  (05) 132-564-3333</a></li>
   <li><a href="#"><i class="fa fa-envelope"></i>  logohere@support.com</a></li>
 </ul>
</code>```

css code :

```<code>ul li {
  list-style: none;
}
</code>```

result picture:
code-result

desire result picture:
desire-result

答:
That`s what you want

        ul li{
list-style:none;
margin: 15px 0;}
a{
    display: inline-flex;
text-decoration: none}
i{
    width:20px;}
    .contact{
        border: 1px solid rgba(129, 116, 116, 0.71);
background: rgba(215, 215, 215, 0.51);
width: 400px;
    }
    h1{
        padding: 0px 40px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="contact">
    <h1>Contact Info</h1>
    <ul class="info-link">
        <li><i class="fa fa-map-marker"></i>  3588 N Stelling road, Brooklyn, NYC,<br /> United State. </li>
        <li><i class="fa fa-phone"></i>  1900-167-168-99 EXT: 001</li>
        <li><i class="fa fa-mobile"></i>  (05) 132-564-3333</li>
        <li><i class="fa fa-envelope"></i>  logohere@support.com</li>
    </ul>
</div></code>```

Body:
html code:

  3588 N Stelling road, Brooklyn, NYC, United State.

  1900-167-168-99 EXT: 001

  (05) 132-564-3333

  logohere@support.com

css code :

ul li {
  list-style: none;
}

result picture:
code-result

desire result picture:
desire-result

Body:
That`s what you want

        ul li{
list-style:none;
margin: 15px 0;}
a{
    display: inline-flex;
text-decoration: none}
i{
    width:20px;}
    .contact{
        border: 1px solid rgba(129, 116, 116, 0.71);
background: rgba(215, 215, 215, 0.51);
width: 400px;
    }
    h1{
        padding: 0px 40px;
    }

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="contact">
    <h1>Contact Info</h1>
    <ul class="info-link">
        <li><i class="fa fa-map-marker"></i><a href="#"> &nbsp;3588 N Stelling road, Brooklyn, NYC,<br /> United State.</a> </li>
        <li><i class="fa fa-phone"></i><a href="#"> &nbsp;1900-167-168-99 EXT: 001</a></li>
        <li><i class="fa fa-mobile"></i><a href="#"> &nbsp;(05) 132-564-3333</a></li>
        <li><i class="fa fa-envelope"></i> <a href="#">&nbsp;logohere@support.com</a></li>
    </ul>
</div>