问:
Strange sbt bug where I cannot import sbt project due to keys colliding with themselves
After changing my build.sbt file in IntelliJ, I get this strange error report where it appears that "keys" (I don't know what these keys even are) are colliding with themselves. Researching this error message only finds github pull requests where people are requesting library maintainers to prefix their keys to avoid key collisions. How can these built-in IntelliJ keys collide with themselves? It makes no sense. Here is the excerpt from the stack trace:

```<code>java.lang.RuntimeException: Some keys were defined with the same name but different types:
'ssExtractBuild' (sbt.Task[org.jetbrains.sbt.structure.BuildData], sbt.Task[org.jetbrains.sbt.structure.BuildData]),
'settingData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.SettingData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.SettingData]]),
'taskData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.TaskData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.TaskData]]),
'extractStructure' (sbt.Task[org.jetbrains.sbt.structure.StructureData], sbt.Task[org.jetbrains.sbt.structure.StructureData]),
'ssExtractDependencies' (sbt.Task[org.jetbrains.sbt.structure.DependencyData], sbt.Task[org.jetbrains.sbt.structure.DependencyData]),
'ssExtractProjects' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]]),
'ssExtractAndroid' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.AndroidData]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.AndroidData]]),
'ssExtractRepository' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.RepositoryData]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.RepositoryData]]),
'ssOptions' (org.jetbrains.sbt.Options, org.jetbrains.sbt.Options),
'commandData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.CommandData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.CommandData]]),
'ssExtractProject' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]]),
'ssExtractPlay2' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.Play2Data]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.Play2Data]])
</code>```

And the full stack trace is here: https://pastebin.com/ymZvgMCj

This happened after I added a dependency to my build.sbt. I thought it was the problem at first and tried removing it, but now my build.sbt doesn't even work in its previous state! I've cleared my intellij's cache, restarted, deleted my .idea folder in that project entirely and reimported the entire project itself into intellij, and I still have the same problem. What could have happened between the last time I changed my build.sbt and now that would break the project like this?

答:
I had the same issue today. My fix was to :

invalidate the cache

close Intellij

delete .idea

import project

Body:
After changing my build.sbt file in IntelliJ, I get this strange error report where it appears that "keys" (I don't know what these keys even are) are colliding with themselves. Researching this error message only finds github pull requests where people are requesting library maintainers to prefix their keys to avoid key collisions. How can these built-in IntelliJ keys collide with themselves? It makes no sense. Here is the excerpt from the stack trace:

java.lang.RuntimeException: Some keys were defined with the same name but different types:
'ssExtractBuild' (sbt.Task[org.jetbrains.sbt.structure.BuildData], sbt.Task[org.jetbrains.sbt.structure.BuildData]),
'settingData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.SettingData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.SettingData]]),
'taskData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.TaskData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.TaskData]]),
'extractStructure' (sbt.Task[org.jetbrains.sbt.structure.StructureData], sbt.Task[org.jetbrains.sbt.structure.StructureData]),
'ssExtractDependencies' (sbt.Task[org.jetbrains.sbt.structure.DependencyData], sbt.Task[org.jetbrains.sbt.structure.DependencyData]),
'ssExtractProjects' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]]),
'ssExtractAndroid' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.AndroidData]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.AndroidData]]),
'ssExtractRepository' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.RepositoryData]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.RepositoryData]]),
'ssOptions' (org.jetbrains.sbt.Options, org.jetbrains.sbt.Options),
'commandData' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.CommandData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.CommandData]]),
'ssExtractProject' (sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]], sbt.Task[scala.collection.Seq[org.jetbrains.sbt.structure.ProjectData]]),
'ssExtractPlay2' (sbt.Task[scala.Option[org.jetbrains.sbt.structure.Play2Data]], sbt.Task[scala.Option[org.jetbrains.sbt.structure.Play2Data]])

And the full stack trace is here: https://pastebin.com/ymZvgMCj

This happened after I added a dependency to my build.sbt. I thought it was the problem at first and tried removing it, but now my build.sbt doesn't even work in its previous state! I've cleared my intellij's cache, restarted, deleted my .idea folder in that project entirely and reimported the entire project itself into intellij, and I still have the same problem. What could have happened between the last time I changed my build.sbt and now that would break the project like this?


来源: stackexchange

问:
jQuery File Upload blueimpl browser freeze
Im using Jquery File Upload bluempl for uploading files.
When i upload lot of number of files like 6000 files using this plugin the browser hangs and freeze many times, alothough when visiting the folder in server/files i can see the files been uploaded.
can you tell what kind of optimization or parameter i can use for uploading many files without the browser freeze.
Im using as example the one in basic.hml of the example file :

```<code>$(function () {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = window.location.hostname === 'blueimp.github.io' ?
                '//jquery-file-upload.appspot.com/' : 'server/php/';
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p/>').text(file.name).appendTo('#files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</code>```

Thanks in advance.

答:
It looks like synchronous upload is the default in blueimp.

Browser freezes have often to do with synchronous instead of asynchronous javascript requests.

<s>Blueimp describes how to upload asynchronously:</s>
https://github.com/blueimp/jQuery-File-Upload/wiki/Submit-files-asynchronously

Update

Ok, the add method described on the page above is just called when files are added to the queue

The options documentation contains parameters sequentialUploads and limitConcurrentUploads, please try using them or one of them.

ContentLicense: CC BY-SA 4.0

Body:
Im using Jquery File Upload bluempl for uploading files.
When i upload lot of number of files like 6000 files using this plugin the browser hangs and freeze many times, alothough when visiting the folder in server/files i can see the files been uploaded.
can you tell what kind of optimization or parameter i can use for uploading many files without the browser freeze.
Im using as example the one in basic.hml of the example file :

$(function () {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = window.location.hostname === 'blueimp.github.io' ?
                '//jquery-file-upload.appspot.com/' : 'server/php/';
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('
').text(file.name).appendTo('#files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});

Thanks in advance.


问:
Problems with $.post
I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.

I have tried the $.post function on jQuery like this:

```<code>$.post("index.php", {
  correcto_obligatorio: true
});

window.location.reload("index.php")
</code>```

However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL

答:
$.post is a separate asynchronous request.
window.location.reload just reloads a page, but doesn't consider all of your async requests.

If you print $_POST['correcto_obligatorio'] not with var_dump, but log to file you will see the value there.

There is two solutions for you.

1) Await for the ajax result and respond to it.

```<code>$.post( "index.php", {
  correcto_obligatorio: true
}, function (data) {
  if (data.passed_validation) {
    window.location.reload("index.php")
  }
});
</code>```

2) Second is to post a form

```<code><form action="/index.php" method="POST" id="my_form">
  <input type="hidden" name="correcto_obligatorio" value="1"/>
</form>

<script>
  function myFunc() {
     $("#my_form").submit()
  }
</script>
</code>```

The most common and rightful one is the first solution.

Title: Problems with $.post

Body:
I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.

I have tried the $.post function on jQuery like this:

$.post("index.php", {
  correcto_obligatorio: true
});

window.location.reload("index.php")

However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL

Body:
$.post is a separate asynchronous request.
window.location.reload just reloads a page, but doesn't consider all of your async requests.

If you print $_POST['correcto_obligatorio'] not with var_dump, but log to file you will see the value there.

There is two solutions for you.

1) Await for the ajax result and respond to it.

$.post( "index.php", {
  correcto_obligatorio: true
}, function (data) {
  if (data.passed_validation) {
    window.location.reload("index.php")
  }
});

2) Second is to post a form

<form action="/index.php" method="POST" id="my_form">
  <input type="hidden" name="correcto_obligatorio" value="1"/>
</form>

<script>
  function myFunc() {
     $("#my_form").submit()
  }
</script>

The most common and rightful one is the first solution.


问:
Lombok SLF4J impl inheritance issues
I'm facing an issue with Lombok in my multimodule maven project. I have two classes :

```<code>@Slf4j
public class Parent {}

@Slf4j
public class Child extends Parent {
    public void m() {
        log.debug("hello");
    }
}
</code>```

There is also a parent maven project in which the lombok dependency is defined. And a child maven project in which I define the parent project as maven parent.

When I use generated log instance in Child class, compilation error occurs :

```<code>[ERROR] log has private access in <Child class>
</code>```

I could resolved the issue in two ways:

I create myself the private field named "log" by hand.

I define the Lombok dependency in the child maven project.

Why so? Any workaround / best way to define the lombok dependency ?

Thanks for your help.

Using :

lombok 1.16.18

JDK 1.8

Maven 3.5.3

答:
Inheritance should not impact your issue in any way. When you use @Slf4j annotation Lombok creates private static final field and static fields are not inherited. In your case generated code looks like this:

```<code>public class Parent {
    private static final Logger log = LoggerFactory.getLogger(Parent.class);

    public Parent() {}
}

public class Child extends Parent {
    private static final Logger log = LoggerFactory.getLogger(Child.class);

    public Child() {}

    public void m() {
        log.debug("hello");
    }
}
</code>```

With multi-module maven project you need to ensure that inter-module dependencies are specified correctly. If lombok is on the classpath everything should work perfectly fine out of the box.

Title: Lombok SLF4J impl inheritance issues

Body:
I'm facing an issue with Lombok in my multimodule maven project. I have two classes :

@Slf4j
public class Parent {}

@Slf4j
public class Child extends Parent {
    public void m() {
        log.debug("hello");
    }
}

There is also a parent maven project in which the lombok dependency is defined. And a child maven project in which I define the parent project as maven parent.

When I use generated log instance in Child class, compilation error occurs :

[ERROR] log has private access in <Child class>

I could resolved the issue in two ways:

I create myself the private field named "log" by hand.

I define the Lombok dependency in the child maven project.

Why so? Any workaround / best way to define the lombok dependency ?

Thanks for your help.

Using :

lombok 1.16.18

JDK 1.8

Maven 3.5.3

Body:
Inheritance should not impact your issue in any way. When you use @Slf4j annotation Lombok creates private static final field and static fields are not inherited. In your case generated code looks like this:

public class Parent {
    private static final Logger log = LoggerFactory.getLogger(Parent.class);

    public Parent() {}
}

public class Child extends Parent {
    private static final Logger log = LoggerFactory.getLogger(Child.class);

    public Child() {}

    public void m() {
        log.debug("hello");
    }
}

With multi-module maven project you need to ensure that inter-module dependencies are specified correctly. If lombok is on the classpath everything should work perfectly fine out of the box.


问:
C++ Matrix Class - Suggestions
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

```<code>template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix<U>&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix<U>&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}
</code>```

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.

答:
If you want to know how it's done properly, see the Eigen project's implementation:

https://bitbucket.org/eigen/eigen/src/49e00a2e570c/Eigen/src/Core/Matrix.h

https://bitbucket.org/eigen/eigen/src/49e00a2e570c/Eigen/src/Core/MatrixBase.h

Eigen is a template-heavy fast matrix library for C++. I'm sure there's a lot of usefulness there.

ContentLicense: CC BY-SA 3.0

Title: C++ Matrix Class - Suggestions

Body:
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.


问:
Android 6.0.1 unable to resolve IP using DNS.
I've have an android 6.0.1 navigation system. The idea is to connect 4G/3G USB modem to have an internet on it constantly.
Found an article how to setup auto installation and configuration of USB modem.
basic idea is to call

```<code>pppd call conf-pppd
</code>```

where conf-pppd

```<code>ttyUSB1
460800
defaultroute
noauth
noipdefault
user ""
password ""
connect "/system/bin/chat -f /etc/ppp/peers/conf-chat"
</code>```

where conf-chat
is set of AT commands

```<code>TIMEOUT 3
ABORT 'BUSY'
ABORT 'ERROR'
ABORT '+CME ERROR:'
TIMEOUT 3
'' 'AT'
OK 'ATZ'
OK 'AT+CGDCONT=1,"IP","fp.com.attz"'
OK 'ATDT*99#'
CONNECT ''
</code>```

After all problems it almost works, I mean modem connects to 4G network and I even can ping any IP from terminal.
But chrome says some DNS error though I've set

```<code>setprop net.dns1 8.8.8.8
setprop net.dns2 8.8.4.4
setprop net.ppp0.dns1 8.8.8.8
setprop net.ppp0.dns2 8.8.4.4
</code>```

here is some android state info which I was able to gather:

DNS info

IP route info

ifconfig

Wasn't able to google anything useful, would appreciate any help, what to check or maybe where to post this question if it isn't appropriate forum.
Thanks.

Body:
I've have an android 6.0.1 navigation system. The idea is to connect 4G/3G USB modem to have an internet on it constantly.
Found an article how to setup auto installation and configuration of USB modem.
basic idea is to call

pppd call conf-pppd

where conf-pppd

ttyUSB1
460800
defaultroute
noauth
noipdefault
user ""
password ""
connect "/system/bin/chat -f /etc/ppp/peers/conf-chat"

where conf-chat
is set of AT commands

TIMEOUT 3
ABORT 'BUSY'
ABORT 'ERROR'
ABORT '+CME ERROR:'
TIMEOUT 3
'' 'AT'
OK 'ATZ'
OK 'AT+CGDCONT=1,"IP","fp.com.attz"'
OK 'ATDT*99#'
CONNECT ''

After all problems it almost works, I mean modem connects to 4G network and I even can ping any IP from terminal.
But chrome says some DNS error though I've set

setprop net.dns1 8.8.8.8
setprop net.dns2 8.8.4.4
setprop net.ppp0.dns1 8.8.8.8
setprop net.ppp0.dns2 8.8.4.4

here is some android state info which I was able to gather:

DNS info

IP route info

ifconfig

Wasn't able to google anything useful, would appreciate any help, what to check or maybe where to post this question if it isn't appropriate forum.
Thanks.

Body:
Android 8.0

////////////////////////////////////////////////////////////

ifconfig usb0 192.168.225.3 netmask 255.255.255.0

ndc network create 9792

ndc network interface add 9792 usb0

ndc network route add 9792 usb0 0.0.0.0/0 192.168.225.1

ndc resolver setnetdns 9792 8.8.8.8 8.8.4.4

ndc network default set 9792

///////////////////////////////////////////////////////////


问:
How to define an empty list of string in jshell in a shortest possible way?
I want to create an empty list of type List<String> in jshell

I am hoping jshell supports some sort of syntax shorthand for example:

```<code>  List<String> args = []
</code>```

However it failed with this error message:

```<code>|  Error:
|  illegal start of expression
|  List<String> args = [];
|                      ^
</code>```

Of course I can just use the standard java expression:

```<code>import com.google.common.collect.ImmutableList
List<String> args = ImmutableList.of()
</code>```

but I want to know if it can be more terse.

答:
What about var keyword this comes with java 10:</p>

```<code>var list = new ArrayList<String>(); // infers ArrayList<String>
</code>```

Body:
I want to create an empty list of type List<String> in jshell

I am hoping jshell supports some sort of syntax shorthand for example:

  List<String> args = []

However it failed with this error message:

|  Error:
|  illegal start of expression
|  List<String> args = [];
|                      ^

Of course I can just use the standard java expression:

import com.google.common.collect.ImmutableList
List<String> args = ImmutableList.of()

but I want to know if it can be more terse.

Body:
What about var keyword this comes with java 10:

var list = new ArrayList<String>(); // infers ArrayList<String>


问:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I installed LAMP on Ubuntu 12.04 LTS (Precise Pangolin) and then set root password on phpMyAdmin. I forgot the password and now I am unable to login. When I try to change password through terminal I get:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket
   '/var/run/mysqld/mysqld.sock' (2)

How can I fix this? I am unable to open LAMP, uninstall it or reinstall it.

答:
This answer is likely to drown here, but maybe somebody stumbles upon it accidentally.

In my case, SELinux prevented the user/application from connecting to the MySQL (MariaDB) server socket. On RHEL, check /var/log/audit/audit.log if you have SELinux enabled.


问:
Read input from command line into the shell script exec using golang
I am using go to run a shell script using exec.command like below and I want to take an input argument using command line say i, and my output should be based on i, how would I do that?

```<code>i := os.Args[1:2]
out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | awk '{print $i/1024}' >> mem_usage.csv").Output()
if err != nil {
    fmt.Println(err.Error())
    return
 }
</code>```

How could I use that i in the shell script?

Without i it works fine i.e if I put $1 or $2 it works fine but I want user to give me the position of i and then calculate accordingly.

答:
You need to format the exec-command string accordingly.

So ie:

fmt.Sprintf("awk '{print $%d/1024}'", i)

This gives: awk '{print $1/1024}' for i = 1 and awk '{print $2/1024}' for i = 2

fmt.Sprintf takes a format string and the arguments to pass into this string and returns the formatted string. (https://golang.org/pkg/fmt/#Sprintf)

And this needs to be inserted into your exec-command:

```<code>i := 2
awkPart := fmt.Sprintf("awk '{print $%d/1024}'", i)
out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | "+awkPart+" | tee -a mem_usage.csv").Output()
</code>```

You should maybe try to disassemble your command a bit more for maintainabilty, but that's not part of the question.

Body:
I am using go to run a shell script using exec.command like below and I want to take an input argument using command line say i, and my output should be based on i, how would I do that?

i := os.Args[1:2]
out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | awk '{print $i/1024}' >> mem_usage.csv").Output()
if err != nil {
    fmt.Println(err.Error())
    return
 }

How could I use that i in the shell script?

Without i it works fine i.e if I put $1 or $2 it works fine but I want user to give me the position of i and then calculate accordingly.

Body:
You need to format the exec-command string accordingly.

So ie:

fmt.Sprintf("awk '{print $%d/1024}'", i)

This gives: awk '{print $1/1024}' for i = 1 and awk '{print $2/1024}' for i = 2

fmt.Sprintf takes a format string and the arguments to pass into this string and returns the formatted string. (https://golang.org/pkg/fmt/#Sprintf)

And this needs to be inserted into your exec-command:

i := 2
awkPart := fmt.Sprintf("awk '{print $%d/1024}'", i)
out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | "+awkPart+" | tee -a mem_usage.csv").Output()

You should maybe try to disassemble your command a bit more for maintainabilty, but that's not part of the question.


答:
1 .Use initializer lists for constructor like, Matrix (...) : r(_r), c(_c)

2.operator + can be simply { return this->Add(M) } (assuming that typenames T and U are compatible and you have implemented some Add() method).
3. If you are constructing something from 2D array then use below technique:

```<code>template<typename T>
class Matrix {
public: // ...
  void Construct (T *arr)
  {
    mat.resize(r);
    for(int i=0;i<r;i++)
      for(int j=0;j<c;j++)
        mat[i].push_back(arr[i*c+j]);
  }
  template<size_t ROW, size_t COL>
  Matrix(T (&arr)[ROW][COL]) : r(ROW), c(COL)
  {
    Construct(arr);
  }
//...
};
</code>```

Thus you don't have to pass the size of the 2D array when you are calling and it will reduce the probability of errors.

For better readability, you can use better names for class members: either this->r or t_r.

Title: C++ Matrix Class - Suggestions

Body:
1 .Use initializer lists for constructor like, Matrix (...) : r(_r), c(_c)

2.operator + can be simply { return this->Add(M) } (assuming that typenames T and U are compatible and you have implemented some Add() method).
3. If you are constructing something from 2D array then use below technique:

template<typename T>
class Matrix {
public: // ...
  void Construct (T *arr)
  {
    mat.resize(r);
    for(int i=0;i<r;i++)
      for(int j=0;j<c;j++)
        mat[i].push_back(arr[i*c+j]);
  }
  template<size_t ROW, size_t COL>
  Matrix(T (&arr)[ROW][COL]) : r(ROW), c(COL)
  {
    Construct(arr);
  }
//...
};

Thus you don't have to pass the size of the 2D array when you are calling and it will reduce the probability of errors.

For better readability, you can use better names for class members: either this->r or t_r.


问:
Embed Power BI Reports in Oracle JET
I have initiated a 60 day trial version of Power BI . I have 2 questions here

1) Is that Trial Version enough to do a small POC on integrating Power BI with Oracle JET

2)Basically I have a Javascript Client Framework Oracle JET where i need to embed the Power BI report Any Document where i can initiate the development as i am very new to this

Thanks

Vikram

答: 60 days trial is enough for any POC but it again it depends on the individual. You can refer to Oracle JET Cookbook which itself makes it easy for developers to start. </p>

Title: Embed Power BI Reports in Oracle JET


问:
Check if variable is a standard type function in Python
I'm looking for a way to catch all the std type functions in Python (int, str, xrange, etc).

Basically anything which has a repr that looks like <type X> instead of <class X>. Here's a full list of all std types in Python 2:
https://docs.python.org/2/library/stdtypes.html

If I use isinstance(X, type) or type(X) == type, it also catches all classes too, but I only want to detect type functions (or any names that's assigned to one of them (i.e. my_int = int).

The only idea that comes to my mind is checking if X.__name__ is in __builtins__ but I'm not sure if that's a clean nor correct solution.

答:
To check if a variable is a class or a builtin type, use inspect module.

```<code>>>> from inspect import isclass
>>> isclass(object)
True
>>> isclass(5)
False
>>> isclass(int)
True
</code>```

Alternatively, try type(). Works both for Python 2.75 and 3.

```<code>>>> type(int) is type(type)
True
</code>```

I didn't understand what you mean by "std type functions", I think they may be called just types.

Body:
To check if a variable is a class or a builtin type, use inspect module.

>>> from inspect import isclass
>>> isclass(object)
True
>>> isclass(5)
False
>>> isclass(int)
True

Alternatively, try type(). Works both for Python 2.75 and 3.

>>> type(int) is type(type)
True

I didn't understand what you mean by "std type functions", I think they may be called just types.


问:
Why repository.delete( entity_with_id_null) kicks off SQL INSERT + DELETE
Why repository.delete( entity_With_Null_Id) kicks off SQL INSERT + DELETE

Using a repository and trying to delete an Entity with id==null kicks off 2 unnecessary SQL orders and no exception !

```<code>    @Test
    public void removeWithIdNull() {

        // ARRANGE
        Info infoWithIdNull = new Info("entity with id null");
        List<Info> listA = infoRepository.findAll();
        assertThat(listA, hasSize(0));

        // ACT
        infoRepository.delete(infoWithIdNull);

        // ASSERT
        List<Info> listResult = infoRepository.findAll();
        assertThat(listResult, hasSize(0));

    }
</code>```

This generates the following SQLs :
An INSERT and then a DELETE =>

```<code>    DEBUG org.hibernate.SQL - insert into info (message, version, id) values (?, ?, ?)
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [entity with id null]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [3] as [BIGINT] - [10]

    DEBUG org.hibernate.SQL - delete from info where id=? and version=?
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [BIGINT] - [10]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]
</code>```

this really annoys me, why does Spring-Data-JPA does not check that the entity exists before deleting it, instead of doing a merge() ..

Code in Data-JPA SimpleJpaRepository which explains this behaviour:

```<code>    @Transactional
    public void delete(T entity) {

        Assert.notNull(entity, "The entity must not be null!");
        em.remove(em.contains(entity) ? entity : em.merge(entity));
    }
</code>```

this code seems over-simplified to me.
What do you think ?

答:
I ended up posting on JIRA and the problem is now FIXED in version spring-data-jpa 2.2.
It was considered a real problem.
https://jira.spring.io/browse/DATAJPA-1535</p>

Body:
Why repository.delete( entity_With_Null_Id) kicks off SQL INSERT + DELETE

Using a repository and trying to delete an Entity with id==null kicks off 2 unnecessary SQL orders and no exception !

    @Test
    public void removeWithIdNull() {

        // ARRANGE
        Info infoWithIdNull = new Info("entity with id null");
        List<Info> listA = infoRepository.findAll();
        assertThat(listA, hasSize(0));

        // ACT
        infoRepository.delete(infoWithIdNull);

        // ASSERT
        List<Info> listResult = infoRepository.findAll();
        assertThat(listResult, hasSize(0));

    }

This generates the following SQLs :
An INSERT and then a DELETE =>

    DEBUG org.hibernate.SQL - insert into info (message, version, id) values (?, ?, ?)
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [entity with id null]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [3] as [BIGINT] - [10]

    DEBUG org.hibernate.SQL - delete from info where id=? and version=?
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [BIGINT] - [10]
    TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]

this really annoys me, why does Spring-Data-JPA does not check that the entity exists before deleting it, instead of doing a merge() ..

Code in Data-JPA SimpleJpaRepository which explains this behaviour:

    @Transactional
    public void delete(T entity) {

        Assert.notNull(entity, "The entity must not be null!");
        em.remove(em.contains(entity) ? entity : em.merge(entity));
    }

this code seems over-simplified to me.
What do you think ?


问:
How to read every Integers in a line from a file in Java?
I have file that has n lines of Integers. I want to add each int in each line and print them (so I should print 3 int at the end, each one for a line).

I tried this but it will read and add all the Integers in the first loop.

```<code>scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
    while (scan.hasNextLine()) {
         sum += scan.nextInt();
    }
    System.out.println(sum);
    sum = 0;
}
</code>```

答:
I think I could do this too...</p>

```<code>read = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = read.nextInt(), j;
int sum = 0;
for (int i = 0; i < n; i++)
{
    String[] str;
    int t = read.nextInt();
    // First str will be ""(it reads the end of each line)
    str = read.nextLine().split(" ");
    // Then it can read what we want
    str = read.nextLine().split(" ");
    for (j = 0; j < str.length; j++)
    {
        sum += Integer.parseInt(str[j]);
    }
    System.out.println(sum);
    sum = 0;
}
</code>```

Body:
I have file that has n lines of Integers. I want to add each int in each line and print them (so I should print 3 int at the end, each one for a line).

I tried this but it will read and add all the Integers in the first loop.

scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
    while (scan.hasNextLine()) {
         sum += scan.nextInt();
    }
    System.out.println(sum);
    sum = 0;
}

Body:
I think I could do this too...

read = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = read.nextInt(), j;
int sum = 0;
for (int i = 0; i < n; i++)
{
    String[] str;
    int t = read.nextInt();
    // First str will be ""(it reads the end of each line)
    str = read.nextLine().split(" ");
    // Then it can read what we want
    str = read.nextLine().split(" ");
    for (j = 0; j < str.length; j++)
    {
        sum += Integer.parseInt(str[j]);
    }
    System.out.println(sum);
    sum = 0;
}


问:
Disable\Enable multiple checkboxes in Kendo UI TreeList
I tried these solutions for disable\enable multiple checkboxes in Kendo UI TreeList when header checkbox is clicked:

1.prop('disabled',true) \ prop('disabled',false)

2.attr('disabled','disabled') \ removeAttr('disabled');

3.$(...)[0].disabled=true \ $(...)[0].disabled=false

But all of them has the same problem which affects just the last item in the TreeList !!!

I really confused and don't know what is going wrong, is it possible to be resolved?

答:
Use jQuery.each() to iterate over all your checkboxes.

For the checking itself, prop is the way to go.


问:
How to export results into a table continuously?
I've exported a dataset from Jan to Dec to a working directory and wanted to follow such one table by other new data with the same heading.

I've tried to export the dataset one by one and then combined all of them together into a single file.

```<code>a1 = getdata(Jan,Feb) ## data from Jan to Feb

write.table(a1,file="D:/q1.csv",sep=",")

a2 = getdata(Mar,Apr) ## data from Mar to Apr

write.table(a2,file="D:/q1.csv",sep=",")

# then I combined all the data in the excel.

</code>```

My trial is inefficient.

答:
You can merge your data in R before you export it</p>

```<code>a <- rbind(a1,a2)
write.table(a,file="",sep=",")
</code>```

Body:
I've exported a dataset from Jan to Dec to a working directory and wanted to follow such one table by other new data with the same heading.

I've tried to export the dataset one by one and then combined all of them together into a single file.

a1 = getdata(Jan,Feb) ## data from Jan to Feb

write.table(a1,file="D:/q1.csv",sep=",")

a2 = getdata(Mar,Apr) ## data from Mar to Apr

write.table(a2,file="D:/q1.csv",sep=",")

# then I combined all the data in the excel.

My trial is inefficient.

Body:
You can merge your data in R before you export it

a <- rbind(a1,a2)
write.table(a,file="",sep=",")


答:
IIUC,

Assume csv1, csv2 imported to pandas as df1, df2. Find matching columns using intersection on columns and sort it. Passing it to df1 and df2. Finally, eq on this sub-set of matching columns of df1 and df2

```<code>matched_list = df1.columns.intersection(df2.columns).sort_values()
df1_mask = df1[matched_list].eq(df2[matched_list])

Out[853]:
   Availability (%)  Domain  Hypervisor     IP  Last Collection Time  Memory  \
0              True    True        True  False                  True    True
1              True    True        True   True                  True    True
2              True    True        True   True                  True    True
3              True    True        True   True                  True    True
4              True    True        True   True                  True    True
5             False   False       False  False                 False   False

   No. CPU  Operating System
0     True              True
1     True              True
2     True              True
3     True              True
4     True              True
5    False             False
</code>```

Note: I change df1.loc[0, 'IP'] to 10.247.52.124 to show False in one value of row 0 of df1 for demonstration

From this df1_mask, you may plug it to df1 to check for NaN. Any NaN is either original value NaN or it is changed between df1 and df2

```<code>df1[df1_mask]

Out[854]:
         Hypervisor             IP                 Operating System   Domain  \
0  lglac125.lss.com            NaN  VMware ESXi 5.5.0 build-9919047  lss.com
1  lglac126.lss.com  10.247.52.126  VMware ESXi 5.5.0 build-9919047  lss.com
2  lglac127.lss.com  10.247.52.127  VMware ESXi 5.5.0 build-9919047  lss.com
3  lglac128.lss.com  10.247.52.128  VMware ESXi 5.5.0 build-9919047  lss.com
4  lglac129.lss.com  10.247.52.129  VMware ESXi 5.5.0 build-9919047  lss.com

         Memory  No. CPU  Availability (%)  Last Collection Time  lol
0  524278.03125      4.0             100.0          1.558599e+09  NaN
1  524278.03125      4.0             100.0          1.558600e+09  NaN
2  524278.03125      4.0               0.0          1.558599e+09  NaN
3  524278.03125      4.0             100.0          1.558600e+09  NaN
4  524278.03125      4.0             100.0          1.558600e+09  NaN
</code>```

Note: your df1 has column lol but no value, so it is originally NaN

Or You can check on df2

```<code>df2[df1_mask]

Out[855]:
         Hypervisor             IP  Arrays                 Operating System  \
0  lglac125.lss.com            NaN     NaN  VMware ESXi 5.5.0 build-9919047
1  lglac126.lss.com  10.247.52.126     NaN  VMware ESXi 5.5.0 build-9919047
2  lglac127.lss.com  10.247.52.127     NaN  VMware ESXi 5.5.0 build-9919047
3  lglac128.lss.com  10.247.52.128     NaN  VMware ESXi 5.5.0 build-9919047
4  lglac129.lss.com  10.247.52.129     NaN  VMware ESXi 5.5.0 build-9919047
5               NaN            NaN     NaN                              NaN

    Domain        Memory  No. CPU  Availability (%)  Last Collection Time  \
0  lss.com  524278.03125      4.0             100.0          1.558599e+09
1  lss.com  524278.03125      4.0             100.0          1.558600e+09
2  lss.com  524278.03125      4.0               0.0          1.558599e+09
3  lss.com  524278.03125      4.0             100.0          1.558600e+09
4  lss.com  524278.03125      4.0             100.0          1.558600e+09
5      NaN           NaN      NaN               NaN                   NaN

  DummyColumn
0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
</code>```

Title: How to compare all entries in columns of 2 csv files (csv1 and csv2) in python/pandas?

Body:
I have 2 CSV files:

CSV1:

"Hypervisor","IP","ABCD","Operating System","Domain","Memory","No. CPU","Availability (%)","Last Collection Time","lol"
"lglac125.lss.com","10.247.52.125","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599031E9"
"lglac126.lss.com","10.247.52.126","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"
"lglac127.lss.com","10.247.52.127","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","0.0","1.558599031E9"
"lglac128.lss.com","10.247.52.128","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"
"lglac129.lss.com","10.247.52.129","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"

CSV2:

"Hypervisor","IP","Arrays","Operating System","Domain","Memory","No. CPU","Availability (%)","Last Collection Time","DummyColumn"
"lglac125.lss.com","10.247.52.125",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599031E9","A"
"lglac126.lss.com","10.247.52.126",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","B"
"lglac127.lss.com","10.247.52.127",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","0.0","1.558599031E9","C"
"lglac128.lss.com","10.247.52.128",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","D"
"lglac129.lss.com","10.247.52.129",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","E"
"DummyRow","10.247.52.129",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","F"

I am trying to compare all the entries of each column (if available in csv2), with corresponding rows. If there is any entry missing or changed, i need to raise a flag. There could be possibility of add or removal of any column in both the files. So i need to first check if the column x is there in csv2 and then match the entry for the same column from csv1.

I've been struggling with this for three days now and couldn't come to a solution. I highly appreciate any help.

Body:
IIUC,

Assume csv1, csv2 imported to pandas as df1, df2. Find matching columns using intersection on columns and sort it. Passing it to df1 and df2. Finally, eq on this sub-set of matching columns of df1 and df2

matched_list = df1.columns.intersection(df2.columns).sort_values()
df1_mask = df1[matched_list].eq(df2[matched_list])

Out[853]:
   Availability (%)  Domain  Hypervisor     IP  Last Collection Time  Memory  \
0              True    True        True  False                  True    True
1              True    True        True   True                  True    True
2              True    True        True   True                  True    True
3              True    True        True   True                  True    True
4              True    True        True   True                  True    True
5             False   False       False  False                 False   False

   No. CPU  Operating System
0     True              True
1     True              True
2     True              True
3     True              True
4     True              True
5    False             False

Note: I change df1.loc[0, 'IP'] to 10.247.52.124 to show False in one value of row 0 of df1 for demonstration

From this df1_mask, you may plug it to df1 to check for NaN. Any NaN is either original value NaN or it is changed between df1 and df2

df1[df1_mask]

Out[854]:
         Hypervisor             IP                 Operating System   Domain  \
0  lglac125.lss.com            NaN  VMware ESXi 5.5.0 build-9919047  lss.com
1  lglac126.lss.com  10.247.52.126  VMware ESXi 5.5.0 build-9919047  lss.com
2  lglac127.lss.com  10.247.52.127  VMware ESXi 5.5.0 build-9919047  lss.com
3  lglac128.lss.com  10.247.52.128  VMware ESXi 5.5.0 build-9919047  lss.com
4  lglac129.lss.com  10.247.52.129  VMware ESXi 5.5.0 build-9919047  lss.com

         Memory  No. CPU  Availability (%)  Last Collection Time  lol
0  524278.03125      4.0             100.0          1.558599e+09  NaN
1  524278.03125      4.0             100.0          1.558600e+09  NaN
2  524278.03125      4.0               0.0          1.558599e+09  NaN
3  524278.03125      4.0             100.0          1.558600e+09  NaN
4  524278.03125      4.0             100.0          1.558600e+09  NaN

Note: your df1 has column lol but no value, so it is originally NaN

Or You can check on df2

df2[df1_mask]

Out[855]:
         Hypervisor             IP  Arrays                 Operating System  \
0  lglac125.lss.com            NaN     NaN  VMware ESXi 5.5.0 build-9919047
1  lglac126.lss.com  10.247.52.126     NaN  VMware ESXi 5.5.0 build-9919047
2  lglac127.lss.com  10.247.52.127     NaN  VMware ESXi 5.5.0 build-9919047
3  lglac128.lss.com  10.247.52.128     NaN  VMware ESXi 5.5.0 build-9919047
4  lglac129.lss.com  10.247.52.129     NaN  VMware ESXi 5.5.0 build-9919047
5               NaN            NaN     NaN                              NaN

    Domain        Memory  No. CPU  Availability (%)  Last Collection Time  \
0  lss.com  524278.03125      4.0             100.0          1.558599e+09
1  lss.com  524278.03125      4.0             100.0          1.558600e+09
2  lss.com  524278.03125      4.0               0.0          1.558599e+09
3  lss.com  524278.03125      4.0             100.0          1.558600e+09
4  lss.com  524278.03125      4.0             100.0          1.558600e+09
5      NaN           NaN      NaN               NaN                   NaN

  DummyColumn
0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN


问:
Xamarin axml Linear layout put icon on bottom of screen
I am new to Xamarin axml , how do i place image button on below of screen as this picture show.

This is my current AXML code

```<code>    <?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "vertical"
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <TextView
        android:text = "@string/HelloXamarin"
        android:textAppearance = "?android:attr/textAppearanceLarge"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:id = "@+id/textView1" />
    <Button
        android:id = "@+id/MyButton"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:text = "@string/ButtonClick" />
    <Button
        android:text="CALL"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonCall" />

</LinearLayout>
</code>```

答:
The best approach for doing this would be to use a RelativeLayout instead,
Something like this :</p>

```<code><RelativeLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent">
 <LinearLayout
   android:orientation = "vertical"
   android:layout_alignParentTop="true"
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content">
   <TextView
    android:text = "@string/HelloXamarin"
    android:textAppearance = "?android:attr/textAppearanceLarge"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:id = "@+id/textView1" />
<Button
    android:id = "@+id/MyButton"
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:text = "@string/ButtonClick" />
<Button
    android:text="CALL"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonCall" />
</LinearLayout>
<ImageView
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_margin="5dp"
android:src="@drawable/imageName"
</RelativeLayout>
</code>```

Body:
I am new to Xamarin axml , how do i place image button on below of screen as this picture show.

This is my current AXML code

    <?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    android:orientation = "vertical"
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <TextView
        android:text = "@string/HelloXamarin"
        android:textAppearance = "?android:attr/textAppearanceLarge"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:id = "@+id/textView1" />
    <Button
        android:id = "@+id/MyButton"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:text = "@string/ButtonClick" />
    <Button
        android:text="CALL"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ButtonCall" />

</LinearLayout>

Body:
The best approach for doing this would be to use a RelativeLayout instead,
Something like this :

<RelativeLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent">
 <LinearLayout
   android:orientation = "vertical"
   android:layout_alignParentTop="true"
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content">
   <TextView
    android:text = "@string/HelloXamarin"
    android:textAppearance = "?android:attr/textAppearanceLarge"
    android:layout_width = "match_parent"
    android:layout_height = "wrap_content"
    android:id = "@+id/textView1" />
<Button
    android:id = "@+id/MyButton"
    android:layout_width = "fill_parent"
    android:layout_height = "wrap_content"
    android:text = "@string/ButtonClick" />
<Button
    android:text="CALL"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ButtonCall" />
</LinearLayout>
<ImageView
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_margin="5dp"
android:src="@drawable/imageName"
</RelativeLayout>


问:
cannot determine the module for component angular 5
I'm getting following error when I build the Angular app using "ng build --prod". This is working when I build with Angular 4 and getting error with Angular 5. With Angular 5 "ng serve" is working perfectly.

ERROR in Error: Cannot determine the module for class TimeAgoPipe in mypath/node_modules/time-ago-pipe/time-ago-pipe.ts! Add TimeAgoPipe to the NgModule to fix it.

Getting error for https://www.npmjs.com/package/time-ago-pipe

Any solutions ?

答:
Import specific component.

Add component to @NgModule.


问:
Added more than 20 tableviewcells but after that not able to scroll tableview to see all cells in jonkykong/SideMenu iOS demo application
Implementing side menu in iOS application using jonkykong/SideMenu library. When i am trying to add more than 20 cells in tableview, after that we cant scroll tableview up.

Check source code:
https://github.com/jonkykong/SideMenu

Expected result:
We can scroll tableview up if more cells are there.

答:
If you are facing this issue on storyboard then increase the height of UIViewController using the following steps:

Click on UIViewController -> Select the size inspector -> Select simulated Size as Freeform -> increase height value.


问:
Siri Intent Query input field not available when editing Intent scheme in xcode
I am writing an app extension for Siri Shortcuts. I'd like to debug it in Xcode and use the option to specify the Siri Intent Query phrase in Run options in Xcode, but the edit field does not show up.

This is the input field I am looking for:

And for my Intent App Extension it is not visible:

I did restart Xcode but it did not help.

I'm using Xcode 10.2.1. I remember using this option in an older Xcode version.

Do you have any ideas?

答: Ok I found the problem. You have to at least once run the Intent inside Siri (set Executable to 'Ask on Launch' and choose Siri when prompted). When you enter the 'Edit Scheme' dialog again, the option appears.</p>


问:
when try to add dynamic file name (linked server) in azure data factory V2 error encountered
I am new to the Azure Data factory V2 and blob storage.
When try to add the file connection(linked server) in copy data from blob storage dynamically the following error is encountered while trying to map the columns by importing the schema from file

"Failed to convert the value in 'container' property to 'System.String' type. Please make sure the payload structure and value are correct.."

I tried:

used static parameters and assign the static parameters to the linked connection

答:
Please refer to my working steps:

1.Configuration of Azure Blob Storage Source DataSet:

parameters:

2.Configuration of Azure Blob Storage Sink DataSet:

3.Configuration of Copy Activity,you could modify the value of parameters here:

4.Result:


问:
Sorting inputted integers into odd and even arrays
I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.

This is my code, I don't understand my mistake.

```<code>int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};

printf("Enter amount of numbers: ");  // asking user for amount of numbers
    scanf("%d", &d);

for (j=0; j<d; j++){
    printf("Enter number %d: ", i+1); // scanning input into 'x' array
        scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
    if (x[i] % 2 == 0) {              // sorting into even array
        even[i]=x[i];
        printf("%d \n", even[i]);
    }
}
    printf("\n Odd numbers: ");
for (i=0; i<d;i++){
    if (x[i] % 2 != 0) {              // sorting into odd array
        odd[i]=x[i];
        printf("%d \n", odd[i]);
    }
}
</code>```

This error message keeps coming up:

```<code>$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
</code>```

答:
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:

```<code>int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
</code>```

You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).

scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:

```<code>for (j = 0; j < d; j++) {
    printf("Enter number %d: ", j + 1); // scanning input into 'x' array
    scanf("%d", &x[j]);
}
</code>```

Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

Body:
I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.

This is my code, I don't understand my mistake.

int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};

printf("Enter amount of numbers: ");  // asking user for amount of numbers
    scanf("%d", &d);

for (j=0; j<d; j++){
    printf("Enter number %d: ", i+1); // scanning input into 'x' array
        scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
    if (x[i] % 2 == 0) {              // sorting into even array
        even[i]=x[i];
        printf("%d \n", even[i]);
    }
}
    printf("\n Odd numbers: ");
for (i=0; i<d;i++){
    if (x[i] % 2 != 0) {              // sorting into odd array
        odd[i]=x[i];
        printf("%d \n", odd[i]);
    }
}

This error message keeps coming up:

$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)

Body:
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:

int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0

You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).

scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:

for (j = 0; j < d; j++) {
    printf("Enter number %d: ", j + 1); // scanning input into 'x' array
    scanf("%d", &x[j]);
}

Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.


问:
Create an empty object/array, based on an existing object/array
I'm writing a function that takes as an argument either an object or an array, and I want to create a new, empty copy of it and populate it with transformed data from the original object.

I'm wondering if there's a way to make this new object/array simply, without having to test what type the thing is and act appropriately.

The 'long' way is currently to do:

```<code>const transf = (thing) => {
  if (typeof(thing) === 'array') {
    const new = []
  }  else {
    const new = {}
  }
}
</code>```

I'm hoping there's a nice 'builtin' way I can do something like:

```<code>const transf = (thing) => {
  const new = thing.emptyCopy()
}
</code>```

I've looked at Object.create but that always makes an object (even if the prototype is an array), and typeof returns a string, which can't be used with e.g. new etc.

Is there a shorthand way to do this, or am I out of luck?

答:
You can use constructor property of thing. And don't use new as variable name.

```<code>const transf = (thing) => {
  const newelm = new thing.constructor()
}
</code>```

Demo:

const transf = (thing) => {
  return new thing.constructor()
}

console.log(transf(['arra']))
console.log(transf({key:'value'}))```

Body:
I'm writing a function that takes as an argument either an object or an array, and I want to create a new, empty copy of it and populate it with transformed data from the original object.

I'm wondering if there's a way to make this new object/array simply, without having to test what type the thing is and act appropriately.

The 'long' way is currently to do:

const transf = (thing) => {
  if (typeof(thing) === 'array') {
    const new = []
  }  else {
    const new = {}
  }
}

I'm hoping there's a nice 'builtin' way I can do something like:

const transf = (thing) => {
  const new = thing.emptyCopy()
}

I've looked at Object.create but that always makes an object (even if the prototype is an array), and typeof returns a string, which can't be used with e.g. new etc.

Is there a shorthand way to do this, or am I out of luck?

Body:
You can use constructor property of thing. And don't use new as variable name.

const transf = (thing) => {
  const newelm = new thing.constructor()
}

Demo:

const transf = (thing) => {
  return new thing.constructor()
}

console.log(transf(['arra']))
console.log(transf({key:'value'}))


问:
kubernetes can't pull image from private docker registry
to reproduce this case, i follow those tutorials first:

DOCKER - part

part 1

part 2

part 3

part 4

( ... All those parts was done on a ubuntu 18 virtual machine ... )

After those tutorials, this is the result:

Here you can see all the step in order to make it works on my local machine (mac os - Mojave)

KUBERNETES - part

I follow this tutorial:

part 1

And you will see the error on the next image:

All those steps are don on my local machine (mac os - Mojave)

I don't know what is the problem.
I don't know how to solve this

Can somebody help me with this, please?

I really want to understand this

Really thanks

答:
You want to pull it from local repo which is not https, add configuration to allow pull from insecure repository. find docker.conf file which for me is in this path <code>/etc/systemd/system/docker.service.d/docker.conf</code> and add below line </p>

```<code>[Service]
ExecStart=/usr/bin/dockerd -H fd:// --insecure-egistry=<repo-address>:<port>
</code>```

Body:
You want to pull it from local repo which is not https, add configuration to allow pull from insecure repository. find docker.conf file which for me is in this path /etc/systemd/system/docker.service.d/docker.conf and add below line

[Service]
ExecStart=/usr/bin/dockerd -H fd:// --insecure-egistry=<repo-address>:<port>


问:
how format date to multiple fields in the model in the rails app?
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

```<code> def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end
</code>```

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

答:
you can config active record default to this format but I suggest following solution. so you can format your date all around of application easily.

monkey patch Date class like this:

```<code># config/initializers/date.rb

class Date
  def to_fd
    strftime('%m/%d/%Y')
  end
end
</code>```

usage:

```<code>Date.today.to_fd
=> "05/28/2019"
</code>```

Body:
I have a form in rails that has a date field with input mask with format mm/dd/yyyy, but at the moment to save it, I am getting an error because of the format in the model is dd/mm/yyyy. I found a solution that maybe can work.

 def organization_date=(val)
   date = Date.strptime(val, “%m/%d/%Y”) if val.present?
   write_attribute(:organization_date, date)
 end

but I need one solution more elegant because I have more field of type date, and I can't do that for each field and updating the format to input mask to dd/mm/yyyy is not an option either because the client's requirement is that it be in the format mm/dd/yyyy

I am using Rails 6.0 beta

I'm grateful for any ideas that help solve this problem

Body:
you can config active record default to this format but I suggest following solution. so you can format your date all around of application easily.

monkey patch Date class like this:

# config/initializers/date.rb

class Date
  def to_fd
    strftime('%m/%d/%Y')
  end
end

usage:

Date.today.to_fd
=> "05/28/2019"


问:
How to get the most recent file using a batch file?
I have a list of zip files with date and time appended like yyyymmdd_hhmmss_Demos.zip. Now how to get the most recently added zip file in the source dir. I need to copy this file in the target using copy command.

I found some info about forfiles, but do not have an idea on how to get it done for seconds.

答:
```<code>set Path="D:\hello\abc\old"
for /f "tokens=*" %%a in ('dir /A:-D /B /O:-D /S %Path%') do set NEW=%%a&& goto:n
:n
echo %NEW%
</code>```


问:
Contact Form 7 always redirecting to the same page when submit
I have use this plugin in all the web sites I worked. I used it for my current site as well with latest wordpress. But I am getting following error.

Instead of jQuery submission it is redirecting the page and this hash “#wpcf7-f1693-o1” appending to the URL. If I fill correctly and submit, mail is sending fine except this hash appending and page redirecting issue.

Why it is redirecting and appending the hash (form ID/action) to the current URL.

Assume I am submitting my contact us form. Then the resulting URL is contact-us/#wpcf7-f1693-o1

Thanks

答:
it seems like you are using your contact form short-code inside html form tag
remove form-tag then it should be working</p>


问:
how to override django save method to update some field dynamically?
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

```<code>     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)
</code>```

答:
Best thing is you override the call in save method any way you have foreginkey.</p>

```<code>    def save(self, *args, **kwargs):
        #self.date_created = timezone.now()
        # YOUR LOGIC HERE
        super(YOUR_OVERRIDING_MODEL , self).save(*args, **kwargs
</code>```

Body:
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)

Body:
Best thing is you override the call in save method any way you have foreginkey.

    def save(self, *args, **kwargs):
        #self.date_created = timezone.now()
        # YOUR LOGIC HERE
        super(YOUR_OVERRIDING_MODEL , self).save(*args, **kwargs


问:
How to destroy the previous frame open opening a new frame
I am building an application in java that has 2 JFrames. 1st frame has a button that upon clicking should open the next JFrame while the previous one should close. I know how to display the next frame but:
How do I close the previous JFrame automatically when the next JFrame opens ?

I tried thie following code:

```<code>addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new GUI();//next frame
                                this.dispose();//compile-time-error
            }
</code>```

答: Where you call this.dispose(), the object referred by this is an instance of ActionListener. To invoke the instance of GUI type GUI.this.dispose() instead.

Body:
I am building an application in java that has 2 JFrames. 1st frame has a button that upon clicking should open the next JFrame while the previous one should close. I know how to display the next frame but:
How do I close the previous JFrame automatically when the next JFrame opens ?

I tried thie following code:

addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new GUI();//next frame
                                this.dispose();//compile-time-error
            }


问:
Multiple check box options in ReactJS
I'm pretty new with react and I was having problems with creating check boxes for my application. I was able to setup something that works for only one checkbox option, however the problem I have now is for multiple check box options.

Whenever I click on one checkbox, it automatically selects all other check boxes

Here's the code I'm currently working on.

```<code>import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple' }, { id: 2, answer: 'Bananas' }, { id: 3, answer: 'Oranges' }],
            isChecked: false,
        };
        this.state = initialState;
    }

    handleCheckbox() {
        this.setState({
            isChecked: !this.state.isChecked
        })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox()}

                                    checked={this.state.isChecked}

                                    key={e.id}
                                />

                                {e.answer}
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}
</code>```

答:
You have to change your code as per below:  </p>

```<code>import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple', isChecked: false }, { id: 2, answer: 'Bananas', isChecked: false }, { id: 3, answer: 'Oranges', isChecked: false }],
       };
        this.state = initialState;
    }

    handleCheckbox(id) {
       const modifiedOptions = [...this.state.options];
       modifiedOptions[id].isChecked = !modifiedOptions[id].isChecked;

    this.setState({
        options: modifiedOptions
    })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox(e.id)}

                                    checked={e.isChecked}

                                    key={e.id}
                                />

                                {e.answer}
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}
</code>```

Title: Multiple check box options in ReactJS

Body:
I'm pretty new with react and I was having problems with creating check boxes for my application. I was able to setup something that works for only one checkbox option, however the problem I have now is for multiple check box options.

Whenever I click on one checkbox, it automatically selects all other check boxes

Here's the code I'm currently working on.

import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple' }, { id: 2, answer: 'Bananas' }, { id: 3, answer: 'Oranges' }],
            isChecked: false,
        };
        this.state = initialState;
    }

    handleCheckbox() {
        this.setState({
            isChecked: !this.state.isChecked
        })
    }

    render() {
        return (

                {
                    [...this.state.options].map((e, i) => {
                        return (

                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox()}

                                    checked={this.state.isChecked}

                                    key={e.id}
                                />

                                {e.answer}

                        )
                    })
                }

        )

    }

}

Body:
You have to change your code as per below:

import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple', isChecked: false }, { id: 2, answer: 'Bananas', isChecked: false }, { id: 3, answer: 'Oranges', isChecked: false }],
       };
        this.state = initialState;
    }

    handleCheckbox(id) {
       const modifiedOptions = [...this.state.options];
       modifiedOptions[id].isChecked = !modifiedOptions[id].isChecked;

    this.setState({
        options: modifiedOptions
    })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox(e.id)}

                                    checked={e.isChecked}

                                    key={e.id}
                                />

                                {e.answer} &nbsp;
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}


问:
how to map violation to Symfony form manually?
OrderType

```<code>$builder
    ->add('items', FormTypes\CollectionType::class, [
        'entry_type' => OrderItemType::class,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false,
        'label' => 'acme.form.order.items',
    ])
    ->add('channel', ChannelSelectType::class, [
        'required' => true,
        'label' => 'acme.form.order.channel',
    ])
</code>```

OrderItemType

```<code>$builder
    ->add('service', ServiceSelectType::class, [
        'label' => 'acme.form.order_item.service',
    ])
    ->add('product', ProductSelectType::class, [
        'label' => 'acme.form.order_item.product',
    ])
    ->add('quantity', FormTypes\IntegerType::class, [
        'label' => 'acme.form.order_item.quantity',
    ]);
</code>```

How to map the error to OrderItemType product field?

the order item is valid when a product is applied to a specific channel. however we have no way to get the submited channel in OrderItemType,
because child form type is submmited before its parent. so $event->getForm()->getParent()->getData()->getChannel() is empty. the only way I have
is to validate order item in OrderType, or create a validator which is added to Order class. the problem is how can I map the error to OrderItemType product field.

```<code>$orderItems = $order->getItems();
$channel = $order->getChannel();

foreach($orderItems as $index => $orderItem) {
    $product = $orderItem->getProduct();
    if (!$this->isProductAvailableForChannel($channel, $product)) {
        $message = sprintf('product %ss is not available for channel "%s"', $product->getName(), $channel->getName());
    }

    if (null !== $message) {
        $this->context
                ->buildViolation($this->constraint->message)
                ->setParameter($message)
                ->atPath("items.children[$index].product")  // this doesn't work, the error will be added to root form.
                ->addViolation()
            ;
    }
}
</code>```

答:
You are able to get the channel on the pre submit event (Symfony\Component\Form\FormEvents::PRE_SUBMIT)
And there you can add your channel based validation for the order item

```<code>$addItems = function (FormEvent $event) {
    $data = $event->getData();
    $form = $event->getForm();

    $options = [];

    if (is_array($data) && array_key_exists('channel', $data)) {
        $options['constraints'] = [
            new OrderItemConstraint(['channel' => $data['channel']])
        ];
    }

    $form->add('items', FormTypes\CollectionType::class, [
        'entry_type' => OrderItemType::class,
        'entry_options' => $options,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false,
        'label' => 'acme.form.order.items',
    ]);
};

$builder->addEventListener(FormEvents::PRE_SET_DATA, $addItems);
$builder->addEventListener(FormEvents::PRE_SUBMIT, $addItems);
</code>```

Body:
OrderType

$builder
    ->add('items', FormTypes\CollectionType::class, [
        'entry_type' => OrderItemType::class,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false,
        'label' => 'acme.form.order.items',
    ])
    ->add('channel', ChannelSelectType::class, [
        'required' => true,
        'label' => 'acme.form.order.channel',
    ])

OrderItemType

$builder
    ->add('service', ServiceSelectType::class, [
        'label' => 'acme.form.order_item.service',
    ])
    ->add('product', ProductSelectType::class, [
        'label' => 'acme.form.order_item.product',
    ])
    ->add('quantity', FormTypes\IntegerType::class, [
        'label' => 'acme.form.order_item.quantity',
    ]);

How to map the error to OrderItemType product field?

the order item is valid when a product is applied to a specific channel. however we have no way to get the submited channel in OrderItemType,
because child form type is submmited before its parent. so $event->getForm()->getParent()->getData()->getChannel() is empty. the only way I have
is to validate order item in OrderType, or create a validator which is added to Order class. the problem is how can I map the error to OrderItemType product field.

$orderItems = $order->getItems();
$channel = $order->getChannel();

foreach($orderItems as $index => $orderItem) {
    $product = $orderItem->getProduct();
    if (!$this->isProductAvailableForChannel($channel, $product)) {
        $message = sprintf('product %ss is not available for channel "%s"', $product->getName(), $channel->getName());
    }

    if (null !== $message) {
        $this->context
                ->buildViolation($this->constraint->message)
                ->setParameter($message)
                ->atPath("items.children[$index].product")  // this doesn't work, the error will be added to root form.
                ->addViolation()
            ;
    }
}

Body:
You are able to get the channel on the pre submit event (Symfony\Component\Form\FormEvents::PRE_SUBMIT)
And there you can add your channel based validation for the order item

$addItems = function (FormEvent $event) {
    $data = $event->getData();
    $form = $event->getForm();

    $options = [];

    if (is_array($data) && array_key_exists('channel', $data)) {
        $options['constraints'] = [
            new OrderItemConstraint(['channel' => $data['channel']])
        ];
    }

    $form->add('items', FormTypes\CollectionType::class, [
        'entry_type' => OrderItemType::class,
        'entry_options' => $options,
        'allow_add' => true,
        'allow_delete' => true,
        'by_reference' => false,
        'label' => 'acme.form.order.items',
    ]);
};

$builder->addEventListener(FormEvents::PRE_SET_DATA, $addItems);
$builder->addEventListener(FormEvents::PRE_SUBMIT, $addItems);


问:
C# WPF Loop & Delete Checked ListView Items
As someone who has recently switched from WinForms to WPF, I'm still struggling and going nuts trying to figure out a way to loop through and delete checked ListView items.

This method gives me error: "ListView does not contain a definition for CheckedItems..."

```<code>    if (lvFilesList != null)
    {
        foreach (ListViewItem lvItem in lvFilesList.CheckedItems)
        {
            lvItem.Checked = False;
        }
    }
</code>```

My XAML Code:

```<code>            <ListView Height="400" Width="400"
              Name="lvFilesList"
              ItemsSource="{Binding}"
              IsSynchronizedWithCurrentItem="True">
                <ListView.View>
                    <GridView>
                        <GridView.Columns>
                            <GridViewColumn>
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                            <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                            <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock FontWeight="Bold" Text="Group"/>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListView.GroupStyle>
            </ListView>
</code>```

答:
It looks odd that the ItemsSource of your ListView is directly bound to the current DataContext by

```<code>ItemsSource="{Binding}"
</code>```

The DataContext would usually hold a view model object with a collection-type property like

```<code>public class Item
{
    public bool IsChecked { get; set; }

    // other properties like ID, File, Author
}

public class ViewModel
{
    public ObservableCollection<Item> Items { get; }
        = new ObservableCollection<Item>();
}
</code>```

and the Binding would be

```<code>ItemsSource="{Binding Items}"
</code>```

Then the view model could have a method that deletes all checked items, like

```<code>public void DeleteCheckedItems()
{
    var checkedItems = Items.Where(item => item.IsChecked).ToList();

    checkedItems.ForEach(item => Items.Remove(item));
}
</code>```

Note that you usually assign an instance of the view model class to the DataContext of your main view, e.g. in the MainWindow constructor:

```<code>private readonly ViewModel viewModel = new ViewModel();

public MainWindow()
{
    InitializeComponent();
    DataContext = viewModel;

    viewModel.Items.Add(new Item { ID = 1, ... });
    viewModel.Items.Add(new Item { ID = 2, ... });
}
</code>```

Body:
As someone who has recently switched from WinForms to WPF, I'm still struggling and going nuts trying to figure out a way to loop through and delete checked ListView items.

This method gives me error: "ListView does not contain a definition for CheckedItems..."

    if (lvFilesList != null)
    {
        foreach (ListViewItem lvItem in lvFilesList.CheckedItems)
        {
            lvItem.Checked = False;
        }
    }

My XAML Code:

            <ListView Height="400" Width="400"
              Name="lvFilesList"
              ItemsSource="{Binding}"
              IsSynchronizedWithCurrentItem="True">
                <ListView.View>
                    <GridView>
                        <GridView.Columns>
                            <GridViewColumn>
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                            <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                            <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock FontWeight="Bold" Text="Group"/>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListView.GroupStyle>
            </ListView>

Body:
It looks odd that the ItemsSource of your ListView is directly bound to the current DataContext by

ItemsSource="{Binding}"

The DataContext would usually hold a view model object with a collection-type property like

public class Item
{
    public bool IsChecked { get; set; }

    // other properties like ID, File, Author
}

public class ViewModel
{
    public ObservableCollection<Item> Items { get; }
        = new ObservableCollection<Item>();
}

and the Binding would be

ItemsSource="{Binding Items}"

Then the view model could have a method that deletes all checked items, like

public void DeleteCheckedItems()
{
    var checkedItems = Items.Where(item => item.IsChecked).ToList();

    checkedItems.ForEach(item => Items.Remove(item));
}

Note that you usually assign an instance of the view model class to the DataContext of your main view, e.g. in the MainWindow constructor:

private readonly ViewModel viewModel = new ViewModel();

public MainWindow()
{
    InitializeComponent();
    DataContext = viewModel;

    viewModel.Items.Add(new Item { ID = 1, ... });
    viewModel.Items.Add(new Item { ID = 2, ... });
}


问:
I get an error when compiling with an imported image resource
This is turning into a nightmare!

I have a C# DLL project and it has the regular About Form. I go to add my own image:

I can see it listed and I accept:

It looks fine:

The moment I compile I get this error:

I have googled the error:

The argument docData must implement the interface IVsTextStream

And it suggests deleting the RES file.

I am confused. I thought this would be a simple exercise and despite several attempts and can't use my own image.

答:
Well, I do not know why the problem was happening. But here is my workaround:

I created a new C# DLL project.

I added the About Form.

I opened the form RESX file in the IDE.

I added the new image.

I set the image as embedded.

I deleted the existing image.

I renamed the new image the same as the old.

I restarted the project and the image showed fine.

I opened the RESX file with NotePad++ and copied the image bit over to my actual project about window RESX file.

It displays and compiles.


问:
Error when creation data source for neo4j in websphere application server
Im trying to create data source for neo4j in websphere application server but its failing to connect. Any pointers on this would be helpful.

JDBC Driver Created with the following parameters:

Name : neo4j Driver

Class path : path of the neo4j jdbc jar/neo4j-jdbc-driver-3.3.1.jar

Implementation class name : org.neo4j.jdbc.Driver

Data source created with the following :

jndi Name: jdbc/neo4j

Custom Properties:

auth : container

type: javax.sql.DataSource

username: neo4j

password: password

url:jdbc:neo4j:bolt://localhost:port

removeAbandonedOnBorrow : true

closeMethod : close

The properties are added based on the pointers provided in https://github.com/neo4j-contrib/neo4j-jdbc

Here is the error from logs:

java.lang.Exception: DSRA8101E: DataSource class cannot be used as
  one-phase: ClassCastException: org.neo4j.jdbc.bolt.BoltDriver
  incompatible with javax.sql.ConnectionPoolDataSource [5/27/19
  13:12:41:533 UTC] 00000111 SystemErr     R     at
  com.ibm.ws.rsadapter.AdapterUtil.createDataStoreAdapterException(AdapterUtil.java:441)
  [5/27/19 13:12:41:533 UTC] 00000111 SystemErr     R     at
  com.ibm.ws.rsadapter.DSConfigHelper.getPooledConnection(DSConfigHelper.java:1340)

答:
According to its documentation  Neo4j is NOT a compliant JDBC driver.

We cover these aspects of the JDBC-APIs, everything that’s not
  explicitely mentioned should be assumed to be not implemented

It also doesn't implement required javax.sql.DataSoruce interface, so it cannot be configured in the server. You will need to handle it in the application code.


问:
Trying to save timeStamp recorded in jmeter results from csv to MSSQL server
I am not able to save proper timeStamp from JMeter to CSV and same CSV to MSSQL server.

I am saving results right now but they appear in a wierd manner like 1559087654 etc

I want proper format of the timeStamp at what time and date exact results were recorded.

答:
You can import the CSV file to the MSSQL (as a table), then you can covert (cast) the timestamp column to datetime.

Please check this answer, it may help you


问:
Using @Value with Gauge framework
How can I use @Value with static Application context?

I built application using gauge spring demo https://github.com/getgauge-examples/ioc-spring.

App is started using AnnotationConfigApplicationContext, look at RegisterIOC.java in demo.

I want to use @Value in this project, but @Value do not see application.yml properties and i have exception:

```<code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder
</code>```

Is there a way to customize this project and use @Value in it?

答: I didn't find solution with aplication.yml, but i created folder env/default/default.properties Gauge found properties and I was able to use @Value

Title: Using @Value with Gauge framework

Body:
How can I use @Value with static Application context?

I built application using gauge spring demo https://github.com/getgauge-examples/ioc-spring.

App is started using AnnotationConfigApplicationContext, look at RegisterIOC.java in demo.

I want to use @Value in this project, but @Value do not see application.yml properties and i have exception:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder

Is there a way to customize this project and use @Value in it?