text:
Q: How do I check if an email address is valid without sending anything to it? I have a client with 5000 emails from an old list he has that he wants to promote his services to. He wants to know which emails on the list are still valid. I want to check them for him - without sending out 5K emails randomly and then being listed as a spammer or something. Ideas?

A: You can validate the email via SMTP without sending an actual email.
http://code.google.com/p/php-smtp-email-validation/
You could also send emails out, and check for bounces.

A: bucabay's answer is the way forward. What a library like that essentially does is checking for existing DNS record for (mail) servers at specified domains (A, MX, or AAAA). After that, it do what's termed callback verification. That's where you connect to the mail server, tell it you want to send to a particular email address and see if they say OK.
For callback verification, you should note greylisting servers say OK to everything so there is no 100% guarantee possible without actually sending the emails out. Here's some code I used when I did this manually. It's a patch onto the email address parser from here.
    #
    # Email callback verification
    # Based on http://uk2.php.net/manual/en/function.getmxrr.php
    #

    if (strlen($bits['domain-literal'])){
        $records = array($bits['domain-literal']);
    }elseif (!getmxrr($bits['domain'], $mx_records, $mx_weight)){
        $records = array($bits['domain']);
    }else{
        $mxs = array();

        for ($i = 0; $i < count($mx_records); $i++){
            $mxs[$mx_records[$i]] = $mx_weight[$i];
        }

        asort($mxs);

        $records = array_keys($mxs);
    }

    $user_okay = false;
    for ($j = 0; $j < count($records) && !$user_okay; $j++){
        $fp = @fsockopen($records[$j], 25, $errno, $errstr, 2);
        if($fp){
            $ms_resp = "";

            $ms_resp .= send_command($fp, "HELO ******.com");
            $ms_resp .= send_command($fp, "MAIL FROM:<>");

            $rcpt_text = send_command($fp, "RCPT TO:<" . $email . ">");
            $ms_resp .= $rcpt_text;

            $ms_code = intval(substr($rcpt_text, 0, 3));
            if ($ms_code == 250 || $ms_code == 451){ // Accept all user account on greylisting server
                $user_okay = true;
            }

            $ms_resp .= send_command($fp, "QUIT");

            fclose($fp);
        }
    }

return $user_okay ? 1 : 0;

A: I think you need to send the emails to find out. Also, this is pretty much exactly what a spammer is, thus the reason for getting put on spammer lists. Sending in bursts will help you hide this fact though.

A: You'll have to email them at least once.

*

*Create a new email list. Send the old list an email with a link they need to click on to continue receiving messages (re-subscribe).

*Send them all an email and collect all reply-to bounces on a real email account, then purge those bounced emails from your main list.

*Send them all an HTML email, and one of the images is remotely hosted and requires a unique ID to request it that you set in each email. When your web server returns that image to their client, you can then consider that email as active. This is called a web bug, and will only work if the person automatically loads remote images in their client.

A: https://github.com/kamilc/email_verifier is a rubygem that will check that the MX record exists and that the SMTP server says the address has a valid mailbox.

A: You can use a paid service like Kickbox to do this as well.

A: You can consider the MailboxValidator service http://www.mailboxvalidator.com/ which should be adequate for your requirement. You can get either a bulk plan where you can upload a CSV file containing your email list or get the API plan if you require programmatic integrations.


text:
Q: Can't ping machine on LAN from 1 out of 3 Kubuntus I have three Kubuntu systems running, one 12.04 and two 13.10.  I have an HP MediaVault (a network attached storage device) on my LAN.
On the 12.04 and one of the 13.10's, I can ping hpmediavault; on the other 13.10 I get the "unknown host" error.  I've installed winbind on all three systems and set the hosts entry in /etc/nsswitch.conf to
hosts:          wins files mdns4_minimal [NOTFOUND=return] dns mdns4

The misbehaving system has a wired connection; the other two have wireless connections.  That's the only difference I'm aware of that might affect this behavior.  I can ping the MediaVault on the third system by using its IP address.
So what do I need to do to get the third system to do its ping?

A: It turns out that I also needed to install the libnss-winbind package, which wasn't mentioned in the instructions for connecting the MediaVault to Linux.  I don't know how that package got installed in 2 systems but not the third.  Installing it solved the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use a CTE to insert multiple records based on hierarchy Lets say I have a Customer table that contains CustomerId as a primary key and ParentCustomerId as a foreign key and I want to cascade an insert statement to create a record for each of the Customers in the hierarchy chain.
I also have a CustomerContact table that has a clustered primary key of CustomerId, PersonId, and DateCreated
So if I have the following:
Customer1: CustomerId: 1 : ParentCustomerId: Null
Customer2: CustomerId: 2 : ParentCustomerId: 1
Customer3: CustomerId: 3 : ParentCustomerId: 2
And I pass 1 into my customer ID, but I want to create 3 (although in this case the 3 is a variable, the hierarchies could go deeper) so that I insert into a different table a row for each customer in the chain.
declare @1 as int      --customerId
declare @2 as int      --personId for the contact
declare @3 as datetime --DateCreated

set @1 = 1
set @2 = 1 --personId
set @3 = GetDate()

--I don't know how to use a CTE to get all the CustomerIds that are
--
--something like
--with cte_customers
--as
--(select CustomerId from customer
--  where ParentCustomerId = @1
--)

insert into CustomerContact
Values(@1, @2, @3)

How can I write a CTE to get the children of all the customers related to param @1 and create a record in CustomerContact for each?

A: You need to use a recursive common table expression using union all.  Here's a reduced example:
with cte as (
    select customerid, parentcustomerid
    from customer
    where customerid = 1
    union all
    select c.customerid, cte.customerid
    from customer c join cte on cte.customerid = c.parentcustomerid)

 insert into customercontact
 select customerId, @1, @2 from cte

With your sample data, this will return 3 records and can also handle deeper relationships.


text:
Q: Customized permission to view Google Script Application I want to permit certain user out of my organization to access(view) the script link. There are only 4 available options to me.
Is there anyway by which i can allow some specific gmail users to use the application?

A: The best solution would be to create a method to validate access to the user list and publish to the public "anyone " not anonymous because you'll need their email address to validate access


text:
Q: Python / Pyserial / Arduino writing serial data to to txt file problem So I have a code that reads the incoming serial data from the Arduino and also writes serial data when specific keys are pressed, I also want to write this incoming serial data to the text file and I am using threading. This is the code:
from pynput import keyboard
import threading
import serial
import sys
import io

class SerialReaderThread(threading.Thread):

    ser = None
    def run(self):
        global ser

        ser = serial.Serial('COM4', baudrate = 9600, timeout = 20)

        while True:
            print(ser.readline().decode('utf-8'))

class FileWriting(threading.Thread):

   def run(self):

       global ser

       while True:

            with io.open("output.txt", "a", encoding="utf-8") as f:
                f.write(ser.readline().decode('utf-8'))

class KeyboardThread(threading.Thread):

    def run(self):
        global ser
        def on_press(key):
            global ser
            try:
                format(key.char)

                if key.char == "1":
                    ser.write(b'1\r\n') #serial write - 1

                elif key.char == "2":
                    ser.write(b'2\r\n') #serial write - 2

                elif key.char == "3":
                    ser.write(b'3\r\n') #serial write - 3

                elif key.char == "4":
                    ser.write(b'4\r\n') #serial write - 4

                elif key.char == "5":
                    ser.write(b'5\r\n') #serial write - 5

                elif key.char == "6":
                    ser.write(b'6\r\n') #serial write - 6

                elif key.char == "0":
                    ser.write(b'0\r\n') #serial write - 0
            except AttributeError:
                print(''.format(key))

        with keyboard.Listener(on_press=on_press) as listener:
            listener.join()

        listener = keyboard.Listener(on_press=on_press)
        listener.start()

serial_thread = SerialReaderThread()
keyboard_thread = KeyboardThread()
file_thread = FileWriting()

serial_thread.start()
keyboard_thread.start()
file_thread.start()
serial_thread.join()
keyboard_thread.join()
file_thread.join()

Now my problem is that I cannot write to the file, the reading serial data works perfectly and the writing to the Arduino also works perfectly, however when I try to additionally write to the file it gives me this error.
    Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\menucode.py", line 33, in run
    f.write(ser.readline().decode('utf-8'))
NameError: name 'ser' is not defined

Any help will be appreciated, thanks alot.

A: global variables are usually initialised at the outermost level, so move your ser = None to line 6. (Your use inside the class is making ser a class variable, not a global.)  You don't need to declare global ser except in a code block where you are going to change its value. So remove all of them except the one before ser = serial.Serial....


text:
Q: conditional expectation in markov chain proof In Durrett's probability theory and examples, when proving chapman-kolmogorov's equation, we do the following:
\begin{align*}
P_x(X_{n+m} = z) &= E_x[P_x(X_{m+n} = z \mid \mathcal{F}_m)]\\
&= E_x [ P_{X_m} (X_n = z)] \quad (\text{by Markov Property})\\
&= \sum_y P_x(X_m = y) P_y(X_n = z)
\end{align*}
To get the first and second equality, I think what he did was
\begin{align*}
P_x(X_{n+m} = z) &= E_x[1_{\{X_{m+n} = z\}}]\\
&= E_x[1_{\{X_{n} = z\}} \circ \theta_m]\\
&= E_x[E_x[1_{\{X_{n} = z\}} \circ \theta_m \mid \mathcal{F}_m]] \quad  (?)\\
\end{align*}
where $\theta_m$ is a shift operator.
How can you take the conditional expectation on $\mathcal{F}_m$ when we don't know whether $1_{\{X_{n} = z\}} \circ \theta_m \in \mathcal{F}_m$?

A: We do not need that  $1_{\{X_{n} = z\}} \circ \theta_m$ is $\mathcal F_m$-measurable (and it does not hold in general). What is used is rather that $\mathbb E\left[X\right]=\mathbb E\left[\mathbb E\left[X\mid\mathcal G\right]\right]$ for any $\sigma$-algebra $\mathcal G$ and any integrable random variable $X$. And this holds without assuming that $X$ is $\mathcal G$-measurable.


text:
Q: Why the absolute value of the max negative integer -2147483648 is still -2147483648? The result of abs(-2147483648) is -2147483648, isn't it?
it seems unacceptable.
printf("abs(-2147483648): %d\n", abs(-2147483648));

output:
abs(-2147483648): -2147483648

A: This is code in abs.c in GNU glibc source code.
/* Return the absolute value of I.  */
int
DEFUN(abs, (i), int i)
{
  return(i < 0 ? -i : i);
}

So,abs(-2147483648) return -(-2147483648) . In x86,it is implement by this two instruction
movl    $-2147483648, %eax
negl    %eax

negl instruction is implemented by this way:
num=0-num;
sbb is implemented by this way:
Subtracts the source from the destination, and subtracts 1 extra if the Carry Flag is set.
So abs(-2147483648) (hex is 0x80000000 ) --> -(-2147483648) --> 0-(-2147483648)   becomes (0x80000000) finally.
details of negl instruction,please
visit http://zsmith.co/intel_n.html#neg
details of sbb instruction ,please visit http://web.itu.edu.tr/kesgin/mul06/intel/instr/sbb.html

A: The standard says about abs():

The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.

And the result indeed cannot be represented because the 2's complement representation of signed integers isn't symmetric. Think about it... If you have 32 bits in an int, that gives you 232 distinct values from INT_MIN to INT_MAX. That's an even number of values. So, if there's only one 0, the number of values greater than 0 cannot be the same as the number of values less than 0. And so there's no positive counterpart to INT_MIN with a value of -INT_MIN.
So, what's unacceptable is calling abs(INT_MIN) on your platform.

A: Negative numbers are usually represented whit binary complement.
To convert positive to negative it is used logic
x -> not(x)+1

For 8 bits arithmetic
01111111b is 127 and -127 becomes
10000000b + 1 = 10000001b
and to opposite direction -127
10000001b becomes
01111110b + 1 = 01111111b
What about -128?
-128 is 10000000b  and there is no positive counterpart of it, because there is no 128 in 8 bits signed arithmetic.
10000000 -> 01111111 + 1 = 10000000 and -128 again
Same applies to original question

A: Since 2147483648 is greater than INT_MAX on your implementation, then abs(-2147483648) is undefined.

A: Try this
printf("abs(-2147483648): %u\n", abs(-2147483648));


text:
Q: What is "Print driver host for applications" and why does it slow down my Excel macros? I tested this on multiple Windows 10 computers running the latest version of Excel (365 subscription) with both Bluebeam PDF and Microsoft XPS Document writer set as the default printer and get the same result. However, I can't consistently create it. When I use a macro-enabled Excel files that has some page setup and other formatting code the task manager shows Microsoft Excel (32 bit) and "Print driver host for applications" open and Excel tends to lock up or say not responding. I never get the "has stopped working" error and eventually (meaning several minutes) Excel will come back. Even if I have multiple Excel files open it will just show these two lines under Microsoft Excel (32 bit):
Task manager: Excel and Print driver host for application
If I right click and end the "Print driver host for applications" process manually Excel comes back pretty quickly & also shows all the Excel files that are open:
Task manager: after force stopping Print Driver Host Process
From what I understand Printer driver host for applications is meant to communicate 64 OS printers with the 32 bit office. Is that right? I use application.printcommunications = false in my excel VBA code so wonder if that is causing an issue when I set printcommunications back to true. I'm going to go through my VBA code and comment out all page setup code to see if that helps. As I said before I'm not able to get the Print driver to show in the task manager consistently, it seems to happen sporadically, and lock up my user's computer.
Any more information on what "Printer driver host for applications" does and what causes it to run? Is there a way to prevent it from loading? I just can't seem to find information on what it does and when it does it.

A:
Blockquote
  Printer driver host for applications is meant to communicate 64 OS printers with the 32 bit office. Is that right?

yes.
You are not the one with such problem. Check https://answers.microsoft.com/en-us/msoffice/forum/all/mircosoft-excel-365-pro-plus-hangs-all-the-time/ea49ac30-24ea-48d7-bc66-c95ea172f458?page=1
I advise to test MS Excel without any installed print queues and drivers, software printers can cause the issue.

A: I don't really have a solution for you, but I give you kudos for a good and researched question.
Have you tried using 64-bit Excel?
Also, have you got any solution altogether?
This really seems like the sort of bug that can be fixed by installing an update.
It's a question from 2 years ago, thus its quite plausible...

A: I've been having this issue for a while now as well. Recently (last few weeks) I have started seeing my GPU 3D utilization spike around 25% whenever this issue happens as well. I can stop the Print Driver Host process but that does not seem make an impact.
However, I was able to mitigate this just now be resetting my video driver using the Ctrl+Shift+Win+B keyboard shortcut (documented here and here). Screen went blank for a second, and when it came back I saw my GPU usage was back to normal, and I was once again able to navigate the Excel spreadsheet.
Next time this happens I will try that shortcut before stopping the Print Driver Host process to see if that makes any difference.
Last note, while I do get this sometimes after using some macros, the spreadsheet that has been causing this issue the most recently does not have any macros in it. The workbook does (only a Workbook_Open() sub) but not this particular spreadsheet. It'll freeze up just scrolling through or clicking a cell after having a different application in focus. It does have about 1000 rows of data with a lot of conditional formatting and cross references. I suspect that something is going on with the page breaks or print area which is triggering the printer driver and freezing up.
So can't help with a root cause, but maybe resetting the video driver resolves the issue whenever it happens.
Edit: I'm using 32-bit Excel, Office 365 Version 2008.


text:
Q: C# text box values from SQL server as typing I am creating a C# application to user for my brother in his store.
I have a SQL Server database that stores all sold items, The items are added from the application.
When the user enters text in the 'CustomerName' field in the application, i want it to do a DB call and check for any previous sales with the same customer name (or what has been typed of the name so far) and fill in the text box will the name.
The problem i am having is: if there is a customer called John and another called Joe and i need to select John, if i type in J in the box, it will just select Joe, and then return the text cursor to the beginning of the text box which is rather annoying and inconvenient.
The ideal solution would be is if i type J in the textbox, a dropdown box just below the text box would appear displaying all the Customers with J, allowing the user to select a customer and then filling in the textbox with the value. If i then type Jo, all the records for Jo would appear in the dropdown etc.
The coding part shouldn't be a problem (hopefully), i just wanted to know the best way to approach this.

A: First add/change these properties in your textbox
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

then you could use this method to get a List of customer names that start with your prefix.
public List<string> GetCustomerInfo(string custName)
{
    List<string> result = new List<string>();
    string sql = "Select Name from Customers Where Name like @partName";
    using(SqlConnection con = GetConnection())
    using(SqlCommand cmd = new SqlCommand(sql, con))
    {
         con.Open();
         cmd.Parameters.AddWithValue("@partName", custName + "%");
         using(SqlDataReader r = cmd.ExecuteReader())
         {
              while(r.Read())
              {
                  if(!r.IsDbNull(0))
                      result.Add(r.GetString(0));
              }
         }
    }
    return result;
}

As a safeguard I will check if the text typed in your combobox is at least three chars
if(textBox1.Text.Length >= 3)
    textBox1.AutoCompleteCustomSource = GetCustomerInfo(textBox1.Text);
else
    textBox1.AutoCompleteCustomSource = null;

A: The best way to do this would be to use jQuery to make an AJAX call to a server side function to do the lookup for you.
Consider this C#:
public string getNames(string prefix)
{
     //logic to perform your name retrieval from the SQL Server database based on the passed in string parameter: "prefix"
     return "John,Joe,Joseph";
}

jQuery:
$(document).ready(function(){
    //assign the getNames() function each time the key is
    //pressed on the txtNames input
    $('#txtName').keyup(function(){
        getNames();
    });
});

function getNames(){
    $.ajax({
        type: 'POST',
        url: 'page-to-post-to.ashx',
        data: {
            prefix: 'J'
        },
        success: function(data){
            //data will return : 'John,Joe,Joseph'
            //use your javascript logic to separate these names by the comma delimiter
            //and use them!
        }
    });
}

HTML:
<input id="txtName" />

This may not be 100% correct, but it should at least get you started down the right path.

A: First you need to set these properties of your textbox or write them to your form :
yourTextbox.AutoCompleteMode = AutoCompleteMode.Suggest;
yourTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;

and then you can create an instance of an ArrayList, a String array or a List (or a dictonary if you will need ID of the customer name) as you prefer..
or just you can use AutoCompleteStringCollection -it is also an implemented string array/collection in C#- class instance to retrieve data into..
then set txtName.AutoCompleteCustomSource = yourListOfTheMatchedNames;
a small example to give you an idea:
void yourTextBox_TextChanged (object sender, EventArgs e)
{
   SqlDataReader dReader;
   SqlConnection conn = new SqlConnection();
   conn.ConnectionString = strConnection;
   SqlCommand cmd = new SqlCommand();
   cmd.Connection = conn;
   cmd.CommandType = CommandType.Text; //better is to use a stored proc or if you use a .NET 3.5 or higher framework then LinqtoSQL
   cmd.CommandText = "Select [yourNameColumn] from yourNameTable where yourNameColumn LIKE" + yourTextBox.Text +"%"; //before lines from this you can set them initializing code part of your form..it will be your choice
   conn.Open();
   dReader = cmd.ExecuteReader();
   if (dReader.HasRows == true)
   {
       yourListOfTheMatchedNames.Clear(); // to clear previous search..its optional to depends of your choice
       while (dReader.Read())
       {
              yourListOfTheMatchedNames.Add(dReader["Name"].ToString());
       }
    }
    else
    {
        MessageBox.Show("There is No Customer Name Starts with You Typed");
    }
    dReader.Close();

    txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
    txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
    txtName.AutoCompleteCustomSource = yourListOfTheMatchedNames;

}


text:
Q: Very slow password checking on Ubuntu 18.04.3 LTS starting a few days ago So whenever my password is entered it is taking 30-60 seconds to check it. This is happening on the unlock screen, when using sudo in the terminal and on any other graphical interface that uses a password. This only started happening 2-3 days ago. I've been using this installation on my laptop for several months now without any problems.
Does anyone have any idea how to fix that, what to check, etc?

A: The problem has been solved. It seems that an installation of Kerberos had gone a bit wrong and the system was trying and failing to authenticate with Kerberos every time. I've completely removed Kerberos from the system now and it is working fine.


text:
Q: In PHP we have santize to ensure String is safe. What is the similar thing for Java In PHP we have santize to ensure String is safe. What is the similar thing for Java.
I know PreparedStatement . But it will not help me in my project.
Is there is something that checks only letters are there in String .
query = "SELECT  Bill_No,No,Item,Count,Rate,GST,Net,Date,Time,Manager FROM bill WHERE Manager = '"+Manager_str+"';  ";
//This is definitely insecure

A: The Character class has a method isAlphabetic, which you may use by looping the characters in your input string.
for(char c : query.toCharArray()) {
    if(!Character.isAlphabetic(c)) {
        return false;
    }
}
return true;

If you are using Java 8 or above, you could use streams:
return query.chars().allMatch(Character::isAlphabetic);

A: try this.
public static void main(String args[]) {
    String str="sadahkk";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));
    str="";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));
    str="sada5hkk";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));
    str="<alert>";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));
    str="-- sadahkk";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));
    str="@fgfg";
    System.out.println("str :"+str +" , isAlphabetsOnly:"+isAlphabetsOnly(str));

}
public static boolean isAlphabetsOnly(String str ) {
    return ((!str.equals(""))
            && (str != null)
            && (str.matches("^[a-zA-Z]*$")));
}

=======================================================
output as follows
str :sadahkk , isAlphabetsOnly:true
str : , isAlphabetsOnly:false
str :sada5hkk , isAlphabetsOnly:false
str : , isAlphabetsOnly:false
str :-- sadahkk , isAlphabetsOnly:false
str :@fgfg , isAlphabetsOnly:false


text:
Q: Alterar atributo no Jquery Queria saber se tem como modificar os atributos de um charts do Google com um Jquery.
Exemplo:
google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'teste',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  }

  $(window).resize(function() {
    if( $(window).width() < 500){

      Alterar aqui!!!!
  }

  });

Queria mudar título lá em var options por exemplo.

A: Para deixar o gráfico responsivo você deve chamar a função resizeCharts() dentro da função drawChart().
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'teste',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);

    function resizeCharts() {
      // redraw charts, dashboards, etc here
      chart.draw(data, options);
    }

    $(window).resize(resizeCharts);
}


text:
Q: C++ Optimization breaking OLE Automation program (non-MFC) I'm writing a program to parse a Word Document and export data out to an Excel Workbook using OLE Automation (the non-MFC way I guess). Works fine in Debug, not so in Release (specifically if optimization is enabled). The error is that the IDispatch::Invoke call failed, specifically:
0x80020004 DISP_E_PARAMNOTFOUND Parameter not found
I checked StackOverflow for some suggestions and the main one seems to be uninitialized variables. That might be what's going on, but I still don't understand this specific case. I've narrowed it down to a single function in my program Automation::Dispatch::Invoke which is responsible for finally calling IDispatch::Invoke. The arguments being passed into Automation::Dispatch::Invoke are correct so the problem is somewhere in its code.
Looking at the base code (from MSDN) that I adapted this from, I was able to get it working and narrow down the exact problem line. Below shows code that does not work, but the comments indicate the line that I moved to get it working (look for the 2 lines with a <--- Problem line comment). In Debug mode, the location of this line does not matter and it works in either spot.

My question is what does this fix, and why is it an issue to start with? Thank you and let me know if I can make the question more clear.

HRESULT Automation::Dispatch::Invoke(int cmd, std::string name, std::vector<VARIANT> values)
{
  USES_CONVERSION;
  HRESULT result;

  /* Get DISPID for name passed */
  DISPID dispID;
  LPOLESTR nameOle=A2OLE(name.c_str());
  result=pObjectInt->GetIDsOfNames(IID_NULL, &nameOle, 1, LOCALE_USER_DEFAULT, &dispID);
  if (FAILED(result)) {
    return result;
  }
  /* Reverse elements in values vector so they are invoked in the correct order */
  std::reverse(values.begin(), values.end());

  /* Allocate memory for object values */
  VARIANT *pValues=new VARIANT[values.size() + 1];
  for (unsigned int i=0; i < values.size(); ++i) {
    pValues[i]=values[i];
  }
  /* Build DISPPARAMS */
  DISPPARAMS dispParams= {NULL, NULL, 0, 0};
  /* DISPID dispidNamed=DISPID_PROPERTYPUT;   <--- PROBLEM LINE moved here makes it work */
  dispParams.cArgs=values.size();
  dispParams.rgvarg=pValues;

  /* Handle special-case for property-puts */
  if (cmd==DISPATCH_PROPERTYPUT) {
    DISPID dispidNamed=DISPID_PROPERTYPUT;   /* <--- PROBLEM LINE here */
    dispParams.cNamedArgs=1;
    dispParams.rgdispidNamedArgs=&dispidNamed;
  }
  /* Make the call */
  if (cmd==DISPATCH_METHOD || cmd==DISPATCH_PROPERTYPUT) {
    result=pObjectInt->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, cmd, &dispParams, NULL, NULL, NULL);
  }
  else {
    VariantInit(&objectData);
    result=pObjectInt->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, cmd, &dispParams, &objectData, NULL, NULL);
  }
  delete[] pValues;
  return result;
}

A: In this code:
if (cmd==DISPATCH_PROPERTYPUT) {
    DISPID dispidNamed=DISPID_PROPERTYPUT;   /* <--- PROBLEM LINE here */
    dispParams.cNamedArgs=1;
    dispParams.rgdispidNamedArgs=&dispidNamed;
}

dispidNamed is a local variable to the code block it is in (i.e. the area delimited by { }).
After the } is reached it ceases to exist. Then rgdispidNamedArgs is a dangling pointer because it no longer points to a variable that exists.
You got unlucky in Debug mode that it didn't trigger an error sooner.


text:
Q: Place icon after text css I need to place an i element that renders an icon, after a paragraph, but when I use the pseudo element "after" I only get pure html and not the icon. How can I get the icon rendering instead of the html text? Thank you.
.myDiv p:after {

    content: '';
}

RESULT
Lorem ipsum dolor sit amet, consectetur adipiscing

A: You have to put the CSS value of the icon. In this example I use Font Awesome.
div p:after {
    content: '\f002';
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
    margin-left:5px;
    color:red;
}

Here is the fiddle : http://jsfiddle.net/uzu7u56h/1/

A: You can't render HTML in :after/:before pseudo selectors. What you can however do is style :after directly, for example:
.myDiv p:after {
    content: '';
    /* Other styling stuff here - optionally can put text into content property above too */
}


text:
Q: undefined reference error in using dlopen in c++ I am trying to cross-compile apache-qpid for an arm system from a debian.
There is undefined reference to __dlopen error, but it seems that it is related to the previous warning:
using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking ...
Here is the detail:
[ 86%] Linking CXX shared library libqpidcommon.so
CMakeFiles/qpidcommon.dir/qpid/sys/posix/Shlib.cpp.o: In function
`qpid::sys::Shlib::load(char const*)':
/home/mert/qpid-cpp-0.34/src/qpid/sys/posix/Shlib.cpp:32: warning: Using
'dlopen' in statically linked applications requires at runtime the shared
libraries from the glibc version used for linking
/home/mert/IDE/cVEND/00.00.14/bin/../arm-feig-linux-
gnueabi/sysroot/usr/lib/libdl.a(dlopen.o): In function `dlopen':
dlopen.c:(.text+0xc): undefined reference to `__dlopen'

I do not know what is happening exactly and how to solve it.
Here there is a similiar thing, I tried to add -static -ldl -lc C_FLAGS but made no difference.
Any help appreciated.
EDIT :
EDIT :
I am not sure exactly what is solved the problem, but I think that -ldl was looking exactly for libdl.so, but in arm directory, it was libdl-2.19.so, thus, probably it was then looking for and finding in another directory. I have linked libdl.so to libdl-2.19.so and now it is compiling.

A: The linker needs the options, not the compiler. See LDFLAGS.
https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html

Extra flags to give to compilers when they are supposed to invoke the
  linker, 'ld', such as -L. Libraries (-lfoo) should be added to the
  LDLIBS variable instead.

A: If this error occurs during the make step try doing
make LIBS=-ldl

And make sure the library path is present in LDFLAGS
export LDFLAGS=-L<path/to/ldl>


text:
Q: PN532 can't read NFC card type B I'm trying to use the PN532 by Elechouse V3 connected through i2c to the raspberry-pi to read debit and credit card and I manage to read the type-A card successfully.
I can't read the type-b cards though.
These are the step I'm following according to the manual
https://www.nxp.com/docs/en/user-guide/141520.pdf:

*

*Setting SAM configuration to normal mode sending bytes [0xD4, 0x14, 0x01, 0x01, 0x00] (not sure this is required though)

*Sending InListPassiveTarget with bytes [0xD4, 0x4A, 0x01, 0x03, 0x01]

I was expecting to be able to read the type-B cards at this point but nothing happens when I try to put a card close to the reader.
I've also tried changing the RF configuration settings sending the bytes
[0xD4, 0x32, 0x0C, 0xFF, 0x17, 0x85] before the InListPassiveTarget and also tried using the InAutoPoll method with all the possible values but still no luck.
Any idea or suggestion would be really appreciated


text:
Q: avoid multiple if-statements when true conditions are rare I want to create a script that compares variables from two different sources.
I need to compare some values a1, a2, ..., an , with some other values b1, b2, ..., bn. I want to know if a1 = b1, a2 = b2, ..., an = bn. If some of them are not equal, I want to know which of them are not equal. These variables are integers and strings. All the pairs have the same possibility to be equal.
I also know that it is extremely rare for these variables to be unequal. In fact, almost 1 pair of variables might be unequal, in 1000 pairs of variables. I will run the script hundrends of times for almost 20 variables each time, so most of the time all pairs will be equal. I was wondering if I can take advantage of that fact somehow.
As a first approach I was thinking something like multiple if-statements. For example:
let equal = true;
let issues = [];

if (a1 !== b1){
   equal = false;
   issues.push("a1!=b1");
}

...

if (a20 !== b20){
   equal = false;
   issues.push("a20!=b20");
}

As long as most of the times there will be no unequal pairs, I was thinking to cancatinate all a1,..,an variables to a single variable variableA and all b1,...,bn to a variable variableB. Compare the 2 variables and only if they are unequal, then do the above process. If my data are cleaned (without null, undefined, "", etc.), does it make sense to do something like that? I am not sure if it reduces time and I think that it might be a bad practice.
let variableA = a1 + a2 + ... + a20;
let variableB = b1 + b2 + ... + b20;
let equal = true;
let issues = [];

if (variableA !== variableB){
   equal = false;

   if (a1 !== b1){
      issues.push("a1!=b1");
   }

    ...

    if (a20 !== b20){
      issues.push("a20!=b20");
    }
}

or instead:
if (!((a1===b1) && (a2===b2) && ... && (a20===b20))){ ...

I also considered to store my variables in arrays or objects and compare them. Storing them in objects might be better, I think. My script will be written in javascript, though I am mostly intrested in the approach and not the language.
Regardless of the way that they can be compared, is there any way to optimize it knowing that almost all the times my conditions will be false?

A: // place variables in 'a' group into ordered array
a_array = [a1, a2, a3, ..., an]

// place variables in 'b' group into ordered array
b_array = [b1, b2, b3, ..., bn]

// compare each item in array storing indexes of items which are not equal
not_equal_indexes = []
for (i = 0; i < a_array.length; i++) {
    not_equal_indexes.push(i) ? a_array[i] != b_array[i] : ""
}
print(not_equal_indexes)

you must use a runtime that accepts multi-typed elements in arrays (i.e. a weakly typed language like PHP, Python or Javascript) for this to work.
Otherwise, create an array for each group and each data type available to the elements of each group. The for loop configuration should look the same, with slight modification in remembering the original index position of the element or its original variable name, irrespective of where it is placed in the strongly typed array group.

A:
is there any way to optimize it knowing that almost all the times my conditions will be false?

If that is the case, the runtime will notice and optimize accordingly. There is no reason for you to do so.
In addition, trying to optimize comparisions by concatenating strings is a very bad idea, because concatenation is more expensive than the comparisions you are trying to optimize. In addition, the cost of comparing strings is roughly proportional with their length, so comparing one long string is not faster than comparing many short ones. And repeated comparisons (first the comparing the concatentation, and then the individual strings) is of course slower than looking at each string just once.
All that said, it doesn't even matter unless that function is executed really often: a modern JavaScript runtime can compare about a billion characters per second. Usually, you'll therefore want to optimizer for programmer time rather than runtime performance, by writing clear and easy to understand code.


text:
Q: Reshape data to make stacked barplot with ggplot in R I would like to make a stacked barplot with in ggplot2 however I don't have actual labels in the dataset that correspond to categories. For example:
require(ggplot2)
x <- c("oct", "nov")
oct <- c(2,4)
nov <- c(5,1)

qplot(x, oct, geom = "bar", stat = "identity")
qplot(x, nov, geom = "bar", stat = "identity")

Here, I would like to make one barplot in which the first bar stacks (2,4) with different colors and then (5,1) for the second bar with different colors such that 2 and 5 have the same color and 4 and 1 have the same color. Thanks.

A: Try this
library(reshape2)
df <- melt(data.frame(x, oct, nov), id.vars="x")
ggplot(df, aes(x, value, fill=variable)) +
  geom_bar(stat="identity")


text:
Q: Can I open up a simple file browser in a django admin action? I'm a little new to customizing the django admin and maybe what I want is a little advanced but I was wondering if I can launch a file browser in my custom action.  Just something simple that will return a list of files.

A: Not quite what I originally had in my head but there's a blog post for a pretty simple file loader solution which shows even the changes needed for the template.
https://blog.rousek.name/2017/08/11/uploading-multiple-files-in-django-admin/


text:
Q: Google Analytics segment to exclude source not working, though reverse does Trying to create a simple segment to excludes a referral source retrospectively (a spam site called trafficbot.link) from all analytics views.
I can:
…set Traffic Sources > Source > contains / starts with / exactly matches, and it will correctly show ONLY the spam/fake accesses (the percentage of users and sessions on the right is refreshed in real time).
I can't:
…do it the other way around, i.e. use does not contain / does not exactly match / is not one of.
The total stays stuck on 100% of sessions.
Am I missing something obvious?
I note this answer which has no input other than from the original questioner, suggesting Google say it's "not possible" to exclude existing requests - surely it is? Isn't that the whole point of segments? How are you supposed to filter out spam otherwise?
(I'm aware analytics filters isn't retrospective.)

A: You are talking about segments but the link you entered refers to filters.
Anyway, retroactively you can apply a segment to see the data without the spam one, you can use an advanced segment, choose conditions and exclude sessions that contain for example browser size equal to (not set).
https://www.fortop.it/journal/tieni-lontano-lo-spam-dai-dati-google-analytics/


text:
Q: How to add new route to autogenerate resources? please help me, I want add new route/func to generate resource (etc. users).
app.Resource("/users", UsersResource{})

I found func addRoute, but doesn't work.
func (a *App) addRoute(method string, url string, h Handler) *RouteInfo { ...

My idea is something like this.
"/users/handleSomething/idOfUser"

Right now i have only this func:
List(Context)
Show(Context)
New(Context)
Create(Context)
Edit(Context)
Update(Context)
Destroy(Context)

Thx for your time and help :)
PS: Sorry for my English :(

A: If you want additional routes you can use the methods GET,POST,PUT, ... that are defined on the *App type. (https://gobuffalo.io/en/docs/routing#supported-http-methods)
To handle dynamic path segments in the route you can use named parameters. (https://gobuffalo.io/en/docs/routing#named-parameters)
Example:
app.PATCH("/users/handleSomething/{id}", handleSomethingHandler)

To retrieve the value of the named parameter you can use c.Param("id") where c is the buffalo context passed in to your handler.


text:
Q: *
* should only show on scroll Hi all I was hoping to get some help with adding a link in a nav menu when you scroll further than the header my site has a header above the navbar and I need the home button to only display on scroll, purely for links, and I'd like to apply an ease in style or jquery ease effect to it. So it comes in from the left to where it is situated now, the whole navbar content needs to be centered before and after this happens so all the other buttons would need the smooth transitioning too.

        DANCE FOR OVARIAN CANCER

HOME

REGISTER

FAQ's

ACTS

ABOUT

CONTACT

I can only ask a question every 90 minutes and am very tired so going to bed and hopefully can wake up to some answers, so here is another question.. I'm making a child site for this site and as you can see their navbar sticks to the top but the header above the navbar doesn't. I've looked for answers on this but they use javascript very relative to the OP's code so I can't get it to work for my solution. Does anyone know and easy alternative so it sticks when it scrolls past the dance for ovarian cancer header and then unsticks when you go back to the top?
Cheers, Nik
I added a margintop class with
.margintop {
margin-top: 100px;

}
but it doesn't work cause ..well for reasons I always realise after the fact but that an experienced programmer would probably forsee. Any how that's how I'm leaving the site so any answers would be great :)

A: Try to set display:none to #navbar div then use this jquery script to show it on scroll.
$(document).ready(function(){
    $(window).scroll(function(){

          $('#navbar').show();

    });
});


text:
Q: Attempting a mouse movement simulator with Tkinter I'm working on a project; It is supposed to upwards mouse movement on your mouse, example; shooting game recoil.
However, I'm faced with a huge issue that I can't wrap my head around; On Tkinter I can't have While Loops because of the way Tkinter was built and its continuous loop.
I need to use the interface because I have a textlabel that is supposed to output if the mouse movement is happening or not.
The goal:
The mouse movement only happens if the user creates a keyboard input, such as pressing 'z' ; mouse-simulator = on // recoil begins to act.
Having some sort of loop to check for keyboard input while with Tkinter imported, and retrieving that data back to txtlabel, then starting the task of mouse movement until user decides to stop.

*

*Sorry If the way I worded is confusing. First time posting here.

Example of the code I had under my Tkinter program,
Program freezes with While Loop
while True:
  # Check for input
  if keyboard.is_pressed('z'):
     movement_bool = not movement_bool
if movement_bool == True and mouse.is_pressed(button='left'):
      #use win32api to move mouse down

A: With tkinter you don't need to do a loop and check for keyboard presses. You can ask tkinter to call any function you want when it detects a key press and/or key release. The terminology is to bind an event to a function. When tkinter detects the requested event, it calls the function and passes an object representing the event.
Here's an example that prints a message when you press the "z" key:
import tkinter as tk

def handle_z(event):
    print("z was pressed")

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# make sure that keyboard events are routed to the canvas
canvas.focus_set()

# call our function when the "z" key is pressed
canvas.bind("<z>", handle_z)

root.mainloop()


text:
Q: Stretching UIView in Swift So I have two view and a button one of the view is hidden "View1" and the other is not "View2" , and once I click on the button "View1" will appear , but I want "View2" to go down , I will add image show what I want to do

A: Brute way, if your views has fix sizes:
1, create 3 variables for the position of the views
var view1Center: CGPoint = CGPoint(x: 100, y: 100)
var view2CenterBefore: CGPoint = CGPoint(x: 100, y: 100)
var view2CenterAfter: CGPoint = CGPoint(x: 100, y: 400)

2, In ViewDidLoad or ViewDidAppear set view's alpha to 0 and the positions
view1.alpha = 0
view2.alpha = 0
view1.center = view1Center
view2.center = view2CenterBefore

3, When you press the button, you should animate the moves and show view1.
@IBAction func showView1(_ sender: Any) {
  UIView.animate(withDuration: 0.5, animations: {
           view2.center = view2CenterAfter
  })
 DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
     UIView.animate(withDuration: 0.5, animatios: {
      view1.alpha = 1
     }
  }
}

A: We can use UIStackView class for this with ease. We can add both the views in a UIStackView instance with vertical axis. view1 height should have Highest constraint priority (999) instead of required (1000). This way when view1 is hidden, it's height constraint won't have conflict.
You can take reference of following code snippet:
let stack = UIStackView()
// aligns subviews in top to bottom manner
stack.axis = .vertical

stack.addArrangedSubview(view1)
stack.addArrangedSubview(view2)

When view1 is kept hidden, view2 will automatically move up. StackView should not be given height constraint so that it will have inferred height of summation of its subviews.


text:
Q: Move EditText up in NestedScrollView when virtual keyboard appears I know that this question was asked some times before, but unfortunately all solutions didn't work for me.
Neither android:windowSoftInputMode="stateAlwaysHidden|adjustResize|adjustPan" nor activityRootView.getViewTreeObserver().addOnGlobalLayoutListener()
When I call virtual keyboard, it appears over EditText and I can't see what I type.
My layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_scrolling">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.CardView
            style="@style/CardViewSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/card_corner_radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/standard_margin"
                android:orientation="vertical">

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_input_awb_no" />

                <RadioGroup
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:orientation="horizontal"
                    android:paddingLeft="30dp"
                    android:paddingTop="@dimen/standard_margin">

                    <RadioButton
                        android:id="@+id/ownAwb"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/own_awb_no" />

                    <RadioButton
                        android:id="@+id/nextAvailable"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/next_available" />

                    <RadioButton
                        android:id="@+id/useOwn"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/use_own_stock" />
                </RadioGroup>

                <EditText
                    android:id="@+id/awbNo"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/standard_margin"
                    android:cursorVisible="true"
                    android:hint="@string/prompt_awn_no" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/small_margin"
                    android:background="@drawable/ripple"
                    android:paddingBottom="30dp"
                    android:paddingTop="30dp"
                    android:text="@string/action_check"
                    android:textColor="@android:color/white" />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            style="@style/CardViewSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/card_corner_radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/standard_margin"
                android:orientation="vertical">

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_date_shipment_ready" />

                <EditText
                    android:id="@+id/dateChooser"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_choose_date" />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            style="@style/CardViewSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/card_corner_radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/standard_margin"
                android:orientation="vertical">

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_airport_departure" />

                <EditText
                    android:id="@+id/departureAirportChooser"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_select_airport"
                    android:inputType="textNoSuggestions" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_airport_departure" />

                <EditText
                    android:id="@+id/destinationAirportChooser"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_destination_cargo"
                    android:inputType="textNoSuggestions" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_hawb" />

                <EditText
                    android:id="@+id/hawb"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:cursorVisible="true"
                    android:hint="@string/prompt_select_hawb"
                    android:inputType="textNoSuggestions" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_hawb_origin" />

                <EditText
                    android:id="@+id/hawbOrigin"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_select_airport"
                    android:inputType="textNoSuggestions" />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            style="@style/CardViewSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/card_corner_radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/standard_margin"
                android:orientation="vertical">

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_total_gross_weight" />

                <EditText
                    android:id="@+id/totalGrossWeight"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="true"
                    android:hint="@string/prompt_total_gross_weight" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_quotation_ref_num" />

                <EditText
                    android:id="@+id/quotationNumber"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="true" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_cargo_description" />

                <EditText
                    android:id="@+id/cargoDescription"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="true"
                    android:hint="@string/prompt_describe_your_cargo" />

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_destination_place" />

                <EditText
                    android:id="@+id/destinationPlace"
                    style="@style/EditTextChooser"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:cursorVisible="true"
                    android:hint="@string/prompt_destination_place" />

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            style="@style/CardViewSection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/card_corner_radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/standard_margin"
                android:orientation="vertical">

                <TextView
                    style="@style/HeaderTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/header_shipper" />

                <EditText
                    android:id="@+id/shipper"
                    style="@style/EditTextMultiline"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/header_shipper" />

            </LinearLayout>
        </android.support.v7.widget.CardView>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ua.pp.ssidit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.LoginActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".view.ScrollingActivity"
            android:label="@string/title_activity_scrolling"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="stateAlwaysHidden|adjustResize|adjustPan"></activity>
    </application>

</manifest>


text:
Q: Flutter Android emulator Nexus 6p API 28 and 3rd party API These 2 methods take a global file that is set later on and send it to OCR Space API to convert and send back a OCR PDF of the file.
The code is running well, and the output value is the OCR correctly, but it is not receiving the the URL of isCreateSearchablePdf (as stated by the OCR Space API)
Is this an issue of emulator? Or is printing value wrong?
OCRSPACEAPI website: https://ocr.space/ocrapi
 void fOCR(File file) async {
        try {
          var uri = Uri.parse('https://api.ocr.space/parse/image?');

          var request = new http.MultipartRequest("POST", uri);

          request.fields["apikey"] = "myApiKey";
          request.fields["language"] = "ara";
          request.fields["isOverlayRequired"] = "true";
          request.fields["isCreateSearchablePdf"] = "true";

          http.MultipartFile multipartFile = await http.MultipartFile.fromPath(
              'pdf',
              file.path
          );

          request.files.add(multipartFile);

          await request.send().then((response) async {
            print("Result: ${response.statusCode}");

              print(value);
            });
          }).catchError((e) {
            print(e);
          });

      } catch(e){
        print(e);
      }
    }

     Future selectFile() async {
        final result = await FilePicker.platform.pickFiles(allowMultiple: false);
        if (result == null) return;
        final path = result.files.single.path!;
        print(result);
        print(File(path));
        setState(() => file = File(path));
        enabled = true;

      }


text:
Q: Minimize angle in pytorch I'm trying to figure out how to minimize a scalar in pytorch that represents the angle of an axis/angle rotation. My target is a sample set of 3D vectors, my input is the target rotated by a particular axis/angle rotation (plus some gaussian noise). The axis is known and fixed. I want to find the angle using pytorch.
What I have so far is this nn.Module:
class AngleModel(torch.nn.Module):
    def __init__(self):
        super(AngleModel, self).__init__()
        self.angle = nn.Parameter(Variable(torch.Tensor([0.0]), requires_grad=True))
        self.qw = torch.cos(self.angle / 2.)
        self.qx = 0.0
        self.qy = 0.0
        self.qz = torch.sin(self.angle / 2.)

    def forward(self, input):
        matrix_np = transform_from_pq([0, 0, 0, self.qw, self.qx, self.qy, self.qz])
        matrix = torch.from_numpy(matrix_np)
        input_ext = torch.cat((input, torch.ones(input.size(0)).reshape(-1, 1)), 1)
        output = torch.matmul(input_ext.float(), matrix.float())
        return output[:, :3]

However using this in an optimizer fails because model.parameters() returns an empty list (i.e. "empty" generator).
I'm completely new to pytorch. What am I doing wrong?
Relevant code
Initialization:
def _init_model(self):
    self.model = AngleModel()
    self.crit = torch.nn.MSELoss()
    l_rate = 0.01
    print(list(self.model.parameters()))
    self.optim = torch.optim.SGD(self.model.parameters(), lr = l_rate)
    self.epochs = 2000

Learning function:
for epoch in range(self.epochs):
    inputs = torch.from_numpy(normalize(input))
    labels = torch.from_numpy(normalize(target))
    _x = Variable(inputs, requires_grad = True) # without it complains about no grad_fn
    _y = Variable(labels)
    self.optim.zero_grad()

    outputs = self.model.forward(_x)
    loss = self.crit(outputs, _y)
    loss.backward()
    self.optim.step()
    print("Epoch %6d loss %05.3f; %s" % (epoch, loss.data[0], self.model.angle))

Update 1:

*

*Code of the Module updated

*Surrounding code added

*This at least does not throw any errors anymore but also does not optimize angle

A: Here are the necessary changes to the AngleModel class to make it work:
class AngleModel(nn.Module):
    def __init__(self):
        super(AngleModel, self).__init__()
        self.angle = nn.Parameter(torch.tensor(0.0))

    def forward(self, input):
        qw = torch.cos(self.angle / 2.)
        qx = 0.0
        qy = 0.0
        qz = torch.sin(self.angle / 2.)

        matrix = torch.zeros(3, 3)

        matrix[0, 0] = 1. - 2. * qy ** 2 - 2. * qz ** 2
        matrix[1, 1] = 1. - 2. * qx ** 2 - 2. * qz ** 2
        matrix[2, 2] = 1. - 2. * qx ** 2 - 2. * qy ** 2

        matrix[0, 1] = 2. * qx * qy - 2. * qz * qw
        matrix[1, 0] = 2. * qx * qy + 2. * qz * qw

        matrix[0, 2] = 2. * qx * qz + 2 * qy * qw
        matrix[2, 0] = 2. * qx * qz - 2 * qy * qw

        matrix[1, 2] = 2. * qy * qz - 2. * qx * qw
        matrix[2, 1] = 2. * qy * qz + 2. * qx * qw

        output = torch.matmul(input, matrix)
        return output

Among others the main reason that it hadn't been working before was that the graph wasn't consistent due to the intermediate use of numpy. Furthermore the quaternion components qw..qz had been calculated only once in the __init__ method. Their calculation had to move to the forward step too.


text:
Q: client.clientAuthorizations.add is undefined in directline API I am trying to run THIS standard directline sample. I generated the keys on the Directline website and input it. I keep getting this error
Error initializing DirectLine client TypeError: Cannot read property 'add' of undefined
    at D:\bots\zupcoin test\twitter\directline_client.js:21:36
    at tryCatcher (D:\bots\zupcoin test\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:693:18)
    at Async._drainQueue (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)
Unhandled rejection TypeError: Cannot read property 'Conversations' of undefined
    at D:\bots\zupcoin test\twitter\directline_client.js:30:11
    at tryCatcher (D:\bots\zupcoin test\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (D:\bots\zupcoin test\node_modules\bluebird\js\release\promise.js:693:18)
    at Async._drainQueue (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (D:\bots\zupcoin test\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)\

This is my complete code with a dummy key for illustration purposes. I haven't modified anything from the example. client.clientAuthorizations is null, any suggestions, thanks in advance
var Swagger = require('swagger-client');
var open = require('open');
var rp = require('request-promise');

// config items
var pollInterval = 1000;
var directLineSecret = 'hjaifnkghsfsgjsgfiagfhsgojisaasoigsohjgjpfsgdsghsfasf';
var directLineClientName = 'Twitter';
var directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';

var directLineClient = rp(directLineSpecUrl)
    .then(function (spec) {
        // client
        return new Swagger({
            spec: JSON.parse(spec.trim()),
            usePromise: true
        });
    })
    .then(function (client) {
        // add authorization header to client
        client.clientAuthorizations.add('AuthorizationBotConnector', new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + directLineSecret, 'header'));
        return client;
    })
    .catch(function (err) {
        console.error('Error initializing DirectLine client', err);
    });

// once the client is ready, create a new conversation
directLineClient.then(function (client) {
    client.Conversations.Conversations_StartConversation()                          // create conversation
        .then(function (response) {
            return response.obj.conversationId;
        })                            // obtain id
        .then(function (conversationId) {
            sendMessagesFromConsole(client, conversationId);                        // start watching console input for sending new messages to bot
            pollMessages(client, conversationId);                                   // start polling messages from bot
        });
});

// Read from console (stdin) and send input to conversation using DirectLine client
function sendMessagesFromConsole(client, conversationId) {
    var stdin = process.openStdin();
    process.stdout.write('Command> ');
    stdin.addListener('data', function (e) {
        var input = e.toString().trim();
        if (input) {
            // exit
            if (input.toLowerCase() === 'exit') {
                return process.exit();
            }

            // send message
            client.Conversations.Conversations_PostActivity(
                {
                    conversationId: conversationId,
                    activity: {
                        textFormat: 'plain',
                        text: input,
                        type: 'message',
                        from: {
                            id: directLineClientName,
                            name: directLineClientName
                        }
                    }
                }).catch(function (err) {
                    console.error('Error sending message:', err);
                });

            process.stdout.write('Command> ');
        }
    });
}

// Poll Messages from conversation using DirectLine client
function pollMessages(client, conversationId) {
    console.log('Starting polling message for conversationId: ' + conversationId);
    var watermark = null;
    setInterval(function () {
        client.Conversations.Conversations_GetActivities({ conversationId: conversationId, watermark: watermark })
            .then(function (response) {
                watermark = response.obj.watermark;                                 // use watermark so subsequent requests skip old messages
                return response.obj.activities;
            })
            .then(printMessages);
    }, pollInterval);
}

// Helpers methods
function printMessages(activities) {
    if (activities && activities.length) {
        // ignore own messages
        activities = activities.filter(function (m) { return m.from.id !== directLineClientName });

        if (activities.length) {
            process.stdout.clearLine();
            process.stdout.cursorTo(0);

            // print other messages
            activities.forEach(printMessage);

            process.stdout.write('Command> ');
        }
    }
}

function printMessage(activity) {
    if (activity.text) {
        console.log(activity.text);
    }

    if (activity.attachments) {
        activity.attachments.forEach(function (attachment) {
            switch (attachment.contentType) {
                case "application/vnd.microsoft.card.hero":
                    renderHeroCard(attachment);
                    break;

                case "image/png":
                    console.log('Opening the requested image ' + attachment.contentUrl);
                    open(attachment.contentUrl);
                    break;
            }
        });
    }
}

function renderHeroCard(attachment) {
    var width = 70;
    var contentLine = function (content) {
        return ' '.repeat((width - content.length) / 2) +
            content +
            ' '.repeat((width - content.length) / 2);
    }

    console.log('/' + '*'.repeat(width + 1));
    console.log('*' + contentLine(attachment.content.title) + '*');
    console.log('*' + ' '.repeat(width) + '*');
    console.log('*' + contentLine(attachment.content.text) + '*');
    console.log('*'.repeat(width + 1) + '/');
}

A: The client.clientAuthorizations API has been replaced with a constructor based API in Swagger 3.x (see here).
You can either downgrade Swagger-JS dependency to 2.x or update your code to Swagger 3.x API


text:
Q: ASP.Net MVC3 Razor website Session Variables disappearing in CHROME I am working on an website with ASP.net MVC3 razor using the Telerik MVC open source controls.
I keep track of the logged in user with the help of session variables.
eg - After the user logs in
        Session.Add("LoggedInUserId", loggedInUser.BillerUserId);
        Session.Add("LoggedInUserEmail", loggedInUser.BillerUserEmail);
        Session.Add("LoggedInUserType", loggedInUser.BillerUserTypeId);
        Session.Add("LoggedInUser", loggedInUser);

Inside the ActionResult for every controller, I look at the session variables and decide if the user has access/permissions to the view. This approach works fine for IE & Firefox. But I face a strange situation in Chrome. When using Chrome after the Session variables are set, I can successfully load the first View ( session variables have their values) . But after this if the user clicks on the menu which will redirect him to a different view (inside any controller) the Session variables are null.
I access the session as -
HttpContext.Current.Session["LoggedInUser"]
I am using the latest version of Chrome (17.0) with Cookies & Javascript enabled.
Please help...
Thanks,
sdd

A: Try to add favicon.ico to the root folder of your site.
See this article.


text:
Q: How can I get increment value after a specific interval using for loop in PHP? I want to show my output 0 to 50 after two digits interval but it's produce an infinity loop and therefore, crash my  browser. How can I solve my issue?
<?php

    for ($x = 0; $x < 50; $x+2) {
        echo "The number is: $x
";
    }

?>

A: You need to set $x:
<?php
   for ($x = 0; $x < 50; $x = $x+2) {
      echo "The number is: $x
";
   }
?>

you could also use $x+=2 as a shorthand instead of $x = $x+2

A: Change the incremet to $x+=2 like:`
for($x=0; $x<50; $x+=2){
//do any thing...  Echo
 }

A: Let's try with do while loop.
$x = 0;
do {
 echo "The number is: $x
";
 $x = $x + 2;
} while($x < 50);


text:
Q: How to build combined _id property of the $group in mongo aggregation using spring data? I found this mongo command in mongodb docs:
db.sales.aggregate(
   [
      {
        $group : {
           _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
           totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
           averageQuantity: { $avg: "$quantity" },
           count: { $sum: 1 }
        }
      }
   ]
)

when using spring data's Aggregation, it is easy to bind one Document property to the _id in $group with calling to Aggregation.group(Feild ...)
but for the above situation, the _id property is combined and i failed to build it in Java. Do you guys have any solution??? I mean how to express the js above in Java??
many thanks...
@update.....
the _id of the $group uses mongo functions like $month $dayOfMonth... How can I do this in Spring data??

A: You could try projecting the fields first by using the SpEL andExpression in the projection operation and then group by the new fields in the group operation:
Aggregation agg = newAggregation(
    project()
        .andExpression("year(date)").as("year")
        .andExpression("month(date)").as("month")
        .andExpression("dayOfMonth(date)").as("day")
        .andExpression("price * quantity").as("grossPrice"),
    group(fields().and("year").and("month").and("day"))
        .sum("grossPrice").as("totalPrice")
        .avg("quantity").as("averageQuantity")
        .count().as("count")
);


text:
Q: Dropdown menus not appearing in correct place for Firefox I have created some drop down menus (which appear if you hover over their parent's link), the drop down menus simply contain links; nothing special.
They work absolutely fine when using Google Chrome (under their parent), but they always appear towards the far left hand side of the screen when using Mozilla Firefox.
Does anyone have any idea as to why this may be happening?
Google Chrome:

Mozilla Firefox:

Drop down HTML inspect example:

Relevant CSS:
/* Sub menu styles */
#headermenu td.hasSubMenu ul {
    display: block;
    float: left;
    position: absolute;
    list-style: none;
    min-width: 200px;
    left: -999em;
    padding: 10px 10px;
    text-align: left;
    background-color: #89B0F1;
    z-index: 100;
    border-top-right-radius: 3px;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    box-shadow: 0px 3px 10px 0px #000000;
}

#headermenu td.hasSubMenu li {
    padding: 10px 5px;
    color: #252B76;
}

#headermenu td.hasSubMenu:hover ul {
    left: 0px;
    top: auto;
}

#headermenu td.hasSubMenu li:hover {
    background-color: #252B76;
    color: #FFFFFF;
}

#headermenu td.hasSubMenu li:hover a {
    color: #FFFFFF;
}

Your help is much appreciated. :)

A: Consider placing the dropdown menu list inside of the same div or container that contains the menu item. Position relative the menu item and use absolute positioning to push the dropdown menu beneath the menu item container. I find this to be a much more reliable method. So for example:

    Menu Text

Sub Menu Item #1

Sub Menu Item #2

Sub Menu Item #3

You will have to adjust the bottom and left values to suite your needs.

A: I have seemingly resolved this myself by tweaking a few things.
Instead of hiding the drop down menus by pushing them off the page (using left: -999em;), I'm now using display: none; and then using display: block; when it's hovered over. This, however meant that the drop down was pushed 10 pixels to the right of it's parent; which didn't look right, to counter this I tried using left: 0px;, but it caused the problem with Firefox rendering the drop down way to the left to reappear. I tried margin-left: -10px; and it worked.
So the CSS I'm now using looks like this:
/* Sub menu styles */
#headermenu td.hasSubMenu ul {
    display: none;
    position: absolute;
    list-style: none;
    min-width: 200px;
    padding: 10px 10px;
    margin-left: -10px;
    text-align: left;
    background-color: #89B0F1;
    z-index: 100;
    border-top-right-radius: 3px;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    box-shadow: 0px 3px 10px 0px #000000;
}

#headermenu td.hasSubMenu li {
    padding: 10px 5px;
    color: #252B76;
}

#headermenu td.hasSubMenu:hover ul {
    display: block;
}

#headermenu td.hasSubMenu li:hover {
    background-color: #252B76;
    color: #FFFFFF;
}

#headermenu td.hasSubMenu li:hover a {
    color: #FFFFFF;
}


text:
Q: Single Store Mode & Template Hints I have enabled single store mode (scoped multi store mode is not an option for this site) on my Magento 2.4.2 (developer mode) website and I cannot get template path hints to display either by the admin or by the command line. Yes, I have run setup:upgrade, setup:di:compile, setup:static-content:deploy, cache:clean, cache:flush...still no luck.
Is there a bug in the template path hints?

A: add this after your url:
?templatehints=magento

A: To enable template path hints for the store only when the URL includes the templatehints parameter, set Enable Hints for Storefront with URL Parameter to Yes. Then set value for the parameter if needed. The default value is magento, but you can use a custom value. For example, if you change the value to lorem, you would use mymagento.com?templatehints=lorem to display template hints.

A: Yeah I tried all that to no avail.
What I found that works great is to install https://github.com/vpietri/magento2-developer-quickdevbar. It has the ability to enable the template path hints when all else fails.


text:
Q: Extract information from Log file using Logstash I had an unstructured logfile which through some modifications in unix i made structured. The log file looks as below:
Module: KFK_PIG_ETL_JOBVW_7DAYS: 2015-06-03 15 28 27,976 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2017  Internal error creating job configuration.
Module: KFK_SONORA_RM_LRF: >>> [ERROR] Wed Jun  3 08 25 07 PDT 2015   Executing command  ssh -K data_svc@lva1-tarockgw01.grid.linkedin.com "export KRB5CCNAME=/export/home/data_svc/krb5cc_data_svc ; hadoop  fs -D appworx.chain.id=2905148 -D appworx.agent=LVA1-ETL04 -D appworx.job.id=2905178.00 -rm -r -skipTrash /jobs/data_svc/etl/tracking/lrf/STG_DAILY_JOB_VIEW/20150602-20150602.gz       "

I am trying to use Logstash to extract the below required information from above log.

*

*Module

*Timestamp

*Error

Basically after extracting all the above 3 fields from log , I want to show in Kibana dashboard that for a period of time and for a particular module what type of errors came.
Can someone suggest the logstash conf file patterns for the same.


text:
Q: How to open base64 pdf in new window Android phonegap Hi There is a requirement, I need to open a base64 pdf file in new window of mobile browser using phonegap. I tried in many ways working in normal desktop browser but not phonegap Android application. Below I am giving syntax which is working in Desktop but not in Android.
window.open("data:application/pdf;base64, " + base64EncodedPDF);

How to achieve this functionality.

A: Try to use Cordova Document Viewer Plugin https://github.com/sitewaerts/cordova-plugin-document-viewer


text:
Q: How to use "PHP Parallel" with DOMDocument in my following PHP Code? I would like to use PHP-8 Parallel (https://github.com/krakjoe/parallel. Or: https://php.net/parallel) in my function follow_links:
function get_details($url) {

    libxml_use_internal_errors(true);
    $parser = new DOMDocument();
    $parser->loadHTMLFile($url);
    // Create an array of all of the title tags.
    $title = $parser->getElementsByTagName("title");
    // There should only be one <title> on each page, so our array should have only 1 element.
    $title = $title->item(0)->nodeValue;
    // Give $description and $keywords no value initially. We do this to prevent errors.
    $description = "";
    $keywords = "";
    // Create an array of all of the pages <meta> tags. There will probably be lots of these.
    $metas = $parser->getElementsByTagName("meta");
    // Loop through all of the <meta> tags we find.
    for ($i = 0; $i < $metas->length; $i++) {
        $meta = $metas->item($i);
        // Get the description
        if (strtolower($meta->getAttribute("name")) == "description")
            $description = $meta->getAttribute("content");

    }

}

    function follow_links($url) {
        global $already_crawled;
        global $crawling;

        libxml_use_internal_errors(true);
        $parser = new DOMDocument();
        $linklist = $parser->getElementsByTagName("a");
        foreach ($linklist as $link) {
            $l =  $link->getAttribute("href");
            if (!in_array($l, $already_crawled)) {
                    $already_crawled[] = $l;
                    $crawling[] = $l;
                    // Output the page title, descriptions, keywords and URL. This output is
                    // piped off to an external file using the command line.
                    echo get_details($l)."\n";
            }

        }
        // Remove an item from the array after we have crawled it.
        // This prevents infinitely crawling the same page.
        array_shift($crawling);
        foreach ($crawling as $site) {
            follow_links($site);
        }

    }

    $starts = ["https://website1.dn", "https://website2.dn", "https://website3.dn", "https://website4.dn"];

    follow_links($starts);

I therefore seek to process all the URLs stored in the variable $starts at the same time in a parallel way in follow_links function knowing that it is the function get_details (using DOMDocument) which retrieves the data of each URL ???
Thank you for helping me.


text:
Q: How to create a list of time ranges based on intersections from two lists of time ranges? I have a problem needing a c# solution, the issue became too complex for a simple solution.
I have two lists of time ranges plus a value for each range: ListA; ListB. There's no relationship between them.
I would like to create a third list (ListC) based on ListB where for every start and end pair in ListB, if the range doesn't exist as a whole in any time range in ListA, create two or more entries in ListC so that the new entries are covered by entries in ListA. (Sorry it's hard to explain without being too verbose)
A simple example which contains one kind of overlap. There could be all kinds of overlaps between the two lists.
List<Tuple<int, DateTime, DateTime>> listA = new List<Tuple<int, DateTime, DateTime>>();
listA.Add(new Tuple<int, DateTime, DateTime>(22,DateTime.Parse("09/01/2013 11:00"),DateTime.Parse("09/01/2013 12:00")));
listA.Add(new Tuple<int, DateTime, DateTime>(66, DateTime.Parse("09/01/2013 12:01"), DateTime.Parse("09/01/2013 14:00")));

List<Tuple<int, DateTime, DateTime>> listB = new List<Tuple<int, DateTime, DateTime>>();
listB.Add(new Tuple<int, DateTime, DateTime>(33, DateTime.Parse("09/01/2013 11:30"), DateTime.Parse("09/01/2013 13:30")));

//Desired List
List<Tuple<int, DateTime, DateTime>> listC = new List<Tuple<int, DateTime, DateTime>>();
//listC should contain 2 tuples: first tuple contains the segment from ListB which falls in the first ListA tuple: Tuple(33, "09/01/2013 11:30","09/01/2013 12:00")
//second tuple contains the segment which falls in second ListA tuple: Tuple(33, "09/01/2013 12:01","09/01/2013 13:30")

A: Here is my try. The solution is quite straightforward, maybe I misunderstood the task.
You might want to cosider if you need using <=, >= instead of <,> in the lines specified in the comments:
        List<Tuple<int, DateTime, DateTime>> listA = new List<Tuple<int, DateTime, DateTime>>();
        listA.Add(new Tuple<int, DateTime, DateTime>(22, DateTime.Parse("09/01/2013 11:00"), DateTime.Parse("09/01/2013 12:00")));
        listA.Add(new Tuple<int, DateTime, DateTime>(66, DateTime.Parse("09/01/2013 12:01"), DateTime.Parse("09/01/2013 14:00")));

        List<Tuple<int, DateTime, DateTime>> listB = new List<Tuple<int, DateTime, DateTime>>();
        listB.Add(new Tuple<int, DateTime, DateTime>(33, DateTime.Parse("09/01/2013 11:30"), DateTime.Parse("09/01/2013 13:30")));

        List<Tuple<int, DateTime, DateTime>> listC = new List<Tuple<int, DateTime, DateTime>>();

        foreach (var rangeB in listB)
        {
            //a range in A overlaps with a range B
            //if any end of the range in A is inside the range in B
            //consider using <= and/or >= in these two lines if needed
            var overlapping = listA.Where(rangeA => rangeB.Item2 < rangeA.Item2 && rangeA.Item2 < rangeB.Item3 ||
                rangeB.Item2 < rangeA.Item3 && rangeA.Item3 < rangeB.Item3).ToList();

            overlapping = overlapping.Select(rangeA =>
                new Tuple<int, DateTime, DateTime> (rangeB.Item1,
                    //If a date of A is outside of B
                    //this will make it equal to the corresponding date of B
                    (rangeA.Item2 < rangeB.Item2) ? rangeB.Item2 : rangeA.Item2,
                    (rangeB.Item3 < rangeA.Item3) ? rangeB.Item3 : rangeA.Item3)).ToList();

            listC.AddRange(overlapping);
        }

A: It would help you significantly if you used a class along these lines to hold your data.
public class Range
{
    public int Id {get; set:}
    public DateTime Start {get; set:}
    public DateTime End {get; set:}
}

It would make it easier for you to compare each of the values in List B with each of the the Start and End values in List A to see if there is any overlap (of which there are only 4 possible types)
Type 1: B.Start < A.Start && B.End > A.End      (where B totally contains A)
Type 2: B.Start >= A.Start && B.End <= A.End    (where A totally contains B)
Type 3: B.Start >= A.Start && B.Start <= A.End  (where B overlaps to the right)
Type 4: B.End >= A.Start && B.End <= A.End      (where B overlaps to the left)

Pseudo code is something like
Loop through all entries in List B
{
    Loop through all entries in A looking for overlaps
    {
        If there is an overlap
        {
            Create a new range from the
            appropriate Start and End values
            from A or B as required.

            Use the ID from B

            Add new Range(s) as required
        }
    }
}

A: You can use the Time Period Library for .NET to calculate the intersections:
// ----------------------------------------------------------------------
public void PeriodIntersection()
{
  // time periods
  ITimePeriodCollection periods = new TimePeriodCollection();
  periods.Add( new TimeRange( new DateTime( 2013, 9, 1, 11, 0, 0 ), new DateTime( 2013, 9, 1, 12, 0, 0 ) ) );
  periods.Add( new TimeRange( new DateTime( 2013, 9, 1, 12, 1, 0 ), new DateTime( 2013, 9, 1, 14, 0, 0 ) ) );

  // search range
  TimeRange searchRange = new TimeRange( new DateTime( 2013, 9, 1, 11, 30, 0 ), new DateTime( 2013, 9, 1, 13, 30, 0 ) );

  // intersections
  foreach ( TimeRange period in periods )
  {
    if ( period.IntersectsWith( searchRange ) )
    {
      Console.WriteLine( "Intersection: " + period.GetIntersection( searchRange ) );
    }
  }
  // > Intersection: 01.09.2013 11.30:00 - 12:00:00 | 0.00:30
  // > Intersection: 01.09.2013 12.01:00 - 13:30:00 | 0.01:29
} // PeriodIntersection


text:
Q: Delegate in not working on dynamically added elements I have problem with delegate. Main problem is, that delegate is not working on dynamically created element.

$('.menu').delegate('> li', 'click', function() {
  var thisId = this.id;
  alert(thisId);
});

$('#but').click(function() {
  $('#2').append('

yyy

');
});

xxx

xxx

xxx

xxx

old

<button id="but">add</button>

Here you can see example of vertical menu with one submenu by default. Next is here button, that is adding submenu. Next I have simple delegate function, that is working on click and is returning id of clicked element. Problem occurs, when I add new submenu by #but button and try to click on it, because I will get Id of parent element only and not id of element and parent as it is with non dynamically added ul (as you can see at the end of html source). So how to edit my script to 'return only one id(id of clicked element only not of clicked and parent) and make it work on dynamically added elements?'

A: Unless it is purely for additional styling, your example does not need .menu on its sub-menus.
You just need to target all LIs within the top .menu (with li) and not just child LIs (you have > li). You also need to stop the click propagating to the parent (otherwise it will fire twice - on the LI clicked  & then again on the grandparent LI).
JSFiddle: http://jsfiddle.net/TrueBlueAussie/xnzs71d2/1/
$('.menu').delegate('li', 'click', function (e) {
    e.stopPropagation();
    var thisId = this.id;
    alert(thisId);
});

In later version of jQuery use a delegated on instead
$('.menu').on('click', 'li', function (e) {
    e.stopPropagation();
    var thisId = this.id;
    alert(thisId);
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/xnzs71d2/3/

A: // jQuery 1.7+
$('.menu').on('click', 'li', function() {
  var thisId = this.id;
  alert(thisId);
});

// jQuery 1.4.3+
$('.menu').delegate('li', 'click', function() {
  var thisId = this.id;
  alert(thisId);
});


text:
Q: onPlaybackNearlyFinished does not work I have the following problem with Java on AWS lambda:
The Intent called "PlaybackNearlyFinished" does not work, aka, does not play the audio file I am feeding it. Can anybody crack exactly why this doesn't work?
Here is my Java Code:
@Override
  public SpeechletResponse onPlaybackFinished(SpeechletRequestEnvelope<PlaybackFinishedRequest>
                                                      speechletRequestEnvelope) {
    // logging info("onPlaybackFinished start");

    SpeechletResponse response = new SpeechletResponse();

    Stream stream = new Stream();
    stream.setToken("test mp3");
    stream.setUrl("https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3");
    stream.setOffsetInMilliseconds(0);

    AudioItem audioItem = new AudioItem();
    audioItem.setStream(stream);

    PlayDirective playDirective = new PlayDirective();
    playDirective.setAudioItem(audioItem);
    playDirective.setPlayBehavior(PlayBehavior.REPLACE_ALL);

    List<Directive> directives = new ArrayList<>();
    directives.add(playDirective);
    response.setDirectives(directives);
    response.setShouldEndSession(true);
    // logging info("onPlaybackFinished end, return testmp3");

    return response;
  }

A: a couple of points here:

*

*The method you showed had the name of onPlaybackFinished while it should have been onPlaybackNearlyFinished

*Looks like the new stream misses the expected previous token. It should be equal to the token of the stream that is finishing - requestEnvelope.getRequest().getToken()

*I would also made it PlayBehavior.ENQUEUE instead of PlayBehavior.REPLACE_ALL but I am not sure here... still experimenting

Hope it helps!


text:
Q: Let $S = \{1,2,3,4\}. X, Y \in \mathcal{P}(S)$ and R be a relation $R(X,Y): |X \cap Y| = 1$. Is the relation R transitive? I'm reading up on Relations and Functions with the book Discrete Mathematics by G. Chartrand, P. Zhang and one of the exercises there proposes that the relation R over $\mathcal{P}(S)$ where $R(X,Y): |X \cap Y| = 1$ is symmetric only — which I can make sense with since my mental model with this is that $(a, b) \in R$ never occurs because $|X \cap Y| = 1$ is only true when $|X|$ or $|Y|$ is 1, therefore only $(a,a) \in R$, thus the implication for symmetry is vacuously true.
My concern is that with my thinking of how the relation R is symmetric, then this can also mean that it's transitive as well, since $(a,b) \in R \land (b,c) \in R$ never occurs and therefore is vacuously true also.
Is my thinking correct? How is relation R symmetric only and why can't it be transitive as well?
Edit
Okay. I had $(a,a) \in R(X \cap Y, X \cap Y)$ in mind for whatever reason when I was thinking $(a, a) \in R$.

A: I have absolutely no idea why you think $|X\cap Y|$ only if $|X|$ or $|Y|$ is $1$.
Simple case $X=\{1,2\}$ and $Y=\{2,3\}$ then $X\cap Y = \{2\}|$ and $|X\cap Y| = 1$ and $R(X,Y)$.
Further more if $Z = \{3,4\}$ then $R(Y,Z)$ but $X\cap Z =\emptyset$ so $\not R(X,Z)$ even though $R(X,Y)$ and $R(Y,Z)$.  So not transitive.
....
Any way  $X \cap X = X$ so $R(X,X)$ only if $|X| = 1$.  So if $|X| \ne 1$ we do not have $R(X,X)$ so it is not reflexive.
$X\cap Y=Y\cap X$ so $|X\cap Y| = |Y\cap X|$ so $R(X,Y) \iff R(Y,X)$ so symmetry holds.
Transitivity:  There no way to determine $X\cap Z$ from $X\cap Y$ and $X\cap Z$.  It is certainly possible for $X$ and $Y$ to have only one thing in common and $Y$ and $Z$ to have one thing in common but $X$ and $Z$ to have nothing or many things in common.
Let $X = $ the prime natural numbers.  Let $Y = $ the even natural numbers.  And let $Z=$ then numbers between $11$ through $13$ inclusively.
$X \cap Y= \{2\}$.  $Y\cap Z=\{12\}$ and $X\cap Z = \{11,13\}$.  Not transitive.