How to encpyt the password using Springboot?

Question: I have already done user register and login. But I want to encrypt the password when create a profile.
This is my current configuration
MongoDB Connection
spring.data.mongodb.uri= mongodb://127.0.0.1:27017/Student
server.port=8080

Model Class:
@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
@Id
@Indexed
private String id;
@Indexed
private String address;
@Indexed
private String name;
@Indexed
private String email;
@Indexed
private String password;
@Indexed
private String role;
}
Repository Class:
public interface userReporsitory extends MongoRepository<User,String> {
    Optional<User> findByEmail(String email);
    List<User> findAllByRole(String role);
}

Service Class:
@AllArgsConstructor
@Service
public class userService {
    private userReporsitory userReporsitory;
    public User saveUser(User user){
        return userReporsitory.save(user);
    }
    public User login(User user){
          User response = userReporsitory.findByEmail(user.getEmail()).orElseThrow(()->new RuntimeException("User Not Found"));

          if(!response.getPassword().equals(user.getPassword())){
            throw new RuntimeException("Bad Credincials");
          }

          return response;
    }

    public List<User> findAllUsers(){
      return userReporsitory.findAllByRole("user");
    }
}

Controller Class:
    @CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("api/v1/user")
public class userController {
   private userService userService;

    @PostMapping("/create")
    public ResponseEntity<User> save(@RequestBody User user){
        HttpStatus status = HttpStatus.EXPECTATION_FAILED;
        User response = userService.saveUser(user);

        if(response != null){
           status = HttpStatus.CREATED;
        }

        return new ResponseEntity<>(response, status);

    }
    @PostMapping("/login")
    public ResponseEntity<User> login(@RequestBody User user){
        return new ResponseEntity<>(userService.login(user),HttpStatus.ACCEPTED);

    }
    @GetMapping("/userList")
    public ResponseEntity<List<User>> userList(){
        return new ResponseEntity<>(userService.findAllUsers(),HttpStatus.ACCEPTED);
    }

}

Comment: the best practice is to hash passwords not encrypt them, as @AndrewThomas use any implementation of PasswordEncoder like BCryptPasswordEncoder
Comment: I think you should consider using spring-security to utilize its `PasswordEncoder` and different ways to compare passwords for equality
Answer: Use

BCryptPasswordEncoder

Class while saving the Password in DataBase.it will convert the normal text to RandomValue.
Define the BCryptPasswordEncoder In config Class.
@Bean
public PasswordEncoder encoder() {
    return new BCryptPasswordEncoder();
}

Repository Class :
   @Autowired
private PasswordEncoder passwordEncoder;

public User newUserAccount(UserDto accountDto) {
        User user = new User();
    user.setFirstName(accountDto.getFirstName());
    user.setLastName(accountDto.getLastName());

    user.setPassword(passwordEncoder.encode(accountDto.getPassword()));

    return repository.save(user);
}

Answer: Utilize this code .. Here I am using InMemoryUserDetailsManager to manage user details that stored in memory.
@Bean
public InMemoryUserDetailsManager createUserDetails(){
    UserDetails user1 = createNewUser("vamsi","vamsi");
    UserDetails user2 = createNewUser("a","a");

    return new InMemoryUserDetailsManager(user1,user2);

}

private UserDetails createNewUser(String username, String password) {
    Function<String, String> passwordEncoder = input ->passwordEncoder().encode(input);
    return User.builder()
            .passwordEncoder(passwordEncoder)
            .password(password)
            .username(username)
            .roles("user","admin")
            .build();
}
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}


mySQL - Generate Additional Lines Between Dates

Question: I have a table like the below.
id     month     duration
001    1/1/16    3
002    3/1/16    4
003    12/1/15   2

I would like to add a new row to the table for every month after the month shown for the number specified minus 1, e.g. below:
id     month    duration
001    1/1/16   3
001    2/1/16   3
001    3/1/16   3
002    3/1/16   4
002    4/1/16   4
002    5/1/16   4
002    6/1/16   4
003    12/1/15  2
003    1/1/16   2

And so on, while duplicating the values in any column not shown.
I have done this in R, where I first populated 'short' data and then reshaped it to long, but after searching online, I still have no idea how to do this in mySQL. Thanks in advance for your help!
Answer: If you could automatically generate rows in MySQL that would be pretty easy; except that you can't. Still, you could use the technique described here to generate some rows and then use a JOIN to get the data you need:
-- Create a VIEW with 16 dummy rows
CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL
   SELECT 15;

Having this generator, your query becomes:
SELECT id, date_add(month, INTERVAL n MONTH), duration
FROM tbl
INNER JOIN generator_16 ON n < duration
ORDER BY id, month

I assumed your table structure is the following:
CREATE TABLE tbl(id varchar(10), month date, duration int);
INSERT INTO tbl VALUES('001', '2016-01-01', 3);
INSERT INTO tbl VALUES('002', '2016-03-01', 4);
INSERT INTO tbl VALUES('003', '2015-12-01', 2);

Comment: Great suggestion! As I'm new to mySQL I'll need some time to digest and attempt. Thank you very much for your time!
Answer: Issues of data display are generally best resolved in the presentation layer (e.g. a simple PHP loop), but just for fun...
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,dt DATE NOT NULL
,duration INT NOT NULL
);

INSERT INTO my_table VALUES
(1,'2016-01-01',3),
(2,'2016-03-01',4),
(3,'2015-12-01',2);

SELECT * FROM my_table;
+----+------------+----------+
| id | dt         | duration |
+----+------------+----------+
|  1 | 2016-01-01 |        3 |
|  2 | 2016-03-01 |        4 |
|  3 | 2015-12-01 |        2 |
+----+------------+----------+

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

 SELECT x.id,x.dt + INTERVAL y.i MONTH,x.duration FROM my_table x JOIN ints y ON y.i < x.duration;
+----+---------------------------+----------+
| id | x.dt + INTERVAL y.i MONTH | duration |
+----+---------------------------+----------+
|  1 | 2016-01-01                |        3 |
|  1 | 2016-02-01                |        3 |
|  1 | 2016-03-01                |        3 |
|  2 | 2016-03-01                |        4 |
|  2 | 2016-04-01                |        4 |
|  2 | 2016-05-01                |        4 |
|  2 | 2016-06-01                |        4 |
|  3 | 2015-12-01                |        2 |
|  3 | 2016-01-01                |        2 |
+----+---------------------------+----------+

Comment: Great suggestion! As I'm new to mySQL I'll need some time to digest and attempt. Thank you very much for your time!


Local ring principal maximal ideal intersection of powers

Question: Suppose $(R,m)$ is a local ring with $m = (x)$ a principal ideal. Suppose that $x^{k} \ne 0 , \forall k \geq 0$. Do we have that $I = \cap_{k \in \mathbb{N}} (x^{k})$ is a finitely generated ideal, and if so why?
Answer: In general, no. Consider the ring of germs at $0$ of $C^{\infty}$ functions from $\mathbb{R}$ to $\mathbb{R}$. This is a local ring with maximal ideal $(x)$, but we have $e^{-1/x^m}\in (x^n)$ for all $n\geq 1$ and for all $m\geq 2$ and these functions are suitably independent.
If $R$ is Noetherian, then not only is $\cap_{n>1} (x^n)$ finitely generated, it's equal to $0$! In fact, this condition is sufficient - a local ring $(R,\mathfrak{m})$ with principal maximal ideal $\mathfrak{m}$ is Noetherian if and only if $\cap_{n>1} \mathfrak{m}^n=0$.


Why the message doesn't send to my outlook mail?

Question: I am creating a website for user to fill out information. After completed fill out information, the user click button to submit a ticket and send email to me as a copy. However, I didn't receive any email after I click to send it. The submit ticket was successful except the email. We use Microsoft Outlook.
Anyone know why or I am missing something?
I did add the reference using Outlook = Microsoft.Office.Interop.Outlook;
C# codes,
protected void BtnIPAM_Click(object sender, EventArgs e)
{
    //codes for submitting ticket then send email

    string uid = Bam.NEAt.GetUserID();

    try
    {
        //Create the Outlook application
        Outlook.Application oApp = new Outlook.Application();
        //Create the new message
        Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
        //Add a recipient
        Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email@example.com");

        oRecip.Resolve();

        //Set the basic properties
        oMsg.Subject = "A Copy of IP Address Request";
        oMsg.Body = "This is a test who sent by " + uid;

        //Send the message
        oMsg.Save();
        oMsg.Send();

        oRecip = null;
        oMsg = null;
        oApp = null;

    }
    catch {}
}

Comment: Why would you use Outlook on a server to send email?? You can just use a `MailMessage` object instead. See http://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp for an example.
Comment: Your empty `catch` block hides any error that might occur in the rest of the code. I'd suggest you remove it.
Comment: Did you install Outlook on your web server?
Comment: I had a case where sending to the same domain did not work correctly.. Is this a possibility?
Comment: Look at my answer, it is a better and more efficient method of sending an email
Answer: use this to send an email:
    using System.Net;
    public static void SendAlertEmail()
    {
       System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
       message.To.Add("firstname.lastname@example.com");
       message.Subject = "Put Subject";
       message.From = new System.Net.Mail.MailAddress("firstname.lastname@example.com");
       message.Body = "Body Message Here";
       System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
       smtp.Host = "put host settings here";
       smtp.Port = 25;
       smtp.EnableSsl = false;
       smtp.Send(message);
    }

To call it use this:
SendAlertEmail();

Comment: the answer I provided does not require a password.  Just make sure your host settings are correct.
Comment: Is there a way to automatic send email from other email without require using password?
Comment: try adding this: smtpt.UseDefaultCredentials = true;
Comment: Thanks! I was able to use Batch account and edit the correct host to make it work.


Restore data from an HP StorageWorks MSA crash

Question: I have an HP StorageWorks (MSA 2012fc) and it has been used for production for a while.
I used parted to set up three 0x83 partitions on it.
After a power off, my Linux box attached to the MSA via fiber channel become enable to see any partitions. And when i do dmesg i get that there are only a volume named as sda ?
Also, when i list the dev directory, there are only /dev/sda.
All partitions are absent, please can you explain what happened,
and how can i restore the hole of my data.
Answer: No, I can't tell you what happened but you can look for clues yourself, look at your logs - sounds like something reinitialised the volumes - I know that model of MSA and even if it did 'die' and damage your disks it wouldn't delete three partitions and create a new linux-format one for you, it would be all or nothing. As for data restoration, I'd suggest restoring from backup, I'm highly doubtful that you could restore the data on the array and I wouldn't then trust it anyway.


Rails Composer doesn't work on Windows. SSL Error

Question: I have RailsInstaller with Ruby 2.0 and Rails 4.0. I create an app with this:
<code>$ rails new myapp -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb
</code>
Then i got this:
<code>apply  https://raw.github.com/RailsApps/rails-composer/master/composer.rb
C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/net/http.rb:918:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/net/http.rb:918:in `block in connect'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/timeout.rb:52:in `timeout'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/net/http.rb:918:in `connect'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/net/http.rb:862:in `do_start'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/net/http.rb:851:in `start'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:313:in `open_http'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:708:in `buffer_open'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:210:in `block in open_loop'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:208:in `catch'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:208:in `open_loop'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:149:in `open_uri'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:688:in `open'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/open-uri.rb:34:in `open'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/thor-0.18.1/lib/thor/actions.rb:216:in `apply'
</code>
What is this?
Thanks a lot!
Answer: Download the cacert.pem file from here. Save this file to C:\RailsInstaller\cacert.pem.
Now make ruby aware of your certificate authority bundle by setting SSL_CERT_FILE. To set this in your current command prompt session, type:
<code>  $  set SSL_CERT_FILE=C:\RailsInstaller\cacert.pem
</code>
That's all. Works fine!


Connect to Samba share with no username/password

Question: I have just set up Samba on a CentOS 5 machine. It works OK, but I would like to configure it so that users can connect to Samba shares without the need to provide a user name and password. I have googled for a smb.conf reference but documentation seems to be quite scattered and not comprehensive. Can somebody explain how to achieve this? Many thanks.
Answer: Example of smb.conf for anonymous access:
#======================= Global Settings

[global]
   workgroup = WORKGROUP
   netbios name = Encre
   security = user
   hosts allow = 192.168.0.0/24 127.0.0.1
   hosts deny = 0.0.0.0/0
   log file = /var/log/samba/%m
   max log size = 50
   socket options = TCP_NODELAY

#============================ Share Definitions

[homes]
   comment = Home Directories
   browseable = no
   writable = yes

[other]
   comment = other!
   path = /home/otheruser/share
   force user = otheruser
   force group = otherusergroup
   read only = No
   guest ok = Yes

#============================

Comment: I hope the "porn" bit is optional!
Answer: I'm using
[global]

security = share

in smb.conf.
This seems to be enough for passwordless access. The computers belong to the same workgroup, but I don't know if this is a mandatory requirement.


CDF of a random variable defined by a coin toss.

Question: Assume that you choose point $\xi$ from $[1,4]$ in the following way. You toss a coin that can give head, tail or stood on edge with equal probabilities. If it stood on edge, then $\xi = 3$. If tail, then you going to choose $\xi$ randomly from $[1,2]$. If head, then randomly from $[2,4]$. The question is what are cumulative density function, mean and variance of such random variable?
Let's start from CDF. It is obvious that for $t \leq 1$ $F_\xi(t) = 0$ and for $t \geq 4$ $F_\xi(t) = 1$. I assumed that $F_\xi(t) = \frac{1}{3}\cdot\frac{t-1}{1}$ for $1 \leq t < 2$ and $F_\xi(t) = \frac{1}{3}+\frac{t-2}{4-2}=\frac{3t-4}{6}$ for $2 \leq t < 4$. Am I right or are there any mistakes here? Further computations of $M\xi$ and $D\xi$ are rather straightforward from CDF (split integral from $1$ to $4$ into two integrals from $1$ to $2$ and from $2$ to $4$ with corresponding derivatives of CDF on each interval).
Comment: You need to assume a nonzero probability for the coin to fall on edge, otherwise the random variable is undefined (experiment never stops). Maybe what you have in mind is setting P(edge)=$\epsilon$ and the taking the limit as $\epsilon\to0$...
Comment: @A.G., the probability that the coin will fall on edge is $\frac{1}{3}$.
Comment: @A.G. I think you have mistook the problem for a more interesting one. It's pretty clear from OP's calculation of the cdf that they mean if the coin lands heads or tails the variable is chosen *uniformly* from the intervals, not recursively.
Comment: @Hasek your cdf is not right. You should have a jump at three. Furthermore, when I plug in $t=4$ to the cdf you wrote down I get $3/2.$ that can't be right.
Comment: @Hasek My bad, did not realize this is a 3-sided coin ;)
Answer: Not quite. You do not seem to have taken into account the fact that the coin could fall on it's edge, so the probability of $3$ appearing is larger than you have shown it.
More precisely, you are right that the CDF is zero before $1$  and one after $4$.
Let us find $P(\xi \leq k)$. Note that if we define the random variable $C = 0,1,2$ with probability $\frac 13$  each (for the coin toss with $0$ representing the coin falling on an edge, $1$ representing tail and $2$ representing head), then $$P(\xi \leq k) = P(C = 0)P(\xi \leq k | C = 0) + P(C = 1)P(\xi \leq k | C = 1)  + P(C = 2)P(\xi \leq k | C = 2)$$
Now we can split into cases. Suppose that $1 \leq k < 2$. Then, note that the first and last term above would be zero, so the answer is just $\frac{1}{3}\frac{k-1}{1}  = \frac {k-1}3$, as you had predicted.
Suppose that $2 \leq k < 3$. Note that the second event occurs with probability $\frac 13$ now, since if $C=1$,  then every element picked uniformly from $[1,2]$ is smaller than $k$. The third event also occurs, and has probability $\frac{k - 2}{6}$. So the answer would be $\frac{1}{3} + \frac{k-2}{6} = \frac{k}{6}$.
For $3 \leq k \leq 4$, all three events above occur. Note that now, both the first and second event occur with probability $\frac 13$ each, and the third event occurs with probability $\frac{k-2}{6}$, again. Hence, here the answer is $\frac{k + 2}{6}$.
Hence, the final CDF is:
$$
F(k) = \begin{cases}
0 & k \leq 1 \\
\frac{k-1}{3} & 1 \leq k < 2 \\
\frac k6 & 2 \leq k < 3 \\
\frac{k+2}6 & 3 \leq k \leq 4 \\
1 & k \geq 4
\end{cases}
$$
NOTE : As expected, there is a jump at $3$ of the CDF : the probability that $\xi = 3$ is non-zero, so this expected. This was not observed in your function, for example.
Now, you can use this function to get down to your expectation and variance calculations.


Changing Text of Button as well fadetoggle function in jquery

Question: <button id="myButton" class="comment-submit button small green">Play Video</button>

$(document).ready(function(){
    $("button").click(function(){
        $("#div1").fadeToggle(3000);
    });
});

So i got this code, which basicly pops up a video when i hit the playbutton, Works like a charm but:
I want the text of the button to change to Hide Video, once they clicked "Play Video", and back to "Play Video" if they click "Hide Video"
I found a bunch of solutions, but the problem is, im a jquery nub, even worse, im pretty new to web building.
So where should i put the code, for example this solution:
$('.SeeMore2').click(function(){
    var $this = $(this);
    $this.toggleClass('SeeMore2');
    if($this.hasClass('SeeMore2')){
        $this.text('See More');
    } else {
        $this.text('See Less');
    }
});

so confused of what im missing
Answer: Here is the demo
HTML:
<button id="myButton" class="videoHidden">Play Video</button>

Video is here

CSS:
#videoWrap {
    width: 150px;
    height: 100px;
    background-color: #9ff;
    display: none;
}

JavaScript:
$(document).ready(function(){
    $('#myButton').click(function(){
        var $this = $(this);
        $("#videoWrap").fadeToggle();//or .toggle() for instant showing/hiding
        $this.toggleClass('videoHidden');

        if($this.hasClass('videoHidden')){
            $this.text('Play Video');
        } else {
            $this.text('Hide Video');
        }
    });
});

So:

Once document is loaded, you have a button which has "Play Video"
text and "videoHidden" class
When you click on the button, it toggles "videoHidden" class on the button (adds if
not exists or removes if exists). It helps you to save some "state" of video playing.
Then you use current "state" to change button's text to corresponding value ("Play Video" if
video isn't playing, "Hide Video" if video is playing)

Edited
There is an error here http://biready.visseninfinland.nl/testing-2/:
At line 467 there is erroneous script

You should remove
 and
 from it

Edited 2
The last version of script (need to perform attaching handler within $(document).ready()):
$(document).ready(function(){
    $('#myButton').click(function(){
        var $this = $(this);
        $("#videoWrap").slideToggle();
        $this.toggleClass('videoHidden');
        if($this.hasClass('videoHidden')){
            $this.text('Play Video');
        } else {
            $this.text('Hide Video');
        }
    });
});

Comment: for some reason i cannot get this to work. might it be my wordpress theme interfering? i work with Avada Theme.
Comment: Do html of button and div equals to answered (class of button and id of div)?
Comment: Yeah, i took ur code line for line and placed it within the corresponding places, but it simply wont work:(
Comment: Used the new script, removed the  and , saved it off, opened the page and...nothing:( the button wont change, the video wont show up. Im so clueless.
Comment: It does give me a unsuspected error: Uncaught Error : Object [object Object] has no method 'live'. No idea or my videofile, which is a customized YouTube video imported with vtubetools.com generated code, conflicts in any of this.
Comment: This error is inside "main.js" and does not related to this question.
Comment: If you want, i could give you login of my wp-site, maybe a look under the hood will clearify things?
Comment: where to? i cant find ur email address:S
Comment: firstname.lastname@example.com
Comment: added a account for you, u should have login in ur email
Comment: See Edited2, change script in that way
Comment: Awesome, that surely did the trick. now i got one problem left. IE... when i click play video, it shows up perfect, but for some reason the video keeps playing after i press the hide video button. how could i resolve this?
Comment: Hey Nikita, i mailed u a followup request to ur email adres.
Answer: I think it can be more easy by this code.


Connecting to samba ubuntu server from linux

Question: In these days I'm setting up a small network with about twenty computers. The users of this network used windows before (now they use linux mint) and they need to access samba ubuntu folders simply using their name (which is same as their login) and password (there's no problem for them with typing access data). In that case I need the simplest way for them to access it. I was thinking of using links (I found out it's impossible) and bookmarks are working well, but I need the solution to be cloneable (I'm cloning user accounts to another computers in the network - /etc/passwd and home directories). Is there any way how to do it simply?
EDIT: If the things upper are not simply possible, please tell me at least some way how to connect to a single server called "Server-desktop".
Comment: It's totally unclear what your problem or objective is.  The title suggests you can't connect to the server.  Then you proceed to talking about links/bookmarks which sounds like web lingo, and all of a sudden an extra server springs up ... what do you need help with?
Comment: I can connect server by File->Connect and I can create bookmark for it, but I need some way to connect server directly from some shortcut as it's possible in windows.
Answer: If your whole network is Linux based - which I think your question implies - why not just set up NFS shares and take Samba out of the picture?  You could also use NIS+ or something similar to handle authentication/authorization and allow the users single signin and access of their folders.
https://help.ubuntu.com/community/SettingUpNFSHowTo
https://help.ubuntu.com/community/SettingUpNISHowTo


Shall I post an answer for the reputation earning?

Question: Today I just cam across one question that is this question
I simply understood the cause behind that error & placed one comment below the question & it solved the error that the P.O. of the question was facing.
Now my question is this shall I post one answer also there which is giving the same information or I should just leave it as it is. It is something like what one should do when he/she is knowing the answer & that answer he/she got to know from some resource

He/she simply put one comment below the question with the link to that resource, from where the P.O. will definitely get the solution.
For earning the reputation one should post it as an answer.

I know It is simply just a state of mind/choice of any person but then also I would like to have an opinion from the great contributors at M.S.E. to give their view on this.
Answer: Off course, you can give the answer to the question as the same type of issue you have faced and have resolved the issue by XYZ  procedure.
But the answer should not be One line or single link answer. You have to give some brief of how you have applied the solution on your case. That will help us with understanding.


Why is the ball hitting any part of the arm now a handball?

Question: During the past season or so I've noticed in most cases when the ball touches any part of a player's arm handball is given. Either the handball rule has changed or the introduction of VAR in top tier leagues has impacted what is being called a handball, as these calls almost always result in a couple of minute stoppage for VAR. When such fouls happen the commentators talk about "the new rule", which makes me think maybe the rule itself was modified.
It's caused numerous goals being taken away and penalties awarded by VAR that would've been counted before this rule change.
Most of these handballs are accidental or the players simply didn't have enough time to react and get their arms out of the way. Not only having goals taken away or goals given (indirectly through penalties) have been impacting games, but sometimes rely on super slow motion shots to look for a handball that totally ignores the athletes' reaction time.
Yesterday, August 8th 2020, Juventus was given a penalty after the ball hit a Lyon defender on a wall in the arm while his arm is closed and pressed against his body. You can see the foul here.
And today, August 9th 2020, a Messi goal was taken back after VAR ruled it a handball. The ball made a slight touch to his arm after/while he controlled it with his chest. I wasn't able to see that in the usual slow motion speed. You can see this goal here.
And there was the infamous Lucas Moura handball. Tottenham Spurs Moura was fouled and as he fell a Sheffield United player kicked the ball at his arm, all while Moura is looking away during his fall. The referee plays advantage, Harry Kayne picks up the loose ball and scores with it. But VAR took the goal back cause Moura's arm made contact with the ball!
I understand by the letter of the law the ball touching an arm is handball, but I don't see how any of these 3 scenarios could be logically considered as a handball
So has the handball rule has been changed or these handball calls we now see are a byproduct of having video review? If the rule has changed, what was FIFA's reasoning behind it?
Comment: A previous conversation has been [moved to chat](https://chat.stackexchange.com/rooms/111608/discussion-on-question-by-alamoot-why-is-the-ball-hitting-any-part-of-the-arm-no). @alamoot for your notice.
Comment: The Lyon defender deliberately moved his elbow out towards the ball. In slow motion we can see he did this after the ball hit him, but because of the speed it happened, the ref must have thought that the ball was deflected because of this deliberate action. This is a really, really great example of what might be a deliberate handball even if the sillouette is not made bigger.
Comment: Harry Kane's goal was ruled out because of the new accidental handball rule. If Kane or any one of his team mates touched the ball immediately before scoring, it is an offence. It doesn't matter how accidental it is, the ball just has to make contact with the arm/hand. If Moura was fouled and advantage was played, the ref could have pulled play back to a free kick in favour of Moura.
Answer: The International Football Association Board (IFAB), which is the body in charge of Laws of soccer, passed a set of rule changes on March 2019 for the 2019/20 season. Some of the main law changes were regarding free kicks, goal kicks, drop balls, and handballs.

So has the handball rule has been changed or these handball calls we now see are a byproduct of having video review?

In short, the rules have changes, and the reasoning behind is to "bring more clarity for  handball".
The following are handball rule changes under Law 12:

Deliberate handball remains an offence

The following 'handball' situations, even if accidental, will be a free kick:

the ball goes into the goal after touching an attacking player's hand/arm
a player gains control/possession of the ball after it has touches their hand/arm and then scores, or creates a goal-scoring opportunity
the ball touches a player's hand/arm which has made their body unnaturally bigger

the ball touches a player's hand/arm when it is above their shoulder (unless the player has deliberately played the ball which then touches their hand/arm)

The following will not usually be a free kick, unless they are one of the above situations:

the ball touches a player's hand/arm directly from their own head/body/foot or the head/body/foot of another player who is close/near
the ball touches a player's hand/arm which is close to their body and has not made their body unnaturally bigger
if a player is falling  and the ball touches their hand/arm when it is between their body and the ground to support the body (but not extended to make the body bigger)
If the goalkeeper attempts to 'clear' (release into play) a throw-in or deliberate kick from a team-mate but the 'clearance' fails, the goalkeeper can then handle the ball

So based on the above rules, an accidental handball not a handball, unless it results in a score or a scoring opportunity. So if the ball hits my arm outside of the box accidentally it's not a handball, but if I gain control of the ball, shoot and score, that handball must be ruled a foul. The way I read it, it means a non offencive handball becomes retrospectively a handball in this situation!
However, in April 2020, there was further amendments to handball law:

Handball:

the boundary between the shoulder and the arm is defined as the bottom of the armpit (see the diagram on p. 14)
'accidental' handball by an attacking player (or team-mate) is only penalised if it occurs 'immediately' before a goal or clear goal-scoring opportunity

It is an offence if a player:

deliberately touches the ball with their hand/arm, including moving the hand/arm towards the ball
scores in the opponents' goal directly from their hand/arm, even if accidental, including by the goalkeeper

Clarification that:

if an attacking player accidentally touches the ball with their hand/arm and the ball then goes to another attacking player and the attacking team immediately scores, this is a handball offence;
it is not an offence if, after an accidental handball, the ball travels some distance (pass or dribble) and/or there are several passes before the goal or goal-scoring opportunity.

So it seems as of the latest updates, accidental handballs are an offense if they immediately result in a score, but if the ball travels some distance or there are number of passes it's not. The rule is still vague as to what distance the ball can travel, or ho many passes before an accidental handball results in a free kick.

If the rule has changed, what was FIFA's reasoning behind it?

IFAB has the following explanation for the rule changes of the 2019/20 season:
Greater clarity is needed for handball, especially on those occasions when 'non-deliberate' handball is an offence. The re-wording follows a number of principles:

football does not accept a goal being scored by a hand/arm (even if accidental)
football expects a player to be penalised for handball if they gain possession/control of the ball from their hand/arm and gain a major advantage e.g. score or create a goal-scoring opportunity
it is natural for a player to put their arm between their body and the ground for support when falling.
having the hand/arm above shoulder height is rarely a 'natural' position and a player is 'taking a risk' by having the hand/arm in that position, including when sliding
if the ball comes off the player's body, or off another player (of either team) who is close by, onto the hands/arms it is often impossible to avoid contact with the ball
When the GK clearly kicks or tries to kick the ball into play, this shows no intention to handle the ball so, if the 'clearance' attempt is unsuccessful, the goalkeeper can then handle the ball without committing an offence

The law changes don't mention VAR, but since goal are reviewed by VAR on top tier leagues, these new handball rules are applied with scrutiny.
Comment: You're right based on the new rules that's a handball, I just happen not to be a fan of the rule. Under the "2020 further amendments" in the answer here I mention that any handball that immediately results in a goal or a goals scoring situation is a handball. In the comment above I only argues that Moura didn't open up his body unnaturally, but as of April 2020 this is not related. It's a handball as of the new rule.
Comment: The video you link as the Lucas Moura goal is handball - Lucas's arm is extended laterally from the body, not below it to prevent falling. It has made the body "unnaturally bigger" and is handball. It isn't magically becoming handball simply because his team scored a goal after it.
Comment: I completely disagree. I don't know about you, but if I got tripped up while running and was about to fall, I'd put one hand in front of me, not directly under me, to avoid landing on the ground with my face first. It's only natural to protect your head at all times.
Comment: Updated answer with the 2020 handball rule changes
Comment: The moment Moura's right elbow lands on the ground (the arm he leans on to fall and the same arm the ball is kicked to), his arm is making a 90 to 120 degree angle to the ground. how could he make a 90 degree ish angle and yet have his arm outstretched?? Let's just agree to disagree on this one. Anyway, I removed the Moura situation out of my answer, as I added the 2020 verbiage instead
Comment: Harry Kane's goal was ruled out because of the new accidental handball rule. If Kane or any one of his team mates touched the ball immediately before scoring, it is an offence. It doesn't matter how accidental it is, the ball just has to make contact with the arm/hand. If Moura was fouled and advantage was played, the ref could have pulled play back to a free kick in favour of Moura.


Problem with mixture discriminant analysis in R returning NA for predictions

Question: I'm trying to do a mixture discriminant analysis for a mid-sized data.frame, and bumped into a problem: all my predictions are NA.
After tracing through way too much code, I figured it had something to do with the fact that some of the coefficients in the mda turn out to be NA. I've created a smaller data.frame that still has the problem:
dfr<-structure(list(min_GCs_last_3_bases = structure(c(1L, 2L, 1L,
1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L,
1L), .Label = c("zero", "one"), class = "factor"), cq = c(-0.334138707578632,
-0.586150643906373, -0.474578712720667, -0.220268433139143, -0.486876877353103,
-0.0912154554410563, 0.00341593805213764, 0.713424582672338,
-0.448914652233824, 2.94156773625266, -0.0954835698859817, -0.238125375419562,
-0.448914652233824, -0.0290299100261503, -0.479666688891261,
-0.596316272919155, -0.0919665779183363, -0.394427887135795,
-0.396749521580081, -0.338156015653477), Coverage = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
1L, 2L, 2L), .Label = c("failure", "success"), class = "factor")), .Names = c("min_GCs_last_3_bases",
"cq", "Coverage"), class = "data.frame", row.names = c("SMURF2_16_1",
"MI0000437", "SMAD6_4_1", "SMAD2_8_1", "MI0003561", "SKP1_6_1",
"MI0003556", "LTBP1_19_1", "MI0006350", "MI0006351", "TGFBR1_6_1",
"MI0000772_1", "MI0003176", "MI0005758", "MI0003639", "MI0003641",
"CUL1_5_1", "APC_3_1", "MI0005769", "KPNB1_5_1"))

When I use this data.frame like so (after loading the package mda):
mda(Coverage~.,data=dfr,subclasses=2)$fit$coef

I get this result:
                                [,1]        [,2]
Intercept                -0.90574883 -0.42382446
min_GCs_last_3_baseszero  1.80667985  0.85786905
min_GCs_last_3_basesone  -0.02302343  0.04884007
cq                                NA          NA

What troubles me about this, is:

Why are there coefficients for both
the values of the factor
min_GCs_last_3_bases?
Why are the    coefficients of cq NA?

I'm willing to assume I have completely misunderstood mda. Can someone please enlighten me? Or did I just bump into a bug?
(note: I've tried if the names of the columns had an influence: they don't)
Comment: Argl. I may have just found the cause: as most forms of DA assume (?) multivariate normality per outcome class, they don't make much sense for categorical predictors (i.e. factors), right? This may be turning into more of a stats.stackexchange question afterall...
Answer: You only have 2 failures Why were you thinking you could estimate more than two coefficients?
Comment: This is not the case in my original data.frame. I didn't consider this when posting the simplified (i.e. smaller dataset). I get the same result, however (it's even the same one that is NA, and the strange presence of both factor levels is there too).
Comment: If you have a numerically singular model matrix, most regression functions will omit variable or levels until they are able to return .  Try putting the `cq` term in explicitly.


Como verificar se um arquivo XML é valido com PHP?

Question: Segundo entendi pelas respostas desta pergunta do SO, o XMLReader::isValid() verifica "apenas o nó atual, não o documento inteiro". O que isso quer dizer?
No caso quero validar se o xml é válido antes de fazer:
$meuXml = simplexml_load_string($meuXml);

Porque algumas vezes acho que o xml vem mal formado, então recebo um erro tipo:

stderr: PHP message: PHP Warning:  simplexml_load_string(): Entity:
  line 1: parser error : Start tag expected, '<

Então basicamente a pergunta é : Qual a melhor forma de verificar se um documento .xml é válido utilizando PHP? Mas também gostaria de saber o que significa "a verificação apenas do nó atual, e não do documento inteiro".
Answer: Basta você fazer o tratamento de erros com essa mesma API de XML do PHP.
A função simplexml_load_string retorna false quando não consegue processar corretamente o XML, então basta analisar o retorno da função.
$meuXml = simplexml_load_string($meuXml);

if (!$meuXml) {
    die("Erro ao processar o XML");
}

Mas dependendo das configurações do seu servidor, a mensagem de warning será exibida no navegador. Para que ela não seja exibida, você pode informar que irá tratar isso internamente com a função libxml_use_internal_errors e libxml_get_errors:
libxml_use_internal_errors(true);

$meuXml = simplexml_load_string($meuXml);

if (!$meuXml) {
    $erros = libxml_get_errors();

    foreach ($erros as $erro) {
        echo $erro->message, PHP_EOL;
    }

    exit;
}

Desta forma, se o XML não for válido, produziria uma saída:
Erro: Start tag expected, '<' not found

E você pode tratar os erros como desejar.
Comment: @gustavox O XML em `$meuXml` inteiro. O retorno de `libxml_get_errors` será um *array* com todos os erros.
Comment: Anderson, neste caso já avalia o XML inteiro ou só um dos nós... btw não entendi ainda muito bem a questão dos nós, se puder dar uma breve explicação...
Answer: O XML é feito de vários nós, quando você utiliza a função XMLReader::isValid(), ele valida somente o nó passado por parâmetro e não os "sub nós" que esse nó contem.
O que você pode fazer é validar o XML junto com o seu XSD usando DOMDocument::schemaValidate.
Caso não tenha o xsd, você pode fazer um tratamento de exceção no simplexml_load_string e mostrar uma mensagem personalizada.
O que você pode fazer também, é checar a validade do documento no da w3schools para averiguar se realmente o problema é o xml.


how to make outbound call using dongle

Question: I have been tried couple of hours to outbound call from Asterisk using dongle. But it shows following error
WARNING[22180]: channel.c:166 channel_request: [dongle0] Request to call on device which can not make call at this moment
[Apr ] WARNING[22180]: app_dial.c:2277 dial_exec_full: Unable to create channel of type 'dongle' (cause 44 - Requested channel not available)

Dialplan command is :
exten => _X.,n,Dial(dongle/dongle0/+73432823232)
Could you please give me solution?
UPDATE : On asterisk*CLI> i can make outboud call using this dongle cmd dongle0 ATD+434343434232;
Answer: Error mean you not configured it correctly or device turned off/unplugged
For more info enable debug or do
dongle show devices

https://github.com/bg111/asterisk-chan-dongle
Comment: I can make outbound call in `Asterisk CLI` command mode. But it doesnt work in dialplan

how to make outbound call using dongle


Question about Decision boundary in Logistical Regression

Question: I am a Machine Learning newbie and studying Logistical Regression.

For the data shown above, a straight line cannot separate all the positive and negative decisions. One thing I could understand is that I would need a higher order polynomial such as
θ0 + θ1x1 + θ2x2 + θ3x21 + θ4x22
But consider that, prediction is hθ(x) = 1/(1 + e- z) where z = θ0 + θ1x1 + θ2x2 (a straight line) and the cost equation is -y.log(hθ(x)) + (1 -y).log(1 - hθ(x)). For this cost equation, whenever hθ(x) tends to 1 and y is 0 OR whenever hθ(x) tends to 0 and y is 1, the cost tends to infinity.
So my questions are:

Will the above mentioned cost function be a convex function?
If we use gradient descent, will it converge to global minimum?

I think that gradient descent will not converge as the cost tends to infinity whenever prediction and actual do not match. Whether I am correct or wrong, please help with an explanation.
Answer: $h_\theta(x)$ can never be $0$ or $1$ for real $x$. And, logistic regression is known to be a convex optimisation problem when cross-entropy loss is used, which means the cost is a convex function wrt parameters. Since the problem is convex, gradient descent can be used to approach the global optimum arbitrarily close, while typical implementations use second-order optimisation methods.
Note: logistic regression will create a linear decision boundary again. $h(x)$ has nothing to do with feature transformation.
Comment: that is correct
Comment: Thanks so much @gunes for the answer and the clarification.
Comment: Thanks for the explanation @gunes. I have made some edits based on your comment and also mentioned the use of straight line for separation. If possible, can you consider the edits to answer the questions?
Comment: @Amit my answer stands. note that you can't make $h$ as $0$ or $1$ using any value of z.
Comment: As I understand from your comment, the cost function will always be convex and gradient descent will converge even if we use a straight line for separation. Of course, I do understand that a straight line is a wrong choice for classification in this problem.


Test class could not be found, namespace/autodiscovery issue?

Question: I've got the following tests written for /core/modules/migrate_drupal_ui/src/Controller/MigrateController.php with
a new test file /core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php.
<?php

namespace Drupal\Tests\migrate_drupal_ui\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Provides a base class for testing the Migrate Controller.
 */
abstract class MigrateControllerTest extends BrowserTestBase {
  /**
   * {@inheritdoc}
   */
  public static $modules = ['migrate_drupal_ui', 'views'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $account = $this->drupalCreateUser(['administer views']);
    $this->drupalLogin($account);
  }

  public function testRedirectDestination() {
    $this->drupalGet('admin/reports/upgrade');
    $this->assertUrl('admin/reports/dblog?type%5B%5D=migrate_drupal_ui');
  }

  public function testRedirectDestinationWithoutView() {
    // Delete the watchdog view
    $this->drupalGet('admin/structure/views/view/watchdog/delete');
    $this->assertResponse(200);

    $this->submitForm([], 'Delete');
    $this->assertResponse(200);

    $this->testRedirectDestination();
  }
}

Following https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial, an existing test runs as expected with ../vendor/bin/phpunit --filter testMigrateUpgradeReviewPage modules/migrate_drupal_ui/tests/src/Functional/MigrateUpgradeFormStepsTest.php.
However, when I do the same for my above test -- ../vendor/bin/phpunit --filter testRedirectDestination modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php -- I get
PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest' could not be found in '/Users/MrWeiner/Sites/DockerSites/testing/web/core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php'. in /Users/MrWeiner/Sites/DockerSites/testing/web/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:102

It looks like a namespace issue but I do not understand why it'd be looking for Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest' instead of Class 'Drupal\Tests\migrate_drupal_ui\Functional\MigrateControllerTest'. Do I need to register my test somewhere or do something else to ensure that it's autodiscovered?
Original Question: We've got https://www.drupal.org/files/issues/2019-04-12/adding-custom-access-2904546-24.patch posted in https://www.drupal.org/project/drupal/issues/2904546 with the request "for a functional test with and without that view enabled". The patch itself is very simple so I'd assume that the test would be very simple as well. I just don't have any experience writing tests so I don't really understand what I'd be testing for/asserting here or how to test for both the view existing and not existing.
Comment: Thanks @mradcliffe, I think your comment helped me to break down what was required. I've edited the question to refer to a specific error I'm receiving now instead of the broader question regarding testing.
Comment: I think this is a bit too broad. heddn mentioned a resource in the issue for getting started with tests. If we take a step back to look at testing in general, usually we want to assert one value (or behavior) that is expected from an issue, user story, acceptance criteria, or whatever. So if "admin/reports/upgrade doesn't correctly redirect. If views is enabled, it should use URL arguments instead of setting the session" is the issue summary, then we should assert we are at a given URL after clicking a link or whatever.
Answer: It turns out that the issue was that MigrateControllerTest was defined as an abstract class. Defining it as a regular class cleared this up.
Comment: Ah, yes. Abstract classes can only be extended, not instantiated.
Comment: Who would have thought that copying code straight from another test wouldn't work as expected?!
Comment: It's another test? Or is it a class that a test extends from (to provide common setups)?
Comment: I think it was `MigrateUpgradeExecuteTestBase` and I'd assumed it was running actual tests since it contains the method `testMigrateUpgradeExecute`. I saw/see that it has "base" in the name, so I figured it was being leveraged elsewhere but I didn't understand that it could inherently only be extended
Comment: I don't have anything in front of me so take this with a grain of salt, but since the class name does not end in *Test* that it was skipped. I.E. `MigrateUpgradeExecuteTestBase` is never ran, you'd extend that and _that_ class would end with *Test* and executed. Like `class My MigrateUpgradeExecuteTest extends MigrateUpgradeExecuteTestBase`. In your code posted above, you'd just change your class to `MigrateControllerTestBase`, then extend that with the actual test class. More on abstract classes: https://www.php.net/manual/en/language.oop5.abstract.php
Comment: Ah okay, that clear up some of the fog around TestBase classes -- thanks for the notes!


Abort NSIS silent installer

Question: I've created an NSIS installer that installs a certain program. Everything works fine but I wonder if it is possible to abort the installation when it runs in silent mode.
So is there a way to abort an installation when I install an NSIS installer via the command line with this command: installer.exe /S /D=Path/To/Directory?
I tried to abort it via CTRL+C as it works for other programs, too, but that didn't work.
Answer: NSIS is not a console program so it is not going to respond to console keyboard shortcuts.
Even if you could trick it into behaving like a console program when started silent it is not going to work in a stable manner because CTRL+C will just kill the process unless the program has added extra code to handle the aborting events...
Comment: Ok thanks, that's what I thought... I'll just accept it that it's not easily possible to abort a silent NSIS installer.

Abort NSIS silent installer


Bayesian analysis used merely as a computational tool?

Question: I have sometimes seen some statisticians used bayesian analysis and related techniques such as MCMC simply as a tool when a frequentist approach is not satisfying, typically for example when the maximum likelihood estimator is hard to find or takes too much time to compute.
In these case they focus only on the definition of the model and estimation (by MCMC for example) and barely on the choice prior distributions (from what I've seen).
I guess they use flat distributions by default but the particular choice of a prior is never discussed, maybe because of the large number of parameters the model may have and the difficulty to assign a meaningful prior distribution to each one of them.
Is it something usual to switch to a bayesian analysis and use it merely a as computational counterpart of a frequentist approach when the latter performs poorly?
My feeling is that bayesian and frequentist are very distinct statistical framework (at least that's what my teachers taught me!) and using one or another shouldn't be justified simply by computational purposes and moreover the choice of the prior distributions should at least be carefully made.
I know this is not really a statistical question but I just would like to know what pure bayesians think about this kind of use of bayesian analysis. Sorry in advance if it does not fit this site.
Comment: A case that I can think of that a Bayesian analysis might be preferred to a frequentist, is when the parameter is not identifiable
Comment: If in the frequentist case you cannot compute the likelihood then also in the bayesian case you will not be able to compute the posterior as it is the product of likelihood with prior. Also, I assume in the frequentist case you use some kind of optimization procedure which I believe in general is a faster procedure than running an MCMC algorithm.
Comment: *"I have sometimes seen some statisticians used bayesian analysis and related techniques such as MCMC simply as a tool when a frequentist approach is not satisfying"* Everything is a *tool*. Frequentist or Bayesian, there is no distinction. If some of these tools might be easier to compute then it certainly will be used more often (I am sure this works in *both* ways).
Answer: The set of methods called "frequentist" statistics is quite broad.  It allows you to specify any proposed estimator you want and then investigate its long-run properties conditional on the true values of the parameters.  This method only counts an estimator out completely if it is "inadmissible", meaning that it is dominated by another available estimator (i.e., it gives equal/higher risk over every possible value of the parameter and higher risk over at least some parameter values).
Now, there is a famous theorem that says that, under wide conditions, Bayesian estimators are admissible --- i.e., they are not dominated by other estimators.  Bayesian estimators tend to be biased (since they incorporate prior information) but they are also consistent under fairly wide conditions.  This means that they are estimators that will tend to perform well in terms of the frequentist criteria.  Consequently, frequentists usually consider these estimators as one option that can be used in their analysis.
By definition, "pure Bayesians" are going to adopt the Bayesian methodology in all cases.  Most pure Bayesians are going to have adopted this methodology by being convinced of its underlying philosophical and mathematical superiority.  However, part of the motivation for adoption of Bayesian methods may be the knowledge that even under the frequentist paradigm, these methods tend to perform well according to frequentist criteria.  As to what a pure Bayesian would think of a frequentist using a Bayesian estimator, I suppose it is somewhat like what a priest would think of an atheist who decides one day to pray for spiritual guidance (e.g., on the basis that it can't do any harm even under their own philosophy).  They would likely see this as a desirable change in behaviour, improperly motivated, but also possibly a useful entry-point to try to convince them that the general philosophy underpinning that activity is coherent and desirable.
Comment: This makes the matter more tribal or theological than I think it now is. Here is a naive example. Is looking at a graph of data alone "frequentist" and so should "pure Bayesians" (your term not mine) decline to do it?  I think many statistical people would recognise that the Bayesians have excellent arguments but don't practise them because (a) they were not trained that way (b) it is, or appears to be, hard work to re-educate yourself (c) the field you are in expects mostly frequentist methods. These are mundane practicalities, but often personally compelling.
Comment: Sorry about that. My fault in missing the original mention. This is a case where the question is familiar and I am interested in the answers....
Comment: @NickCox: No, not my term; OP's term.  I agree that OP is asking about a hypothetical extreme class of people, but that is what he is asking.  (I also put "pure Bayesians" in quotes because I share your scepticism of the term.)
Answer: In a 2002 paper with Arnaud Doucet and Simon Godsill, Marginal maximum a posteriori estimation using Markov chain Monte Carlo, we use an MCMC approach to derive the maximum likelihood estimator in latent variable models where the observed likelihood is not available. By repeating the number of repetitions of said latent variables in a simulated annealing spirit. Similar proposals were proposed subsequently by

Gaetan and Yao (2003) under the name of multiple imputation Metropolis-EM
Lele et al. (2007) under the name of data cloning
Jacquier, Johannes and Polson (2007) under the name of MCMC maximum likelihood
Answer: Comment: Here are a few reasons why a frequentist statistician might use a Bayesian approach.
Computational convenience, as @Fiodor1234 says, may not be high on the list.
One such example might be use of the Jeffreys posterior probability interval as a confidence interval for a binomial proportion. For example, if you have $x = 42$ successes in $n=100$ trials, the asymptotic Wald interval is not the best
choice because of the small sample size. The Agresti-Coull interval is easy to compute and comes close to more accurate intervals that are somewhat intricate to compute. The Jeffreys interval, based on the noninformative Bayesian prior $\mathsf{Beta}(.5, .5)$, is easy to compute in R and has good frequentist properties.
<code>p.hat = 42/100
CI.Wald = p.hat + qnorm(c(.025,.975))*sqrt(p.hat*(1-p.hat)/100)
round(CI.Wald,4)
[1] 0.3233 0.5167

p.est = (42+2)/(100+4)
CI.Agr = p.est + qnorm(c(.025,.975))*sqrt(p.est*(1-p.est)/104)
round(CI.Agr,4)
[1] 0.3281 0.5180

CI.Jeff = qbeta(c(.025,.975), 42+.5, 100-42+.5)
round(CI.Jeff,4)
[1] 0.3267 0.5179
</code>
Proper support of distribution. In an attempt to find
the prevalence of a disease from screening test data, traditional methods can give an interval for prevalence
that extends beyond $(0,1).$ By using a Gibbs sampler with a beta prior distribution, it is possible to get a useful
interval estimate for prevalence. (Since the beta prior has the unit interval as support, then the posterior distribution will also.) See example..
'Simulate' latent data. Sometimes one wants to test or to give
a parameter estimate for latent data, which can be reliably reconstructed using a Gibbs sampler. One simple example is to know the variability of groups in a one-way random-effects ANOVA. Observed values from the groups are available, but the components of variance due to the various groups (separate from overall variance) are typically latent.
Comment: @SingleMalt. See [Wikipedia](https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval) under Jeffreys Interval. Beta prior conjugate to binomial likelihood gives relevant beta posterior. // Suspect that claim there of good frequentist properties is consensus based on fairly widespread use.  // Prior $\mathsf{Unif}(0,1) \equiv \mathsf{Beta}(1,1)$ is sometimes used instead of Jeffreys prior $\mathsf{Beta}(.5,.5)$ preferred by Bayesians for technical reasons.
Comment: Edits show 4 decimal places for CIs and repair typos.
Comment: "[H]as good frequentist properties" is a consequence of the Jeffreys interval being computed by a conjugate prior?
Answer: Other reasons to use Bayesian approaches include

getting more accurate inference when the log-likelihood is very non-Gaussian.  For example, in binary logistic regression standard p-values and confidence intervals may be inaccurate whereas Bayesian quantities are exact.
getting accurate uncertainty intervals for complex derived parameters.  In the frequentist world we frequently have to resort to the delta method to get approximate confidence intervals.  Not only is this labor intensive, but the result is often very unsatisfactory because such intervals are forced to be symmetric when they should have been asymmetric in order to have accurate coverage with respect to both tails.  One example is state occupancy probabilities in a state transition model, which involve recursive matrix multiplications are a mess to deal with in the frequentist domain.  With MCMC (let's say you have 4000 posterior draws from the multivariate distribution of all parameters together) you just compute the complex derived parameter 4000 times and estimate the highest posterior density interval from those 4000 numbers.


Best way to update from Windows 10 Enterprise 1607 to 1903 offline

Question: We have a customer that our manufacture shipped some (4) PCs to a customer with a Windows Enterprise 1607 edition on them. The customer found a virus and want to run Windows update on these systems.
As I test, I ran Windows updates on the same OS. After about 3 hours it, was stuck on this download:
<code>2019-04 Cumulative Update for Windows 10 version 1607 for x64-based Systems (KB4493470) at 95%.
</code>
I was accidentally cut the power to it, and after several reboots, it now seems to be successfully updated to Windows 10 1903.
Question: Is there a way I can do all the downloads offline, then just apply them? How would I identify exactly which files I need?
WSUS is not an option as this is a customer site and we have no control over how they do Windows updates.
I also that you can do it with an iso. I this possible, or would that wipe out the existing software?
Any help or suggestions are much appreciated. The hardest part is knowing if it's downloading or just stuck (as it apparently was this morning).
Answer: If you select the options correctly when booting the ISO, it is entirely possible. It should be obvious when running the setup. Worth noting, you can start the installer from the ISO whilst the machine is running, just double click the ISO in explorer to mount it and then run the setup exe in the mounted ISO.
Although, this kind of thing does nothing to mitigate the impact of the virus, you should ensure you're absolutely positive that the system has been disinfected. Good luck!


Struggling to apply the Implicit function theorem

Question: I'm struggling with applying the implicit function theorem for the following expression. As an economist I'm not sure if I'm missing something extremely easy, if so, I apologise. For other derivatives in the paper I'm successful using the IFT. Any help at pointing me in the right direction would be greatly appreciated.
Let $c^*$ be defined implicitly as
\begin{equation}
c^*=\frac{b(e)y+a\int_0^{c^*}c\;G(c)\;dc}{r+b(e)+aG(c^*)}
\end{equation}
where $G$ is a distribution.
I would like to find the following derivative $\frac{dc^*}{de}$. The papaer I'm reading states that
\begin{equation}
\frac{dc^*}{de} = \frac{(y-c^*)b'(e)}{r+b(e)+aG(c^*)}
\end{equation}
The idea is to use the implicit function theorem on $H(c^*,e)=c^*-\frac{b(e)y+a\int_0^{c^*}c\;G(c)\;dc}{r+b(e)+aG(c^*)}$ which should give
\begin{equation}
\frac{dc^*}{de} = - \frac{\frac{\partial H}{\partial e}}{\frac{\partial H}{\partial c^*}}
\end{equation}
I find
\begin{equation}
\frac{\partial H}{\partial e} = -\frac{b'(e)(r+b(e)+aG(c^*))-b'(e)(b(e)y+a\int_{0}^{c^*}cG(c)dc)}{(r+b(e)+aG(c^*))^2}
\end{equation}
\begin{equation}
\frac{\partial H}{\partial c^*} = 1-\frac{ac^*G(c^*)(r+b(e)+aG(c^*))-aG'(c^*)(b(e)y+a\int_{0}^{c^*}cG(c)dc)}{(r+b(e)+aG(c^*))^2}
\end{equation}
Answer: I found it easier to type the variable $c^* $ as $C$ in what follows.
P.S. This revised answer  corrects a mistake I made earlier when I tried to type (1). However, even with this corrected equation for (1)  as written below, I still am unable to reconcile the results that you reported  occurred in the paper. Perhaps that paper has a typo??
The easiest way to apply the implicit function theorem is to first completely clear of denominators:  re-write your initial identity as
(1) $$0= C (r + b(e) + a G(C)) -b(e)y - a \int _0^C cG(c)dc= H(C, e)$$
With this choice of the implicit defining function $H(e,C)$ you see readily that
$$\partial H/\partial C= (r + b(e) + a G(C)) + a C G'(C) - a CG(C)  = r+ b(e) + a CG'(C) + a G(C) - a CG(C)$$
and $\partial H/\partial e= (C-y) b'(e) $
hence
$dC/de=- \frac{\partial H/\partial e}{\partial H /\partial C}=- \frac{(C-y) b'(e)}{ r+ b(e) + a CG'(C) + a G(C) - a CG(C)}$
This answer disagrees with what you claim the paper asserts. Perhaps there was a  typo in the paper you read, or perhaps you mistyped the equations that were in that paper?
Comment: Yep that exactly what I needed to do! In fact you made a typo when defining $H(C,e)$. The integral is missing the $C$ multiplying $G(c)$ in the integrand. Correct answer follows after that. Thanks!


Qual significado do simbolo || '-' || no SQL?

Question: Estou realizando uma consulta em um banco de dados Oracle e me deparo com esta simbologia  || '-' ||, na minha query. Qual o significado?
Select
  xf0cdloc || '-' ||  XN4CDEMP AS LOCOMOTIVA,
From
  Trem

Comment: @MarllonNasser no SqlServer e no MySQL por exemplo a concatenação de colunas é diferente. No SqlServer vc concatena utilizando o + por exemplo
Comment: Pode colocar pelo menos toda a expressão que tem isso? OU a *query* toda. Desta forma, está incompleto.
Comment: Isso varia de banco para banco.
Comment: desculpa minha ignorância, @rray, sei que a pergunta pode aparentar incompleta... pra mim isso é o "simbolo" de concatenação entre colunas, não? Mas minha pergunta pra ti é: o que pode variar de banco pra banco? Oo. Isso pra mim sempre vai ser concatenação entre colunas.. rs
Answer: No Oracle e no Postgres os dois pipes (||) são o operador de concatenação.
Já o MySQL por padrão não usa um operador mas uma função, concat() entretanto é possível trocar ela pelos pipes alterado o valor da variável sql_mode para PIPES_AS_CONCAT
SELECT 'teste' || 'algo'

Retorna uma coluna concatenando os dois valores.
Documentação - Oracle
Documentação - Postgres
Documentação - MySQL
Answer: O que seu código está fazendo é é selecionar duas colunas da tabela Trem, a xf0cdloc e a XN4CDEMP, e está construindo uma coluna virtual que só existirá nessa consulta. Essa coluna virtual chama LOCOMOTIVA e seu conteúdo é a concatenação do conteúdo de xf0cdloc depois um traço ('-') e em seguida já cola o conteúdo de XN4CDEMP.
O || é o operador de concatenação. Ele é definido na especificação do SQL padrão. Mas alguns sistemas de banco de dados que não o implementam, então esta sintaxe pode não funcionar dependendo de onde use. Por causa disto algumas pessoas recomendam usar a função CONCAT() quando deseja que o código seja portável para outros sistemas.
Em outros sistemas ou outras linguagens seria o equivalente a fazer isto:
Select
  xf0cdloc + '-' + XN4CDEMP AS LOCOMOTIVA,
From
  Trem

Coloquei no GitHub para referência futura.
Answer: Server Para Concaternar String, no Oracle é possivel concaternar string com number, entretanto no SQL SERVER é necessário converter number para string


line.split("[ ]+") means split with space?

Question: Hello if i have txt file containing lines like:
newmtl material0
Ka 1.000000 1.000000 1.000000
Kd 1.000000 1.000000 1.000000
Ks 0.000000 0.000000 0.000000
Tr 1.000000

and it's being split like:
if(line.startsWith("Ks")){
String[] str=line.split("[ ]+");}

It returns
0.000000
0.000000
0.000000

How come "[ ]+" means split with spaces?? Couldn't find anything where this was referenced.
Answer: [ ] is a space within brackets. With a + added, it means "1 or more spaces." This is a regular expression (click here to learn more).
For example, [abc]+ will match aaa, acba, cbabcbab, or any combination of one or more of the letters a, b, and c. The [] means "one of the things in here" and the + means "one or more."
More examples:
f[ao]o      will match "foo" and "fao"
ya+y        will match "yay" or "yaaaaay" or "yaaaaaaaaaaaay"
hooray[!1]+ will match "hooray!!!!" or "hooray!!1!!1!!!!1" or "hooray!111"

Answer: String.split() takes a regex as an argument. And this one is poorly written, it could have been:
" +"

which is a regex matching one or more spaces.
This is documented in the Javadoc.
Answer: In this case, your question suggests that a space is required in the Regex. But what seems to be your intention is capturing one or more spaces.
Though you can write " +" for this, commonly, "\n" and "\t" are also considered for accuracy. Hence, you can use the expression:
"\s+"

which is represented in Java as:
"\\s+"

to avoid compiler errors.


Suffix incrementally by group in a vector

Question: Hi suppose I have a vector as such:
v <- c( "k", "k", "c", "c", "k", "c")
#I can suffix this by doing a paste
paste0 (v,"1")
"k1" "k1" "c1" "c1" "k1" "c1"

However is there a way to to incrementally add one to each of the group?
What I want is the below without looping.
"k1" "k2" "c1" "c2" "k3" "c3"

Is this possible?
Answer: We can use base R ave with seq_along to calculate occurence of each unique value in v and paste it as suffix.
ave(v, v, FUN = function(x) paste0(x, seq_along(x)))
#[1] "k1" "k2" "c1" "c2" "k3" "c3"

Or a bit more compact :
paste0(v, ave(v, v, FUN = seq_along))
#[1] "k1" "k2" "c1" "c2" "k3" "c3"

Answer: We can use make.unique which will increment for each duplicated element
make.unique(v, sep="")
#[1] "k"  "k1" "c"  "c1" "k2" "c2"


Python: change elements position in a list of instances

Question: I have a list that is made of class instances:
MyList = [<instance1>, <instance2>, <instance3>]

I would like to change the position of the third element, <instance3>, that should now stay in the position index = 1, so with the following output:
MyList = [<instance1>, <instance3>, <instance2>]

I have built a simple example that works:
a = [1,2]
b = [3,4]
c = [5,6]
d = [a,b,c]

The code above gives me the following print d output:
d = [[1, 2], [3, 4], [5, 6]]

I'm able to swap the elements (1) and (2) with the following method:
d.remove(c)
d.insert(c,1)

which gives me the following output (that is the one that I want):
d = [[1, 2], [5, 6], [3, 4]]

However, when I try to make the same with my list of instances, I get the following AttributeError:
AttributeError: entExCar instance has no attribute '__trunc__'

Someoene can tell me if I'm wrong in the method (example: you cannot use this technique with list of instances, you should rather do "this or that") or in the way I'm setting the code? The following script is the actual code I'm trying to run getting the error:
newElement = self.matriceCaracteristiques[kk1]
self.matriceCaracteristiques.remove(newElement)
self.matriceCaracteristiques.insert(newElement,nbConditionSortieLong)

Thanks in advance.
EDIT: SOME DETAILS MORE
entExCar is the class which is being instatiating
self.matriceCaracteristiques is the list I want to manipulate
newElement is the element I want to remove from its original position (kk1) and put back into the new position (nbConditionSortieLong).
Comment: see http://stackoverflow.com/questions/2493920/how-to-switch-position-of-two-items-in-a-python-list
Comment: In general, your code looks fine. Note that if you want to swap two elements in a list, your can do it like this: `my_list[1], my_list[2] = my_list[2], my_list[1]`. There should be no issue doing this with a list of instances. Moving on from that, I think there must be something else that is wrong. Is the Error coming when you swap the elements, or later when you try and use `self.matriceCaracteristiques`? Is `nbConditionSortieLong` an integer?
Comment: @laike9m thanks for your suggestion. The problem is that I don't want to swap the elements, but just moving some of them from one position to the other (for some reasons). I mean, if I have:
`MyList = [1,2,3,4,5]` and I want the 5 to come after the 2, I cannot swap the elements `3` and `5` cause I would get this: `MyList = [1,2,5,4,3]` and instead I need to get this `MyList = [1,2,5,3,4]`
Comment: @three_pineapples yes, but as I wrote to laike9m swap is not exactly the action I want to take. So, the error comes exactly when I execute the last instruction (the `insert` method to the list) and yes, `nbConditionSortieLong` is an integer and there's no way it can not to be :)
Answer: What about:
MyList.insert(index_to_insert,MyList.pop(index_to_remove))

Answer: First, I didn't get the error you mentioned.
Second, it seems that you made a mistake in using insert, should be insert(1, c) rather than insert(c, 1), see docs
>>> d = [[1, 2], [5, 6], [3, 4]]
>>> c = d[1]
>>> d.remove(c)
>>> d
[[1, 2], [3, 4]]
>>> d.insert(c, 1)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    d.insert(c, 1)
TypeError: 'list' object cannot be interpreted as an integer
>>> d.insert(1, c)
>>> d
[[1, 2], [5, 6], [3, 4]]

Comment: Ok, this is really funny because I swear in my Python shell (when I was trying the method) I wrote `d.insert(1,c)` but I swapped them into the project :D Thanks a lot, now it works!
Answer: values[0], values[1] = values[1], values[0]

this work fine for me.


If $A,B$ are $n\times n$ matrices and we have that $AB= I_n$, why do we need to show that $BA=I_n$ as well to show that $A$ is an inverse of $B$?

Question: If $A,B$ are $n\times n$ matrices and we have that $AB= I_n$, why do we need to show that $BA=I_n$ as well to show that $A$ is an inverse of $B$?
Comment: [related](https://math.stackexchange.com/q/3852/12952)
Answer: No, we do not need to show this, since in the group $GL_n(K)$ it follows that a left inverse is also a right inverse.
Reference: For square matrix, right or left inverse is equivalent to inverse.
Comment: @OP: Technically you *do* need to show that $BA=I$. But as Dietrich Burde pointed out, this is automatically true when $A,B$ are matrices.

For linear maps in infinite dimensions, you can have $AB=I$ while $BA\neq I$, so generally speaking you should be aware that one *should* show $AB=I$ *and* $BA=I$.
Answer: At first glance, it might seem necessary to show this because it is a matter of definition.
Moreover, consider the real vector space $E$ of all $C^\infty$ maps $f:\mathbb{R}\to\mathbb{R}$, the ring $A$ of all linear maps $T:E\to E$ and the two following elements of $A$ :
$\phi:E\to E,f\mapsto f'$
and
$\psi:E\to E,f\mapsto[x\mapsto\int_0^xf(t)\,dt]$
It can be seen that $\phi$ has a right inverse but no left inverse and $\psi$ has a left inverse but no right inverse.
In fact : $\phi\circ\psi=id_E$ but neither $\phi$ nor $\psi$ is a bijection.

Now, if $u,v:\mathbb{R}^n\to\mathbb{R}^n$ are linear maps such that $u\circ v=id_{\mathbb{R}^n}$ then $u$ is surjective and $v$ is injective, hence both are bijective (because both are linear and $\mathbb{R}^n$ is finite dimensional.
It is now clear that : $v\circ u=u^{-1}\circ\left(u\circ v\right)\circ u=u^{-1}\circ u=id_{\mathbb{R}^n}$.
Hence the proposition : if $A,B$ are square $n\times n$ matrices such that $AB=I_n$ then $BA=I_n$.
Answer: Here is an easy way to prove that $AB=I_n$ implies $BA=I_n$ without appealing to any advanced concepts or algebraic structures.
Recall that a matrix is invertible if and only if its determinant is different from $0$.
Now, taking the determinant of both sides we have that $\det(AB)=1$. Since the matrices are square, this means that $\det A \cdot \det B=1$. This implies that $\det A, \det B \neq 0$, so $A$ and $B$ are invertible.
Left multiply the initial relation by $A^{-1}$ to get that $B=A^{-1}$. Now since $A^{-1}\cdot A=I_n$, we get that $BA=I_n$.
Answer: This answer addresses the author's original question without appealing to (basic facts of) groups.
As to how to prove that the right-inverse implies the left-inverse, there are many answers of that here.
As to the why this must be proven, which is at the crux of the original question, it is clear from the definition of matrix multiplication and working with examples that the operation is not commutative. Thus, if $AB = I_n$, then there is no guarantee that $BA = I_n$.
Comment: can you have $AB=I_n$ without $BA=I_n$?
Comment: @stochasticmrfox No, see the second link in my answer.


Como publicar um .EXE seguro, sem ser através do Click Once .Net

Question: O meu cenário é composto da seguinte maneira:
Possuo aplicativos, que são configurados conforme cada cliente, são aplicativos vendidos em massa, tenho um sistema de apoio, que automatiza essa configuração e gera um executavel por cliente.
Após gerar esse executavel(Instalador Inno Setup), o mesmo e enviado para o ftp do nosso site, até ai tudo bem.
Porém, quando o cliente vai baixar esse sistema ele exibe aquela mensagem que o arquivo pode não ser seguro, se deseja manter.
ex: http://goo.gl/2OSqgV
O que preciso fazer para que esse arquivo possa se tornar "seguro", é algo no site? ou na aplicação? Estamos perdendo muitos clientes devido a essa complicação no download.
[upd]
Seguindo a dica do amigo tentei:
Mas ainda não consegui resolver meu problema, gerei o certificado através do makecert, dei o sign. O download ainda fica como se fosse perigoso.
Ai peguei esse certificado e instalei na minha maquina, ai o sistema detectou corretamente, porém não posso instalar esse certificado na maquina de cada cliente, será que sendo assim só posso utilizar os certificados pagos?
Answer: Basicamente você vai precisar de um Certificado Digital de Assinatura de Código.
Há duas maneiras de se conseguir um Certificado Digital:

Fornecedor Certificado - Ex: Comodo
Gerar seu próprio certificado com Makecert

E Para você assinar o aplicativo pode usar uma ferramenta de Authenticode da microsoft o SignCode.
Para ter mais conhecimentos sobre isso sugiro dar uma pesquisada sobre Certificado Digital, Authenticode, etc.

Gerar o seu próprio certificado não é uma opção válida, vide que ele
  serve apenas para testes. O uso de um certificado só faz sentido pelo
  fato dele ser emitido por uma entidade que é considerada confiável
  pelo seu navegador e ela pode confirmar que o certificado realmente é
  válido. - @Leandro Godoy Rosa

Links para consulta:
Implantação e a assinatura de Authenticode
Comodo
Certificado Digital
Comment: Gerar o seu próprio certificado não é uma opção válida, vide que ele serve apenas para testes. O uso de um certificado só faz sentido pelo fato dele ser emitido por uma entidade que é considerada confiável pelo seu navegador e ela pode confirmar que o certificado realmente é válido.
Comment: Criando meu próprio Certificado, posso ter algum problema? Porque seria vantagem comprar? caso posso fazer o meu?
Obrigado pela resposta @MeuChapeu já clareou algumas coisas.
Comment: Creio que não teria problema em criar o próprio certificado, porém ele não seria emitido por uma `Certificadora Digital`.  Da uma olhada neste link --> http://www.devmedia.com.br/gerando-um-certificado-digital-proprio/31506
Comment: Posso ter entendido errado, mas ainda não consegui resolver meu problema, gerei o certificado, dei o sign. O download ainda fica como se fosse perigoso, ai peguei esse certificado e instalei na minha maquina, ai o sistema detectou corretamente, porém não posso instalar esse certificado na maquina de cada cliente, será que sendo assim só posso utilizar os certificados pagos?
Comment: Exatamente isso que o @LeandroGodoyRosa.
Comment: @MeuChapeu acho que vc pode complementar sua resposta com o comentário do Leandro.
Comment: @MeuChapeu um servidor, contendo um certificado SSL, poderia auxiliar em alguma coisa?


hibernate query for select * from table where id in (query)

Question: What is hibernate query for below sql?
select * from DB_GROUP
where DB_GROUP_ID in
(select DB_GROUP_ID from DB_GROUP_ORG where DB_ORG_ID='306132');

Answer: You need to specify entity column names while using in this query.I used same names what you gave in the table
select model from  DB_GROUP  model where model.DB_GROUP_ID
in
(select model2.DB_GROUP_ID from DB_GROUP_ORG model2 where model2.DB_ORG_ID='306132');


como pegar uma sequencia correta no order by mysql?

Question: tem uma sequência de números 1 à 20 eu gostaria de saber se tem como pegar a sequencia de numero correta por exemplo:
1,2,3,4,5,6,7,8,9,10,11...
como essa query select * from tabela order by numero asc;
ele pega assim:
1,10,11,12,13,14,15,16,17,18,19,2,20...
tem uma maneira de pegar a primeira sequencia que mostrei acima usando o order by
ja tentei usar um field para o order by não deu certo
Comment: O melhor mesmo seria arrumar a coluna pro tipo certo. Se são só números, não devia ser CHAR/VARCHAR.
Comment: A coluna que possui essa sequencia de números está no tipo numerico?
Answer: SELECT * FROM tabela ORDER BY CAST(coluna_numero AS unsigned) ASC
Comment: juliano sua dica deu certo valeu
Answer: Podem existir outras maneiras de resolver isso,
mais você pode tenar da seguinte forma:

SELECT * FROM table ORDER BY LENGTH(id), id


Run foreach on parsed JSON nested array

Question: Building a table using parsed JSON file as data input.
Each value inside the JSON array should be distributed, meanwhile when running the code both values in the JSON array is injected in the same element xml value.
In the code area where I build the "xsl:element" I can manually swap between following which gives me the array content one at at time, but I don't understand how I would make the code iterate over the array data:
<xsl:value-of select="*[1]"/>
<xsl:value-of select="*[2]"/>

JSON:
<data>
{
  "balance-sheets": {
    "sheet-results": {
      "sales": {"values": [3, 5], "title": "Annual sales summary"},
      "costs": {"values": [7, 9], "title": "Accumulated costs per year"}
    }
  }
}
</data>

XSL:
<?xml version="1.0" encoding="UTF-8"?>

<xsl:transform version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ix="http://www.example.org/1"
  xmlns:se="http://www.example.org/2"
  expand-text="yes"
>

  <xsl:output method="xml" indent="yes"/>

  <xsl:mode on-no-match="shallow-skip"/>

  <xsl:attribute-set name="base">
    <xsl:attribute name="name">se:{parent::*/@key}</xsl:attribute>
  </xsl:attribute-set>

  <xsl:template match="data">
    <store>
      <xsl:apply-templates select="json-to-xml(.)/*"/>
    </store>
  </xsl:template>

  <xsl:template match="*[@key='sheet-results']">

        <xsl:for-each select="*">

            <xsl:value-of select="*[2]"/>

          <xsl:for-each select="*">

                <xsl:element
                  name="ix:nonFraction"
                  use-attribute-sets="base"
                  >
                  <xsl:value-of select="*"/>
                </xsl:element>

          </xsl:for-each>

        </xsl:for-each>

  </xsl:template>

</xsl:transform>

Result:
<?xml version="1.0" encoding="UTF-8"?>
<store xmlns:ix="http://www.example.org/1" xmlns:se="http://www.example.org/2">

         Annual sales summary

               <ix:nonFraction name="se:sales">3 5</ix:nonFraction>

               <ix:nonFraction name="se:sales"/>

         Accumulated costs per year

               <ix:nonFraction name="se:costs">7 9</ix:nonFraction>

               <ix:nonFraction name="se:costs"/>

</store>

Wanted result:
<?xml version="1.0" encoding="UTF-8"?>
<store xmlns:ix="http://www.example.org/1" xmlns:se="http://www.example.org/2">

         Annual sales summary

               <ix:nonFraction name="se:sales">3</ix:nonFraction>

               <ix:nonFraction name="se:sales">5</ix:nonFraction>

         Accumulated costs per year

               <ix:nonFraction name="se:costs">7</ix:nonFraction>

               <ix:nonFraction name="se:costs">9</ix:nonFraction>

</store>

Answer: Consider the following simplified example:
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:js="http://www.w3.org/2005/xpath-functions"
exclude-result-prefixes="js">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">

        <xsl:for-each select="json-to-xml(data)/js:map/js:map/js:map/js:map">

                    <xsl:value-of select="js:string[@key='title']"/>

                <xsl:for-each select="js:array[@key='values']/js:number">

                        <xsl:value-of select="."/>

                </xsl:for-each>

        </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Applied to your input example, this will return:
Result
<?xml version="1.0" encoding="UTF-8"?>

      Annual sales summary
      3
      5

      Accumulated costs per year
      7
      9

Run foreach on parsed JSON nested array


Duplicate UPDATE MySQL in 2 or more connections

Question: I have a high traffic app which sometimes caused a problem while updating a record. For example, there are 5 balls on sale. Then, 2 users make the same connection on the same time to buy that 5 balls. Then, we are going to use this query
UPDATE table SET balls=balls-5 WHERE marketId=3212
The problem, that balls is updated to -5 (negative 5). This happen occasionally but I just want to know how to prevent this one. The problem only happened when the update updated on the same timestamp. There is no time diff.
How to handle MySQL UPDATE properly in multiple connections
Answer: Assuming that a prerequisite for doing this update is that the balls value cannot end up being negative, you could just add a check for that to the update statement:
UPDATE yourTable
SET balls = balls-5
WHERE balls >= 5 AND marketId = 3212;

Then, if two threads come in at the same time, only one of them should get a lock on the marketId = 3212 record to update it.  In the scenario you described in your question, the first thread should succeed, while the second should fail to update.
Comment: Thank you, I understand how it works now. So, the conclusion is UPDATE or DELETE is locking a row and SELECT does not lock it? That is why, when user get positive, they both will update the row
Comment: On the top of code before UPDATE method, I am doing SELECT balls FROM table WHERE balls >= 5, when balls is not enough it will cancel the process.
Comment: @StuartWilliam ... but that's not enough, because if the two threads both simultaneously select and get a positive result, they will then proceed to attempt doing the update.
Comment: More or less, yes, what you stated is correct.  You may the MySQL [documentation here](https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html) for more information.


ImageIO.read illegal argument exception - raster bands/colour space components?

Question: Apologies for the somewhat vague title, I can't work out what the keywords are here. The setup's quite simple, I'm opening an image with
ImageIO.read(new File(filename));

This works for most files, however for one I get an IllegalArgumentException with the detail: "numbers of source Raster bands and source color space components do not match". This image was obtained via wget on a valid Flickr URL, and I've used other images obtained this way, so the method for obtaining images seems sound in principle. I'm not sure what's causing the exception.
A workaround would be more than acceptable - I'm not fussed with using ImageIO in particular, and the image looks fine visually. I just need to get it being read without Java freaking out!
Here's the image in question, in case it's of any use:
Comment: I get the same error (at least when using `ImageIO.read(new URL("http://i.imgur.com/rC6Jk.jpg"));`). Is this the only B/W image you are processing?
Comment: Hard to say - the nature of the image retrieval process is very undirected (the idea is that the software is autonomous!) It's the only one with such low saturation though. Do you think that's the cause?
Comment: Have you found any solution for this?
Comment: Nope. I've had to rely on the fact that other images will be found if this error is raised.
Answer: So I was having this same issue and found that the image was gray-scale and that the default ImageIO.read implementation was not figuring that out because the image metadata wasn't quite as expected.  I wrote a work around that retries the load as 'BufferedImage.TYPE_BYTE_GRAY' if it fails the main load.
            Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);

        Exception lastException = null;
        while (iter.hasNext()) {
            ImageReader reader = null;
            try {
                reader = (ImageReader)iter.next();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(stream, true, true);
                Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
                while (imageTypes.hasNext()) {
                    ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                    int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                    if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                        param.setDestinationType(imageTypeSpecifier);
                        break;
                    }
                }
                bufferedImage = reader.read(0, param);
                if (null != bufferedImage) break;
            } catch (Exception e) {
                lastException = e;
            } finally {
                if (null != reader) reader.dispose();
            }
        }
        // If you don't have an image at the end of all readers
        if (null == bufferedImage) {
            if (null != lastException) {
                throw lastException;
            }
        }

Comment: The beauty of SO:  A problem that would have taken me two hours to figure out now takes 10 minutes.  Thank you, Tate Moore.
Comment: Wonderful stuff! Never thought anyone would come back and knock this one down but you did! Lovely stuff.
Comment: when I use this solution after it fails with ImageIO.read(InputStream) it does not execute the rest of the code (while (iter.hasNext()) is false), but if I omit ImageIO.read(InputStream) part it does the job.
What is wrong with my code?
Comment: +1 because it works on some gray-scale cases, not working with ImageIO.read(...). But note, this code forces image load as gray-scale, even if it's not.  Yout have to make first a ImageIO.read(...) & if it fails, use this method.
Comment: In case anyone is wondering how to get that `stream`, if can be created by using `ImageIO.createImageInputStream(InputStream)` (this argument can be `FileInputStream`, `ByteArrayInputStream` etc).
Answer: The error message is informative and indicates that the number of raster bands, as mentioned in the ICC color profile, seems to be incorrect. I used ImageMagick to strip the ICC profile from the  image. ImageIO subsequently has no problems reading the images (~1k bad images). Hope that helps.
Comment: It did! Thanks. I definitely think the message is informative, it's just above my level of understanding, not their fault. Thanks for commenting :)
Answer: It is possible to read this image using TwelveMonkeys ImageIO, which is a more robust and forgiving replacement for the original ImageIO provided by the JRE.
See https://github.com/haraldk/TwelveMonkeys/
I found this solution in the PDF Box Jira https://issues.apache.org/jira/browse/PDFBOX-3637
In order to use TwelveMonkeys, it is sufficient to add it as a maven dependency. It then registers itself before the default image processor.
<dependency>
    <groupId>com.twelvemonkeys.imageio</groupId>
    <artifactId>imageio-jpeg</artifactId>
    <version>3.10.1</version>
</dependency>


Show examples in tensorflow datasets not working

Question: I want to load the tensorflow flowers dataset and visualize it using tfds.show_examples.
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow_hub as hub
import tensorflow_datasets as tfds
from tensorflow.keras import layers

import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

(train_examples, validation_examples), info = tfds.load(
    'tf_flowers',
    with_info=True,
    as_supervised=True,
    split=['train[:70%]', 'train[70%:]'],
)

fig = tfds.show_examples(train_examples, info)

When I run my code, instead of seeing images, I get an error message:
AttributeError                            Traceback (most recent call last)

<ipython-input-13-dcdedbcd800d> in <module>()
      6 )
      7
----> 8 fig = tfds.show_examples(train_examples, info)

/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/visualization.py in show_examples(ds_info, ds, rows, cols, plot_scale, image_key)
     68     # Infer the image and label keys
     69     image_keys = [
---> 70         k for k, feature in ds_info.features.items()
     71         if isinstance(feature, features_lib.Image)
     72     ]

AttributeError: 'DatasetV1Adapter' object has no attribute 'features'

Why is this not working?
Comment: Since tfds is a high-level wrapper for tf.data, I'd make sure that your tfds version is compatible with your tf version.
Comment: My TF is 2.2.0.
Answer: I had the same problem using Colab. Try this
pip install --upgrade tensorflow-datasets

and restart the kernel


Regarding the notion of having zero divergence everywhere

Question: If a vector field has zero divergence at all points in space, then according to Divergence theorem, the outward flux through the surface enclosing any volume in this space should be zero. Electric field has zero divergence everywhere. Yet the flux through any surface is given by Gauss law. I know I am making a mistake somewhere but I am not able find it out. Could someone help me find the mistake I am making?
Comment: Gauss's law says that $\nabla\cdot\mathbf{E} = \rho/\varepsilon_{0}$ (in SI units, anyway), so the electric field doesn't necessarily have zero divergence everywhere, right?
Comment: When you calculate  ∇⋅E,  it  turns out be zero. https://www.youtube.com/watch?v=8PmIarVZmc8&t=98s&ab_channel=Dr.TreforBazett
Comment: Check out the answer I just posted--does that help? I didn't watch the video, though, so it might not answer your question directly.
Comment: Thanks a lot. I understood where I was going wrong.
Answer: I think some confusion can arise when using the divergence theorem to treat, say, a point particle. Consider the force field
\begin{equation*}
\mathbf{F} = \frac{\hat{\mathbf{r}}}{r^{2}}.
\end{equation*}
Just calculating the divergence, as you say, does yield zero
\begin{equation*}
\nabla \cdot \mathbf{F} = \frac{1}{r^{2}}\frac{\partial}{\partial r}\left(r^{2}\cdot\frac{1}{r^{2}}\right) = 0.
\end{equation*}
But if we pick a sphere centered at the origin, we have the surface integral
\begin{equation*}
\iint{\mathbf{F}\cdot\hat{\mathbf{n}}\,\mathrm{d}S} = 4\pi
\end{equation*}
so the divergence theorem, which says that
\begin{equation*}
\iint{\mathbf{F}\cdot\hat{\mathbf{n}}\,\mathrm{d}S} = \iiint{\nabla\cdot\mathbf{F}\,\mathrm{d}V}
\end{equation*}
seems to fail.
The problem is that $\nabla\cdot\mathbf{F}$ is zero everywhere except at the origin. To correctly define the divergence of $\mathbf{F}$, we need to write
\begin{equation*}
\nabla\cdot\left(\frac{\hat{\mathbf{r}}}{r^{2}}\right) = 4\pi\delta^{3}(\mathbf{r}).
\end{equation*}
This way, we obtain
\begin{equation*}
\iiint{\nabla\cdot\mathbf{F}\,\mathrm{d}V} = \iiint{4\pi\delta^{3}(\mathbf{r})\,\mathrm{d}V} = 4\pi,
\end{equation*}
and the divergence theorem holds after all.
(Actually, the divergence theorem together with the fact that the surface integral is $4\pi$ implies the form of the divergence of $\mathbf{F}$, just to keep the logic correct.)


laravel blade datetime dynamic timezone on view

Question: I have a view on blade view with DateTime as a column of datatable. the DateTime timezone is UTC. I wanted to change it to the local timezone with the client browser.
so if the data is 00:00 a.m., then for someone accessing from UTC+5, the DateTime will be 05:00.
the column is currently like this, it generates me 2022-01-02 00:00am:

        {{ $data->createdDate->format('d M Y H:ia') }}

and then I try to manipulate the DateTime using the timezone below and it works. but I hard-coded the timezone on it. so I got 2022-01-01 19:00pm which is correct (UTC-5).
 {{ $data->createdDate->setTimezone('America/New_York')->format('d M Y H:ia') }}

is there a way to dynamically set the timezone ('America/New_York') on the view page?
because the users could be accessed from different regions.
I know on javascript I can generate the timezone using
Intl.DateTimeFormat().resolvedOptions().timeZone

but how can I pass the timezone to that?
Answer: You can pass a timestamp to the blade view and then create local time using javascript, something like this:
PHP
$dt = new DateTime('2020-12-24 4:45',new dateTimeZone('UTC'));  //example
echo '
getTimeStamp() * 1000;).'">?
';

Javascript
var el = document.getElementById("datejs");
var ts = parseInt(el.getAttribute("data-ts"));
el.innerHTML = new Date(ts).toLocaleString();

I tested it without Laravel and Blade. Output for my time zone: 24.12.2020, 05:45:00
If a specific formatting of PHP pages is desired, a format string can also be passed via a data element. A framework such as moment.js is then helpful for the formatting itself.
Answer: You can add timezone field to users table, then update it once the user login using for example momentjs library on login form.
Finally you can easily display the time according to user timezone, something like this :
{{ $data->createdDate->setTimezone(auth()->user()->timezone)->format('d M Y H:ia') }}