text:
Q: Update query not working in codeigniter I am trying to update record with id using where clause but no success. I echo the last query and try that in phpmyadmin run sql query but not success. I have check the table name column names, all are fine.
    $updateData = array(

    'task_forward_to'=> 9,
    'task_forward_by'=>8
    );

    $this->db->where('id', 32);
    $this->db->update('tasks', $updateData);

    echo $this->db->last_query();

    "update tasks set task_forward_to = 9, task_forward_by = 8 where id = 32

data types of both columns are int(11)


text:
Q: Update jProgressBar from another thread I'm new in java. I'm trying to understand thraeads and timers in java. It was big problem for me to undate ProgressBar from another thread. I read many posts and found answers. So can you say is this the best way to resolw my task. So, what I want is to run second thread and when it's done, stop progress bar and change text on the button. So I creat Frame with button and progress bar in Test class:

After I realize action listener for Button to run second thread:
       public class Test extends javax.swing.JFrame {

              RunBg thread = new RunBg();

            ....
    // declaration for button, progressbar and main() method
    ....

            private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

// needed to check is the thread running at first time else creat new object and rund hread again cause thread can be executed once

                    if(thread == null){
                        thread = new RunBg();
                    }

                    if (jProgressBar1.isIndeterminate()) {
                        jProgressBar1.setIndeterminate(false);
                        jButton1.setText("Run!");
                        thread.suspend();
                    } else {

                        jButton1.setText("Working...");
                        jProgressBar1.setIndeterminate(true);

// let us know is the second thread running or nope so we can know resume it or pause
                        if (thread.isAlive()) {
                            thread.resume();
                        } else {
                            thread.start();
                        }

                        timer.start();

                    }

                }

    /*
    Then I creat timer to know is my thread still alive else change Progress bar and button

    */

       Timer timer = new Timer(100, new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if(!thread.isAlive()){

                            thread.stop();
                            jProgressBar1.setIndeterminate(false);
                            jButton1.setText("Запустить!");
                            timer.stop();
                        //    thread.interrupt();
                            thread = null;

                        }
                    }
        });

      ...
    // end of class
    }

And my second class for another thread named RunBG:
public class RunBg extends Thread{

    int i = 0;

    public void run(){

        while(i<20000){
                System.out.println(">>>"+i);
                i++;
            }
        System.out.println("<<<Finished>>>");

    }

}

Everythig works fine , but I have question. Is there a better way to realize my task or maybe I made some mistakes. Also I thik that my code will help another beginners who looking for help to understand how it's work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel Storage path not matching I can store files to public folder, when receiving the file I also store the url in the database.
I can access the file using domain/storage/profile/img.jpeg but the url stored in db is showing me /public/profile/img.jpeg
$path = $request->file('image')->store('public/profile');
$user->image()->create(['url' => $path]);

The public prefix in url is wrong, this needs to be storage, so I can show the image in the frontend.
What is the correct here?
Thanks!


text:
Q: How do i add year (date) criteria to DSUM? I have a database that looks like this:

(A1)Client              (B1) Date                       (C1) debts
(A2)1                   (B2) Mon 2 november 2008        (C2) 1500$
(A3)2                   (B3) Thu 7 february 2008        (C3) 1000$
(A4)3                   (B4) Sat 28 March 2009          (C4) 800$
(A5)4                   (B5) Mon 16 March 2009          (C5) 1200$

The date format is 24/11/2008.
I have to use DSUM to get the sum of the debts clients had in 2008.
I already did a table that looks like this:

(A7)Client             (A7) Date                        (C7) debts
                       (A9) 2008

and the function =DSUM(A1:C5,3,A7:C8) but it seems I can't extract the value of 2008 from the date 24/11/2008.

A: It is generally not a good idea to store dates as text, change your 2008 to 1/1/2008 and format as "YYYY"
To use DSUM to sum entries that fall in a calendar year you will have to define the start and end date, so your filter data will look like this:
Client  Date           Date
debts   =">=1/1/2008"  ="<1/1/2009"


text:
Q: java how to send email via any account I am able to send email using this code below. But I need to change the mail.smtp.host and mail.smtp.port depending on which type of account the user has.
I am creating an App where I want the user just to supply his email address and password, and then the code figures out the details. Is there a way to do this? I could try try and figure the type of account from the email address but it is not always obvious.
 import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.nio.ByteBuffer;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Properties;
    import java.util.Scanner;

import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailProjectClass {
    //final static String username = "info@mail.com";
    //final static String password = "xxxx";
    final static String username = "yyyy@gmail.com";
    final static String password = "yyyy";
    static Transport bus;

public static void main(String[] args) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);

    //props.put("mail.smtp.host", "smtpout.europe.secureserver.net");
    //props.put("mail.smtp.port", "80"); //25, 3535, 80    465
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587"); //25, 3535, 80    465

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

        sendEmail(session,"zzzz@wherever.com");

  }

    public static void sendEmail(Session session, String emailAddress)  {

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO,  InternetAddress.parse(emailAddress));
            message.setSubject("Homework");

            Multipart multipart = new MimeMultipart("alternative");

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            String content = "Blank";
            try {

                content = readFile("C:\\Letter.txt", Charset.defaultCharset());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            messageBodyPart.setContent(content, "text/plain");
            messageBodyPart.setDisposition(Part.INLINE);
            multipart.addBodyPart(messageBodyPart);

            try {

                content = readFile("C:\\Letter.htm", Charset.defaultCharset());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            messageBodyPart.setContent(content, "text/html");
            messageBodyPart.setDisposition(Part.INLINE);
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            Transport.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

EDIT 1
If I do want to code most of the details needed myself - is there a java class that does the dialogue for me - i.e. allows for getting all the different information needed depending on the account type?

A: You can not do that, otherwise there would be million of sites offering you to access your Email wherever it is, Username and password alone are not enough to determine which SMTP you need unless you cover the known ones by parsing the Email adress which is not what you are looking for.

A: You could do as follows,

*

*Create a static map with 'gmail' as key and 'smtp.gmail.com' as value like this put all the mail details such as gmail, hotmail, yahoo and etc..

*Create one more static map for port with 'gmail' as key and '587' as value.

*Before adding host & port into properties, Get the Host & port from map based on your username. Get the key from username substring.

A: Have you ever attempted to set up an email client such as Outlook Express, Thunderbird, or various others? If so, you'll know that they need far more information that just an email address and password. This might serve as a clue that what you want can't be done.

A: Things you can try to figure out server settings:

*

*Store the data for big providers (hotmail, gmail, etc.) in your program, that should cover the majority of the cases

*check the mx record for the host part of the email on your nameserver, this will give you the SMTP server for that domain, in most cases the IMAP/POP3 Server is the same.

*Try the default ports on these servers and try to connect with the possible protocol combinations (SMTP/POP3/IMAP with SSL/TLS/plain/etc...)

But there will always be settings the user has to choose, for example if he wants to use IMAP or POP3.


text:
Q: How can I call built-in functions in Python using Boost.Python I know we can import modules and just embed Python code in C++ and evaluate it. But how can I use built-in functions like print or open? These functions off course aren't module. Evaluating embedded open statement just gives me the following error:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'open' is not defined

Stuck. Please help me.

A: Try importing the builtins and io module and if you want any other function just call the __module__ attribute to find about which module to import
>>> print.__module__
'builtins'
>>> open.__module__
'io'


text:
Q: Save gif to android gallery Using https://github.com/koush/ion image Loader to display gif files into ImageView
I save the jpg images into gallery by this code
    MediaStore.Images.Media.insertImage(
                                    getActivity().getContentResolver(), bitmap,
                                    "XXX", "Image1");

but this way is not working with gif files.
Do you have any idea how can i accomplish this?

A: Bitmaps are single images, so GIFs will not work with this API. To save a GIF, you'll need to download the gif to a file on external storage, and then notify MediaScanner to scan it. It will then show up in the gallery.

A: You could save gif using this code
  File file = new File(getBaseContext().getExternalCacheDir(),
                    "gif_name"+ ".gif");
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(gif.getData());//gif is gif image object
                fos.flush();
                fos.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

This code will save the gif in cache directory on your external sd card but will not be visible in Gallery.


text:
Q: Confusion on the purpose of using active current-meters I was reading about current to voltage converters and simple opamp current-meters.
I found myself in confusion comparing them to passive current meters.
Active current-meter:

As you see above the Iin passes through R and the voltage drops to -Iin*R as Vout. So Vout is linearly changing and with Iin.
And below is measuring current without an opamp:
Passive current-meter:

Above the same logic, the Iin passes through R and Vout is linearly changing with Iin.
Can someone explain what is the point/benefit to use opamp here? What is the advantage of using opamp/active version over the passive one?

A: In your first circuit, so long as the current is small enough and it changes slowly enough, the negative feedback circuit keeps the inverting input of the op-amp at 0 V, so the source sees effectively 0 load impedance.
In the second circuit, the source sees a load impedance equal to the resistor value, which could change the current it produces. Furthermore, the higher the resistance value (increasing the resolution of whatever is measuring the voltage across the resistor), the greater the resistance seen by the source, so the greater the effect on its output.

the "current source seeing some load impedance" [issue]... is a bit confusing since the load resistance will be in series with the current source and why would it have affect on the current. A simple illustration would help a lot if you have time,

simulate this circuit – Schematic created using CircuitLab
If Rsense is 0, then all of the source current goes through Rsense and the measurement does not disturb the thing being measured.
If Rsense is non-zero, then some of the source current is diverted internally through the source's internal conductance, and the measured current is lower than it would have been if measured with a 0-resistance sensor.

A: A DC coil current meter has a certain loss of winding resistance often rated at 20kΩ/V which yields 50uA full scale.  Shunt R's are then added across for precise ratios to scale the full scale current.
An OpAmp due to the negative feedback will have an input impedance of Rf/Aol for the feedback R and open Loop Gain of 1e6, thus provides lower loss and higher gain and of course also can convert I to V at a wide frequency range unlike a DC coil meter and also very low currents with high gain and can be bipolar AC to DC with latter stages of precision rectifiers.
Whatever the source impedance is, the current sensor must be much lower impedance to sense all of the current.

simulate this circuit – Schematic created using CircuitLab
Obviously it depends if you want a DMM output or an analog meter output for choice and AC uses a rectifier in coil meters, scaled to measure rms/peak or rms/avg so unless a pure sine may be in error and DC for rms/pk measure twice the actual in AC V or A mode in analog meters.

A: Tony has things correctly stated. I thought I'd just add another way of writing similar things without getting mired. Let's redraw the circuits:

simulate this circuit – Schematic created using CircuitLab
I've drawn the regular analog meter movement on the top, and its equivalent. Here, you can see that the meter does actually inject a potentially significant resistance in series (which may upset the measurement, depending on circumstances.) The analog meter movement here presents \$500\:\Omega\$ of DC resistance.
I've drawn the opamp circuit on the bottom, and its equivalent. Here, you can see that the effective series resistance may be very significantly diminished, now. (\$A_O\$ is the open loop gain of the opamp.) The open loop gain of the opamp would have to be as bad as 100 to present the same series resistance. But that's not the usual case. Open loop gains are much, much higher in even the cheapest opamps. (I've neglected offset voltage and current and bias currents, to focus on the central point.)
By the way, you can often use much cheaper analog panel meters as a result, as well, and still get significant reductions in the impact on a circuit under measurement using an opamp. And opamps, even expensive ones, are often a lot cheaper than a very high quality analog D'Arsonval movement will be. I suspect this has largely killed wide-scale production of sensitive D'Arsonval movements, despite the somewhat more recent advent of very powerful Neodymium permanent magnets.


text:
Q: Improve speech recognition ( web speech api) I'm trying to write a speech recognition program that involves recognizing medical jargon(words like Prozac,Methadone and Vicodin). Now I recently found out that the grammar for the Web Speech API has no practical implementation. See this answer for additional details.
Is there any way I can make my program be better at handling speech to text recognition in the current case?
Or is there any better alternative or approach I can use for my scenario here?


text:
Q: Prove that $R/I$ and $S/\phi(I)$ are isomorphic
$R,S$ are commutative rings with $\phi : R \rightarrow S$ an isomorphism between them.
$I \subset R$ is an ideal and $\phi(I) \subset S$ is an ideal as well.
Show that $R/I$ and $S/\phi(I)$ are isomorphic.

This is how I approached this problem:
The natural homomorphism $\pi : R \rightarrow R/I$ is a surjective ring homomorphism with $ker(\phi) = I$.
Given that $\phi : R \rightarrow S$ an isomorphism, then it should follow that $\psi : R \rightarrow S/\phi(I)$ is also a ring isomorphism, meaning it is both surjective and injective.
Thus, by the isomorphism theorem, because there exists a surjective homomorphism $\pi : R \rightarrow R/I$ and a surjective homomorphism $\psi : R \rightarrow S/\phi(I)$, then it follows that there exists an isomorphism $\sigma : R/I \rightarrow S/\phi(I)$.
The reason I am not sure about this proof is because I have made an assumption that I am not sure is correct and also because I haven't really done anything with the elements within these rings.
Any help would be greatly appreciated.

A: There is a natural surjective homomorphism $\pi \colon S \to S/\phi(I)$. Also $\phi$ is surjective since it is an isomorphism. Then $\psi = \pi \circ \phi$ is a surjective homomorphism $R \to S/\phi(I)$. Check that $\ker \psi = I$, so then by the first isomorphism theorem $R/I \cong S/\phi(I)$.


text:
Q: Parameter Identification in a (Simple) Mixture Model I have a very mundane clarification question from some old lecture notes. The notes:

Consider the model $$Y_i=(1+D_i)\varepsilon_i$$ where $(D_i,\varepsilon_i)\overset{iid}{\sim}Bernoulli(p)\times N(0,1),p\in(0,1)$, and we observe $Y_i$. The parameter $p$ is point identified.

By the law of total probability $$f_Y(y)=\phi(y)(1-p)+\frac{1}{2}\phi\left(\frac{y}{2}\right)p$$ and solving for $p$, we have...

Where does the $\frac{1}{2}$ factor in front of the second $\phi(\cdot)$ come from? My attempts start with $f_Y(y)=\phi(y)(1-p)+\phi\left(\frac{y}{2}\right)p$, which leads to a different value for $p$.

A: From the law of total probability we have
$$
P(Y\leq y) = P(Y\leq y \mid D = 0) (1-p) + P(Y\leq y \mid D = 1) p \\
= \Phi(y)(1-p) + \Phi(y/2)p
$$
so
$$
f_Y(y) = \varphi(y)(1-p) + \frac 12 \varphi(y/2)p
$$
by the chain rule.
Regarding your mistake, the law of total probability is about measuring a set by splitting it over a bunch of other sets, so it's at the level of probability measures. Since CDFs are bijective with probability measures on $(\mathbb R, \mathbb B)$ we can just start with $P(Y\leq y)$ rather than $P(Y\in A)$ for a Borel $A$. Only after we have the law of $Y$ confirmed do we get its Lebesgue density, i.e. we differentiate to get $f_Y$.


text:
Q: TypeError: Cannot read property 'split' of undefined in Nodejs i get the following error, using the jwt-simple lib:
TypeError: Cannot read property 'split' of undefined
    at module.exports (C:\my_application\services\mylist.js:5:40)
    at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\my_application\node_modules\express\lib\router\route.js:131:13)
    at Route.dispatch (C:\my_application\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
    at C:\my_application\node_modules\express\lib\router\index.js:277:22
    at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12)
    at next (C:\my_application\node_modules\express\lib\router\index.js:271:10)
    at C:\my_application\api.js:39:3
    at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\my_application\node_modules\express\lib\router\index.js:312:13)
    at C:\my_application\node_modules\express\lib\router\index.js:280:7
    at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12)
    at next (C:\my_application\node_modules\express\lib\router\index.js:271:10)
    at logger (C:\my_application\node_modules\morgan\index.js:144:5)
    at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5)

and here is mylist.js file:
var jwt = require('jwt-simple');

module.exports = function (req, res) {
  var token = req.headers.authorization.split(' ')[1];
  var payload = jwt.decode(token, "shhh..");
  if(!payload.sub) {
    res.status(401).send({
      message: 'Authentication failed'
    });
  }
  if(!req.headers.authorization){
    return res.status(401).send({
      message: 'You are not authorized'
    });
  }
  res.json(mylist);
};

var mylist = [
  'Proj 1',
  'Proj 2',
  'Proj 3',
  'Proj 4'
];

i am trying to see if the user is authorized to access the mylist resource on frontend.
does anyone have any idea?

A: you assume it's a string, even if you don't know if there really is a string there.
You should add some error checking first
module.exports = function (req, res) {
  if (typeof req.headers.authorization !== 'string') {
    res.sendStatus(400);
    return;
  }

  var tokens = req.headers.authorization.split(' ');

  if (tokens.length < 2) {
    res.sendStatus(400);
    return;
  }

  var token = tokens[1];

  var payload = jwt.decode(token, "shhh..");
  if(!payload.sub) {
    res.status(401).send({
      message: 'Authentication failed'
    });
  }
  ...
};

Edit: But why exactly do you want the second token and not the first?


text:
Q: API to API - With a Service Account I am trying to call an API (API2) from another API (API1) with the help of client credentials flow. Is it possible to grant access to only some parts of API2?
To give some context, When making call from API1 to API2, I am currently using a service account that decides what parts of API2 are allowed access. The service account is created and configured (with roles) in API2 and shared with API1 ahead.
I am trying to achieve this same with oAuth's client credential flow but I could not find any information on restricted access inside API. I believe ApiScopes won't work in this case.
Could you let me know if restricted API access is possible in client credentials flow? or can this be achieved in any other flow?
Regards,
Siva

A: Yes, you can use the built in authorization system in ASP.NET Core to control access based on the claims inside the received access token. what AddJwtBearer do is to convert your access token (once authenticated) into a ClaimsPrincipalUser object.
See these links for details:

*

*Policy-based authorization in ASP.NET Core

*Claims-based authorization in ASP.NET Core

A: Alternatively, we can define a new Application Role for the API2. This role will have access to selected parts of the API2. Then we can add this role to the Client_id you are using in Client Credentials flow.


text:
Q: Selected item does not spin I have a menu with icons and I am trying to make the fontawesome icon of the selected list rotate by adding the class .fa-spin. I have no idea why my code is not working eventhough I made the Index equal to the clicked item.
I appreciate some insights.

 1

 2

 3

 4

 5

 6

Here is my Jquery code:
 $('nav ul li a').click(function(){
        $('nav ul li .fa').eq($(this).index()).addClass('fa-spin').siblings().removeClass('fa-spin');
});

A: Your target elements are wrong - you need to add/remove the classes from the anchor elements

$('nav ul li a').click(function () {
    $(this).addClass('fa-spin').parent().siblings().find('.fa-spin').removeClass('fa-spin');
});
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">

 1

 2

 3

 4

 5

 6

A: Try using the Web Animation API
Element.animate();

Then you won't need to add classes and remove classes
Simplest reference: http://updates.html5rocks.com/2014/05/Web-Animations---element-animate-is-now-in-Chrome-36


text:
Q: Execute multiple queries using a single JDBC Statement object In JDBC, can I use single Statement object to call executeQuery("") multiple times? Is it safe? Or should I close the statement object after each query, and create new object for executing another query.
E.G:
Connection con;
Statement s;
ResultSet rs;
ResultSet rs2;
try
{
    con = getConnection();
    // Initially I was creating the Statement object in an
    // incorrect way. It was just intended to be a pseudocode.
    // But too many answerers misinterpretted it wrongly. Sorry
    // for that. I corrected the question now. Following is the
    // wrong way, commented out now.
    // s = con.prepareStatement();

    // Following is the way which is correct and fits for my question.
    s = con.createStatement();

    try
    {
        rs = s.executeQuery(".......................");

        // process the result set rs
    }
    finally
    {
        close(rs);
    }

    // I know what to do to rs here
    // But I am asking, should I close the Statement s here? Or can I use it again for the next query?

    try
    {
        rs2 = s.executeQuery(".......................");

        // process the result set rs2
    }
    finally
    {
        close(rs2);
    }
}
finally
{
    close(s);
    close(con);
}

A: I can't find anything in the API docs that would state, that you shouldn't call executeQuery() on a given PreparedStatement instance more than once.
However your code does not close the PreparedStatement - a call to executeQuery() would throw a SQLException in that case - but the ResultSet that is returned by executeQuery(). A ResultSet is automatically closed, when you reexecute a PreparedStatement. Depending on your circumstances you should close it, when you don't need it anymore. I would close it, because i think it's bad style not to do so.
UPDATE Upps, I missed your comment between the two try blocks. If you close your PreparedStatement at this point, you shouldn't be able to call executeQuery() again without getting a SQLException.

A: A Prepared Statement tells the database to remember your query and to be prepared to accept parameterized variables to execute in that query. It's a lot like a stored procedure.
Prepared Statement accomplishes two main things:

*

*It automatically escapes your query variables to help guard against SQL Injection.

*It tells the database to remember the query and be ready to take variables.
Number 2 is important because it means the database only has to interpret your query once, and then it has the procedure ready to go. So it improves performance.
You should not close a prepared statement and/or the database connection in between execute calls. Doing so is incredibly in-efficient and it will cause more overhead than using a plain old Statement since you instruct the database each time to create a procedure and remember it. Even if the database is configured for "hot spots" and remembers your query anyways even if you close the PreparedStatement, you still incur network overhead as well as small processing time.
In short, keep the Connection and PreparedStatement open until you are done with them.
Edit: To comment on not returning a ResultSet from the execution, this is fine. executeQuery will return the ResultSet for whatever query just executed.

A: Yes you can re-use a Statement(specifically a PreparedStatement) and should do so in general with JDBC. It would be inefficient & bad style if you didn't re-use your statement and immediately created another identical Statement object. As far as closing it, it would be appropriate to close it in a finally block, just as you are in this snippet.
For an example of what you're asking check out this link: jOOq Docs

A: Firstly I am confused about your code
s = con.prepareStatement();

Is it work well?I can't find such function in JAVA API,at least one parameter is needed.Maybe you want to invoke this function
s = con.createStatement();

I just ran my code to access DB2 for twice with one single Statement instance without close it between two operation.It's work well.I think you can try it yourself too.
    String sql = "";
    String sql2 = "";
    String driver = "com.ibm.db2.jcc.DB2Driver";
    String url = "jdbc:db2://ip:port/DBNAME";
    String user = "user";
    String password = "password";
    Class.forName(driver).newInstance();
    Connection conn = DriverManager.getConnection(url, user, password);
    Statement statement = conn.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    int count = 0;
    while (resultSet.next()) {
        count++;
    }
    System.out.println("Result row count of query number one is: " + count);
    count = 0;
    resultSet = statement.executeQuery(sql2);
    while (resultSet.next()) {
        count++;
    }
    System.out.println("Result row count of query number two is: " + count);

A: I am not sure why you are asking. The API design and documentation show it is perfectly fine (and even intended) to reuse a Statement object for multiple execute, executeUpdate and executeQuery calls. If it wouldn't be allowed that would be explicitly documented in the Java doc (and likely the API would be different).
Furthermore the apidoc of Statement says:

All execution methods in the Statement interface implicitly close a statment's [sic] current ResultSet object if an open one exists.

This is an indication that you can use it multiple times.
TL;DR: Yes, you can call execute on single Statement object multiple times, as long as you realize that any previously opened ResultSet will be closed.
Your example incorrectly uses PreparedStatement, and you cannot (or: should not) be able to call any of the execute... methods accepting a String on a PreparedStatement:

SQLException - if [...] the method is called on a PreparedStatement or CallableStatement

But to answer for PreparedStatement as well: the whole purpose of a PreparedStatement is to precompile a statement with parameter placeholders and reuse it for multiple executions with different parameter values.


text:
Q: Writing continious numpy array in raw representation via socket I need to send big fixed sized buffers from python to c/c++ code side.
From python side I have buffers in form of:
array = np.zeros([1000], dtype=np.uint8)
array = fill(array)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 1010))

Code below is used to recv data from connected socket from C/C++ side.From the c/c++ side I need to have this buffer as raw 1000 byte array, I don't need any headers, I need just data. Unfortunately I haven't found howto do it. In general np.tofile()- makes things I need but in file.
int recvBuffer(uint8_t *p_buff, uint32_t size, int socket)
{
    uint32_t recived = 0;
    uint8_t *p_curr = p_buff;
    while (recived < size)
    {
        int ret = recv(tcp_sock, p_curr, size - recived, 0);
        if (ret != -1)
        {
            p_curr += ret;
            recived += ret;
        }
        else
        {
            return false;
        }
    }
    return true;
}

A: I found solution.
I found it in np.tofile description.
np_array = np.zeros([1000], dtype=np.uint8)
np_array = fill(np_array)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 1010))
raw_buffer = np_array.to_bytes()
s.send(raw_buffer)

Makes exactlty what I wanted. raw_buffer - holds np.array buffer as raw c-stype buffer.


text:
Q: line breaking has no effect in doublespace I am trying to break a doublespace content without any success.
\documentclass{article}
\usepackage{amsmath, amssymb, graphics, setspace}

\begin{document}

\begin{doublespace}
\noindent \(\left\{\left\{ aaa \right\},
\\ ~ \\ ~ \\ ~ \\
\left\{bbb\right\}\right\}\)
\end{doublespace}

\end{document}

The part {bbb} does not go to the new line as if \\ has no effect in doublespace


text:
Q: Deep Convolutional Autoencoder for movie similarity i am new to python and i have a dataset that contains movie descriptions and i am trying to create a model that can calculate movie similarity based on these descriptions.
so i started by turning each movie description into a Word2Vec vector where each word has a size 100,since the longest movie description in my dataset has 213 words, each movie description is turned into a vector of size 21300.
now my next step is to reduce the dimensionality of these vectors using a convolutional autoencoder.
it was recommended to me that i turn each 21300-sized vector into a 150 by 142 matrix so i did that, my goal is to compress these matrices from 150 by 142 to 5 by 5 matrix which i will then flatten and use to calculate cosine similarity between different compressed movie vectors.
now here is my faulty code so far:
encoder_input = keras.Input(shape=(21300,), name='sum')
encoded= tf.keras.layers.Reshape((150,142),input_shape=(21300,))(encoder_input)
x = tf.keras.layers.Conv1D(32, 3, activation="relu", padding="same",input_shape=(16,150,142))(encoded)
x = tf.keras.layers.MaxPooling1D(2, padding="same")(x)
x = tf.keras.layers.Conv1D(32, 3, activation="relu", padding="same")(x)
x = tf.keras.layers.MaxPooling1D(2, padding="same")(x)
x = tf.keras.layers.Conv1D(16, 3, activation="relu", padding="same")(x)
x = tf.keras.layers.MaxPooling1D(2, padding="same")(x)
x = tf.keras.layers.Conv1D(16, 3, activation="relu", padding="same")(x)
x = tf.keras.layers.MaxPooling1D(2, padding="same")(x)
x = tf.keras.layers.Conv1D(8, 3, activation="relu", padding="same")(x)
x = tf.keras.layers.MaxPooling1D(2, padding="same")(x)
x=tf.keras.layers.Flatten()(x)
encoder_output=keras.layers.Dense(units=25, activation='relu',name='encoder')(x)
x= tf.keras.layers.Reshape((5,5),input_shape=(25,))(encoder_output)

# Decoder

decoder_input=tf.keras.layers.Conv1D(8, 3, activation='relu', padding='same')(x)
x = tf.keras.layers.UpSampling1D(2)(decoder_input)
x = tf.keras.layers.Conv1D(16, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(16, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(32, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(32, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
#x=tf.keras.layers.Flatten()(x)
decoder_output = keras.layers.Conv1D(1, 3, activation='relu', padding='same')(x)

opt = tf.keras.optimizers.Adam(learning_rate=0.001, decay=1e-6)

autoencoder = keras.Model(encoder_input, decoder_output, name='autoencoder')

autoencoder.compile(opt, loss='mse')
autoencoder.summary()

history = autoencoder.fit(
movies_vector,
movies_vector,
epochs=25

        )

print("ENCODER READY")
#USING THE MIDDLE LAYER
encoder = keras.Model(inputs=autoencoder.input,
   outputs=autoencoder.get_layer('encoder').output)

running this code produces the following error:
ValueError: Dimensions must be equal, but are 100 and 21300 for '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT](mean_squared_error/remove_squeezable_dimensions/Squeeze, IteratorGetNext:1)' with input shapes: [?,100], [?,21300].

how can i fix this autoencoder?

A: I was able to reproduce the error with dummy data. Changing the decoder model  as follows will help.
decoder_input=tf.keras.layers.Conv1D(8, 3, activation='relu', padding='same')(x)
x = tf.keras.layers.UpSampling1D(2)(decoder_input)
x = tf.keras.layers.Conv1D(16, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(16, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(32, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x = tf.keras.layers.Conv1D(32, 3, activation='relu')(x)
x = tf.keras.layers.UpSampling1D(2)(x)
x=tf.keras.layers.Conv1D(213, 3, activation='relu', padding='same')(x)
decoder_output = tf.keras.layers.Flatten()(x)

Please find the gist here. Thank you.


text:
Q: Reading rows from an Oracle Object that is a table of other objects Forgive me, this is my first attempt at an Oracle Package, so I am hopefully missing something simple.
EDIT I sorted it...
Need to reference the actual declaring sub-type, as such:
 FOR j in outvar(i).tbl_ORDER_TENDERS.first..outvar(i).tbl_ORDER_TENDERS.last LOOP
         DBMS_OUTPUT.PUT_LINE('tender record : '
         || to_char(outvar(i).tbl_ORDER_TENDERS(j).TENDER_AMT)      || ' '

I created several a couple new Oracle Types, that will hold row data from my DB, as such:
create or replace
TYPE ORDERS_TABLE
IS TABLE OF ORDER_HEADER;

And that refers to my other type:
create or replace
TYPE ORDER_HEADER FORCE
AS OBJECT (
  TRANSACTION_NUMBER    VARCHAR2(20),
  LOCATION_NUMBER       VARCHAR2(10),
  TERMINAL_NAME         VARCHAR2(25),
  START_DATETIME        TIMESTAMP(6),
  GROSS_SALES_AMOUNT    NUMBER(20,0),
  NET_SALES_AMOUNT      NUMBER(20,0),
  SAVINGS_AMOUNT        NUMBER(20,0),
  SAVINGS_PRECISION     NUMBER(6,0),
  TOTAL_TAX             NUMBER(20,0),
  CUSTOMER_IDENTIFIER   VARCHAR2(50),
  tbl_ORDER_LINES       ORDER_LINES,
  tbl_ORDER_TENDERS     ORDER_TENDERS,
  TBL_ORDER_REBATES     ORDER_REBATES
);

And for example, take the ORDER_TENDERS type:
create or replace
TYPE ORDER_TENDERS  FORCE
AS TABLE OF ORDER_TENDER;

Which contains the rows of tender data:
create or replace
TYPE ORDER_TENDER AS OBJECT
(
  TENDER_LINE_ID            NUMBER(20,0),
  TENDER_CODE               VARCHAR2(10),
  TENDER_AMT                NUMBER(20,0),
  UNENCODED_ACCOUNT_NUMBER  VARCHAR2(25)
);

So my package I think is working, where I can fill these objects (verified the HEADER stuff working at least.)  But I'm not sure how to test/debug/view the results when I call this package to see if I'm getting the ORDER_TENDER/ORDER_TENDERS data...
For example, this works fine:
declare
 invar varchar2(5);
 outvar ORDERS_TABLE;
 O_ORDER_TENDERS ORDER_TENDERS;
 O_ORDER_TENDER  ORDER_TENDER;
 begin
 sales_trickler.GetSales(invar, outvar);

 FOR i in 1..outvar.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE(' record : '
      || to_char(outvar(i).TRANSACTION_NUMBER)      || ' '
      || to_char(outvar(i).LOCATION_NUMBER)         || ' '
      || to_char(outvar(i).TERMINAL_NAME)           || ' '
      || to_char(outvar(i).CUSTOMER_IDENTIFIER));

   END LOOP;
end;

But how do I see the ORDER_TENDERS/ORDER_TENDER data?
I tried putting this extra FOR LOOP in, but it doesn't like how I'm referring to ORDER_TENDER(S)...
declare
 invar varchar2(5);
 outvar ORDERS_TABLE;
 O_ORDER_TENDERS ORDER_TENDERS;
 O_ORDER_TENDER  ORDER_TENDER;
 begin
 sales_trickler.GetSales(invar, outvar);

 FOR i in 1..outvar.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE(' record : '
      || to_char(outvar(i).TRANSACTION_NUMBER)      || ' '
      || to_char(outvar(i).LOCATION_NUMBER)         || ' '
      || to_char(outvar(i).TERMINAL_NAME)           || ' '
      || to_char(outvar(i).CUSTOMER_IDENTIFIER));
      FOR j in 1..outvar(i).O_ORDER_TENDERS.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE('tender record : '
      || to_char(O_ORDER_TENDERS(j).TENDER_AMT)      || ' '
      );
      END LOOP;

   END LOOP;
end;

I tried relating to outvar(i).ORDER_TENDERS but that didn't work either... any ideas?

A: The problem was in the calling code, I shouldn't refer to new instances of the sub-objects, I should refer to them 'as they live' in the original parameter being passed, as such:
 tbl_ORDER_LINES       ORDER_LINES,
 tbl_ORDER_TENDERS     ORDER_TENDERS,
 TBL_ORDER_REBATES     ORDER_REBATES

Here's the actual statement:
declare
 invar varchar2(5);
 outvar ORDERS_TABLE;
 begin
 sales_trickler.GetSales(invar, outvar);

 FOR i in 1..outvar.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE(' record : '
      || to_char(outvar(i).TRANSACTION_NUMBER)      || ' '
      || to_char(outvar(i).LOCATION_NUMBER)         || ' '
      || to_char(outvar(i).TERMINAL_NAME)           || ' '
      || to_char(outvar(i).CUSTOMER_IDENTIFIER));

       FOR j in outvar(i).tbl_ORDER_TENDERS.first..outvar(i).tbl_ORDER_TENDERS.last LOOP
         DBMS_OUTPUT.PUT_LINE('tender record : '
         || to_char(outvar(i).tbl_ORDER_TENDERS(j).TENDER_AMT)      || ' '

  );
  END LOOP;
  --lines
   FOR j in outvar(i).tbl_ORDER_LINES.first..outvar(i).tbl_ORDER_LINES.last LOOP
     DBMS_OUTPUT.PUT_LINE('line record : '
     || to_char(outvar(i).tbl_ORDER_LINES(j).SKU)      || ' '

  );
  END LOOP;

END LOOP;
end;


text:
Q: How do I update my Spyder version 3.3.6 launch icon? A few weeks ago, I installed Anaconda and Spyder 3.1.3 on my Pixelbook's Debian/Crostini VM. A few days ago, I upgraded to Spyder 3.3.6  Since I'm new to Spyder, I tried to keep the original installation as user-friendly as possible by using Anaconda and Package Manager.  See the code I used to update Spyder below:
#upgrade Spyder
# https://github.com/spyder-ide/spyder/releases
$ conda update qt pyqt
conda install spyder=3.3.6

Issue: Clicking the Spyder launch icon still opens the old 3.1.3 version.  How do I update the icon to launch version 3.3.6?  Also, I do not need the old version... should I uninstall it?  If so, how?
Typing "spyder" in the terminal launches version 3.3.6, while typing "spyder3" in the terminal launches version 3.1.3.
(conda_env) jaromf@penguin:~$ spyder3
(conda_env) jaromf@penguin:~$ spyder
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-jaromf'

BTW - only "spyder" version 3.3.6 returns the XDG_RUNTIME... line (could this be related to the issue?)

A: $ sudo apt-get remove spyder3 successfully removed the old 3.1.3 version while not disturbing the newer 3.3.6 version. The old icon was also automatically removed. Since I usually open spyder from the terminal, I'm not too concerned about creating an icon for the 3.3.6 version


text:
Q: How to check Variant for null? I am getting answer from DB and need to check if it is not null before placing it's to value.
I tried few variants of checking, but my code is still crush:
foreach(i, point;myPointsLonLat)
{

    try
    {
        carGPSPoint cargpspoint;
        cargpspoint.id = point[0].coerce!ulong;

        cargpspoint.recordDate = DateTime.fromSimpleString(point[1].coerce!string).toISOExtString(); // some magic to get string in 2016-10-31T15:37:24 format
        if(point[2].hasValue) //check if we have some data
            cargpspoint.velocity = point[2].coerce!double;
        if(point[3].hasValue)
            cargpspoint.lat = point[3].coerce!double;
        if(point[4].hasValue)
            cargpspoint.lon = point[4].coerce!double;
        cargpspoints[i] = cargpspoint;
        b.next();
    }
    catch(Exception e)
    {
        writeln("\n----------------------------ERRRRRR-----------------------");
        writeln(point);
        writeln("1111: ", point[2].coerce!double);
        writeln("2222: ", point[3].coerce!double);
        writeln("3333: ", point[4].coerce!double);
        writeln(e.msg);
    }
}

Output:
----------------------------ERRRRRR-----------------------
Row([1478698195002489886, 2016-Nov-09 13:29:55, 153, null, null], [false, false, false, true, true])
1111: 153

object.Exception@C:\D\dmd2\windows\bin\..\..\src\phobos\std\variant.d(823): Type typeof(null) does not convert to double

As you see it's print 1111: 153. But crashing on other null variables.
I also tried:
    if(point[2].type !is null) //check if we have some data
        cargpspoint.velocity = point[2].coerce!double;
    if(point[3].type !is null)
        cargpspoint.lat = point[3].coerce!double;
    if(point[4].type !is null)
        cargpspoint.lon = point[4].coerce!double;

Same result. What I am doing wrong?

A: hasValue checks if it has been initialized, and the database library does initialize it, just to null.
I'd suggest checking the type directly:
 if(auto pt = point[3].peek!double)
                cargpspoint.lat = *pt;

peek checks if it has that exact type and returns a pointer to the value if it does. It is an exact match, meaning if it is float or something else, this won't work, so make sure you are matching what the database gives you (that's best for performance and accuracy anyway), but then it will be null and thus skip the if it isn't right and you can set if it is.
Just repeat that pattern for all your points.

A: Here's a solution to implement the isNull function and a hasValue2 function in the way you wanted:
import std.variant;
import std.stdio;

void main()
{
    Variant v;
    writefln("%s %s %s", v.hasValue, !v.isNull, v.hasValue2);
    v = null;
    writefln("%s %s %s", v.hasValue, !v.isNull, v.hasValue2);
    v = "";
    writefln("%s %s %s", v.hasValue, !v.isNull, v.hasValue2);
}

@property bool isNull(Variant v)
{
    return v.type == typeid(typeof(null));
}

@property bool hasValue2(Variant v)
{
    return v.hasValue && !v.isNull;
}

Result:
false true false
true false false
true true true

So in your code you should check for typeid(typeof(null)) instead. You might be right that hasValue should check for typeof(null) as well. IIRC Variant predates typeof(null), nowadays it might even make sense to use only typeof(null) and never allow uninitialized Variants.
Please start a discussion at https://forum.dlang.org/group/general or file a bug report at https://issues.dlang.org to discuss this with the appropriate library maintainers.


text:
Q: Ti.Android.currentActivity.startActivity() stops launching activities I'm basically using the navigation controller from forging titanium (Nav Controller). I'm also trying to launch various web pages with the code below. The issue is that after navigating around the app for a bit, the intents seem to not start activities any more.
Has anyone else ran into a similar issue? If so, how was it resolved?
Thank you for your time
exports.openWebPage = function(url) {
    if (Ti.Network.online) {
        if (Ti.Platform.osname === 'android') {
            var intent = Ti.Android.createIntent({
                action: Ti.Android.ACTION_VIEW,
                data: encodeURI(url),
                className: 'com.android.browser.BrowserActivity',
                packageName: 'com.android.browser'
            });
            intent.addCategory(Ti.Android.CATEGORY_BROWSABLE);
            Ti.Android.currentActivity.startActivity(intent);
            Ti.API.info('openWebPage: ' + url);

        }
        else {
            Ti.Platform.openURL(url);
            Ti.API.info('openWebPage: ' + url);
        }
    }
    else {
        alert('Please establish an internet connection first');
    }
};

A: Maybe you could help this is what happened to me recently when carrying a url from an intent
Intent i = new Intent (Intent.ACTION_VIEW, Uri.parse (url));
startActivity (i);

URL must start with http:// or https:// otherwise you will get a very nice exception.


text:
Q: Bootstrap Tooltips initialising but not showing I am trying to set up Bootstrap Tool Tips and it doesn't seem to be working.

This is a sentence with a tooltip

and
$(document).ready(function(){
    $("a").tooltip();
});

I have set up the following jsFiddle
The html appears to be transformed to the following:

This is a sentence with a tooltip

And the tooltip html is rendered:

A collection of words.

With the correct CSS styles:

But it is never shown in the browser?

A: It does work, it's just that in jsfiddle, everything outside the HTML box is hidden.
Updated version to show padding: http://jsfiddle.net/ytpAy/3/
Fred


text:
Q: how to check virtual memory page size without getconf I need to check vm pagesize on an embedded device running linux. Do not have the getconf to check the same.
Is there a way to check the page size in linux without getconf, is it possible to derive it from some proc entries.

A: In Linux most of the system related information present under "/proc/" directory. PAGESIZE information also can grab from here present in "/proc/1/smaps" file.
For example (using grep in /proc):
$ grep -ir pagesize /proc/1/smaps

KernelPageSize:        4 kB
MMUPageSize:           4 kB


text:
Q: Is It Efficient and Scalable for a Neural Network to Rely on Weights that Require Database Interaction? I'm a high school senior interested in computer science and I have been programming for almost nine years now. I've recently become interested in machine learning and I have decided to implement a neural network. I haven't begun to code it yet and have been in the designing stage for  a while now. The objective of the program is to analyze a student's paper, along with some other information, and then predict what grade the student will receive, much like PaperRater. However, I plan to make it far more personal than PaperRater.
The program has four inputs, one is the student's paper, the second is the student's id (i.e, primary key), third is the teacher's id, and finally the course id. I am implementing this on a website where registered, verified users alone can submit their papers for grading. The contents of the paper are going to be weighed in relation to the relationship between the teacher and student and in relation to the course difficulty. The network adapts to the teacher's grading habits for certain classes, the relationship between the teacher and student (e.g., if a teacher dislikes a student you might expect to see a drop in the student's grades), and the course-level (e.g., a teacher shouldn't grade a freshman's paper as harshly as a senior's paper).
However, this approach poses some considerable problems. There is an inherent limit imposed, where the numbers of students, teachers and courses prove to be too much and everything blows up! That's because there is no magic number which can account for every combination of student, teacher and course.
So, I've concluded that each teacher, student, and course must have an individual (albeit arbitrary) weight associated with them, not present in the Neural Network itself. The teacher's weight would describe her grading difficulty, and the student's weight would describe her ability as a writer. The weight of the course would describe the difficulty of the course. Of course, as more and more data is aggregated, the weights should adapt to become more accurate representations.
I realize that there is a relation between teachers and students, teachers and courses, and students and courses; therefore, I plan to make three respective hidden layers which sum the weights of its inputs and apply an activation function. How could I store the weights associated with each teacher, student and course, though?
I have considered storing it in their respective tables, but I don't know how well that would scale (or for that matter, if it would work). I also considered storing it in a file and calling it like that, but I'm sure that would be even worse than storing it in a database.
So the main question I have is: is it (objectively) efficient, in terms of space and computational complexity, and scalable, to store and manage separate, individual weights for each possible element of certain inputs in a SQL database outside of the neural network, if there are a finite (not necessarily small) amount of possible choices for such inputs, and still receive a reasonable output?
Regardless, I would like an explanation as to how come. I believe it would be just fine, but I can't justify it myself and so I'm asking for help. Thanks in advance!
(P.S.: If you realize any problems with my approach not covered in the scope of this question, or have general advice, please include it as an addendum to your answer or please message me).


text:
Q: HTML video speed controller for Internet Explorer I'm trying to find a way to control the speed of a custom HTML video playback app that I use for work. It is designed for and only runs in Internet Explorer. I've tried messing around in the console with some of the commands others have recommended but they keep throwing me errors. The Application we use takes VLC video files and plays back the audio. VLC has a way to control playback speed, but I can't figure out how to control that through the application either. In the console I've tried:
document.querySelector('video').defaultPlaybackRate = 2.0;

and
document.querySelector('video').playbackRate = 1.25;

but they both give me the error:

Unable to set property 'defaultPlaybackRate' of undefined or null reference

or 'playbackRate' for the other command.
In either instance, it seems like 'video' is a variable I need to assign? I've tried substituting the file name of the specific file I'm trying to play, but it still gives me syntax errors.
edit:
I've also tried:
const video=document.querySelector(nowPlaying);
video.playbackRate=2;

which gives me a syntax error.
edit 2:
As requested, here is a sample of the code I've been playing with today. The functions like slower(); and pause(); are not defined anywhere in the rest of the code; I'm thinking they may be VLC functions? If that is the case perhaps there is a VLC function I can call that will change the playback speed for me, but I can't find anything in VLC's code.

Note: The first and last buttons were added by me while I was messing around.

A: According to your description, there are two main problems:
First, Unable to set property of undefined or null reference means that you didn't get the page elements correctly, you may use it before the page is loaded, and this problem occurs. If this is the case, you need to put the script code in window.onload(). A simple demo:

    <video controls="controls">
        <source src="https://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4" />
    </video>

    <input type="button" name="slowerBtn" id="slowerBtn" value="Slower" />
    <input type="button" name="fasterBtn" id="fasterBtn" value="Faster" />

Second, the required parameter of Document.querySelector() is a valid element selector. What is the parameter nowPlaying you provided? I think it should be invalid.
If you can post your code sample, this will better identify the cause of the problem and solve it.


text:
Q: How to define orthogonal complement in an arbitrary vector space In this article about codimension there is the following remark:
The codimension of a subspace  $L$ of a vector space $V$ is equal to the dimension of any complement of $L$ in $V$, since all complements have the same dimension (as the orthogonal complement).
I know the definition of orthogonal complement in a Hilbert space but it's not clear to me how the orthogonal complement is defined in an arbitrary vector space.

How to define it in this case?

Also,

What's the definition of a (non-orthogonal) complement of a subspace?

Edit
"complement" is also used in this answer here. It's really not clear to me how to define a complement (if it's not orthogonal).

A: (1) Let $X$ be a finite-dimensional vector space, $W \subset X$ a vector subspace.
A complement of $W$ in $X$ is any subspace $S \subset X$ such that
$$X = W \oplus S.$$
(2) Let $X$ be a finite-dimensional inner product space, $W \subset X$ a vector subspace.
The orthogonal complement of $W \subset X$ is the subspace $W^\perp := \{x \in X \colon \langle x,w \rangle = 0 \ \forall w \in W\}$.  The orthogonal complement satisfies
$$X = W \oplus W^\perp.$$
Therefore, the orthogonal complement is a complement of $W$.

(3) Let $X$ be a Banach space, $W \subset X$ a closed vector subspace.
A (Banach space) complement of $W$ in $X$ is any closed subspace $S \subset V$ such that
$$X = W \oplus S.$$
(4) Let $X$ be a Hilbert space, $W \subset X$ a closed vector subspace.
The orthogonal complement of $W \subset X$ is the subspace $W^\perp := \{x \in X \colon \langle x,w \rangle = 0 \ \forall w \in W\}$.  The orthogonal complement is a closed subspace of $X$, and satisfies
$$X = W \oplus W^\perp.$$
Therefore, the orthogonal complement is a (Banach space) complement of $W$.

Edit: As Nate Eldredge points out in the comments, in the case where $X$ is an inner product space (of any dimension) and $W \subset X$ is not necessarily closed, then what we have is
$$X = \overline{W} \oplus W^\perp.$$
If $X$ is finite-dimensional, then any subspace $W \subset X$ is automatically closed, and so $\overline{W} = W$ in that case.

A: The most general statement of orthogonality I've seen is in a Banach space. If you have a Banach space $X$ and denote it's dual by $X^{*} $ then, for $V \subseteq X$, the complement of $V $ is defined as all $x^{*} \in X^{*}$ s.t for every $v \in V $, $x^{*}(v)=0$.


text:
Q: How to select the right zoom on Google Maps I build an app which use GMaps with several markers. The user can add or delete markers but my problem is to select the good zoom level to display all the markers.
That zoom level can change if the user add or delete markers.
For centering the camera I use the following code :
double xMin = 90.0 ;
double xMax =  0.0 ;
double yMin = 90.0 ;
double yMax =  0.0 ;

LatLngBounds.Builder builder = new LatLngBounds.Builder();

for (Place place : places) {
                if (place.getLatitude() < xMin)
                    xMin = place.getLatitude();

                if (place.getLatitude() > xMax)
                    xMax = place.getLatitude();

                if (place.getLongitude() < yMin)
                    yMin = place.getLongitude();

                if (place.getLongitude() > yMax)
                    yMax = place.getLongitude();

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(new LatLng(place.getLatitude(), place.getLongitude()));
                markerOptions.title(String.valueOf(place.getId()));
                Marker marker = this.googleMap.addMarker(markerOptions);
                allMarkersMap.put(marker, place);
                displayMarkersMap.put(marker, place);
                builder.include(marker.getPosition());
            }

            double xPos = (xMax + xMin) / 2;
            double yPos = (yMax + yMin) / 2;

            LatLngBounds bounds = builder.build();
            int padding = 1; // offset from edges of the map in pixels
            //CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
            //this.googleMap.moveCamera(cameraUpdate);
            LatLng latLng = new LatLng(xPos, yPos);
            CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(2).build();
            this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

But I don't find a solution to have a good zoom value.

A: I understand that you need to define a center for your map and ensure that all your markers are within the view.
In this case you can compute the LatLngBounds that include your markers and then extend it using the SphericalUtil.computeOffset, SphericalUtil.computeDistanceBetween and SphericalUtil.computeHeading methods from the Google Maps API Utility Library
private LatLngBounds findBounds(List<LatLng> positions, LatLng center) {
    // Add all the positions to a LatLngBounds (including center)
    LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
    for (LatLng position : positions) {
        boundsBuilder.include(position);
    }
    boundsBuilder.include(center);
    LatLngBounds bounds = boundsBuilder.build();

    // Compute the farthest location from the center among the bound corners
    LatLng northWest = new LatLng(bounds.northeast.latitude, bounds.southwest.longitude);
    LatLng southEast = new LatLng(bounds.southwest.latitude, bounds.northeast.longitude);
    LatLng farthest = findFarthestLocation(center, bounds.northeast, northWest, southEast, bounds.southwest);

    // Expand the bounds adding the projection of the farthest location from the center
    // in the oposite direction
    bounds = bounds.including(SphericalUtil.computeOffset(center,
            SphericalUtil.computeDistanceBetween(center, farthest),
            SphericalUtil.computeHeading(center, farthest) + 180));

    return bounds;
}

private LatLng findFarthestLocation(LatLng from, LatLng... locations) {
    LatLng farthest = null;

    for (LatLng location : locations) {
        if (farthest == null ||
                SphericalUtil.computeDistanceBetween(from, location) > SphericalUtil.computeDistanceBetween(from, farthest)) {
            farthest = location;
        }
    }

    return farthest;
}

You can test this method doing
LatLng center = new LatLng(40.384213, -3.875244);
List<LatLng> positions = new ArrayList<>();
positions.add(new LatLng(43.153102, 2.914307));
positions.add(new LatLng(42.976521, 1.508057));
positions.add(new LatLng(42.492353, 0.123779));

Display display = getActivity().getWindowManager().getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                int width  = size.x;
                int height = size.y;

LatLngBounds bounds = findBounds(positions,center);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,width,height,10));

A: map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_MYPOSITION, 16);
map.animateCamera(update);

Try this , i think 16 zoom will be enough to see the markers


text:
Q: Categorizing date by week with dynamic alias name We have one column in our table which stores a number of records in "date" type, we want to separate them by each week and find the number of repetitions for each week that we have in our column.
the database is in oracle.
I think for creating a dynamic alias name we need cursor.
this image below may help:

A: you can use mysql function week()
here the info: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
an example
select concat('Week ',week(date)), count(date)
from table
group by week(date)

A: Try this syntax;
SELECT     to_char(date,'WW') week, COUNT(date) number
FROM       your_table
GROUP  BY  to_char(date,'WW')

Have a look at TO_CHAR function.


text:
Q: Why is my form not submitting or posting The form is not submitting or posting to the database with the connector.php. I have tried removing validation to no avail I do not know what is wrong.   This issue has been bugging me for a day or two. Please help people.
`

<title>Sign up</title>
<link href="css/alldatcookies.css" rel="stylesheet" type="text/css" />

Home

Login

Sign Up

Contact

<form id="msform" name="msform" onSubmit="return checkForm(this)"         action="connector.php" method="POST" >
Menu

Account Setup

 Profile

Personal Details

    <fieldset>

Create your account

Step 1

        <input id="username" name="username" placeholder="In Game Username"/>
    <input id="email" name="email" placeholder="email"/>

    <input type="password" id="pass" name="pass" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}"onchange="form.cpass.pattern = this.value;">

   <input type="password" id="cpass" name="cpass" placeholder="Confirm Password" onKeyUp="checkPass(); return false;"  pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}"/>

    <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset> <fieldset>
Social Profiles

Your presence on the social network

    <input type="text" name="twitter" placeholder="Twitter" />
    <input type="text" name="facebook" placeholder="Facebook" />
    <input type="text" name="gplus" placeholder="Google Plus" />
    <input type="button" name="previous" class="previous action-button" value="Previous" />   <input type="button" name="next" class="next action-button" value="Next" />   </fieldset>
    <fieldset>

Personal Details

     <input type="text" id="firstname" name="firstname" placeholder="First Name" value="" />

    <input type="text" id="lastname" name="lastname" placeholder="Last Name" />

     <input type="tel" id="phone" name="phone" placeholder="Phone" />

     </textarea>
      <input type="button" name="previous" class="previous action-button" value="Previous" />
      <input type="submit" name="submit" id="msform"class="submit action-button" value="Submit"/>
      </fieldset>
      </form>

      `

A: It doesn't appear that you have anything in your script that activates it.  Typically you want a script to start on a click or something like that... your code doesn't appear to have any events to trigger the functions.
Take a look at this site that demonstrates enabling a submit button with .addEvent.


text:
Q: nginx 404 .php extension with fpm When I visit a non-existent url with .php extension I get a ngnix 404 error page, however url without .php extension it works as expected using the try_files. Where the 404 is handled via php application.
It has happened since I added this code as suggested
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
    return 404;
}

Reason for adding this was to fix error in logs: FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream
This error was happening when I visited non-existent.php file. I read lots of posts about the problem being to do with 'SCRIPT_FILENAME' being missing but this wasn't the case for me.
example.conf
server {
  listen 443 ssl;
  listen [::]:443 ssl;

  server_name example.com;

  root /var/www/example/public/public;

  access_log  /var/log/nginx/example.access.log main_ext;
  error_log  /var/log/nginx/example.error.log warn;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  include /etc/nginx/include.d/ssl.conf;

  # Laravel
  rewrite ^/index.php/(.*) /$1 permanent;

  location = / {
    try_files /page-cache/pc__index__pc.html /index.php?$query_string;
  }

  location / {
    try_files $uri $uri/ /page-cache/$uri.html /index.php?$query_string;
  }

  location ~ [^/]\.php(/|$) {
    include /etc/nginx/include.d/php.conf;
    fastcgi_pass unix:/var/run/php/php8.0-fpm-example.sock;
  }
}

php.conf
# Check file exists
try_files $uri =404;

# https://www.nginx.com/nginx-wiki/build/dirhtml/start/topics/examples/phpfcgi/
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
    return 404;
}

fastcgi_index index.php;

# Mitigate https://httpoxy.org/ vulnerabilities
fastcgi_param HTTP_PROXY "";

fastcgi_intercept_errors off;

# include the fastcgi_param setting
include fastcgi_params;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

Example URL:
https://example.com/foo - Works fine shows pretty 404 inside php app.
https://example.com/foo.php - Shows default ngnix 404.

A: If you want those URIs to be processed as any other non-existent URIs, change try_files $uri =404; to the try_files $uri /index.php?$query_string; in your php.conf file.

If your PHP app really makes use of PATH_INFO FastCGI variable (which I doubt about), you should use
fastcgi_split_path_info ^(.+\.php)(/.+)$;

try_files $fastcgi_script_name /index.php?$query_string;

set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

(see this nginx trac ticket).


text:
Q: Prove that sum of n-th degree roots of complex number is 0 I'm trying to prove, that sum of all complex roots of n-th degree of a complex number $z$ is equal to 0. I know how to prove it for $z = 1$ (roots of unity), however i have to prove it for any complex number $z$. Can anyone help me?

A: Sketch:
Method 1: The negative sum of all the roots of a monic polynomial of degree $n$ in $x$ is the coefficient of $x^{n-1}$.  You are interested in the roots of the polynomial $x^n-z$.  The coefficient of $x^{n-1}$ in this polynomial is $0$.
Method 2: Suppose that $x$ is an $n^{\text{th}}$ root of $z$ and $\omega$ is a primitive $n^{\text{th}}$ root of unity.  Then, the $n^{\text{th}}$ roots of $z$ are $x$, $x\omega$, $x\omega^2$, $\dots$, $x\omega^{n-1}$.  Their sum factors nicely and you can show that one of the factors is $0$.

A: You can use polar coordinates:
$$
z = r e^{i \phi + 2\pi ik} \quad (k \in \mathbb{Z})
$$
Taking the $n$-th root means:
$$
z^{1/n} = r^{1/n} e^{i \phi / n + 2 \pi ik/n} = r^{1/n} \omega_k
$$
So you can use your already shown sum for the $n$ different unit roots $\omega_k$:
$$
\sum_k z^{1/n} = r^{1/n} \sum_k \omega_k  = 0
$$

A: The $n$th roots of $\zeta$ are the solutions to the equation $$z^n-\zeta = 0$$  We know that the sum of the roots of an $n$th degree polynomial is the negative of the coefficient of the term of degree $n-1$, which is $0$ in this case.


text:
Q: SQLite: How to count references to each ROWID in a table, then insert the count I need some help writing a SQL statement. I have two tables in a SQLite database:
CREATE TABLE users (
  user_id INTEGER PRIMARY KEY,
  item_id INTEGER
);

CREATE TABLE items (
  item_id INTEGER PRIMARY KEY,
  ref_count INTEGER
);

I'm seeking a SQLite statement that will be like the following pseudocode:
for each row in items
    items[ row ].ref_count = SELECT COUNT(users.item_id)
                               FROM users
                              WHERE users.item_id=row;

A: It looks like you can use the REPLACE command as follows:
REPLACE INTO  items (item_id, ref_count)
SELECT        item_id, COUNT(*) AS ref_count
FROM          users
GROUP BY      item_id;

Test case:
INSERT INTO users VALUES (1, 1);
INSERT INTO users VALUES (2, 1);
INSERT INTO users VALUES (3, 1);
INSERT INTO users VALUES (4, 2);
INSERT INTO users VALUES (5, 2);
INSERT INTO users VALUES (6, 3);

Result after running the REPLACE query:
SELECT * FROM items;

item_id       ref_co
------------  ------
1             3
2             2
3             1

Adding some further items:
INSERT INTO users VALUES (7, 1);
INSERT INTO users VALUES (8, 4);
INSERT INTO users VALUES (9, 4);

And after re-running the REPLACE query:
SELECT * FROM items;

item_id       ref_co
------------  ------
1             4
2             2
3             1
4             2


text:
Q: Illegal assignment from list to list for custom class and aggregateResult I have a custom controller and visualforce page. The page loads fine with the SummaryList. When the user enters parameters, it should filter the list according to the runSearch method. I'm getting an error with runQuery2: illegal assignment from list to list. The database.query does not get an error if I create a separate list of type aggregateResult, and I use that list instead of SummaryList; but that is not going to work, because I can't query an aggregateResult type. How do I make this work?
Controller:
public with sharing class inspectionsDashboard {

    public List<AggregateResult> Result {get;set;}
    public List SummaryList {get;set;}
    public List<Account> AcctList {get;set;}
    public Map<Id, Account> IdAccount {get;set;}
    List<Id> Ids {get;set;}
    private String soql {get;set;}
    private String soql2 {get;set;}

    public String sortDir {
        get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
        set;
    }

    // the current field to sort by. defaults to last name
    public String sortField {
        get  { if (sortField == null) {sortField = 'Name'; } return sortField;  }
        set;
    }

    // format the soql for display on the visualforce page
    public String debugSoql {
        get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
        set;
    }

    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        // run the query again
        runQuery();
    }

    public inspectionsDashboard() {
        SummaryList = new List();
        Result = new List<AggregateResult>();
        Ids = new List<Id>();
        AcctList = new List<Account>();
        IdAccount = new Map<Id, Account>();
        soql = 'SELECT Name,BillingState FROM Account WHERE Id IN : Ids';

        Result = [SELECT Count(Id) Total, Sum(Home_Inspection_dollars__c) Dollars, Franchise__c
                  FROM Inspection__c
                  WHERE Month_Since_Launch__c > 0 AND Status__c = 'Completed'
                  GROUP BY Franchise__c];

        for(AggregateResult a : Result) {
            Ids.add((Id)a.get('Franchise__c'));
        }

        System.debug('Account List' + AcctList);

        runQuery();

        for(Account a : AcctList) {
            IdAccount.put(a.Id, a);
        }

        System.debug('Ids and Accounts are ' + IdAccount);

        for(AggregateResult a : Result) {
            Account TempAcct = new Account();
            TempAcct = IdAccount.get((Id)(a.get('Franchise__c')));
            system.debug('Account Name is ' + TempAcct.Name);
            SummaryList.add(new Summary(a, TempAcct.Name, TempAcct.BillingState));

        }
    }

    public void runQuery() {

        try {
          AcctList = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
        } catch (Exception e) {
          ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
        }
    }

    public void runQuery2() {

        try {
          SummaryList = Database.query(soql2);
        } catch (Exception e) {
          ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
        }
    }

    public class Summary {
        public Integer Total {get;set;}
        public Decimal Dollars {get;set;}
        public String AcctName {get;set;}
        public String StateProvince {get;set;}

        public Summary(AggregateResult a, String AccountName, String State) {
            Total =  (Integer)a.get('Total');
            Dollars = (Decimal)a.get('Dollars');
            AcctName = AccountName;
            StateProvince = State;
        }
    }

    public PageReference runSearch() {

        String AccountName = Apexpages.currentPage().getParameters().get('AccountName');
        String State = Apexpages.currentPage().getParameters().get('State');
        //soql = 'SELECT Name,BillingState FROM Account WHERE Id IN : Ids';
        soql2 = 'SELECT AcctName,StateProvince,Dollars,Total FROM Summary__c WHERE AcctName != null';

        List<String> li = new List<String>();
        if (!AccountName.equals(''))
          li.add(' AcctName LIKE \''+String.escapeSingleQuotes(AccountName)+'%\'');
        if (!State.equals(''))
          li.add(' StateProvince LIKE \''+String.escapeSingleQuotes(State)+'%\'');
        String c = String.join( li, ' or ');
        if (c.length() > 0)
            c = ' and (' + c + ')';
        system.debug('condition: ' + c);
        soql2 += c;

        // run the query again

        runQuery2();

        return null;
    }
}

Visualforce Page:
<apex:page controller="inspectionsDashboard" sidebar="false">
    <apex:form >
    <apex:pageMessages id="errors" />

        <apex:pageBlock title="Find Me A Franchisee!" mode="edit">

            <apex:pageBlock title="Parameters" mode="edit" id="criteria">

              <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
                  <apex:param name="AccountName" value="" />
                  <apex:param name="State" value="" />
              </apex:actionFunction>

                Account Name

                <input type="text" id="AccountName" onkeyup="doSearch();"/>

                State/Province

                <input type="text" id="State" onkeyup="doSearch();"/>

              </apex:pageBlock>

        <apex:pageBlock mode="edit" id="results">
            <apex:pageblockTable value="{!SummaryList}" var="r">

                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="Account Name" action="{!toggleSort}" rerender="results,debug">
                            <apex:param name="sortField" value="{!r.AcctName}" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputText value="{!r.AcctName}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="State/Province" action="{!toggleSort}" rerender="results,debug">
                            <apex:param name="sortField" value="{!r.StateProvince}" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputText value="{!r.StateProvince}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="Number of Home Inspections" action="{!toggleSort}" rerender="results,debug">
                            <apex:param name="sortField" value="{!r.Total}" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputText value="{!r.Total}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="Home Inspection $" action="{!toggleSort}" rerender="results,debug">
                            <apex:param name="sortField" value="{!r.Dollars}" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputText value="{!r.Dollars}"/>
                </apex:column>

            </apex:pageblockTable>
        </apex:pageBlock>

        <apex:pageBlock title="Debug - SOQL" id="debug">
            <apex:outputText value="{!debugSoql}" />
        </apex:pageBlock>

        </apex:pageBlock>
    </apex:form>
</apex:page>

A: You have to do the same thing you did originally; extract the resulting values, and convert them to a new List:
SummaryList.clear();
for(AggregateResult result: (AggregateResult[])Database.query(soql2)) {
  ...
  SummaryList.add(new Summary(...));
}


text:
Q: Searching/filtering all columns in an excel sheet for a string and then copying the containing rows to the first blank row in another sheet New to stackoverflow and VBA (and to scripting in general to a lesser extent) so I apologise if I've broken any rules or made any silly mistakes.
Currently I have a one dimentional array containing several strings. I want to build a loop that for each string in the array searches all of the columns of sheet1 for the string and then copies the containing rows to the first blank row in sheet2.
The issue is that I can't find a built in subroutine that will allow me to search multiple/all columns for the search term, only ones that look in a single column. I assume there is something built in that does this as it seems like an obvious thing to have- where can I find it? And if you're feeling kind and you have some example code please post it :)
Thanks,
Louis
P.S. If anyone has some VBA guides/documentation that they would like to recommend, please do! My google fu is weak and I've not found much so far.

A: This is not really an efficient code, but it should give you a pretty good idea how to use loops (columns, rows, array)
note: if you have some sort of structure in your spreadsheet (for example headers) then you can find the last used column in row - which is more efficient then looping through ALL columns in the sheet.
   Sub doTheJob()
        Application.ScreenUpdating = False
        Dim ws1 As Worksheet, ws2 As Worksheet, arr() As String, str$, i&, j&, k&

        Set ws1 = ThisWorkbook.Sheets(1)
        Set ws2 = ThisWorkbook.Sheets(2)

        str = "this is your string"
        arr = Split(str, " ")

        For i = 1 To ws1.Columns.Count
            For j = 1 To ws1.Cells(Rows.Count, i).End(xlUp).Row
                For k = LBound(arr) To UBound(arr)
                    If StrComp(CStr(ws1.Cells(j, i).Value), arr(k), vbTextCompare) = 0 Then
                        ws1.Rows(j & ":" & j).Select
                        Selection.Copy
                        Dim nxt&
                        nxt = ws2.Range("A" & Rows.Count).End(xlUp).Row + 1
                        ws2.Rows(nxt & ":" & nxt).Select
                        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                        :=False, Transpose:=False
                    End If
                Next k
            Next j
        Next i
    Application.ScreenUpdating = True
End Sub

Post edit - it should copy entire rows now...


text:
Q: Why using span tag give me result that is not to be expected? I wanted to get the result like this.

My code is :
<!DOCTYPE html>

// Prints 5 to the console
console.log(5);

A: I took some time to play around with your code. Your


text:
Q: Uncaught exception 'PHPMailer\PHPMailer\Exception' could not connect SMTP certificate error I am trying to send email from my localhost with gmail smtp server and phpmailer.
 when I submit my form I am getting following error.
2018-02-05 18:36:19 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP e22sm5767718ioj.79 - gsmtp
2018-02-05 18:36:19 CLIENT -> SERVER: EHLO localhost
2018-02-05 18:36:19 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [142.237.177.21]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2018-02-05 18:36:19 CLIENT -> SERVER: STARTTLS
2018-02-05 18:36:19 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2018-02-05 18:36:19 Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [C:\wamp64\www\test\phpmailer\src\SMTP.php line 405]
SMTP Error: Could not connect to SMTP host.
2018-02-05 18:36:19 CLIENT -> SERVER: QUIT
2018-02-05 18:36:19
2018-02-05 18:36:19
2018-02-05 18:36:19 Connection: closed
SMTP Error: Could not connect to SMTP host.

( ! ) Fatal error: Uncaught exception 'PHPMailer\PHPMailer\Exception' with message 'SMTP Error: Could not connect to SMTP host.' in C:\wamp64\www\test\phpmailer\src\PHPMailer.php on line 1898

I tried everything I could do but nothing works out.
below is my code .

<?php

require_once 'dbconfig.php';

class USER
{

 private $conn;

 public function __construct()
 {
  $database = new Database();
  $db = $database->dbConnection();
  $this->conn = $db;
    }

 public function runQuery($sql)
 {
  $stmt = $this->conn->prepare($sql);
  return $stmt;
 }

 public function lasdID()
 {
  $stmt = $this->conn->lastInsertId();
  return $stmt;
 }

 public function register($uname,$email,$upass,$code)
 {
  try
  {
   $password = md5($upass);
   $stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass,tokenCode)
                                                VALUES(:user_name, :user_mail, :user_pass, :active_code)");
   $stmt->bindparam(":user_name",$uname);
   $stmt->bindparam(":user_mail",$email);
   $stmt->bindparam(":user_pass",$password);
   $stmt->bindparam(":active_code",$code);
   $stmt->execute();
   return $stmt;
  }
  catch(PDOException $ex)
  {
   echo $ex->getMessage();
  }
 }

 public function login($email,$upass)
 {
  try
  {
   $stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userEmail=:email_id");
   $stmt->execute(array(":email_id"=>$email));
   $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

   if($stmt->rowCount() == 1)
   {
    if($userRow['userStatus']=="Y")
    {
     if($userRow['userPass']==md5($upass))
     {
      $_SESSION['userSession'] = $userRow['userID'];
      return true;
     }
     else
     {
      header("Location: index.php?error");
      exit;
     }
    }
    else
    {
     header("Location: index.php?inactive");
     exit;
    }
   }
   else
   {
    header("Location: index.php?error");
    exit;
   }
  }
  catch(PDOException $ex)
  {
   echo $ex->getMessage();
  }
 }

 public function is_logged_in()
 {
  if(isset($_SESSION['userSession']))
  {
   return true;
  }
 }

 public function redirect($url)
 {
  header("Location: $url");
 }

 public function logout()
 {
  session_destroy();
  $_SESSION['userSession'] = false;
 }

 function send_mail($email,$message,$subject)
 {

 require 'C:\wamp64\www\test\phpmailer\src\Exception.php';
 require 'C:\wamp64\www\test\phpmailer\src\PHPMailer.php';
 require 'C:\wamp64\www\test\phpmailer\src\SMTP.php';
  $mail = new PHPMailer\PHPMailer\PHPMailer(true);
  $mail->IsSMTP();

  $mail->SMTPDebug = 3;
  $mail->SMTPAuth   = true;
  $mail->SMTPSecure = 'tls';
  $mail->Host       = 'smtp.gmail.com';
  $mail->Port       = 587;
  $mail->Username= "solankij978@gmail.com";
  $mail->Password= "9724929143";
  $mail->SetFrom('solankij978@gmail.com','Sachin Patel');
  $mail->AddReplyTo('deeshanpatel@gmail.com','Sachin Patel');
  $mail->AddAddress($email);
  $mail->Subject    = $subject;
  $mail->MsgHTML($message);
  $mail->Send();
 }
}

please help me out.


text:
Q: Using ArcPy to query ArcSDE geodatabase? I have three variables: view_name, column_name, and column_content.
column_name contains id, name, address, etc.
column_content contains 123, John, 200 King st, etc.
user specifies the column_name and column_content
a SDE connection file located: c:\gdb.dmz.sde
how to query the database in the view = view_name where column_name = column_content?
using arcpy.da.SearchCursor() function.

A: It sounds like column_name is your field name, and column_content is the value you are looking for. Using da.SearchCursor will certainly get you where you want to be. I am assuming you then wish to find other information from the row once the row is matched. To get this information, the da.SearchCursor requires the feature class or table you wish to query and a list of fields you wish to find the values of as its inputs. The cursor returns a tuple of the values in the fields you indicated as your da.SearchCursor input. You can use an if statement to find the value you are after.
Something like this:
fc = r"feature/class/full/path"

column_name = "ADDRESS"
column_content = "123 Way Street"

otherfields = ["ID", "NAME", "ADDRESS"]

fields = [column_name] + otherfields

cursor = arcpy.da.SearchCursor (fc, fields)
for row in cursor:
    if row[0] == column_content:
        print "ID:", row[1]
        print "NAME:", row[2]
        print "ADDRESS:", row[3]
del row
del cursor


text:
Q: Why is this class in my Java 6 JDK look like the Java 5 version? I'm running IntelliJ with Java 6 to build my project.  I'm doing a clean checkout via SVN and trying to do a mvn clean install  It runs successfully but then when I try to deploy my application I get a compile time error.  It says that I'm trying to use a constructor that doesn't exist.
Specifically, I'm trying to use a constructor from Here . This constructor is NOT in the Java 5 version.  But for some reason, the .class file in my jdk 1.6 install appears to be the Java 5 version.  The location of the .class file is /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar!/javax/xml/ws/Service.class and that path was copied directly from IntelliJ when I drill down .
Here is the decompiled code from IntelliJ
  // IntelliJ API Decompiler stub source generated from a class file
  // Implementation of methods is not available

package javax.xml.ws;

public class Service {
    private javax.xml.ws.spi.ServiceDelegate delegate;

    protected Service(java.net.URL url, javax.xml.namespace.QName qName) { /* compiled code */ }

    public <T> T getPort(javax.xml.namespace.QName qName, java.lang.Class<T> aClass) { /* compiled code */ }

    public <T> T getPort(javax.xml.namespace.QName qName, java.lang.Class<T> aClass, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public <T> T getPort(java.lang.Class<T> aClass) { /* compiled code */ }

    public <T> T getPort(java.lang.Class<T> aClass, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public <T> T getPort(javax.xml.ws.EndpointReference endpointReference, java.lang.Class<T> aClass, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public void addPort(javax.xml.namespace.QName qName, java.lang.String s, java.lang.String s1) { /* compiled code */ }

    public <T> javax.xml.ws.Dispatch<T> createDispatch(javax.xml.namespace.QName qName, java.lang.Class<T> aClass, javax.xml.ws.Service.Mode mode) { /* compiled code */ }

    public <T> javax.xml.ws.Dispatch<T> createDispatch(javax.xml.namespace.QName qName, java.lang.Class<T> aClass, javax.xml.ws.Service.Mode mode, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public <T> javax.xml.ws.Dispatch<T> createDispatch(javax.xml.ws.EndpointReference endpointReference, java.lang.Class<T> aClass, javax.xml.ws.Service.Mode mode, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public javax.xml.ws.Dispatch<java.lang.Object> createDispatch(javax.xml.namespace.QName qName, javax.xml.bind.JAXBContext jaxbContext, javax.xml.ws.Service.Mode mode) { /* compiled code */ }

    public javax.xml.ws.Dispatch<java.lang.Object> createDispatch(javax.xml.namespace.QName qName, javax.xml.bind.JAXBContext jaxbContext, javax.xml.ws.Service.Mode mode, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public javax.xml.ws.Dispatch<java.lang.Object> createDispatch(javax.xml.ws.EndpointReference endpointReference, javax.xml.bind.JAXBContext jaxbContext, javax.xml.ws.Service.Mode mode, javax.xml.ws.WebServiceFeature... webServiceFeatures) { /* compiled code */ }

    public javax.xml.namespace.QName getServiceName() { /* compiled code */ }

    public java.util.Iterator<javax.xml.namespace.QName> getPorts() { /* compiled code */ }

    public java.net.URL getWSDLDocumentLocation() { /* compiled code */ }

    public javax.xml.ws.handler.HandlerResolver getHandlerResolver() { /* compiled code */ }

    public void setHandlerResolver(javax.xml.ws.handler.HandlerResolver handlerResolver) { /* compiled code */ }

    public java.util.concurrent.Executor getExecutor() { /* compiled code */ }

    public void setExecutor(java.util.concurrent.Executor executor) { /* compiled code */ }

    public static javax.xml.ws.Service create(java.net.URL url, javax.xml.namespace.QName qName) { /* compiled code */ }

    public static javax.xml.ws.Service create(javax.xml.namespace.QName qName) { /* compiled code */ }

    public static enum Mode {
        MESSAGE, PAYLOAD;

        public static javax.xml.ws.Service.Mode[] values() { /* compiled code */ }

        public static javax.xml.ws.Service.Mode valueOf(java.lang.String s) { /* compiled code */ }

        private Mode() { /* compiled code */ }
    }
}

Can anyone explain what is going on?
Edit #1: It doesn't error at deploy, its errors at compile time.  I communicated that poorly above.  You can see the red squiggles in IntelliJ.  When I try to drill down on the constructor, it shows me the decompiled code seen above.  The issue is that it does NOT look like the Java 6 class, it appears to be the Java 5 class but it is in my Java 6 SDK.  Also, someone pointed out that the constructor is protected so I can't use it.  However, my class extends service so its allowed to use the constructor.
Output from mvn -v
<machine_name>:record-replay carlos$ mvn -v
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 08:51:28-0500)
Maven home: /Users/carlos/workspace/dev/apache-maven/current
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.9.4", arch: "x86_64", family: "mac"

Edit #2: @Didier Yeah, I can get around it by using the Jaxb and jaxws version of Service.class  Thanks for that.  But I'm more interested in why this class in my Java 6 SDK is failing when the API says it should have the constructor

A: The actual javax.xml.ws.Service included in JDK6 is the one from JAXB/JAX-WS 2.0 and does not have this constructor. The actual documentation is here.
You are referring to the documentation of Java EE 6 which includes JAXB/JAX-WS 2.1 with the new constructor.
You should be able to fix your issue following these instructions. See also this question.


text:
Q: Windows Phone 8 development - Logging & IOC Design Patterns I am new to Windows Phone development, especially to WP8. I have some minor experience with developing with WPF and I tried some proof-of-concept solutions with WP7.
So far I have been digging around the WP8 and didn't come to any answer that is targeting logging/tracing on WP8 and some usage of IOC. I have been developing for Android and been using Guice with RoboGuice. I have experience with both Windsor and Ninject, but it seems that WP8 isn't supported by any of those yet.

*

*What is the suggested way to perform logging/tracing on WP8?

*What are the best development and design patterns that should be used?

*Is there any IoC or Service locator or any library targeting those features?

Can you suggest some good libraries/tools/frameworks?
Thanks.

A: Probably the BugSense may be interesting for you.
Also as a starter ("just to have something") solution you can save trace data to IsolatedStorage and then share it on http://pastebin.com/ so that other can access it.


text:
Q: Is there a way to formulate relativistic dynamics in a way that "hides" the finite speed of light? I'm not referring to the dimensional choice that makes $c=1$; rather I'm imagining something more about replacing all references that apparently involve velocities with the appropriate $\gamma$ factors or rapidity. In this description, the kinematic feature that maps to speed would then be defined on $[0,\infty)$, and we wouldn't have to deal with the question of "why is the speed of light finite, and has the value that it has?" $^*$
$^*$ Or, at least we wouldn't have to deal with it as a fundamental question about the universe.

A: If you need equations without velocities, just with $\gamma$, just replace any $v$ by $c\sqrt{\gamma^2-1}/\gamma$ and you're done.
Incidentally, $\gamma$ isn't the only useful function of $v$ that takes values between $0$ and $\infty$. You could also use the rapidity $\eta={\rm arctanh}(v/c)$.
It's good to use $\gamma$ and $\eta$ and in various situations, it simplifies physics or makes it clearer. However, it's still true that $d\vec x / dx^0=\vec v$ and nothing else for the trajectory of a particle, so this basic defining equation of the slope of the trajectory takes the simplest form with $\vec v$! And this "actual velocity" is smaller than $c$ for all massive bodies: this basic statement of relativity is surely not just a convention and can't be hand-waved away by some change of variables. Only one quantity, $v$, deserves to be called the velocity.
Also note that $\gamma$ and even $\eta$, if defined in the easy way above isn't even a vector: it only knows about the magnitude of the speed, not its direction.

A: Use a pure four-space notation $x^0 = ct$. Expressions such as $(1/c) (d/dt)$ transform to $(d/dx^0)$. For instance the typical $(v/c)$ terms transform to $(dx/dx^0)$.
For proper-time derivatives use $ds = cd\tau$.