text:
Q: return multiple values in done() of angularjs's e2e test I have the following working e2e test code:
it('should ...', function () {
    var promise = element('#id').query(function (elements, done) {
        var children = elements.children();
        done(null, children.prevObject[0].innerHTML);
    });

    var pattern = /...some pattern.../;
    expect(promise).toMatch(pattern);
});

However, I want to return a list of data in done() and then test each element. How to do that? The angularjs's e2e document is very poor and I can't find anything useful there.
I want something like this:
it('should ...', function () {
    var promise = element('#id').query(function (elements, done) {
        var children = elements.children();
        done(null, children.prevObject);
    });

    var pattern = /...some pattern.../;
    expect(item.innerHTML in promise).toMatch(pattern);
});

Thanks in advance!

A: You can always loop through your array prevObject and write an expectation within the loop.
for(var i = 0; i < promise.length; i++) {
  expect(promise[i].innerHTML).toMatch(pattern);
}


text:
Q: Replace entire file in directory with file at URL endpoint in ruby Let's say I have the following file in my working directory:
path/to/my/file/fileToBeReplaced.json

And I have a file at the following URL endpoint:
mywebsite.com/fileToCopy.json

I want to take the file at the URL endpoint (fileToCopy.json) and fetch the contents there to overwrite the file in my working directory (fileToBeReplaced.json). It's also important that I preserve the json formatting when writing the file to my working directory. How can this be accomplished within a Ruby script?

A: You can do something like this:
require 'net/http'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   f.write Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
end

If your JSON from URL is not well formatted, then, you can try something like this:
require 'net/http'
require 'json'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   json_str = Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
   json_hash = JSON.parse(json_str)
   f.puts JSON.pretty_generate(json_hash)
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting string value with comma to Decimal with correct Locale I am trying to create Double object from decimal string value where comma is floating separator.
Passing locale arguments to vm:
-Duser.country=BR
-Duser.language=PT

String value = "500,21";
Double dob = new Double(value);

Getting exception:

java.lang.NumberFormatException: For input string: "500,21"   at
  sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
    at java.lang.Double.valueOf(Double.java:475)    at
  java.lang.Double.(Double.java:567)

A: You can try with a localized NumberFormat:
String value = "500,21";
// replace the hard-coded Locale definition with your arguments, or
// Locale.getDefault(), etc.
NumberFormat nf = NumberFormat.getInstance(new Locale("pt", "BR"));
try {
    Double d = nf.parse(value).doubleValue();
    System.out.println(d);
}
catch (ParseException pe) {
    // TODO
}

Output
500.21

A: It looks like that new Double(value) does not take into consideration the locale setting.
The implementation ends up calling this method here and it is only looking for ".".
With the locale set as you did you can use this:
NumberFormat.getInstance().parse(value).doubleValue()

Here is a similar discussion.


text:
Q: Dynamic Diamond Operator Parameters I have the following code:
@FXML
TableView dataTable;

for(HashMap column : columns){

    String dataType = (String)column.get("DATA_TYPE");

    if(dataType.matches("char|date")){
        TableColumn<String, String> tableColumn;
    }else if(dataType.matches("int")){
        TableColumn<String, Integer> tableColumn;
    }else{
        TableColumn<String, String> tableColumn;
    }

    tableColumn = new TableColumn<>((String)column.get("COLUMN_NAME"));
    dataTable.getColumns().add(tableColumn);
}

What I am not sure about, is the Diamond Operators. The second value of that operator will change depending on what is in the database. The issue I am having, is that it says that it can't find tableColumn on this line:
tableColumn = new TableColumn<>((String)column.get("COLUMN_NAME"));

Is there a solution that will allow me to have dynamically changing Diamond Operator parameters?

A: Declare one
 TableColumn<String, Object> tableColumn

and use this, but keep track of the class of values (according to column.get("DATA_TYPE"). You may use this to branch processing when you extract values, cast to the approproate data type.
Not very elegant, but since the data is any of three types...


text:
Q: Jquery, ajax won't alert some message So I am doing a shopping cart site, using CodeIgniter on backend
Here is the catch, I loop the product list, with 'add to cart' button, inside a form tag.
So let's say, I have 5 products to display, there will be 5 form tag as:
<?php foreach ($products as $vid):?>

<form id='cart' method='post' action='<?php echo base_url();?>cart/add'>
<input type='hidden' id='vid' name='vid' value='<?php echo $vid['id'];?>'/>

      <a href="#<?php echo $vid['id'];?>" name='modal'>
     <img src="<?php echo base_url(); ?>assets/images/<?php echo $vid['video_thumbnail'];?>" alt="<?php echo $vid['title'];?>" border="0" height='150' width='100' />

    <?php if($this->session->userdata('nric')===FALSE ) {
     echo "Please Login to Rent/Purchase"; } else { ?>
     <input type='image' id='btn-add' src="<?php echo base_url(); ?>assets/images/rent_btn.png" alt="Rent" border="0" />
     <?php } ?>

</form>
 <?php endforeach;?>

And my javascript/jquery script:

As my controller (in form action) localhost/site/cart/add:
public function add() {
    $vid=$_POST['vid'];

    if($this->session->userdata('shoppingCart')===FALSE)
    {

        $shoppingCart = array (
                            $vid => 1
                        );
        $this->session->set_userdata('shoppingCart',$shoppingCart);
         echo 'newses';

    } else {

        $tmp = $this->session->userdata('shoppingCart');
        if(array_key_exists($vid, $tmp)) {
            //only allow user to add qty:1 to the same product
            echo 'exists';

        } else {
            $tmp[$vid]= 1;
            $this->session->set_userdata('shoppingCart',$tmp);
            echo 'new_added';

        }
    }

}

So the problem now, I can add the product to my shopping cart with no problem, all the stuff inside cart/add controller runs fine, the output is as expected.
But I need to alert the customer whether the product has been added or failed (as shown in my jquery code).
Problem is, the script will run fine only for the 1st  created.
Means, if there is 5 products, it will loop and create 5 form-tag right, only the 1st form-tag will run the script successfully (after the button is clicked). The 2nd-5th form will redirect to other blank page, echoing the result (e.g "newses", "new_added", "exists"), not alerting the user as stated in the script (but the shopping cart function works properly).
What did I do wrong?

A: Try this
<?php foreach ($products as $vid):?>

<form id='cart' method='post' action='<?php echo base_url();?>cart/add'>
<input type='hidden' class='vid' name='vid' value='<?php echo $vid['id'];?>'/>

      <a href="#<?php echo $vid['id'];?>" name='modal'>
     <img src="<?php echo base_url(); ?>assets/images/<?php echo $vid['video_thumbnail'];?>" alt="<?php echo $vid['title'];?>" border="0" height='150' width='100' />

    <?php if($this->session->userdata('nric')===FALSE ) {
     echo "Please Login to Rent/Purchase"; } else { ?>
     <input type='image' class='btn-add' src="<?php echo base_url(); ?>assets/images/rent_btn.png" alt="Rent" border="0" />
     <?php } ?>

</form>
 <?php endforeach;?>

Jquery
$(document).ready(function() {
    $(".btn-add").click(function() {
        var $this = $(this);
        var $form = $this.parents('form');
        var action = $form.attr('action');
        var vid = $form.find('input.vid').val();
        var form_data = {
            vid : vid,
            is_ajax : 1
        };
        $.ajax({
            type : "POST",
            url : action,
            data : form_data,
            success : function(response) {
                if (response == 'exists') {
                    alert("This item is in your cart already! You can only add 1 same item once");
                }
                if (response == 'newses') {
                    alert("This item has been added succesfully!");
                    document.location.reload(true);
                }
                if (response == 'new_added') {
                    alert("This item has been added succesfully1!");
                    document.location.reload(true);
                }
            }
        });
        return false;
    });
});


text:
Q: Why is $p^2-q^2 = p-q$ when $p+q = 1$? I'm having trouble to see why it is that:
$p^2-q^2 = p-q$ when $p+q = 1$
If I take a number for which $p+q \not= 1$, this doesn't hold. What's so special about the former case? Can someone take me through this, algebraically?

A: Complementing the other answer, the formula has a name: Difference of two squares formula.
Moreover, it also goes the other way, if $p\not = q$. That is: if $p^2-q^2=p-q$ and $p\not=q$, then $p+q=1$.

A: $$p^2 - q^2 = (p-q)(p+q){}{}{}{}$$


text:
Q: Including .h File for 2 Classes I want to turn this single .cpp file into multiple ones but I'm having trouble doing so. I'm getting undeclared identifier and 'children' : is not a member of 'Node' compiler errors.
Here is my original entire code:
#include <iostream>
#include <vector>
using namespace std;

class Node {
public:
    Node();
    ~Node() {}
    char content();
    void setContent(char c);
    bool wordMarker();
    void setWordMarker();
    Node* findChild(char c);
    void appendChild(Node* child);
    vector<Node*> children();

private:
    char m_Content;
    bool m_Marker;
    vector<Node*> m_Children;
};

class Trie {
public:
    Trie();
    ~Trie();
    void addWord(string s);
    bool searchWord(string s);
    void deleteWord(string s);
private:
    Node* root;
};

Node::Node()
{
    m_Content = ' '; m_Marker = false;
}

char Node::content()
{
    return m_Content;
}
void Node::setContent(char c)
{
    m_Content = c;
}
bool Node::wordMarker()
{
    return m_Marker;
}
void Node::setWordMarker()
{
    m_Marker = true;
}
void Node::appendChild(Node* child)
{
    m_Children.push_back(child);
}
vector<Node*> Node::children()
{
    return m_Children;
}

Node* Node::findChild(char c)
{
    for (int i = 0; i < m_Children.size(); i++)
    {
        Node* tmp = m_Children.at(i);
        if (tmp->content() == c)
        {
            return tmp;
        }
    }

    return NULL;
}

Trie::Trie()
{
    root = new Node();
}

Trie::~Trie()
{
    // Free memory
}

void Trie::addWord(string s)
{
    Node* current = root;

    if (s.length() == 0)
    {
        current->setWordMarker(); // an empty word
        return;
    }

    for (int i = 0; i < s.length(); i++)
    {
        Node* child = current->findChild(s[i]);
        if (child != NULL)
        {
            current = child;
        }
        else
        {
            Node* tmp = new Node();
            tmp->setContent(s[i]);
            current->appendChild(tmp);
            current = tmp;
        }
        if (i == s.length() - 1)
            current->setWordMarker();
    }
}

bool Trie::searchWord(string s)
{
    Node* current = root;

    while (current != NULL)
    {
        for (int i = 0; i < s.length(); i++)
        {
            Node* tmp = current->findChild(s[i]);
            if (tmp == NULL)
                return false;
            current = tmp;
        }

        if (current->wordMarker())
            return true;
        else
            return false;
    }

    return false;
}

// Test program
int main()
{
    Trie* trie = new Trie();
    trie->addWord("Hello");
    trie->addWord("Balloon");
    trie->addWord("Ball");

    if (trie->searchWord("Hell"))
        cout << "Found Hell" << endl;

    if (trie->searchWord("Hello"))
        cout << "Found Hello" << endl;

    if (trie->searchWord("Helloo"))
        cout << "Found Helloo" << endl;

    if (trie->searchWord("Ball"))
        cout << "Found Ball" << endl;

    if (trie->searchWord("Balloon"))
        cout << "Found Balloon" << endl;

    delete trie;
}

My attempt:
node.h
#ifndef NODE_INCLUDED
#define NODE_INCLUDED

class Node {
public:
    Node();
    ~Node() {}
    char content();
    void setContent(char c);
    bool wordMarker();
    void setWordMarker();
    Node* findChild(char c);
    void appendChild(Node* child);
    vector<Node*> children();

private:
    char m_Content;
    bool m_Marker;
    vector<Node*> m_Children;
};

#endif // NODE_INCLUDED

trie.h
#ifndef TRIE_INCLUDED
#define TRIE_INCLUDED
class Trie {
public:
    Trie();
    ~Trie();
    void addWord(string s);
    bool searchWord(string s);
    void deleteWord(string s);
private:
    Node* root;
};
#endif //TRIE_INCLUDED

node.cpp
#include "node.h"
#include <iostream>
#include <vector>
using namespace std;

Node::Node()
{
    m_Content = ' '; m_Marker = false;
}

char Node::content()
{
    return m_Content;
}
void Node::setContent(char c)
{
    m_Content = c;
}
bool Node::wordMarker()
{
    return m_Marker;
}
void Node::setWordMarker()
{
    m_Marker = true;
}
void Node::appendChild(Node* child)
{
    m_Children.push_back(child);
}
vector<Node*> Node::children()
{
    return m_Children;
}

Node* Node::findChild(char c)
{
    for (int i = 0; i < m_Children.size(); i++)
    {
        Node* tmp = m_Children.at(i);
        if (tmp->content() == c)
        {
            return tmp;
        }
    }

    return NULL;
}

trie.cpp
Trie::Trie()
{
    root = new Node();
}

Trie::~Trie()
{
    // Free memory
}

void Trie::addWord(string s)
{
    Node* current = root;

    if (s.length() == 0)
    {
        current->setWordMarker(); // an empty word
        return;
    }

    for (int i = 0; i < s.length(); i++)
    {
        Node* child = current->findChild(s[i]);
        if (child != NULL)
        {
            current = child;
        }
        else
        {
            Node* tmp = new Node();
            tmp->setContent(s[i]);
            current->appendChild(tmp);
            current = tmp;
        }
        if (i == s.length() - 1)
            current->setWordMarker();
    }
}

bool Trie::searchWord(string s)
{
    Node* current = root;

    while (current != NULL)
    {
        for (int i = 0; i < s.length(); i++)
        {
            Node* tmp = current->findChild(s[i]);
            if (tmp == NULL)
                return false;
            current = tmp;
        }

        if (current->wordMarker())
            return true;
        else
            return false;
    }

    return false;
}

main.cpp
#include "node.h"
#include <iostream>
#include <vector>
using namespace std;

// Test program

#include "node.h" //is this needed?
#include "trie.h" //is this needed?
int main()
{
    Trie* trie = new Trie();
    trie->addWord("Hello");
    trie->addWord("Balloon");
    trie->addWord("Ball");

    if (trie->searchWord("Hell"))
        cout << "Found Hell" << endl;

    if (trie->searchWord("Hello"))
        cout << "Found Hello" << endl;

    if (trie->searchWord("Helloo"))
        cout << "Found Helloo" << endl;

    if (trie->searchWord("Ball"))
        cout << "Found Ball" << endl;

    if (trie->searchWord("Balloon"))
        cout << "Found Balloon" << endl;

    delete trie;
}

A: So here is what I got working, I comment on things I have added or removed.
node.h
#ifndef NODE_INCLUDED
#define NODE_INCLUDED

#include <vector> //Class Node uses vector so it should be included
#include <iostream> //Class Node uses iostream so it should be included

class Node {
public:
    Node();
    ~Node() {}
    char content();
    void setContent(char c);
    bool wordMarker();
    void setWordMarker();
    Node* findChild(char c);
    void appendChild(Node* child);
    std::vector<Node*> children();

private:
    char m_Content;
    bool m_Marker;
    std::vector<Node*> m_Children;
};

#endif // NODE_INCLUDED

trie.h
#ifndef TRIE_INCLUDED
#define TRIE_INCLUDED

#include "node.h" //Class Trie uses Node so it should include it
#include <string> //Class Node uses string so it should include it

class Trie {
public:
    Trie();
    ~Trie();
    void addWord(string s);
    bool searchWord(string s);
    void deleteWord(string s);
private:
    Node* root;
};
#endif //TRIE_INCLUDED

node.cpp
#include "node.h"
//#include <iostream>
//#include <vector>
using namespace std;
//Here you got all includes right but they should be in the header file!

Node::Node()
{
    m_Content = ' '; m_Marker = false;
}

char Node::content()
{
    return m_Content;
}
void Node::setContent(char c)
{
    m_Content = c;
}
bool Node::wordMarker()
{
    return m_Marker;
}
void Node::setWordMarker()
{
    m_Marker = true;
}
void Node::appendChild(Node* child)
{
    m_Children.push_back(child);
}
vector<Node*> Node::children()
{
    return m_Children;
}

Node* Node::findChild(char c)
{
    for (int i = 0; i < m_Children.size(); i++)
    {
        Node* tmp = m_Children.at(i);
        if (tmp->content() == c)
        {
            return tmp;
        }
    }

    return NULL;
}

trie.cpp
#include "trie.h" //Trie.cpp should at least contain its header file

Trie::Trie()
{
    root = new Node();
}

Trie::~Trie()
{
    // Free memory
}

void Trie::addWord(string s)
{
    Node* current = root;

    if (s.length() == 0)
    {
        current->setWordMarker(); // an empty word
        return;
    }

    for (int i = 0; i < s.length(); i++)
    {
        Node* child = current->findChild(s[i]);
        if (child != NULL)
        {
            current = child;
        }
        else
        {
            Node* tmp = new Node();
            tmp->setContent(s[i]);
            current->appendChild(tmp);
            current = tmp;
        }
        if (i == s.length() - 1)
            current->setWordMarker();
    }
}

bool Trie::searchWord(string s)
{
    Node* current = root;

    while (current != NULL)
    {
        for (int i = 0; i < s.length(); i++)
        {
            Node* tmp = current->findChild(s[i]);
            if (tmp == NULL)
                return false;
            current = tmp;
        }

        if (current->wordMarker())
            return true;
        else
            return false;
    }

    return false;
}

main.cpp
//#include "node.h" //You don't use Node here, so don't include it!
                    //Keep your code simple
#include <iostream>
#include <vector>
using namespace std;

// Test program

//#include "node.h" //is this needed? Not needed because you don't use
                    //its declarations directly here and
                    //you had it declared before
#include "trie.h" //is this needed? Yes, it is. You use that class
                  //directly here, so it should include it
int main()
{
    Trie* trie = new Trie();
    trie->addWord("Hello");
    trie->addWord("Balloon");
    trie->addWord("Ball");

    if (trie->searchWord("Hell"))
        cout << "Found Hell" << endl;

    if (trie->searchWord("Hello"))
        cout << "Found Hello" << endl;

    if (trie->searchWord("Helloo"))
        cout << "Found Helloo" << endl;

    if (trie->searchWord("Ball"))
        cout << "Found Ball" << endl;

    if (trie->searchWord("Balloon"))
        cout << "Found Balloon" << endl;

    delete trie;
}

By the way, you should not use using namespace in header files as it is a bad practice


text:
Q: How to create a grid of modals images? I'm a creating a website that features a grid of images. I want each image to expand into a modal when clicked. I've gotten it to work with one image but I have to create a new modal , new myImg and new script for each image. Is there anyway I can just have one modal and one myImg and write a script to make it work generally for each image so that I don't have to create a new modal and myImg for each image as that will quickly become ridiculously long.
Example of Grid:
Source Code:
<!DOCTYPE html>

    <?php
        $myfile = fopen("header.html", "r") or die("Unable to open file!");
        echo fread($myfile,filesize("header.html"));
        fclose($myfile);
    ?>

            ×

            ×

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

            <a1 href="abe_lincoln_riding_a_grizzly.png">

            </a1>

A: Use Jquery to get id and info of clicked img and make function to create modal with id and info parameters and pass id and info of clicked img to function then add them to vars ex:
var modalImg = document.getElementById("img" + imgIdNumber);
etc...

so it will be dynamic.


text:
Q: 3 classes imbalanced and hierarchical classification I need to classift a dataset with 3 classes:
A - 85% of the data
B - 10% of the data
C - 5% of the data
Where C is a subset of B.
What should be the best way to approach it?


text:
Q: Get all products which have both product category I need all products which have both categories. I am using a query below:
$args = array(
                        'post_type' => array('product', 'product_variation'),

                        'tax_query' => array(
                            array(
                                'taxonomy' => 'product_cat',
                                'field' => 'slug',
                                'terms'    => array( 'shop', 'cat1' ),
                                'operator' => 'AND',
                            )
                        )
                    );

It's working correctly if cat1 category does not have any subcategory like cat1-1,cat1-2 etc. But when i made subcategory in backend of cat1 than result will give zero.
Query is same just no result if cat1 have subcategory.
Thanks

A: Set include_children to false in the tax_query.
$args = array(
'post_type' => array( 'product', 'product_variation' ),

'tax_query' => array(
    array(
        'taxonomy'         => 'product_cat',
        'field'            => 'slug',
        'terms'            => array( 'shop', 'cat1' ),
        'include_children' => false,
        'operator'         => 'AND',
    )
)

);
See https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters


text:
Q: java.sql.SQLException: No suitable driver found for jdbc:sqlite:db/Fakturi.sqlite I'm Using Java SWING + SQLite. When I export executable jar (option Extract required libraries into generated JAR) and try to run, there is error: ....>java -jar g222.jar
java.sql.SQLException: No suitable driver found for jdbc:sqlite:db/Fakturi.sqlit
e
If I run it under Eclipse - it's works. Here is my code:
public class MainFrame extends JFrame {

    private JPanel contentPane;
    private JTextField textField_6;
    private JTextField textField_7;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     * @throws SQLException
     */
    public MainFrame() throws SQLException {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 643, 298);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        panel.setBounds(10, 11, 670, 287);
        contentPane.add(panel);

        JPanel panel_2 = new JPanel();
        panel_2.setLayout(null);
        panel_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
        panel_2.setBounds(196, 51, 249, 100);
        panel.add(panel_2);

        JLabel label_21 = new JLabel("\u0411\u0440\u043E\u0439:");
        label_21.setBounds(10, 40, 128, 16);
        panel_2.add(label_21);

        textField_6 = new JTextField();
        textField_6.setText("0");
        textField_6.setHorizontalAlignment(SwingConstants.RIGHT);
        textField_6.setEditable(false);
        textField_6.setColumns(10);
        textField_6.setBackground(new Color(135, 206, 250));
        textField_6.setBounds(150, 37, 42, 22);
        panel_2.add(textField_6);

        JLabel label_22 = new JLabel("\u041E\u0431\u0449\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0441 \u0414\u0414\u0421:");
        label_22.setBounds(10, 70, 135, 16);
        panel_2.add(label_22);

        textField_7 = new JTextField();
        textField_7.setText("0.00 \u043B\u0432.");
        textField_7.setHorizontalAlignment(SwingConstants.RIGHT);
        textField_7.setForeground(Color.RED);
        textField_7.setFont(new Font("Tahoma", Font.BOLD, 11));
        textField_7.setEditable(false);
        textField_7.setColumns(10);
        textField_7.setBackground(new Color(255, 160, 122));
        textField_7.setBounds(150, 67, 87, 22);
        panel_2.add(textField_7);

        JLabel label_23 = new JLabel("\u041F\u0440\u043E\u0444\u043E\u0440\u043C\u0430 \u0444\u0430\u043A\u0442\u0443\u0440\u0438");
        label_23.setHorizontalAlignment(SwingConstants.CENTER);
        label_23.setForeground(Color.GRAY);
        label_23.setBounds(6, 6, 224, 14);
        panel_2.add(label_23);

        String danOsnInvoices = ConnectionToDb.stmSqlQuery("SELECT printf('%.2f', ROUND(sum(quantity*price), 2)) FROM invoices_out WHERE number = '0000000001'");
        textField_6.setText(danOsnInvoices);

    }
}

And Connection class is:
public class ConnectionToDb {

    public Connection conn = null;
    public static final String DBURL = "jdbc:sqlite:db/Fakturi.sqlite";

    public static Connection connectDb() throws ClassNotFoundException,SQLException {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection(DBURL);
        return conn;
    }

    public static String dmlSqlQuery(String value) throws SQLException, ClassNotFoundException {

            Statement stmt;
            String result = null;

                Class.forName("org.sqlite.JDBC");

                Connection c = DriverManager.getConnection(DBURL);
                c.setAutoCommit(false);

                stmt = c.createStatement();
                String sql = value;
                stmt.executeUpdate(sql);

                stmt.close();
                c.commit();
                c.close();

            return result;
        }

    public static String stmSqlQuery(String value) throws SQLException {

        String result = null;
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        Connection con = DriverManager.getConnection(DBURL);

        Statement statement = con.createStatement();

        // Enables us to retrieve values as if querying from a table
        ResultSet rs = statement.executeQuery(value);

        if (rs.next()) {
            result = rs.getString(1); // get first column returned
        }

        rs.close();
        statement.close();
        con.close();
        return result;
    }
}

I can't understand Why this error shows.

A: SOLVED:
I just add:
ConnectionToDb.connectDb(); before any SQL queries.


text:
Q: c++: Performance increase on non-template delegate class This is a simple delegate class that only works for methods of the format void ClassType::MethodType( InputType& ), but can easily be expanded to more generic functions, not shown simply because it would be too large.
class Delegate
{
public:
    Delegate( void ) : Object( NULL ), Argument( NULL ) { }
    virtual ~Delegate( void ) { }

    template <class ClassType, class InputType, void (ClassType::*MethodType)( InputType )>
    void Create( ClassType* SetObject, void* SetArgument = NULL )
    {
        Object = SetObject;
        Argument = SetArgument;
        StaticCall = &CallMethod<ClassType, InputType, MethodType>;
    }

    template <class InputType>
    inline void operator()( InputType InputValue ) const
    {
        (*StaticCall)( Object, static_cast<void*>(InputValue) );
    }

    inline void operator()( void ) const
    {
        (*StaticCall)( Object, Argument );
    }

protected:
    typedef void (*FunctionCallType)( void*, void* );

    void* Object;
    void* Argument;
    FunctionCallType StaticCall;

private:
    template <class ClassType, class InputType, void (ClassType::*MethodType)( InputType )>
    static inline void CallMethod( void* SetObject, void* PassArgument )
    {
        (static_cast<ClassType*>( SetObject )->*MethodType)( static_cast<InputType>(PassArgument) );
    }
};

It's flexible and can be used to pool callback classes, but one problem I have with it is that so far it's on par with (or even slower when used in large vectors like I plan to) than a virtual call if it's used as a base class.  I'm looking for any suggestions on how to increase performance since I'm out of ideas, even if it affects functionality.
The simplest performance measuring code I used (with -O3) was:
class VirtualBase
{
public:
    virtual void TestCall( int* Data ) {}
};

class VirtualTest : public VirtualBase
{
public:
    VirtualTest() : Value(0) {}

    void TestCall( int* Data )
    {
        Value += *Data;
    }
private:
    int Value;
};

class DelTest : public Delegate
{
public:
    DelTest() : Value(0)
    {
        Create<DelTest, int*, &DelTest::TestCall>( this );
    }

    void TestCall( int* Data )
    {
        Value += *Data;
    }
private:
    int Value;
};

int main( int argc, char **argv )
{
    clock_t start;
    int Value = 1;

    VirtualBase* NewBase = new VirtualTest;

    start = clock();
    for( size_t Index = 0; Index < 1000000000; ++Index )
    {
        NewBase->TestCall( &Value );
    }
    delete NewBase;
    std::cout << (( std::clock() - start ) / (double)CLOCKS_PER_SEC) << std::endl;

    Delegate* NewDBase = new DelTest;
    start = clock();
    for( size_t Index = 0; Index < 1000000000; ++Index )
    {
        NewDBase->operator()( &Value );
    }
    delete NewDBase;
    std::cout << (( std::clock() - start ) / (double)CLOCKS_PER_SEC) << std::endl;

    return 0;
}

I should mention that I'd like the class to stay non-template, as it makes classes using callbacks to anything easy to iterate through in a single vector.

A: You might want to look at this Lightweight Generic C++ Callbacks article on CodeProject
Some of the code from the linked article, showing the use of a function template to do the forwarding:
template<typename R, typename P1, typename P2>
class Callback
{
public:
    typedef R (*FuncType)(void*, P1, P2);
    Callback() : func(0), obj(0) {}
    Callback(FuncType f, void* o) : func(f), obj(o) {}
    R operator()(P1 a1, P2 a2)
    {
        return (*func)(obj, a1, a2);
    }

private:
    FuncType func;
    void* obj;
};

template<typename R, class T, typename P1, typename P2, R (T::*Func)(P1, P2)>
R Wrapper(void* o, P1 a1, P2 a2)
{
    return (static_cast<T*>(o)->*Func)(a1, a2);
}

class Foo
{
public:
    float Average(int n1, int n2)
    {
        return (n1 + n2) / 2.0f;
    }
};

float Calculate(int n1, int n2, Callback<float, int, int> callback)
{
    return callback(n1, n2);
}

int main()
{
    Foo f;
    Callback<float, int, int> cb
        (&Wrapper<float, Foo, int, int, &Foo::Average>, &f);
    float result = Calculate(50, 100, cb);
    // result == 75.0f
    return 0;
}

There is also a great write up on stackoverflow here which will give you better insight.


text:
Q: How to get make code from char in JavaScript? I am working on v86 emulator for node from this library. I need to send some keyboard inputs, but I first need convert it to make code. Is there any JavaScript function to do it?
a => 0x1E
b => 0x30
c => 0x2E

Here is the table of that codes:
Key      Make  Break        Key    Make  Break

    Backspace     0E    8E          F1  3B    BB
    Caps Lock     3A    BA          F2  3C    BC
    Enter         1C    9C          F3  3D    BD
    Esc       01    81          F4  3E    BE
    Left Alt      38    B8          F7  41    C1
    Left Ctrl     1D    9D          F5  3F    BF
    Left Shift    2A    AA          F6  40    C0
    Num Lock      45    C5          F8  42    C2
    Right Shift   36    B6          F9  43    C3
    Scroll Lock   46    C6          F10 44    C4
    Space         39    B9          F11 57    D7
    Sys Req (AT)  54    D4          F12 58    D8
    Tab       0F    8F

            Keypad Keys            Make   Break

            Keypad 0  (Ins)     52  D2
            Keypad 1  (End)         4F  CF
            Keypad 2  (Down arrow)  50  D0
            Keypad 3  (PgDn)        51  D1
            Keypad 4  (Left arrow)  4B  CB
            Keypad 5            4C  CC
            Keypad 6  (Right arrow) 4D  CD
            Keypad 7  (Home)        47  C7
            Keypad 8  (Up arrow)    48  C8
            Keypad 9  (PgUp)        49  C9
            Keypad .  (Del)         53  D3
            Keypad *  (PrtSc)       37  B7
            Keypad -            4A  CA
            Keypad +            4E  CE

           Key    Make  Break          Key    Make  Break

        A      1E    9E         N      31    B1
        B      30    B0         O      18    98
        C      2E    AE         P      19    99
        D      20    A0         Q      10    90
        E      12    92         R      13    93
        F      21    A1         S      1F    9F
        G      22    A2         T      14    94
        H      23    A3         U      16    96
        I      17    97         V      2F    AF
        J      24    A4         W      11    91
        K      25    A5         X      2D    AD
        L      26    A6         Y      15    95
        M      32    B2         Z      2C    AC

           Key    Make  Break          Key    Make  Break

        1      02    82         -      0C    8C
        2      03    83         =      0D    8D
        3      04    84         [      1A    9A
        4      05    85         ]      1B    9B
        5      06    86         ;      27    A7
        6      07    87         '      28    A8
        7      08    88         `      29    A9
        8      09    89         \      2B    AB
        9      0A    8A         ,      33    B3
        0      0B    8B         .      34    B4
                        /      35    B5

And yes. I can rewrite it to JavaScript, but there is also some other keyboard keys and it will take long time to do it, so this is reason why I am asking this.

A: All of the answers and comments here completely miss the point. There is no Unicode code for Right Shift press and there is no Unicode code for Right Shift release. Likewise, you cannot make a string out of a Right Shift press and Print Screen release to parse it and print the codes. How could you even possibly put a Right Shift release in a string? Apparently some people here have bigger imagination than me.
The make and break codes have nothing to do with characters that can be printed on the screen or stored in strings. Those are codes that the keyboard sends to signal key presses and releases. Then the operating system can translate those codes into characters but not directly. For example if a shift was pressed but was not released and then a code that corresponds to a press of a letter Q on a QWERTY keyboard is detected then the operating system may interpret it as an uppercase Q (unless the caps lock was on) and if it doesn't detect a release of the Q letter it may also start automatically repeating it until it detects the release of the letter Q. But the same code that is sent for the letter Q on a QWERTY keyboard is sent for the letter A on an AZERTY keyboard. It doesn't matter what is printed on the key, the physical location and electrical connection of the key is what matters.
Now, there are some modules on npm that you may take a look at:

*

*https://www.npmjs.com/search?q=keycodes

*https://www.npmjs.com/search?q=keypress

*https://www.npmjs.com/search?q=keyboard
but I doubt you will actually find something useful because yu normally don't work on such a low level of keyboard hardware with JavaScript or Node.
If you don't find anything useful on npm and you end up rewriting the table that you included in JavaScript then consider publishing it on npm so others could use it.
Update
I just found this module:

*

*https://www.npmjs.com/package/node-key-sender
It seems to include some of the codes that you need. You may be able to get it from its source code.


text:
Q: ESP32 MQTT event processing I am trying to use arduino-esp32 methods defined in file mqtt_client.h for my ESP32/Arduino IDE project :
I am struggling to make an event handler out of this.
I currently have:
#include <mqtt_client.h>

void MQTTEvent(esp_mqtt_event_t event) {
  // process event
}

void setup() {
  esp_mqtt_client_config_t mqtt_cfg;
  mqtt_cfg.host = "192.168.0.126";
  mqtt_cfg.port = 1883;
  mqtt_cfg.client_id = "ESP32";
  mqtt_cfg.uri = "HOMEPC";
  mqtt_cfg.event_handle = MQTTEvent;

  esp_mqtt_client_handle_t mqtt_client = esp_mqtt_client_init(&mqtt_cfg);
  esp_mqtt_client_start(mqtt_client);
}

void loop() {

}

... but it fails with:
*invalid conversion from 'void (*)(esp_mqtt_event_t)' to 'mqtt_event_callback_t {aka int (*)(esp_mqtt_event_t*)}' [-fpermissive]*

on line mqtt_cfg.event_handle = MQTTEvent;

I wasn't able to find any example. Could someone please help me with this?

A: The type of your event handle is wrong, it should return an esp_err_t so instead be:
esp_err_t MQTTEvent(esp_mqtt_event_t *event) {
  ...
  return ESP_OK; // you will need to return esp error codes
}

See the definition here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/mqtt.html#_CPPv419esp_mqtt_event_id_t


text:
Q: ReactJS: How to make redux store inaccessible outside the react How can I make the redux store inaccessible outside of react?
Is there any way I can store a value in a private variable throughout the session?

A: store is available only with react component that are connected with the store using connect() hoc and if super parent component in the app wrapped into provider.
no other react component can access the store.

A: Truly inaccessible isn't really possible in Javascript. Code can be minified and obfuscated but ultimately it is all available, however hard to read.
There is an article about hooking up Twitter's redux store to the redux dev tools here. https://medium.com/statuscode/dissecting-twitters-redux-store-d7280b62c6b1

A: Store is a single source of truth and whatever set there will be available in the scope of parent  component but you can restrict to access store data by hooks as below:
Initialize store:
const initialState = {
  user: null,
  permissions: [],
  isAuthenticating: false,
  authError: null,
}

Reducer function:
function reducer(state, action) {
  switch(action.type) {
    case 'AUTH_BEGIN':
      return {
        ...state,
        isAuthenticating: true,
      }

    case 'AUTH_SUCCESS':
      return {
        isAuthenticating: false,
        user: action.user,
        permissions: action.permissions
        authError: null,
      }

    case 'AUTH_FAILURE':
      return {
        isAuthenticating: false,
        user: null,
        permissions: []
        authError: action.error,
      }

    default:
      return state
  }
}

App Component:
function App() {
  const [store, dispatch] = useReducer(initialState)

  return (
    <React.Fragment>
      <Navbar user={store.user} />
      <LoginPage store={store} dispatch={dispatch} />
      <Dashboard />
      <SettingsPage permissions={store.permissions} />
    </React.Fragment>
  )
}

Here you can see store is optional to pass in particular component in above example  component can not access store.


text:
Q: Apache2 certificate with Certbot without DNS I'm trying to setup https with apache2 and certbot. I'm using certbot for create a certificate, but when I'm using it I'm receiving this error:
IMPORTANT NOTES:
- The following errors were reported by the server:

  Domain: www.nowbikesistemi.com
  Type:   dns
  Detail: DNS problem: NXDOMAIN looking up A for
  www.nowbikesistemi.com - check that a DNS record exists for this
  domain; DNS problem: NXDOMAIN looking up AAAA for
  www.nowbikesistemi.com - check that a DNS record exists for this
  domain

This is my 000-default.conf of apache:
<VirtualHost *:80>
    ServerName www.nowbikesistemi.com
    ServerAlias www.nowbikesistemi.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    SSLEngine on
    SSLCertificateFile /etc/apache2/certificate/apache-certificate.crt
    SSLCertificateKeyFile /etc/apache2/certificate/apache.key

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

I don't know how it works on apache2, so anyone can tell me what I'm doing wrong and what I should do?


text:
Q: Pandas Dataframe, average non 0 value I have the following Pandas Dataframe 'df':
a1  a2  a3  b1
0   0   0   1
1   2   0   2
3   0   0   3
2   4   0   4

How do I get the average value of "a" for from a1, a2, a3, ignoring the 0 value?
a1  a2  a3  b1  avg(a)
0   0   0   1   0
1   2   0   2   1.5
3   0   0   3   3.0
2   4   0   4   3.0

I'm stuck with manual approach where I convert the value > 0 to 1

A: You can .filter the a like columns, then .mask the zeros in these columns and take .mean along axis=1:
a = df.filter(like='a')
df['avg'] = a.mask(a.eq(0)).mean(1).fillna(0)

# OR df['avg'] = a[a > 0].mean(1).fillna(0)

   a1  a2  a3  b1  avg
0   0   0   0   1  0.0
1   1   2   0   2  1.5
2   3   0   0   3  3.0
3   2   4   0   4  3.0

A: import pandas as pd

df = pd.DataFrame({'a1': [0, 1, 3, 2],
                   'a2': [0, 2, 0, 4],
                   'a3': [0, 0, 0, 0],
                   'b1': [1, 2, 3, 4]})

# remove the last column
df1 = df.drop('b1', 1)

# counting non-zeros
df2 = df1.astype(bool).sum(axis=1)

# sum and divide
df3 = df1.sum(axis=1) / df2
df['avg(a)'] = df3.fillna(0)
print(df)

   a1  a2  a3  b1  avg(a)
0   0   0   0   1     0.0
1   1   2   0   2     1.5
2   3   0   0   3     3.0
3   2   4   0   4     3.0


text:
Q: PHP Parse error: syntax error, unexpected ';', expecting ')' 'light' => array(
            'label' => __( 'Light Themes from jQuery UI', 'ipt_fsqm' ),
            'themes' => array(
                'default' => array(
                    'label' => 'Default Theme',
                    'src' => array(),
                    'colors' => array( 'f4fcfd', '333333', '3ac7ff', '01a8bd' ),
                ),
                'excite-bike' => array(
                    'label' => 'Excite Bike',
                    'src' => array(
                        'common' => $path . 'excite-bike/form.css',
                        '1.9' => $path . 'excite-bike/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'excite-bike/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'eeeeee', '282828', '2293f7', 'e69700' ),
                ),
                'cupertino' => array(
                    'label' => 'Cupertino',
                    'src' => array(
                        'common' => $path . 'cupertino/form.css',
                        '1.9' => $path . 'cupertino/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'cupertino/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'f2f5f7', '362b36', 'aed0ea', '74b2e2' ),
                ),
                'blitzer' => array(
                    'label' => 'Blitzer',
                    'src' => array(
                        'common' => $path . 'blitzer/form.css',
                        '1.9' => $path . 'blitzer/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'blitzer/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'ffffff', '333333', 'e3a1a1', 'cc0000' ),
                ),
                'black-tie' => array(
                    'label' => 'Black Tie',
                    'src' => array(
                        'common' => $path . 'black-tie/form.css',
                        '1.9' => $path . 'black-tie/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'black-tie/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'f9f9f9', '000000', 'cccccc', '777777' ),
                ),
                'hot-sneaks' => array(
                    'label' => 'Hot Sneaks',
                    'src' => array(
                        'common' => $path . 'hot-sneaks/form.css',
                        '1.9' => $path . 'hot-sneaks/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'hot-sneaks/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'ffffff', '232323', 'ccd232', 'db4865' ),
                ),
                'humanity' => array(
                    'label' => 'Humanity',
                    'src' => array(
                        'common' => $path . 'humanity/form.css',
                        '1.9' => $path . 'humanity/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'humanity/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'f4f0ec', '232323', 'f5ad66', 'd49768', 'cb842e' ),
                ),
                'redmond' => array(
                    'label' => 'Redmond',
                    'src' => array(
                        'common' => $path . 'redmond/form.css',
                        '1.9' => $path . 'redmond/1.9/jquery-ui-1.9.2.custom.min.css',
                        '1.10' => $path . 'redmond/1.10/jquery-ui-1.10.3.custom.min.css',
                    ),
                    'colors' => array( 'fcfdfd', '333333', 'accbe3', '5c9ccc' ),
                ),
                'pepper-grinder' => array(
                    'label'             ),
        'Supermercado_One' => array(
            'label' => "'Supermercado One', cursive",
            'include' => 'Supermercado+One',
        ),
        'Averia_Libre' => array(
            'label' => "'Averia Libre', cursive",
            'include' => 'Averia+Libre',
        ),
        'Croissant_One' => array(
            'label' => "'Croissant One', cursive",
            'include' => 'Croissant+One',
        ),
        'Averia_Gruesa_Libre' => array(
            'label' => "'Averia Gruesa Libre', cursive",
            'include' => 'Averia+Gruesa+Libre',
        ),
        'Overlock' => array(
            'label' => "'Overlock', cursive",
            'include' => 'Overlock',
        ),
        'Lobster_Two' => array(
            'label' => "'Lobster Two', cursive",
            'include' => 'Lobster+Two',
        ),
        'Bevan' => array(
            'label' => "'Bevan', cursive",
            'include' => 'Bevan',
        ),
        'Pompiere' => array(
            'label' => "'Pompiere', cursive",
            'include' => 'Pompiere',
        ),
        'Kelly_Slab' => array(
            'label' => "'Kelly Slab', cursive",
            'include' => 'Kelly+Slab',
        ),
        'Carter_One' => array(
            'label' => "'Carter One', cursive",
            'include' => 'Carter+One',
        ),
        'Inconsolata' => array(
            'label' => "'Inconsolata'",
            'include' => 'Inconsolata',
        ),
        'Ubuntu_Mono' => array(
            'label' => "'Ubuntu Mono'",
            'include' => 'Ubuntu+Mono',
        ),
        'Droid_Sans_Mono' => array(
            'label' => "'Droid Sans Mono'",
            'include' => 'Droid+Sans+Mono',
        ),
        'Source_Code_Pro' => array(
            'label' => "'Source Code Pro'",
            'include' => 'Source+Code+Pro',
        ),
        'Nova_Mono' => array(
            'label' => "'Nova Mono'",
            'include' => 'Nova+Mono',
        ),
        'PT_Mono' => array(
            'label' => "'PT Mono'",
            'include' => 'PT+Mono',
        ),
        'Cutive_Mono' => array(
            'label' => "'Cutive Mono'",
            'include' => 'Cutive+Mono',
        ),
        'Crete_Round' => array(
            'label' => "'Crete Round', serif",
            'include' => 'Crete Round',
        ),
        'EB_Garamond' => array(
            'label' => "'EB Garamond', serif",
            'include' => 'EB+Garamond',
        ),
        'Cardo' => array(
            'label' => "'Cardo', serif",
            'include' => 'Cardo',
        ),
        'Fanwood_Text' => array(
            'label' => "'Fanwood Text', serif",
            'include' => 'Fanwood+Text',
        ),
        'Trocchi' => array(
            'label' => "'Trocchi', serif",
            'include' => 'Trocchi',
        ),
        'Fauna_One' => array(
            'label' => "'Fauna One', serif",
            'include' => 'Fauna+One',
        ),
        'Prata' => array(
            'label' => "'Prata', serif",
            'include' => 'Prata',
        ),
    );

its saying the error is at the last code );
i couldnt find wats going on wrong ..
PHP Parse error:  syntax error, unexpected ';', expecting ')'
on line 1660 which is the last line above..
tyvm whoever can help <3

A: You have a missing ) somewhere in your array. Find it, fix it. Even PHPSTorm says it's missing. My guess, edit the last ); as ), );

A: You are missing 2 ) in the end of array use some php editor like netbean to check your array formation
$array = array(
    'light' => array(
        'label' => __('Light Themes from jQuery UI', 'ipt_fsqm'),
        'themes' => array(
            'default' => array(
                'label' => 'Default Theme',
                'src' => array(),
                'colors' => array('f4fcfd', '333333', '3ac7ff', '01a8bd'),
            ),
            'excite-bike' => array(
                'label' => 'Excite Bike',
                'src' => array(
                    'common' => $path . 'excite-bike/form.css',
                    '1.9' => $path . 'excite-bike/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'excite-bike/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('eeeeee', '282828', '2293f7', 'e69700'),
            ),
            'cupertino' => array(
                'label' => 'Cupertino',
                'src' => array(
                    'common' => $path . 'cupertino/form.css',
                    '1.9' => $path . 'cupertino/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'cupertino/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('f2f5f7', '362b36', 'aed0ea', '74b2e2'),
            ),
            'blitzer' => array(
                'label' => 'Blitzer',
                'src' => array(
                    'common' => $path . 'blitzer/form.css',
                    '1.9' => $path . 'blitzer/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'blitzer/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('ffffff', '333333', 'e3a1a1', 'cc0000'),
            ),
            'black-tie' => array(
                'label' => 'Black Tie',
                'src' => array(
                    'common' => $path . 'black-tie/form.css',
                    '1.9' => $path . 'black-tie/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'black-tie/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('f9f9f9', '000000', 'cccccc', '777777'),
            ),
            'hot-sneaks' => array(
                'label' => 'Hot Sneaks',
                'src' => array(
                    'common' => $path . 'hot-sneaks/form.css',
                    '1.9' => $path . 'hot-sneaks/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'hot-sneaks/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('ffffff', '232323', 'ccd232', 'db4865'),
            ),
            'humanity' => array(
                'label' => 'Humanity',
                'src' => array(
                    'common' => $path . 'humanity/form.css',
                    '1.9' => $path . 'humanity/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'humanity/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('f4f0ec', '232323', 'f5ad66', 'd49768', 'cb842e'),
            ),
            'redmond' => array(
                'label' => 'Redmond',
                'src' => array(
                    'common' => $path . 'redmond/form.css',
                    '1.9' => $path . 'redmond/1.9/jquery-ui-1.9.2.custom.min.css',
                    '1.10' => $path . 'redmond/1.10/jquery-ui-1.10.3.custom.min.css',
                ),
                'colors' => array('fcfdfd', '333333', 'accbe3', '5c9ccc'),
            ),
            'pepper-grinder' => array(
                'label'),
            'Supermercado_One' => array(
                'label' => "'Supermercado One', cursive",
                'include' => 'Supermercado+One',
            ),
            'Averia_Libre' => array(
                'label' => "'Averia Libre', cursive",
                'include' => 'Averia+Libre',
            ),
            'Croissant_One' => array(
                'label' => "'Croissant One', cursive",
                'include' => 'Croissant+One',
            ),
            'Averia_Gruesa_Libre' => array(
                'label' => "'Averia Gruesa Libre', cursive",
                'include' => 'Averia+Gruesa+Libre',
            ),
            'Overlock' => array(
                'label' => "'Overlock', cursive",
                'include' => 'Overlock',
            ),
            'Lobster_Two' => array(
                'label' => "'Lobster Two', cursive",
                'include' => 'Lobster+Two',
            ),
            'Bevan' => array(
                'label' => "'Bevan', cursive",
                'include' => 'Bevan',
            ),
            'Pompiere' => array(
                'label' => "'Pompiere', cursive",
                'include' => 'Pompiere',
            ),
            'Kelly_Slab' => array(
                'label' => "'Kelly Slab', cursive",
                'include' => 'Kelly+Slab',
            ),
            'Carter_One' => array(
                'label' => "'Carter One', cursive",
                'include' => 'Carter+One',
            ),
            'Inconsolata' => array(
                'label' => "'Inconsolata'",
                'include' => 'Inconsolata',
            ),
            'Ubuntu_Mono' => array(
                'label' => "'Ubuntu Mono'",
                'include' => 'Ubuntu+Mono',
            ),
            'Droid_Sans_Mono' => array(
                'label' => "'Droid Sans Mono'",
                'include' => 'Droid+Sans+Mono',
            ),
            'Source_Code_Pro' => array(
                'label' => "'Source Code Pro'",
                'include' => 'Source+Code+Pro',
            ),
            'Nova_Mono' => array(
                'label' => "'Nova Mono'",
                'include' => 'Nova+Mono',
            ),
            'PT_Mono' => array(
                'label' => "'PT Mono'",
                'include' => 'PT+Mono',
            ),
            'Cutive_Mono' => array(
                'label' => "'Cutive Mono'",
                'include' => 'Cutive+Mono',
            ),
            'Crete_Round' => array(
                'label' => "'Crete Round', serif",
                'include' => 'Crete Round',
            ),
            'EB_Garamond' => array(
                'label' => "'EB Garamond', serif",
                'include' => 'EB+Garamond',
            ),
            'Cardo' => array(
                'label' => "'Cardo', serif",
                'include' => 'Cardo',
            ),
            'Fanwood_Text' => array(
                'label' => "'Fanwood Text', serif",
                'include' => 'Fanwood+Text',
            ),
            'Trocchi' => array(
                'label' => "'Trocchi', serif",
                'include' => 'Trocchi',
            ),
            'Fauna_One' => array(
                'label' => "'Fauna One', serif",
                'include' => 'Fauna+One',
            ),
            'Prata' => array(
                'label' => "'Prata', serif",
                'include' => 'Prata',
            ),
        )
    )
);


text:
Q: What mean in the layout description the "$" character conca two components? I have see this character in a View description in the next code...the view is building using 2 custom components but I am looking for a explanation about this:
<view
        class="com.icemobile.staatsloterij.ui.component.CustomCarousel$CustomViewFlipper"
        android:id="@+id/carousel_flipper"
        android:layout_width="275dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
/>

A: CustomViewFlipper is a inner class in CustomCarousel. $ it's the way to reference that class(because the java compiler will generate the name CustomCarusel$CustomViewFlipper for the CustomViewFlipper  class).

A: java static member class
CustomViewFlipper is CustomCarousel's static inner class


text:
Q: What's the best practice for reusing functions on different models in NestJS? I have declared some functions for a MongoDB collection Model A, now I want to create another collection Model B and most of the functions in Model A can be reused for Model B.  Currently, I fall into a situation where I have to repeat myself recreating these functions just for a different model. What's the best practice to reuse these functions on a different model (How to improve my code)? I am using NestJS framework. Example code that I have:
export class Service {
  constructor (
    @inject('ModelA')
    private modelA: Model<IModelA>,
    @inject('ModelB')
    private modelB: Model<IModelB>,
  ){}

 public async findModelA() {
   return await this.modelA.find().exec();
 }

 // How to avoid repeating creating the same functions here?

 public async findModelB() {
   return await this.modelB.find().exect();
 }
}

The repeated functions which are similar to the above example are all over the place. So I really want to get rid of this pain. Thank you in advance for the help!


text:
Q: Error code full_adder.vhd(18): near ")": (vcom-1576) expecting IDENTIFIER I have this error code
full_adder.vhd(18): near ")": (vcom-1576) expecting IDENTIFIER.

I have tried the following and the error still occurs, does anyone have an idea?
LIBRARY IEEE;

USE IEEE.std_logic_1164.ALL;

USE IEEE.numeric_std.ALL;

ENTITY full_adder IS
  PORT (

a_i: in std_logic;

b_i: in std_logic;

c_i: in std_logic;

s_o: out std_logic;

c_o: out std_logic;

);

END full_adder;

ARCHITECTURE calcul OF full_adder IS

signal full_adder: std_logic;

BEGIN

 s_o <= c_i xor a_i xor b_i;

c_o <= c_i and(a_i xor b_i) or (a_i and b_i);

END calcul;

A: The last item in your ports should not have a ';'. The ';' for that port is the one after the close bracket ');'.
port (
  a_i: in std_logic;
  ...
  s_o: out std_logic;
  c_o: out std_logic   -- Do not need ';' here
);                     -- It is here


text:
Q: Java, Selenium, Debian for Raspberry Pi 4, geckodriver error prints garbage Im making a Java program that uses Selenium to access webpages and retrieve data, it works on Windows, pure Debian and Ubuntu but when I run it on my RPI4 with Debian for Raspberry Pi 4, the geckodriver gives cryptic errors and the program crashes.
The errors are as follows:
/usr/local/bin/geckodriver: 2: /usr/local/bin/geckodriver: YM9sHIiHMIi԰: not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: Syntax error: end of file unexpected (expecting ")")
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: 6: not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: : not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: : not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: 6: not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: $/: not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: GNUu¬wת,岹PXH: not found
/usr/local/bin/geckodriver: 1: /usr/local/bin/geckodriver: ELF: not found
Exception in thread "main" org.openqa.selenium.WebDriverException: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:29555
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'raspy', ip: '192.168.1.33', os.name: 'Linux', os.arch: 'aarch64', os.version: '5.9.0-0.bpo.5-arm64', java.version: '11.0.9.1'
Driver info: driver.version: FirefoxDriver
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:92)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:147)
        at net.ddns.creepercrack.Main.main(Main.java:40)
Caused by: java.net.ConnectException: Failed to connect to localhost/0:0:0:0:0:0:0:1:29555
        at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:247)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:165)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at org.openqa.selenium.remote.internal.OkHttpClient.execute(OkHttpClient.java:103)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:105)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
        ... 5 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
        at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
        at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
        at java.base/java.net.Socket.connect(Socket.java:609)
        at okhttp3.internal.platform.Platform.connectSocket(Platform.java:129)
        at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:245)
        ... 27 more

The program also creates this file: ''$'\001\022\002''@@'$'\230\204''y@8'$'\a''@'$'\035\032\001\005''@@t'$'\202''6t'$'\202''6', but I did not program that myself. This does not happen when the program works, only when it crashes.
It may be that it just does not work but I would like to know the answer.
The geckodriver is correcly in the PATH inside the program and is executable
Also, firefox-esr and default-jre.

A: *

*With regard to the "garbage" being printed when using
'gekodriver', perhaps it is because its not meant for the platform
(hardware + operating_system) you are using?

*With regard to

Exception in thread "main" org.openqa.selenium.WebDriverException:
java.net.ConnectException: Failed to connect to
localhost/0:0:0:0:0:0:0:1:29555 Build info: version: 'unknown',
revision: 'unknown', time: 'unknown' System info: host: 'raspy', ip:
'192.168.1.33', os.name: 'Linux', os.arch: 'aarch64', os.version:
'5.9.0-0.bpo.5-arm64', java.version: '11.0.9.1'

That would indicate that there is nothing listening on 29555 on tcp6 ip protocol.
Above are just guesses that you can try looking into until someone better informed comes along.


text:
Q: Need to filter data based on column value in phpmyadmin I need to execute a query based on the column value database record. Here are some current values:

id    column_name
-------------------
5       30
6       39
2       10
1       38
9       54
3       37

If I pass the 39 and 54 it should display output like this:

id    column_name
-------------------
6       39
2       10
1       38
9       54

Query:
select CONVERT(column_name as CHAR(50)) as column_name from table name where CONVERT(column_name as CHAR(50)) >= 39 AND CONVERT(column_name as CHAR(50)) <=38

A: Your query is right but some modifications are needed.
Use like this:
SELECT CONVERT(`column_name`, CHAR(50)) as `column_name` from `table_name` WHERE CONVERT(`column_name`, CHAR(50)) >= 39 AND CONVERT(`column_name`, CHAR(50)) <=54;

For more visit: SQL server convert() and Mysql convert()

A: No where clause logic could bring these lines based on the values 39 and 38.
If a SELECT would always bring these rows in that order than you could start thinking about using:
SELECT.... WHERE...   LIMIT x, 3...


text:
Q: "Interface Locale" admin language problem In my admin page, the "Interface Locale" dropdown is not working. I already switched the default language to German, but is still shows English. The same with Chinese. How can I solve this problem?

A: English is the default if no translation package for the selected language is installed.
Some language packs can be found on Magento Connect:
https://www.magentocommerce.com/magento-connect/customer-experience/internationalization-localization.html


text:
Q: Organic vs Paid traffic in Javascript Is there a way to (in Javascript+jQuery), extract the data of whether a visitor is Paid vs. Organic traffic (or other such metrics)?
For the scope of the question, you can assume that Universal Analytics is running on the landingpage, but I'm limited to console-level Javascript only.
Little background: For a test we want to run, we're looking to target different visitors in different ways in a sort of tag manager-tool. The tool limits us to only using Javascript, so we can not directly use the information from Analytics.
I've seen this question. However, that question appears to be outdated, because (as is written in the comments of the answer), the answer does not work with UA.
This information is available in Analytics, so you'd think they'd be able to retrieve it from somewhere. My question is, could I find this information through Javascript?

A: You can identify the traffic on the landingpage, since with UA paid traffic either needs to have a gclid (a Google click id from Google Adwords) or campaign parameters ("utm parameters", most notably utm_campaign) that identify if this is a paid channel. Then you'd have to store the information via a cookie or localstorage.
Other than that the Universal Analytics tracking code will not reveal anything about the visitor except the client id, which says nothing about paid vs. organic.
For completeness sake: In theory you could store client ids as a custom dimension in GA and use the API to create a service that let's you retrieve information about a given client id via an ajax call, but that would have a certain lag (since GA needs a few hours before it has processed data for a visit), would probably not be very efficient and might have privacy implications that might put you at odds with the Google TOS and national laws.


text:
Q: Progress bar in Shiny using furrr and future I am developing a Shiny app where I split time consuming calculation to multiple session using furrr:: and future. I would like to update the progress bar after every (or every n) calculations. The below example I found updates the progress bar but only once a session has been fully completed. This means that the 6 updates happen almost simultaneously at the end. For the non-Shiny version there is the argument .progress = T which leads to the updates I would like (see second example).
Is there something similar which could be used for a shiny progress bar? It would even be fine if the updates just depend on the first worker since the calculation is almost the same for all workers.
Thanks for any help in advance!
Example 1:
library(shiny)
library(progressr)

app <- shinyApp(
  ui = fluidPage(
    plotOutput("plot")
  ),

  server = function(input, output) {
    output$plot <- renderPlot({
      X <- 1:24
      future::plan(future::multisession(workers = 6))

      withProgressShiny(message = "Calculation in progress",
                        detail = "This may take a while ...", value = 0, {
                          p <- progressor(along = X)
                          y <- furrr::future_map(X, function(x) {
                            Sys.sleep(1)
                            p()
                          })
                        })
      plot(cars)
    })
  }
)

Example 2:
X <- 1:24

future::plan(future::multisession(workers = 6))

y <-
  furrr::future_map(X, function(x) {Sys.sleep(1)
    p()
    }, .progress = T)

future::plan(future::sequential())


text:
Q: html email table element not inline in outlook I have a email template table with another table inside it for a two column width style layout. Problem is that the table is rendering correctly in all but outlook 365. What's weird is that in outlook online it renders out fine. I'm completely stumped and need some help.
Code is:

                                                                                Our Vertical Sliders include

• 10 Day turn around

• 10% off your first order

• 7 Colours from stock

• Timeless Elegance looks

• Built in Security bar

• Made in our Sheffield Factory

                    We match any like for like quote

                      <![if !mso]>
                        Read more

                    <![endif]>

Fiddle is here: https://jsfiddle.net/fsc71og6/


text:
Q: Comparing products using PHP keeping the product on page as cookie I am trying to make a simple product compare system so far what i have made is that i am able to make it like when i click add to compare button i send jquery ajax request and get a call back response , of that product but i don't know how do it keep the product on page or display the items on compare-container as cookies so when users refresh the product is still there on place my code is like ,
COMPARE.PHP

         <?php
    mysql_connect("localhost",'root','GoogleFacebook') or die(mysql_error());
    mysql_select_db('phones') or die(mysql_error());
    $query = mysql_query("SELECT * FROM mobiles");
    while($row = mysql_fetch_array($query)){

         echo "
";
         echo "";
         echo $row['phone_name']."
";
         echo "";
         echo "
";
         echo "";
         echo "<button class='compare'>Compare</button>";
         echo "
";
    }
    ?>

post.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = $_GET['id'];
mysql_connect("localhost",'root','GoogleFacebook') or die(mysql_error());
mysql_select_db('phones') or die(mysql_error());
$query = mysql_query("SELECT * FROM mobiles WHERE id='$id'");
$row = mysql_fetch_array($query);
echo "";
echo "".$row['phone_name']."";}
?>

I got confused how do i keep the contents on the page

A: $.get('post.php?id='+$(this).parent().attr('data-compare-id'),function (data) {
    $('.compare_container').append(data);
},'html');

If you're using jquery, you should be using $() to find your dom elements.  The code above will do an ajax get call to the post.php and fetch your html.  It will pass the result through the function as the data variable and then you append that data to the container.
You have further issues with your code though.  You should be escaping all get tokens to avoid SQL injection and it is a best practice to use mysqli (improved) versus just mysql.  You should also avoid doing SELECT * to avoid using excessive resources on the database--use SELECT phone_img,phone_name instead.
Also upon further review, you're loading jquery 1.11.2 when the latest version is 2+, which is likely causing you problems.


text:
Q: Wordpress Paid user Registration I have some content in my website which I want to show to paid user only.
1.To achieve this I want to register two types of subscribers, default and paid.
2.Default user can register simply using default user registration form.
3.I want to add paid user Registration form, so that I can make get paid user registration.
4.Then I want to make pages visible to only paid user.
5.If user is default subscriber I want to hide paid content from the user. Is there any plugin to register paid user. So that I can make pages visible to paid user only.
I am using wordpress version 3.7
And I know least of php coding.
Any simple approach....

A: You should try Paid Memberships Pro with Flexible content control by Membership Level, Reports, Affiliates and Discounts.
In Which you can Set up unlimited membership levels and provide restricted access to pages, posts, categories, videos, forums, downloads, support, single "a la carte" page access, and more. Paid Memberships Pro is flexible enough to fit the needs of almost all online and offline businesses. It works great out of the box, but is easy for developers to customize to fit your needs.

A: If you want a simple approach a plugin is often the best way forward. I would start with looking at this one. i am not affiliated with this plugin.
http://wordpress.org/plugins/s2member/


text:
Q: Wait for all HTTP requests to finish in XCode UI tests? Is there a way to wait for all network requests to finish when testing UI in XCode?
I have an app that sends HTTP requests to get some data from a server, and, in UI tests, I'd like to wait for this data to be retrieved before continuing. Currently I'm using sleep(1) but this approach doesn't seem reliable.

A: Your best bet is to wait for some UI element to appear or disappear. Think of it this way:

The framework acts like a user. It doesn't care what code is running under the hood. The only thing that matters is what is visible on the screen.

That said, here is how you can wait for a label titled "Go!" to appear in your UI Tests.
let app = XCUIApplication()
let goLabel = self.app.staticTexts["Go!"]
XCTAssertFalse(goLabel.exists)

let exists = NSPredicate(format: "exists == true")
expectationForPredicate(exists, evaluatedWithObject: goLabel, handler: nil)

app.buttons["Ready, set..."].tap()
waitForExpectationsWithTimeout(5, handler: nil)
XCTAssert(goLabel.exists)

You could also extract that into a helper method. If you use some Swift compiler magic you can even get the failure message to occur on the line that called the method.
private fund waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) {
    let existsPredicate = NSPredicate(format: "exists == true")
    expectationForPredicate(existsPredicate, evaluatedWithObject: element, handler: nil)

    waitForExpectationsWithTimeout(5) { (error) -> Void in
        if (error != nil) {
            let message = "Failed to find \(element) after 5 seconds."
            self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
        }
    }
}

A: You can set up your methods with delegates or completion blocks, and in your test cases use a XCTestExpectation which you can fulfill when the data has been returned.


text:
Q: how to get flavor specific information of HLS(cupertino) live streaming using wowza server module api I am working on wowza live streaming analytics module for hls and rtmp streams.
i want to fetch following information from HLS and RTMP type live streaming...

*

*viewer's information

*viewer-end user-agent

*total data streamed to viewer

*total play duration of media

*flavours played during the stream.

i've fetched this data for RTMP live streaming using following listener and classes:

*

*Listener: IMediaStream.addClientListener()

*Notifier: IMediaStreamActionNotify3

*Some wowza's basic server API

i am not aware about the listener to get stream specific information in case of HLS[cupertino] live streaming.
i've achieved following in case of HLS[cupertino] live streaming:

*

*total data transferred to viewer

*user-agent

*viewer's information

and the information that is not achieved yet in HLS live streaming:

*

*total play duration of media

*flavors played during the stream

i've tried a listener HTTPStreamerApplicationContextCupertinoStreamer.addVODActionListener() but it works with VOD type applications only.
Can you please help me on this to achieve it?
Thanks.


text:
Q: how to set icon in edittext in android in API level 15 or 16 <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:drawableLeft="@mipmap/ic_launcher"
        android:hint="Cursor Color changed"
        android:textCursorDrawable="@drawable/cursor"/>

This code work but for API level 17


text:
Q: Увеличить время сессии В массиве _SESSION есть два элемента, так вот можно ли увеличить время жизни для каждого элемента в отдельности (один должен жить долго, второй в зависимости от условия), и как это реализовать, не прибегая к изменениям в php.ini?
A: Как насчет передавать элементы в разных запросах?
A: обернуть элементы в какой нибудь синглтон, рядом хранить время установки элементов, и по get-е элемента, проверять не устарел ли он. Ну естественно максимальное время жизни будет равно максимальному времени сессии.


text:
Q: How do I get divided 6 columns equal 100%? I have a problem with dividing in SQL Server.
I am dividing 100/6.00. And it gives me 16.67, 16.67, 16.67, 16.67, 16.67, 16.67
Which is 100.02 at the end.
Is there a way to divide 100/6.00 and get 16.66, 16.66, 16.67, 16.67, 16.67, 16.67 as a result?
I don't look for solution like iif(final sum>100) then . Is there other way to do this?
Thanks

A: If you want exact division, then the general answer here is to use an exact type, such as NUMERIC or DECIMAL.  Consider:
WITH yourTable AS (
    SELECT CAST(100.0 AS NUMERIC(10, 2)) AS num
)

SELECT num / 6 AS output       -- output is 16.666666
FROM yourTable;

A: ...test
declare @amount decimal(9,4) = 100;
declare @den decimal(9,4) = 6.00;
declare @dp tinyint = 2; --decimal points for rounding

select val as colid,
round(@amount/ceiling(@den), @dp,1) +
case when val <= power(10, @dp) * ((@amount- ceiling(@den) * round(@amount/ceiling(@den), @dp,1))%ceiling(@den)) then power(10.0000000000, -@dp)
else 0.00000 end

from (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) as v(val) --max denominator:10
where val <= ceiling(@den);

A: Can this somehow help you?
DECLARE @counter numeric(5,2)
DECLARE @row int
DECLARE @number numeric(2,1)
SET @counter= 100
SET @number = 6.0
SET @row = 1
while @counter != 0
BEGIN
    select @counter,@number,@row,@counter/@number
    set @counter = @counter - @counter/@number
    set @number = @number - 1
    set @row = @row + 1
END


text:
Q: Comparing two rows at a time in PySpark I am new to Spark, and am looking for help with best practices. I have a large DataFrame, and need feed two rows at a time into a function which compares them.
actual_data is a DataFrame with an id column, and several value columns.
rows_to_compare is a DataFrame with two columns: left_id and right_id.
For each pair in rows_to_compare, I'd like to feed the two corresponding rows from actual_data into a function.
My actual data is quite large (~30GB) and has many columns, so I've reduced it to this simpler example:
import pandas as pd
from pyspark.sql import SQLContext
from pyspark.sql.functions import col
import builtins

sqlContext = SQLContext(sc)
# Build DataFrame of Actual Data
data = {
    'id': [1,2,3,4,5],
    'value': [11,12,13,14,15]}
actual_data_df = sqlContext.createDataFrame(
    pd.DataFrame(data, columns=data.keys()))

# Build DataFrame of Rows To Compare
rows_to_compare = {
    'left_id': [1,2,3,4,5],
    'right_id': [1,1,1,1,1]}
rows_to_compare_df =
    sqlContext.createDataFrame(
        pd.DataFrame(rows_to_compare, columns=rows_to_compare.keys()))

result = (
    rows_to_compare_df
        .join(
            actual_data_df.alias('a'),
            col('left_id') == col('a.id'))
        .join(
            actual_data_df.alias('b'),
            col('right_id') == col('b.id'))
        .withColumn(
            'total',
            builtins.sum(
                [col('a.value'),
                 col('b.value')]))
        .select('a.id', 'b.id', 'total')
        .collect())

This returns the desired output:
[Row(id=2, id=1, total=23), Row(id=5, id=1, total=26), Row(id=4, id=1, total=25), Row(id=1, id=1, total=22), Row(id=3, id=1, total=24)]
When I run this, it seems quite slow, even for this toy problem. Is this the best way of approaching this problem? The clearest alternative approach I can think of is to make each row of my DataFrame contain the values for both rows I'd like to compare. I'm concerned about this approach though since it will involve a tremendous amount of data duplication.
Any help is much appreciated, thank you.


text:
Q: Fix errors in Tarfix.pl to make a tar file from an android adb backup I've backed up my android phone using this adb backup command
./adb backup -f /mnt/tvshows/android/backup2.img -shared -nosystem

I now have a 19GB image, but it won't open with tar. Numerous sites suggest a script called tarfix.pl that can fix the file but when I run it, the output looks like this:
[21:40: Downloads$] perl tarfix.pl /mnt/tvshows/android/backup2.img /mnt/tvshows/android/backup.
Wide character in oct at tarfix.pl line 107.
Illegal binary digit '�������������' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal binary digit '�������������' ignored at tarfix.pl line 107.
Illegal binary digit '\' ignored at tarfix.pl line 107.
Illegal binary digit 'p' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal octal digit '_' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal hexadecimal digit 'Q' ignored at tarfix.pl line 107.
Illegal hexadecimal digit ' ignored at tarfix.pl line 107.
Illegal octal digit '8' ignored at tarfix.pl line 107.
Illegal hexadecimal digit 'v' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal binary digit '' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal binary digit '�������������' ignored at tarfix.pl line 107.
Illegal hexadecimal digit 'Q' ignored at tarfix.pl line 107.
Illegal binary digit 'h' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal hexadecimal digit '&' ignored at tarfix.pl line 107.
Wide character in oct at tarfix.pl line 107.
Illegal hexadecimal digit '�������������' ignored at tarfix.pl line 107.
Illegal binary digit ' ignored at tarfix.pl line 107.
Illegal octal digit '9' ignored at tarfix.pl line 107.

Can someone tell me how to fix this please? The script and details behind it is here and I've pasted it inline below:
#!/usr/bin/perl
#============================================================= -*-perl-*-
#
# tarfix.pl: Fix broken tar files produced by android backup when using
#            -shared flag
#
# USAGE
#   tarfix [<input file>|-] [<output file>|-]
#
# DESCRIPTION
#
#  'adb backup' is buggy and for some combinations of '-shared' with
#   other options it produces an *uncompressed* (despite the
#   compression line being 1) corrupted tar output. The corruption
#   occurs as follows:
#
#   1. The 512-byte header block for each file is preceded by an extra
#      four bytes "00 00 02 00". Note that the 3rd byte '02' is
#      (trivially) twice the number of blocks taken up by the header
#
#   2. The data is divided into groups of 64 512-byte blocks with the
#      final group being as many blocks as needed to fill out the
#      data.  Before each group, 4 bytes are inserted of form "00 00
#      xy 00" where the hex pair xy is equal to twice the number of
#      512-byte blocks in the group. So, if the group is a full 64
#      blocks, then "00 00 80 00" is inserted. Similarly, if there
#      only Z blocks in the group then 'xy' is equal to 2*z in hex.
#
#   Note: Summing the third bytes of all the skips equals two times
#   the total number of blocks in the tar file (headers + data).
#
#   Note: The file ends with a 17-byte string starting with '78 da'
#   which happens to be the magic number used by 'adb backup' for zlib
#   deflate.  When this 17-byte string is inflated, it yields a
#   1024-byte file filled with nulls (00). This 17-byte string is
#   obviously meaningless and is discarded.
#
# AUTHOR
#   Jeffrey J. Kosowsky
#
# COPYRIGHT
#   Copyright (C) 2012 Jeffrey J. Kosowsky
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#========================================================================
#
# Version 0.1, released June 2012
#
#========================================================================
# CHANGELOG
#     0.1 (June 2012)  - Initial version
#========================================================================

use strict;
use warnings;
#use Data::Dumper; #Just for debugging...

#========================================================================
### I/O Setup
my ($in, $out);

my $infile = $ARGV[0];
if(! defined($infile) || $infile eq '-') {
    $in = *STDIN;
}else {
    (open($in, "<:raw", $infile) or
     die "Error: Can't open input file: $infile\n");
}

my $outfile = $ARGV[1];
if(! defined($outfile) || $outfile eq '-') {
    $out = *STDOUT;
}else {
    (open($out, ">:raw", $outfile) or
     die "Error: Can't open output file: $outfile\n");
}

binmode $in;
binmode $out;

#========================================================================
#Skip four bytes "00 00 02 00" before reading each new 512-byte header.
#In a sense, this corresponds to two times the number of header blocks.
while(seek($in, 4, 1) && (my $bytes=read($in, my $header, 512))) {
    if($bytes == 17 && unpack('H4', $header) eq '78da') {
        last; #17-byte (nonsense) trailer at end of backup file
    }elsif($bytes < 512) {
        die "Error: Unknown data at end of tar file...\n";
    }

    #Note: number of data bytes in the file is an 11 digit octal
    #string starting at position 124 in the header. The data is
    #divided into 512-byte blocks.
    my $blocks = int((oct(substr($header, 124, 11)) + 511)/512);

    print $out $header; #Print header

    for(my $i=1; $i <= $blocks; $i++) { #Print data
        seek($in, 4, 1) unless ($i-1)%64;
        #Skip 4 bytes at the beginning of every group of 64 blocks of
        #data.  Note we are skipping 00 00 xy 00 00 where xy is equal
        #to two times the number of blocks following before either the
        #next group of 64 blocks (i.e. 80 = 128 or 2 times 64 blocks)
        #or the end of the data section.
        #Hence the sum of all the 3rd bytes for all the skips is equal
        #to twice the total number of blocks.

        read($in, my $data, 512) or
            die "Error: Can't read next block of data...\n";
        print $out $data;
    }
}

A: So, I had the same problem and figured out how to extract the files, so at least it's a start.
I used HxD, the freeware hex editor, to modify/split the original image file. Based on my understanding of how adb makes the image, it looks like it backs up "shared" last. The bug was that this part wasn't encrypted. So, what you essentially have to do here is to find the point in the original image file in the hex editor where the encrypted portion ends, and the "plain text" unencrypted (shared) portion begins.
To do this, I searched for the first instance of the word "shared". This brought me right to this junction. Just preceding this you should see 00 00 02 00 hex values. You need to split the file selecting just prior to this. Selecting directly to the left of 00 00 02 00, Ctrl-Shift-Home to select to the very top of the file, then delete. This will leave you with just the unencrypted part of the file. You save this as a differently named file. Now you can run the tarfix.pl line on this file (no need for the backupdecrypt script), which will extract the shared portion of the image. You'll get an error at the very end, but my experience was that everything there extracted properly.
Next, you have to go in to the original file again and highlight and delete 00 00 02 00 all the way down to the end of the file (Ctrl-Shift-End), and save this as a differently named file (leaving you this time with the encrypted part of the image.) On this, you can now run the backupdecrypt script (no need for the tarfix script). This will produce a tar file that you can extract using 7-zip.
FYI, I did get some errors at the end of running the backupdecrypt script, as well as when extracting the tar file with 7-zip, but all the files seemed to extract fine.
The scripts, as well as this explanation that I've just provided, and more details can be found in the scripts' original thread here: http://forum.xda-developers.com/showthread.php?t=1730309
I'm sure there's a cleaner way to do all of this to avoid the errors and such, and even a way to put the image all back together, but I just wanted to go ahead and get the rough method out there so that we can get the ball rolling on a complete solution.


text:
Q: CTRL+V @ wiki to trigger image upload from clipboard
*

*Can I upload an image to a document library using javascript?

*Can I use that information together with, for example, clipboardData?
https://stackoverflow.com/questions/6333814/how-does-the-paste-image-from-clipboard-functionality-work-in-gmail-and-google-c
The solution does not have to be cross-browser (it's enough if it only works in Chrome, for example)
What I'm aiming at is that a content manager could paste a screenshot to a SharePoint wiki page using CTRL+V, javascript would notice the event, show a dialog asking for the file name, and when user has entered the filename read the file from clipboard, upload it to the default document library (specified somewhere) and create an img tag pointing to the file. From now on the user could interact with the image using oob SharePoint.
An example of pasting a screenshot to a html page using Chrome is here: http://strd6.com/2011/09/html5-javascript-pasting-image-data-in-chrome/ (just paste a screenshot to that page).
Would there be some problems preventing this? (like, do SharePoint file upload APIs support the file formats clipboardData provides, or would there be some other showstoppers?)


text:
Q: Javascript/jQuery tree renderer I need some help in choosing a "tree renderer" similar to jsTree. Since my requirements might be a little different, I would like to ask you to recommend a (preferably jQuery based) plugin for me.
I am trying to (re) write an organization browser, which shows who reports to who etc. The catch is that my server can only throw back JSON (or whatever format) one time to the client. That is, on page load, my HTML would have a JSON map containing about 2000 employees, and jsTree/whatever-solution-you-recommend, would render this as a tree.
By one-time, I mean that the client JS cannot repeatedly / progressively ask the server for more data in an AJAX-y fashion. (This is due to some complexities at the server side).
Do you think jsTree is fit for this? I don't want the entire user experience to become sluggish with a 1500-2000 employee org-chart (2000 is the limit here).
Any pointers would help, thanks!

A: you can try jQuery plugin
Plugins/Treeview/treeview
http://docs.jquery.com/Plugins/Treeview/treeview


text:
Q: How to divide by infinite series? Suppose you face the following problem:
You have to give scholarships to 10 students and to determine which students will get the scholarship, you have the following rating system:
Published a scientific paper - 2 points
Participated as an active speaker on a conference - 1 point
Volounteer - 0.5 points
Participated in a state competition in his/her field of study - 3 points
Participated in an international competition in his/her field of study - 5 points
The number of collected points + GPA = the total number of the student's points. Ten students who collected the most points will get the scholarship. The maximum number of points is 16.5.
However, now you face another problem: some studies don't have state or international competitions. Therefore, it is possible that the students of those studies would be discriminated against as they have a smaller chance of getting this scholarship. To solve this problem you could calculate the number of points each student collected and divide it with the maximum number of point he/she could have collected - 16.5 for studies in which there is a state/international competition and 8.5 for studies in which there is no state/international competition.
But how would you solve this problem if students can go to more than 1 competition, publish more than one scientific paper and participate in more than one conference? The maximum number of points that a student can collect is actually infinite and to solve the problem as mentioned above you would actually have to divide by infinite series. How would you go on in solving this problem?


text:
Q: Django accumulating data before storing to DB In my django website I need a tracker, which measuses how long a user performed particular activity each day.
For this purpose, browser sends an ajax request to server every 30 seconds while the user is performing his activity. So when recieving this request, the server increments user activity counter by 30 seconds. These counters are stored in the database.
I thought it would be quite inefficient to update data in the database every 30 seconds for every website user.  So my idea was to accumulate all tracked time in a global dictionary of {user_id: seconds}. So when the ajax activity request is recieved I could just find the user_id in the dictionary and increase corresponding seconds value.
Then this dictionary could be flushed to the database every 10 minutes.
I relalise that this scheme is not super reilable, and if server crashes I will lose up to last 10 minutes of activity for all users, and I'm ok with that.
What bothers me is:

*

*As far as I understand, django running with gunicorn can have many worker processes, so I won't be able to have a global dictionary. I can't be even sure that the same user will always by handled by the same process.

*I'd like to flush the dictionary to the database when the worker process is about to be stopped, which doesn't seem to be a trivial task.
Two above problems and the lack of obvious solution look like a hint that I'm doing something wrong.
Maybe I'm overoptimizing things and it's ok to store to the database every 30 seconds for each user, or maybe there is a better well-known practice to cache stuff in memory before submitting it to the database, which I'm missing?
Could someone guide me to the right direction, please?