text:
Q: Average Distances From The Origin
Consider all points $(m,n)$ where $m$ and $n$ are natural numbers,
  $m\leq10$, and $n\leq5$. What is the average distances from each point
  to the origin $(0,0)$?

I know how to find the distance $d$ between the points $(x_1,y_1)$ and $(x_2,y_2)$;
$d=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$.
In this case, the first point is $(m,n)$ and the second point is the origin, therefore the distance, $d=\sqrt{m^2+n^2}$.
It is annoying to find all distances, summing them, and dividing them by the number of distances, is not it annoying?
What if the given conditions, $m\leq10$ and $n\leq5$, were changed to $m\leq49$ and $n\leq36$?!

A: There is a quick solution for a related problem, even though it's not quite what you are asking. If you are willing to compute squares of distances of all points, then you get
$$
\begin{split}
f(m,n)
 &= \sum_{i=1}^m \sum_{k=1}^n \left(i^2 + k^2\right) \\
 &= \sum_{i=1}^m \sum_{k=1}^n i^2 + \sum_{i=1}^m \sum_{k=1}^n k^2 \\
 &= n \sum_{i=1}^m i^2 + m \sum_{k=1}^n k^2 \\
 &= n \frac{m(m+1)(2m+1)}{6} + m \frac{n(n+1)(2n+1)}{6} \\
 &= \frac{mn}{6} \left[(m+1)(2m+1) + (n+1)(2n+1)\right]
\end{split}
$$
As expected, $f(m,n)$ is symmetric in $m,n$, in other words, $f(m,n) = f(n,m)$...


text:
Q: For Soap NSURLConnection, Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required I've submitted my app in AppStore, they reject if due to following reason.
Hello,

        Thank you for providing this information. Upon further review, we were still unable to login to the app.

        Please note that apps are reviewed on an IPv6 network. Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required.

        For information about supporting IPv6 Networks, refer to Supporting iPv6 DNS64/NAT64 Networks.

        For a networking overview, please see About Networking.

        Best regards,

        App Store Review

I am using SOAP Envelope service to use it,
Here is my code
@property(retain,nonatomic)NSString *xmlString;

@property(nonatomic,retain)NSMutableData *webResponseData;

-(void)method_GetUpcomingLotteries
{

    NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                             "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"urn:Lottery.Intf-ILottery\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:enc=\"http://www.w3.org/2003/05/soap-encoding\">\n"
                             "<env:Body>\n"
                             "<ns1:GetUpcomingLotteries env:encodingStyle=\"http://www.w3.org/2003/05/soap-encoding\">\n"
                             "<EntityID xsi:type=\"xsd:int\">2</EntityID>\n"
                             "<Password xsi:type=\"xsd:string\">Smart@Winners</Password>\n"
                             "<SortBy xsi:type=\"xsd:int\">0</SortBy>\n"
                             "<limit xsi:type=\"xsd:int\">0</limit>\n"
                             "</ns1:GetUpcomingLotteries>\n"
                             "</env:Body>\n"
                             "</env:Envelope>"];

    NSURL *sRequestURL = [NSURL URLWithString:@"http://isapi.mekashron.com/soapclient/soapclient.php?"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:sRequestURL];
    NSString *sMessageLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue: @"urn:Lottery.Intf-ILottery/GetUpcomingLotteries" forHTTPHeaderField:@"SOAPAction"];
    [request addValue: sMessageLength forHTTPHeaderField:@"Content-Length"];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSLog(@"soapMessage===\n %@",soapMessage);

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if( theConnection ) {
        NSLog(@"hiii");
        self.webResponseData = [NSMutableData data];
    }else {
        NSLog(@"Some error occurred in Connection");

    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Received Bytes from server: %lu", (unsigned long)[self.webResponseData length]);

    NSString * strXml = [[NSString alloc] initWithBytes: [self.webResponseData mutableBytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding];

    NSLog(@"---- %@" ,strXml);

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    [self.webResponseData  setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.webResponseData  appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Some error in your Connection. Please try again.");

}

My question :
1) Please tell me do I need to change my method or I've to change the server end to transfer my API from IPv4 to IPv6 ?
2) Code for IpV6 using SOAP method under ios9 that work replacing NSURLConnection

A: At WWDC 2015, apple announced the transition to IPV6-only network services in iOS 9. Now from June 1, 2016 apple has made mandatory that the app should support iPV6.
If developers use the standard networking APIs like NSURLSession and CFNetwork APIs provided by apple, they should not experience any problem. Otherwise you will have to move your code to the APIs that support IPV6.
If you are looking for to use some standard network library like AFNetworking. According to this site AFNetworking 3.0 support IPV6.
Apple has a documentation on how to test IPV6 support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MUTUAL AUTHENTICATION failed in EMV card I am trying to send a STORE DATA command to my EMV card to store DGI values. I've got a document that describes the APDU command to install and personalize EMV application on JCOP 2.4.1 Revision 3.
In the document, the sequence of commands is:
SELECT
INITIALIZE UPDATE
EXTERNAL AUTHENTICATION
STORE DATA FOR DGI
...
...
STORE DATA FOR DGI.

Line written in this Document is:

the key value of issuer security domain(encryption, MAC,and key encryption key): 404142434445464748494a4b4c4d4e4f. and the value of sequence counter is 0.

I just downloaded GPSHELL 1.4.4 and try to run following script:-
mode_211
enable_trace
establish_context
card_connect
select -AID A000000003000000
open_sc -security 1 -keyind 0 -keyver 0 -mac_key 404142434445464748494a4b4c4d4e4f -enc_key 404142434445464748494a4b4c4d4e4f // Open secure channel
card_disconnect
release_context

however my output is:
D:\users\Amitp\My Documents\Downloads\GPShell-1.4.4\GPShell-1.4.4>GPShell.exe he
lloInstalll.txt
mode_211
enable_trace
establish_context
card_connect
select -AID A000000003000000
Command --> 00A4040008A000000003000000
Wrapped command --> 00A4040008A000000003000000
Response <-- 6F658408A000000003000000A5599F6501FF9F6E06479100783300734A06072A864
886FC6B01600C060A2A864886FC6B02020101630906072A864886FC6B03640B06092A864886FC6B0
40215650B06092B8510864864020103660C060A2B060104012A026E01029000
open_sc -security 1 -keyind 0 -keyver 0 -mac_key 404142434445464748494a4b4c4d4e4
f -enc_key 404142434445464748494a4b4c4d4e4f // Open secure channel
Command --> 80CA006600
Wrapped command --> 80CA006600
Response <-- 664C734A06072A864886FC6B01600C060A2A864886FC6B02020101630906072A864
886FC6B03640B06092A864886FC6B040215650B06092B8510864864020103660C060A2B060104012
A026E01029000
Command --> 8050000008FB3EE9FE0812ABFF00
Wrapped command --> 8050000008FB3EE9FE0812ABFF00
Response <-- 0000322000186396921901020000CEBCF3A2D47130C736B6480E4DD59000
mutual_authentication() returns 0x80302000 (The verification of the card cryptog
ram failed.)

Why does the authentication fail? To send the STORE command I need to passed authentication. How can I pass authentication?

A: Usually the 40..4F keys are used for sample cards. If you receive other cards you need to request the keys from the supplier (possibly NXP). If the default key is present it usually has index 255 (instead of 1, which is the first key found), so you could try -keyind 255 in your open_sc command.


text:
Q: Shortcut to the @name feature? When leaving comments to comments, it feels rather random to type in people's names. Is there a way to automatically insert a user's name?
ETA Like I mentioned to @Code in the comments, "random" means this:
I mean that it feels like I could make typos, I need to figure out if people are called "argnfrllg" or "argfnrllg" or "argnfllrg", which I don't want to do. I don't care about their names, but SO is making me. I need to flick my eyes from the text I entered to the name in the comment box. Is that "marig" or "mariq"??
EDIT: Should this be marked as "implemented" now, since there is a tab-completion  feature of user names to the comment field?

A: It's quite unlikely that this will ever be implemented as an official feature of the site.
But there's already a user script that provides such functionality. If you're interested in this sort of thing and the additional clutter doesn't bother you, consider installing it.

A: A few guidelines:

*

*@name is not required, ever, when talking to the post owner. The post owner is always notified of every single comment on their post no matter what, in all circumstances, forever and ever amen.

*@name is optional in the case when the post owner is entering a comment after another person. That is:

question -- User A
comment (User B): why didn't you frozz the bimblee?
comment (User A): I tried frozzing the bimblee but then my nachos reticulated.

Here, B would be notified of A's comment even without @username because it can be reliably inferred. Obviously the post owner, User A, is not talking to him/herself here...

*You only need to enter the first 3 characters of a name for a valid match to a previous commenter username, so when replying to Oguers Ancewwa you do NOT need to type @oguersancewwa -- just type @ogu or @oguers

A: On SE sites there isn't a button to reply to another comment; there is a button to add a comment, but the comment could be a comment to the post.
As there isn't a button to reply to another comment, it is difficult to know which text should be used to pre-fill the comment.
The feature seems going in the opposite direction of the recent changes that remove the @-reference when not required.


text:
Q: DRY code to implement action listener (JAVA) I'm now implementing a tray game, in which i use some JButton to represent the tray. But the tray makes 7x7, so to implement the action listener it's not so fun. I have a code like this now :
public void actionPerformed(ActionEvent ae)
    {
        if (ae.getSource() == Bouton11)
            {
                this.PosePion(1, 1, Bouton11);
            }
            else if (ae.getSource() == Bouton21)
            {
                this.PosePion(2, 1, Bouton21);
            }
            else if (ae.getSource() == Bouton31)
            {
                this.PosePion(3, 1, Bouton31);
            }
            ......
    }

How can i reduce this sort of code please ? :/
Thank you :)

A: Place your JButtons in a 2D, 7x7 array when they are created.
Then in the listener method, loop through the array to determine which JButton was clicked.  Your looping indexes will help you determine what to pass to PosePion.

A: Make your own listener type. Your type should implement ActionListener (and thus the actionPerformed method), and be constructed with three parameters: the button and the two integers. The reason why you need these three parameters is so that you can pass them to the PosePion method (which should be capitalized posePion, by the way).
For example:
class PoseActionListener implements ActionListener {

    private JButton button;
    private int a, b;

    public PoseActionListener(JButton btn, int a, int b) {
        this.button = btn;
        this.a = a;
        this.b = b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        posePion(a, b, btn);
    }
}

Then:
button11.addActionListener(new PoseActionListener(button11, 1, 1);
button12.addActionListener(new PoseActionListener(button12, 1, 2);

Or, even better, create all buttons at once:
for (int i=1; i<=7; i++) {
    for (int j=1; j<=7; j++) {
        JButton btn = new JButton("Button " + i + ", " + j);
        // store the button in an array if you want
        btn.addActionListener(new PoseActionListener(btn, i, j);
    }
}

A: I would suggest that you learn the Sun Java coding conventions.  Your code is hard to read.
I would consider having an individual ActionListener for each instance rather than one for all.
I'd also recommend a data structure and Command implementation to cut down on the mindless repetition.


text:
Q: Django with Microsoft API 365 - Service Discovery error I'm trying to make a Django application that can autheticate users with Microsoft 365 accounts, and I found this project on Github: https://github.com/jasonjoh/pythoncontacts
I followed the documentation and I get to the point where I'm prompted to the Microsoft account log-in page, where I give consent to the Azure AD app.
After reading the code, I understand that the Django app is trying to get the services available at: https://api.office.com/discovery/v1.0/me/services
The problem is that the link is giving me this error:
{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":"Access denied. You do not have permission to perform this action or access this resource."}}

I don't know if this problem is due to the Azure AD app permissions or due to the code.
Is my understanding that the Django app is asking the Azure AD Authorization Endpoint to log-in. This endpoint is returning the Sign-in window, and after the authentication I get the authorization code. With it, I should redeem the authorization code and acquire an access token at the Azure AD Token Endpoint, to be able to call the Office 365 API with it.
This are the permissions my app has in Azure AD

A: You need to add in the Permissions to other applications the following: "Office 365 Exchange Online".
If you don't see it, make sure you have a paid subscription in Azure and in Office 365. If you have only a subscription in Azure, you will see the "Default Directory" that won't show you the application named above.
Hope it helps :)

A: rGonzalez is correct.  The code sample uses the Office 365 APIs that are in production before Office 365 Unified API was announced (in public preview).  You have 2 options:
- Option #1 (recommended): Use Office 365 Unified APIs.  You will need to modify your app to skip the step to call Discovery APIs, and instead call the endpoint https://graph.microsoft.com/beta. See here for API docs.
- Option #2: Get an Exchange subscription for your Office 365 tenant, so you see Office 365 Exchange Online listed as an option in your app registration page, and select "Read and write user calendars", "Send mail as a user", and "Read and write user mail" as permissions for your app.
Also, in the screenshot you attached, you don't "Read user calendars" and "Read user mail" permissions for your app, as they are already included in "Have full access to user calendars" and "Read and write access to user mail" permissions respectively.

A: To access the discovery service you need to get a token with resource=https://api.office.com/discovery/
Now, if you are using the new Office 365 unified API there is no need for using the discovery service as all the information is served from a single endpoint https://graph.microsoft.com
hope that helps


text:
Q: data not shown in my JTable The scrollbar and the button will be painted but not the cells in the table,and the console has printed the data correctly so I am wondering where I have done wrong.
public class MyGUIManager extends JPanel {

    protected JFrame frame;
    protected JScrollPane scrollPane=null;
    protected JTable table=null;
    protected TableModel model=null;
    protected JButton btnInsert=null;

    protected String dbname,tblname;
    protected Vector<String> colNames;
    protected Vector<Vector<String>> data,backup;
    protected int col;

    protected MySQLGUIManager() throws Exception{

        frame =new JFrame("MySQL Manager");
        frame.setContentPane(this);
        frame.setMinimumSize(new Dimension(800,600));
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        init();
    }

    protected void init() throws Exception{
        //some inrrelevant operations about database
        loadTbl();
    }

    protected void loadTbl() throws SQLException{
        table=new JTable(data,colNames){
            private static final long serialVersionUID = 1L;
            public void tableChanged(TableModelEvent e){
                int column=e.getColumn();
                assert e.getFirstRow()==e.getLastRow():"more than 1 row have been changed!";
                int row=e.getFirstRow();
                if(scrollPane!=null){
                    //some codes
                }
            }
        };

        model=table.getModel();
        scrollPane=new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(scrollPane,BorderLayout.CENTER);
        btnInsert=new JButton("Insert a row");
        add(btnInsert,BorderLayout.SOUTH);
        repaint();
        revalidate();
//      scrollPane.repaint();
//      scrollPane.revalidate();
        System.out.println(model.getColumnCount()+" "+model.getRowCount());
        for(int i=0;i<data.size();i++){
            for(int j=0;j<data.get(0).size();j++){
                System.out.print(model.getValueAt(i, j)+" ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) throws Exception {
        new MySQLGUIManager();
    }

}

(Some codes are omitted but they have nothing to do with GUI.)
Thanks in advance!

A: I don't see anywhere in the code where you actually add the table to any of the UI's existing containers.
Also, it's probably a good idea to create the table and add it to it's intended parent component before calling pack().
You might want to think about separating the creation of the table from loading the data.
Also, the omitted "some codes" may have have a very large effect on the behavior of the table, so be careful there.

A: Ok...here is an example how to fill your table using DefaultTableModel model because your pseudo SSCCE is useless:
package com.model.impl;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class FillTable extends JFrame{

    JPanel panel = new JPanel();
    JLabel lblName = new JLabel("Name: ");
    JLabel lblIp = new JLabel("Ip: ");
    JTextField txtName = new JTextField(10);
    JTextField txtIp = new JTextField(10);
    JButton btnAdd = new JButton("Add");
    JTable table = new JTable();
    DefaultTableModel model = new DefaultTableModel(new Object[][]{}, new String[]{"Name","Ip"});

    public FillTable(){
        super("Test table");
        setLayout(new BorderLayout());
        add(panel,BorderLayout.NORTH);
        panel.add(lblName);
        panel.add(txtName);
        panel.add(lblIp);
        panel.add(txtIp);
        panel.add(btnAdd);
        table.setModel(model);
        add(new JScrollPane(table),BorderLayout.CENTER);

        btnAdd.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String name = txtName.getText();
                String ip = txtIp.getText();

                model.addRow(new Object[]{name,ip});
            }});
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                FillTable ft = new FillTable();
                ft.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                ft.setLocationByPlatform(true);
                ft.pack();
                ft.setVisible(true);
            }});
    }
}

I hope it will help. Good luck!

A: *

*Nothing is added to the data/column models

*The data and column models are uninitialized

*Creating a JFrame from within a JPanel only to add itself to the frame is bad practice

You're not call super.tableChanged from within you tableChanged method
table = new JTable(data, colNames) {
    private static final long serialVersionUID = 1L;

    public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        int column = e.getColumn();
        assert e.getFirstRow() == e.getLastRow() : "more than 1 row have been changed!";
        int row = e.getFirstRow();
        if (scrollPane != null) {
            //some codes
        }
    }
};


text:
Q: I have issue while automating Odoo application i am automating Odoo pos application. but while adding product to the cart, i got error like "Element is not clickable at point (659,166)". i have already created 1 item and trying to add that in cart but element is not found. need help.
      package odoo1;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

public class odoo {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);

        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

        // for Log in functionality
        driver.get("https://www.odoo.com/trial?selected_app=point_of_sale");
        driver.findElement(By.id("username")).sendKeys("mark");
        driver.findElement(By.id("email")).sendKeys("mark@gmail.com");
        driver.findElement(By.id("company-name")).sendKeys("odooo");
        driver.findElement(By.id("phone")).sendKeys("561234897");
        driver.findElement(By.id("country-id")).sendKeys("India");
        driver.findElement(By.name("lang")).sendKeys("English");
        Select sell=new Select(driver.findElement(By.name("company_size")));
        sell.selectByIndex(2);;
        Select sell1=new Select(driver.findElement(By.id("plan")));
        sell1.selectByIndex(2);
        driver.findElement(By.xpath(".//*[@id='wrapwrap']/main/div/div/div[2]/div[2]/div/form/input[8]")).click();

        // for creating product

    driver.findElement(By.xpath("html/body/div[3]/div[3]/div[1]/a[2]/div[2]")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/a")).click();
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[2]/ul/li[3]/a/span")).click();
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/button")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).sendKeys("iphone");
    driver.findElement(By.xpath(".//*[@id='o_field_input_4']")).click();
    driver.findElement(By.xpath(".//*[@id='o_field_input_13']")).sendKeys("abcd");
    driver.findElement(By.xpath(".//*[@id='o_field_input_14']")).sendKeys("123456");
    driver.findElement(By.xpath(".//*[@id='o_field_input_15']"));
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_16']")).sendKeys("25000");
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).clear();
    driver.findElement(By.xpath(".//*[@id='o_field_input_20']")).sendKeys("25000");
    Thread.sleep(1000);
    driver.findElement(By.xpath("html/body/div[3]/div[2]/div[1]/div/div[2]/button[1]")).click();

    Thread.sleep(900);
    driver.findElement(By.xpath("html/body/nav/div/ul[1]/li[1]/a/span")).click();

    driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/div[2]/div/div[1]/button")).click();
    Thread.sleep(500);
    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]")).click();

    Thread.sleep(700);
    driver.findElement(By.xpath("//button")).click();

    Thread.sleep(5000);

    driver.findElement(By.xpath("html/body/div[1]/div[2]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[2]/td/div/div/div/div/span[2]/div[1]/img")).click();

   }

    }

A: By looking at the exception, it looks like the right path is not selected.
I have just checked the website which you are trying to automate.
Steps I have followed:

*

*Click on Open Cart tab.

*Select Shipping option.

*Click on Add to Cart for the product which you want to add in your path.

Xpath Used for Add To Cart button:
//h3[normalize-space()="Opencart Marketplace"]/../div[3]//button
I have selected the product "Opencart Marketplace". You can select any product you want. Just replace Opencart Marketplace with the product which you want to select.
Code:
System.setProperty("webdriver.gecko.driver", "src/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("https://store.webkul.com/OpenCart-Modules.html");
Thread.sleep(2);
driver.findElement(By.xpath("//h3[normalize-space()='Opencart Marketplace']/../div[3]//button")).click();
driver.findElement(By.xpath("//div[@class='product_cart_container']/button")).click();


text:
Q: É possível juntar o OwlCarousel ao Highcharts? Eu tenho um slider feito pelo OwlCarousel quero que passem gráficos de pizza renderizados pelo HighCharts. Ou seja, Eu tenho 4 pie charts Com legendas, e quero que ao passar os 4 pies, fiquem também sem a legenda apenas em Mobile.
fiddle: http://jsfiddle.net/pedropcruz/0hv2cjjz/23/

A: Sim, é possível, você já esta trabalhando com div's, basta coloca-las todas dentro de uma outra div e adicionar as class que criam esse efeito....
USANDO O FLICKITY

    ...

E claro, carregar as bibliotecas necessárias e adicionar a seguinte linha no seu arquivo .js:
$('.main-gallery').flickity({
  cellAlign: 'left',
  contain: true
});

jsFiddle do exemplo usando o flickity
USANDO O OWLCAROUSEL

    ...

Carregar as bibliotecas: Theme.css, carousel.css, carousel.js necessárias e adicionar a seguinte linha no seu arquivo .js:
$(document).ready(function() {
  $("#owl-example").owlCarousel();
});

jsFiddle do exemplo usando o OwlCarousel


text:
Q: C# user control needs access to external cs file in end application I'm somewhat of a beginner to C# and I am developing some user controls that will get used in several different applications with different implementations. What I want to do is include the implementation specific items in a file, call it Implementation.cs and then have a user control compiled into control.dll. Implementation.cs will contain static methods that control.dll will use, such as "int GetValue(string tag)" or something like that.
The end application will reference both control.dll and Implementation.cs So my question is, how do I tell the code in control.dll that there is a method of "int GetValue(string tag)" since GetValue() lives in Implementation.cs ? I tried the extern keyword, but it seems to want the dllimport specifier which I don't want since I'm not using a separate dll file for the implementation.
I'd be happy to look for more information myself but I'm having trouble even getting the right keywords to do a search.

A: If I understand correctly your question then, you will find the following resources valuable:

*

*Abstract class

*Interface

*Dependency injection


text:
Q: dplyr filter with multiple conditions and OR I have a large tibble that I need to reduce by filtering. Specifically I need to filter different combinations of multiple conditions (but all from the same columns).
My filter condition are something like
  filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400))
 filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))

What of course works is something like
filtered1<- df %>%
  filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400))
filtered2<- df %>%
  filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))
filtered<-bind_rows(filtered1, filtered2)

I'm wondering how I would combine these with some sort of OR statement like
  filtered<- df %>%
    filter(str_detect(id, "^M.+(KIT|FLEECE)"), between(f1, 300, 400),  between(f2, 1300, 1400)) OR
    filter(str_detect(id, "^M.+(GOOSE)"), between(f1, 200, 350),  between(f2, 1200, 1400))

Here is an MWE of some sample data
id<-rep(c("M1_1_KIT_1", "M3_2_FLEECE_2", "M2_4_GOOSE_3", "M6_4_KIT_5"), 3)
f1<-sample(200:500, 12)
f2<-sample(1200:1500, 12)
df<-data.frame(id, f1, f2)
df

          id  f1   f2
1     M1_KIT 268 1238
2  M3_FLEECE 270 1459
3   M2_GOOSE 409 1471
4     M4_KIT 344 1337
5     M1_KIT 400 1419
6  M3_FLEECE 210 1379
7   M2_GOOSE 321 1356
8     M4_KIT 478 1284
9     M1_KIT 391 1439
10 M3_FLEECE 382 1317
11  M2_GOOSE 468 1273
12    M4_KIT 306 1270

I would be even more happy for a more general solution, like where I put the filter values into a separate tibble and iterate over the rows, but that is beyond my R knowledge.

A: You can put them in parentheses using & and then use the pipe | to mean "or"
df %>%
  filter(
    (str_detect(id, "^M.+(KIT|FLEECE)") & between(f1, 300, 400) & between(f2, 1300, 1400)) |
    (str_detect(id, "^M.+(GOOSE)") & between(f1, 200, 350) & between(f2, 1200, 1400))
  )


text:
Q: Does the set of ideals, whose Jacobson radical & nilradicals coincide, form a lattice? Let $R$ be a commutative ring and $L(R)$ denote the lattice of ideals of $R$. Let $\mathcal{S}\subseteq L(R)$ be the set of all ideals whose Jacobson radicals and nilradicals coincide.
Question: For which classes of rings $\mathcal{S}$ is a sublattice (respectively, $\sigma$-complete or complete sublattice) ?
For example, $\mathcal{S}=L(R)$ iff $R$ is a Hilbert-Jacobson ring, so $\mathcal{S}$ is trivially a complete lattice.

Bits: 1. Let $I,J\in\mathcal{S}$. It is well known that $rad(I\cap J) = rad(I)\cap rad(J)$ and $rad(rad(I)+rad(J)) = rad(I+J)$ for both radicals. Thus, $I\wedge J\in\mathcal{S}$ for any ring, but $I\vee J = I+J$ may not be in $\mathcal{S}$ in general.
2.Within $\mathcal{S}$, we could define $I\vee_S J$ as the smallest ideal in $\mathcal{S}$ containing $I+J$. However, we do not know if such an ideal exists for a given pair of ideals $I,J$. For what classes of rings $I\vee_S J$ exists for any $I,J\in\mathcal{S}$?
3.Let $I\subseteq R$ be a semiprimitive ideal, then $I\in\mathcal{S}$. The intersection $J=\bigcap_{n=1}^{\infty} I^n$ is not in $\mathcal{S}$ in general. It would be great to know a condition equivalent to $J\in\mathcal{S}$ whenever $I\in\mathcal{S}$ is semiprimitive.


text:
Q: Java 8 - Static Method Reference Rule I have the following piece of code:
public class Chap20 {

    public static void main(String[] args) {
        String[] names = { "John", "Jane" };
        Stream<String> namesStream = Stream.of(names);

        Path path = Paths.get(".");
        Stream<Path> files;
        try {
            files = Files.list(path);
            files.forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Now here´s the file.forEach method signature:
void java.util.stream.Stream.forEach(Consumer<? super Path> action)

I´m reading it as a method that accepts a consumer of a type which is at least a Path type or a superclass of Path, but I´m probably missreading it, since System.out is not a superclass of Path.
Can someone please explain how to correct read it?

A: ? super Path says: 'It has to be a super class of Path.
System.out.println accepts an Object. Object is a super class of Path hence this is correct.

A: You are reading that entirely correct IMO, you are just mislead by the :: notation probably. And it's not about System.out being a Path or not - it's about the implied parameter x (for example) that you can't see because of the method reference (read further).
There are a couple of things here, first one is called PECS; that is why the declaration is ? super P_OUT or ? super Path. Basically that means you can read any super type of Path. The only safe one would be Object (or any sub type of that, but you just don't know which exactly).
To make it simpler, you can write it like this for example:
Stream.of("John", "Jane")
            .forEach((Object x) -> System.out.println(x)); // Object

Or since the compiler can see (infer) the type to be String :
Stream.of("John", "Jane")
            .forEach((String x) -> System.out.println(x));  // String

Or you can omit that declaration at all and let the compiler do it's job:
Stream.of("John", "Jane")
            .forEach(/* this is infered as String here */ x -> System.out.println(x));

Now the second part is called a Method Reference.
Instead of writing:
 Stream.of("John", "Jane")
            .forEach(x -> System.out.println(x));

You could write it simpler:
 Stream.of("John", "Jane")
            .forEach(System.out::println);

The x parameter (which is of type ? super T) is implied here.

A: The method signature indicates the forEach method of Stream takes a Consumer, which consumes each element from the Stream upon which it is iterating, in your case a collection of Paths.
Consumer refers to a functional interface that accepts an input and returns no result. It is one of many implemented in Java 8 to work with Lambdas and method references. A functional interface contains exactly one abstract method, also called its functional method.
The forEach method is used for iterating over a collection and applying an operation on each element. The operation, or "behavior" (any class implementing the Consumer interface), that's passed is the action, or lambda, performed on each element of the collection.
The forEach is an API (also added with Java 8) in the Iterable interface, which "performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception". It differs from the Java for loop in that it is an internal iterator, rather than an external one.


text:
Q: Is there a way to refer to external drive by its name other than the letter? Say I have a external drive with name Drive A assigned to letter E in Windows. Is there a way I can access this particular drive with name Drive A rather than E example "Drive A:/test.word"

A: Negative answer : This is not supported in Windows.
If you need to convert the disk-label to its drive-letter, see the post
Refer to/select a drive based only on its label?


text:
Q: Multiple joins not working with createQueryBuilder When I use createQuery it works:
$this->getEntityManager()
    ->createQuery(
        'SELECT e FROM CPBundle:Event e, CPBundle:Player p, CPBundle:EventType et
        WHERE e.player = p.id AND e.eventType = et.id';
    )
    ->getResult();

but when I try the same query with createQueryBuilder it doesn't work:
public function findEventsByParams($params)
{
    $qb = $this->getEntityManager()->createQueryBuilder();

    $query = $qb->select('e', 'p', 'et')
        ->from('CPBundle:Event', 'e')
        ->innerJoin('CPBundle:Player', 'p')
        ->innerJoin('CPBundle:EventType', 'et')
        ->where('e.player = p.id')
        ->andWhere('e.eventType = et.id');

    if ($params['username']) {
        $qb->andWhere('p.username = :username')
            ->setParameter('username', $params['username']);
    }

    //TODO: other params

    return $query->getQuery()->getResult();
}

I'm getting this error message:

[Syntax Error] line 0, col 73: Error: Expected Literal, got 'JOIN'

A: See this answer: https://stackoverflow.com/questions/17989473/symfony2-doctrine-multiple-joins-returns-error
public function findEventsByParams($params)
{
    $qb = $this->getEntityManager()->createQueryBuilder();

    $query = $qb->select('e')
        ->from('CPBundle:Event', 'e')
        ->innerJoin('e.player', 'p')
        ->innerJoin('e.eventType', 'et');

    if ($params['username']) {
        $qb->andWhere('p.username = :username')
            ->setParameter('username', $params['username']);
    }

    //TODO: other params

    return $query->getQuery()->getResult();
}


text:
Q: Missing page on wordpress "Pages" dashboard I just put up a new site (http://universalpluminfo.azurewebsites.net/) and was starting to add the base pages.
I think something may have went wrong as I have 5 pages on the navigation bar, but only 4 pages on the Pages Dashboard. I am missing the "Home" page that I created from the dashboard.
Any ideas on what could cause this or how to remedy?

A: I think you might have added just navigation item in menu, named Home. Go to Appearence> menus and modify the menu in question. There should be the extra item, named Home, which is not created as page.

A: The "catch-base" theme was the culprit.
Appearance > Customize > Static Front Page then had to set the options for the Front page and the extra "Home" button went away.
Thanks!


text:
Q: What is an srcset attribute in IMG tag and how to use it? I want to know how could I start using the HTML srcset img attribute in my mobile apps. Or Is there any other jQuery plugin which helps me to solve image resolution problem.

A: In short, Srcset is a new attribute which allows you to specify different kind of images for different screen-sizes/orientation/display-types. The usage is really simple, you just provide a lot of different images separating them with a comma like this: <img src="image.jpg" alt="image" srcset=" <descriptor>, ..., <img_n> <descriptor_n>">. Here is an example: srcset="image.jpg 160w, image2.jpg 320w, image3.jpg 2x"

This is a longer answer which explains things in more details.
Difference between srcset and picture. Both srcset and picture does approximately the same things, but there is a subtle difference: picture dictates what image the browser should use, whereas srcset gives the browser a choice. A lot of things can be used to select this choice like viewport size, users preferences, network condition and so on. The support for srcset is pretty good and almost all current browsers more or less support it. Situation with a picture element is a little bit worse.
Descriptors are just a way to show what kind of image is hidden behind the resource. There are various kinds of descriptors:

*

*density descriptor. srcset="image.jpg, image-2X.jpg 2x"
The display density values—the 1x, 2x, etc.—are referred to as display density descriptors. If a display density descriptor isn't provided, it is assumed to be 1x. Good variant to target retina displays.

*width descriptor. srcset="image-240.jpg 240w, image-640.jpg 640w". I am sure this is self explanatory. The only problem is that by itself width descriptor is not really helpful. Why? read here

*size descriptor, which only makes sense if you use width descriptor. srcset="image-160.jpg 160w, image-320.jpg 320w, image-640.jpg 640w, image-1280.jpg 1280w" sizes="(max-width: 480px) 100vw, (max-width: 900px) 33vw, 254px">. The instructions for the browser would look like this: (max-width: 480px) 100vw — if the viewport is 480 pixels wide or smaller, the image will be 100% of the viewport width. (max-width: 900px) 33vw — if the viewport is 480 pixels wide or smaller, this rule will never be reached because of the previous media condition. And 254px is when there is no media condition listed, the length is assumed to be a default value used when none of the other media conditions are met.

Just for completeness will add here that there is an image-set() attribute for a background image in CSS and some other helpful link here

A: Here is a good article on the srcset attribute and how to use it. srcet allows you to declare a set of images to be displayed on different viewport sizes. You just have to save and image at different resolutions e.g. banner-phone-HD.jpeg would be the highest resolution.
Exmaple:

The above would serve banner-phone.jpeg to devices with viewport width under 640px, banner-phone-HD.jpeg to small screen high DPI devices, banner-HD.jpeg to high DPI devices with screens greater than 640px, and banner.jpeg to everything else.
There are also other methods like CSS media queries you can use to produce the same effect.
I am not aware of any JQuery plugins which would help with this.

A: Here is a detailed guide on srcset along with code samples.
srcset allows you to define a list of different image resources along with size information so that browser can pick the most appropriate image based on the actual device's resolution.
Each comma-separated item in srcset has:

*

*Image URL, e.g. http://ik.imagekit.io/demo/default-image.jpg or relative path /demo/default-image.jpg

*An empty space

*The actual width of the image or display density:

*

*Either using display density descriptor, for example, 1.5x, 2x etc.

*Or, using width descriptors, for example, 450w. This is the width of the image in pixels.

Using display density descriptor
The syntax for display density descriptors is straightforward. srcset provides a comma-separated list of image resources along with display density it should be used, for example1x, 2x etc.

Live demo - https://imagekitio.github.io/responsive-images-guide/srcset-density.html.
Using width descriptor
The syntax is similar to the display density descriptor, but instead of display density values, we provide the actual width of the image.

This lets the browser pick the best image
Using width descriptor allows the browser to pick the best candidate from srcset based on the actual width needed to render that image on that particular display at runtime.
Note that display pixel density is also taken into account by the browser while calculating the required width.
For example, assuming an image takes up the whole viewport width - On a 300px wide screen with DPR 2, the browser will pick medium.jpg because it needs a 300x2=600px wide image. On a 300px wide screen with DPR value 3, the browser will select large.jpg because it needs a 300x3=900px wide image.
Demo - srcset with width descriptor
Let see this in action with a live demo - https://imagekitio.github.io/responsive-images-guide/srcset-width.html.


text:
Q: How to identify message of finish when click a button with selenium I have to execute a sequence of buttons with selenium, there are diferents take different minuts, Then I need to identify when finish the process of the button, this show a panel with a message "Ha concluido la ejecución..."

*

*When click on button show

*

*When process finish show.

I have a control:
span_control = driver.find_element_by_css_selector("span[class='status-execution-process']")
text_value = span_control.text
text_value could be values 0, 1, 2
0 when no execute button
2 while are executing button
1 when finish button executed
How to do something that while text_value is equal to 2, continue in a while, but when is text_value es equal to 1, finish this while.


text:
Q: Unity trigger reference to an other script I have a prefab with a Trigger and want the OnTriggerStay methode in a gamobject in the Gamescene. Does someone know how i can make a reference from the scene to the trigger of the prefab and call the OnTrigger methodes in the scenesripts?
Thank you in advance!

A: I am not fully understand your question.
But OnTriggerStay method working when you have two objects and while intersection happening between objects OnTriggerStay method is working.
By the way one objects collider attribute should be selected as trigger.
If you want to trigger events from another script. You can create an event system. Unity have lovely tutorial for this one.
Please check this tutorial, if that is what you need.
https://learn.unity.com/tutorial/create-a-simple-messaging-system-with-events#


text:
Q: Coercivity of a ferromagnetic material? I understand that coercivity is the field/force required to demagnetize/magnetize a ferromagnetic material.
What if we had two opposite magnetic fields of different strengths values H acting on the same ferromagnet what would happen?
H1 = 50 Oe
H2 = 10 Oe
The coercivity of the material is 0.5 Oe, what would happen? Will it stay magnetized to the stronger field(H1)? Or magnetization = 0?

A: Magnetic field is additive, so if I understand you correctly your magnet would be in 40 Oe field in direction of H1. As this is more than coercivity magnet will be magnetized by that effective field.
As a sidenote: in ferromagnetic materials it's not that easy to obtain zero magnetization. In zero field you would have spontaneous magnetization. But this can be (almost) done by applying alternating field with amplitude lowering over time. See degaussing on Wikipedia for example (section about CRTs to be precise). Magnetization is not entirely removed, but randomized, and it's amplitude vastly diminished.
EDIT:
If you have no magnetization and you don't exceed coercive field you will have magnetization which is not permanent, and will vanish soon after you take your field away. If you exceed coercivity you will get permanent magnetization which will decrease slightly if you take field away. Now if you change direction of field to opposite you will get decreasing magnetization with growing field. At field strength equal to coercivity you will get zero magnetization, and then direction of your magnetization will switch if you keep increasing field any further. Look up histeresis curve. Here you have it really nicely detailed. In your example all of this is unimportant as field strength is much higher than coercivity so sample will magnetize in direction of stronger field no matter what.


text:
Q: How to resize ViewController root view automatically to fit its content? When creating a new UIViewController the root view within the corresponding XIB file can be set to any fixed height. However, the root view should automatically fit its content. How can this be done?

*

*Create a new XIB file:

*Add a new subview to the root view and give it some fixed width and height.

*Add a leading constraint to the subview to define the X position

*Add a top constraint to the subview to define the Y positon

*Add a bottom constraint to the subview to define the content height (top + subview height + bottom)

*Until now everything is fine because top + subview height + bottom equals the height of the root view.

*If the top or bottom constraint is set to another value I would expect that the root view is resized to match its content. However, IB complains about conflicting constraints instead.

How can this be solved?
Of course in most cases the size of the root view is not defined by its content but by the screen, modal view, etc. the ViewController is displayed in.
However, I would like to show the ViewController as content of a ScrollView within another ViewController. In this case the ContentViewController should match its content and the ScrollView would make sure that the complete content is reachable.
Can this be solved within IB without manipulating the constraints in code?

A: After some more trial and error an found a working solution: Simply do not use the root view :-)
I added another view at root level to the XIB file and moved the root view into it, making the root view a subview of the new view. As long as the VCs view outlet still points to the root view (which isn't at root level anymore) this works fine.
The root view can still be accessed by theViewController.view. Since it is not placed at root level it is no problem to size it by its content.
While this works fine it is quite hacky. Is there any cleaner solution which does not require a dummy wrapper view?


text:
Q: Runtime error in vb.net i made email form which works on localhost however after uploading it on server it coming like this message on page
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a  tag within a "web.config" configuration file located in the root directory of the current web application. This  tag should then have its "mode" attribute set to "Off".
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

A: Two simple ways to see what might be causing the error. You can...
A) follow the instructions it gives you and enable the webpage to show the error through the webconfig.
B) Remote desktop connect to the web server and use it's browser. If you connect to the site from the server itself, it will also show the full error.
be warned - The first option can be a security problem. It does not discriminate who it shows errors to. If you keep this enabled it can reveal the inner working of your site to people you may not want seeing it.


text:
Q: Why is my value showing as None, when returned from a function? My code:
def inverse(A,R,C):
    D,E=[],[]
    for i in range(R):
        for j in range(C):
            D.append(A[j][i])
        E.append(D)
        D=[]

    Column_major(E,R,C)

def Column_major(A,R,C):
    s=0
    for i in range(R):
        for j in range(C):
            if i==j:
                s+=A[i][j]

    #print(s)        #<-- shows the correct output
    return s         #<-- shows it as None

T=int(input())
A,B=[],[]
c=1
for i in range(T):
    R,C=input().split()
    R,C=int(R),int(C)

    for j in range(R):
        for k in range(C):
            B.append(c)
            c+=1
        A.append(B)
        B=[]

    s=inverse(A,R,C)
    print(s)
    A,c=[],1

In the above given code, my s value shows as None when I run it from the main() method, but when I print it inside the function Column_major(), then it shows the correct output. Why is it showing None when I return the value?

A: You're missing return in the inverse function when you call Column_major():
def inverse(A,R,C):
    D,E=[],[]
    for i in range(R):
        for j in range(C):
            D.append(A[j][i])
        E.append(D)
        D=[]

    return Column_major(E,R,C)  # return here


text:
Q: PAM pwhistory module is not prompting for choose another password if password has been already used I want set history password reusability limit. I am trying to use pwhistory pam module.
Below is  configuration in /etc/pam.d/common-password file in Ubuntu (VERSION 20.04.1 LTS)
password        requisite      pam_pwhistory.so remember=24
password        [success=1 default=bad]      pam_unix.so obscure sha512 use_authtok

Below is output
root@localhost:/etc/pam.d# passwd test1
New password:
Retype new password:
Password has been already used.
passwd: password updated successfully
root@localhost:/etc/pam.d#

PAM pwhistory module is not prompting for choose another password if password has been already used
How  can I achieve to reject password if its been already used in past?

A: One thing with editing these files is that pam-auth-update has a tendency to futz with your configs if you make modifications to common-*
Be that as it may, I found that just adding remember=[N]  to the end of pam_unix.so was sufficient. I came here looking for a better answer than that, but this might help someone.
The options in that [success=1 default=bad] part choose what command to evaluate next. (either deny or permit). Running pw_history by itself is enough to pester the end user, but not enough to prevent their action from taking place.


text:
Q: Android BLE Scanning: permission denial message in logcat I read Bluetooth LE ScanFilters don't work on Android M, but it doesnt solve my problem
I am scanning my app on nexus 5 (os: 6.0.1). I keep getting following message in logcat
BluetoothUtils: Permission denial: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan

Gradle file has following settings:
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
    applicationId "XX.XX.XX"
    minSdkVersion 19
    targetSdkVersion 21
    versionCode 16
}

I am not using API 23 (or above) any where in my gradle but my phone has 6.0.1 OS.
Also, I have following defined in AndroidManifest
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

I donot ask for runtime permissions as specified in this blog because, I am targeting API 21
http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html
(when I tried to ask runtime permissions anyway, I get compiler warnings; so I am using GPS instead in the code)
How can I get rid of this warning from logcat
Permission denial: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results


text:
Q: Angular: Cannot retrieve value of ng-model when ng-minlength is not satisifed Given:
<input type="password" ng-model="ctrl.fields.password" ng-minlength="8" />

{{ ctrl.fields.password.length }}

Nothing shows up until you've met the minimum length as required by the validation. That is, if the length of the password is less than 8, then the value of the model is null. Removing ng-minlength solves that problem.
This is quite unexpected behavior, as the validity of the field should have no bearing on the access to the model's value.
Is there a way to work around this in Angular 1.5? I want to show the user the length of their password as they type, but since the value is null until it's at least 8 characters, then I can't.

A: This is the way Angular $validators work: if validatiion fails, value is not passed from view to model, and model is reset.
Here's a good introduction to how Angular built-in validation works:
http://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html
If you don't like this, angular-ui-validate is a good package that works in a non-disruptive way (i.e. model is always updated and you decide on what to do with the validation result).


text:
Q: Constant "Not Delivered" errors in iMessage I am getting incredibly frequent "Not Delivered" errors when sending messages on my Macbook. They're iMessage messages (as opposed to SMS messages), and I just get spats of them where it seems like every message I try to send throws up this error:

The super frustrating part is that the messages ARE sending. The other party seems to be receiving them just fine. I hit resend and it succeeds, or I hit ignore and it's not a problem. But this damn error window opens up constantly.
I've tried deleting the conversation with the person (or people), re-linking my iPhone to the Macbook, disabling the Jabber account, and signing out and back into my Apple account. Nothing thus far has worked. Is there any way to get additional details as to what is triggering this error?


text:
Q: Error on assigning a value to a Rectangle in Pygame I was trying to make a function that drew a rectangular map onto the screen. This function is:
def parseMap(mapIndex):
    tileRect = pygame.Rect(0, 0, 32, 32)
    for x in maps.mapData[mapIndex]:
    tileRect.x = x*16
    for y in x:
        tileRect.y = y*16
        c.blit(maps.grass, tileRect)
        if maps.mapData[mapIndex][x][y] == 1: c.blit(maps.tallGrass, tileRect)

Though, I was getting an error,
TypeError: invalid rect assignment

on the line:
tileRect.x = x*16

and I can't see anything wrong with the code. Thanks!

A: If x is a list, then x * 16 does list repetition, not multiplication.
i.e., you're getting something like
tileRect.x = [1, 1, 1, 1, ...]


text:
Q: Tracking cart event I have a 3rd. party CRM system from which i am in the process of implementing tracking.
ihave with help, successfully added tracking to the product pages using this:
add_action('wp_head', 'zz_add_tracking_codes');
function zz_add_tracking_codes(){
    // adding on product page only
    if(is_singular( 'product' )){
        $produc_id = get_the_id();
        // Remember a product can have multiple categories so if you can only add one you get the frist element form array.
        $categories = get_the_terms( $produc_id, 'product_cat');
    ?>
        <script type="text/javascript" language="javascript">
        const PRODUCTID = '<?php echo $produc_id; ?>';
        const CATEGORYID = '<?php echo $categories[0]->term_id; ?>';
        const CATEGORYNAME = '<?php echo $categories[0]->name; ?>';
        var hlt;
        var BiTrackingLoaded = function (BiTracking) {
        hlt=BiTracking;
        BiTracking.initialize('INSERTAPIKEYHERE', INSERTSESSIONTIMEHERE);
        hlt.visit(PRODUCTID,CATEGORYID,CATEGORYNAME) }
        </script>
        <script>
        (function (d, t) {
        var g = d.createElement(t),
        s = d.getElementsByTagName(t)[0];
        h = "https:" == document.location.protocol ? "https://" : "http://";
        g.src = h + 'tracking.heycommerce.dk/hlbi.js';
        s.parentNode.insertBefore(g, s);
        }
        (document, 'script'));
        </script>
    <?php
    }
}

What i need to do on the cart page is kind of similar, but i need it to fire an event for each of the products in the cart, and the hlt.visit(PRODUCTID,CATEGORYID,CATEGORYNAME)
is replaced with: hlt.addToBasket(PRODUCTID, PRODUCT COUNT, CATEGORYID, BASKETID, CATEGORYNAME);
Can i somehow reuse the code from the product pages and loop through the items in the cart?


text:
Q: Where am I going wrong So I am very new to Django and I am confused where am I going wrong. I am trying to create a simple calculator to calculate profit estimates. Here is what it shows in my HTML so far. Kind of confused where am I going wrong. Any help appreciated.

This the HTML file code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>

    {% block content %}
    <form action = "something" method = "post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value=Submit>
    </form>
    {% endblock %}

</body>
</html>

This is forms.py
from django import forms
from .models import Calc

class Calculator(forms.ModelForm):
    class Meta:
        model = Calc
        fields = ['gross_receivable', 'TDS', 'bank_charges', 'vendor_payable']

This is the models.py
from django.db import models

# Create your models here.
class Calc(models.Model):
    gross_receivable = models.IntegerField()
    TDS = models.BooleanField(default=False)
    bank_charges = models.BooleanField(default=False)
    vendor_payable = models.IntegerField()

This is the views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import Calc

    def something(request):
        form = Calc()
        context = {'form': form}
        return render(request, "calculator1.html", context)

A: Your form name is Calculator but you are importing your model as form.
You should change
from .forms import Calc

to
from .forms import Calculator

and in the something function
form = Calculator()


text:
Q: Permuting bottom element with top element in a stack #include <stdio.h>
#include <stdlib.h>
#include <conio.h>

struct node
{
    int data;
    struct node *next;
};
struct node *top;

int count=0;
void push(int n);
void Print();
void permute();

int main()
{
 int no, ch, e;
 printf("\n1 - Push");
 printf("\n4 - Print");
 printf("\n7 - Permute first and last element");
while (1)
    {
        printf("\n Enter choice : ");
        scanf("%d", &ch);
switch (ch)
        {
        case 1:
            printf("Enter data : ");
            scanf("%d", &no);
            push(no);
            break;
        case 4:
            Print();
            break;

        case 7:
            permute();
            break;
        default :
            printf(" Wrong choice, Please enter correct choice  ");
            break;
        }
    }

}
void push(int no)
{
    struct node *temp=(struct node*)malloc(sizeof(struct node));
    temp->data=no;
    temp->next=top;
    top=temp;
    count++;
}
 void Print()
{
    struct node *temp=top;
    printf("List is:");
    while(temp!=NULL)
    {
        printf("%d  ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
void permute()
{
    int i;
    struct node *temp=(struct node*)malloc(sizeof(struct node));
    struct node *temp1=(struct node*)malloc(sizeof(struct node));
    struct node *temp2=(struct node*)malloc(sizeof(struct node));
    temp=top;
    temp1=NULL;
    for(i=0;i<count-1;i++)
    {
        temp1=temp1->next;
    }
    temp1->next=temp2;
    temp2->data=temp1->next->data;
    temp1->next=temp;
    temp->data=top->data;
    temp=NULL;
    temp2->next=top;
    top=temp2;
}

So my implementation of a stack works fine as for pushing and printing the elements in the stack, but when I want to permute the bottom element with the top element the program crashes. I think I am messing something up in my permute function. Thank you for any help before hand.

A: If I have correctly understood it is enough simply to swap values of data member data of two nodes. The function can be defined the following way
void permute()
{
    if ( top && top->next )
    {
        int data = top->data;

        struct node *last = top->next;

        while ( last->next ) last = last->next;

        top->data = last->data;
        last->data = data;
    }
}

A: If you wish to permute nodes, here is a solution. Since there is no new node in the stack when a permutation is performed, there is no need to allocate memory. It is just pointer handling.
Notice the additional test to treat the case of an empty stack, or a stack with a single element.
A removed the cast of the return of malloc() in push() and tested the return value of malloc(). malloc() may fail if there is not enough memory available.
The following code is compiled by gcc main.c -o main -Wall :
#include <stdio.h>
#include <stdlib.h>
//#include <conio.h>

struct node
{
    int data;
    struct node *next;
};
struct node *top;

int count=0;
void push(int n);
void Print();
void permute();

int main()
{
    int no, ch;
    printf("\n1 - Push");
    printf("\n4 - Print");
    printf("\n7 - Permute first and last element");
    while (1)
    {
        printf("\n Enter choice : ");
        scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            printf("Enter data : ");
            scanf("%d", &no);
            push(no);
            break;
        case 4:
            Print();
            break;

        case 7:
            permute();
            break;
        default :
            printf(" Wrong choice, Please enter correct choice  ");
            break;
        }
    }

}
void push(int no)
{
    struct node *temp=malloc(sizeof(struct node));
    if(temp==NULL){printf("malloc failed\n");exit(1);}
    temp->data=no;
    temp->next=top;
    top=temp;
    count++;
}
void Print()
{
    struct node *temp=top;
    printf("List is:");
    while(temp!=NULL)
    {
        printf("%d  ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
void permute()
{
    if(count<2){return;}
    int i;
    struct node *temp1=top;
    struct node *temp2;
    for(i=0;i<count-2;i++)
    {
        temp1=temp1->next;
    }
    temp2=temp1->next;
    temp1->next=top;
    temp2->next=top->next;
    top->next=NULL;
    top=temp2;

}


text:
Q: Creating a complex HTML tree which aligns I'm trying to recreate a list as shown below, with the boxes containing text, and there being text and numbers underneath some of the boxes as well.

So far I've managed to create a list and a tree, but it's not in the exact order I'd want it to be. Don't mind the gaps between the lines and boxes. It doesn't need to be interactive in the slightest, just display text so that it's searchable.

Thank you in advance.
Code:
HTML

188

                10

                2

                3

                7

17

                    1

                    3

                    1

                    9

7

1

1

1

3

10

1

1

3

11

1

3

51

9

1

7

70

18

3

54

8

3

35

CSS
.tree,
.tree ul,
.tree li {
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
}
.tree {
    margin: 0 0 1em;
    text-align: center;
}
.tree,
.tree ul {
    display: table;
}
.tree ul {
    width: 100%;
}
.tree li {
    display: table-cell;
    padding: .5em 0;
    vertical-align: top;
}
.tree li:before {
    outline: solid 1px #666;
    content: "";
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
}
.tree li:first-child:before {
    left: 50%;
}
.tree li:last-child:before {
    right: 50%;
}
.tree code,
.tree span {
    border: solid .1em #666;
    border-radius: .2em;
    display: inline-block;
    margin: 0 .2em .5em;
    padding: .2em .5em;
    position: relative;
}
.tree ul:before,
.tree code:before,
.tree span:before {
    outline: solid 1px #666;
    content: "";
    height: .5em;
    left: 50%;
    position: absolute;
}
.tree ul:before {
    top: -.5em;
}
.tree code:before,
.tree span:before {
    top: -.55em;
}
.tree>li {
    margin-top: 0;
}
.tree>li:before,
.tree>li:after,
.tree>li>code:before,
.tree>li>span:before {
    outline: none;
}


text:
Q: scroll-function doesn't trigger a result I want to add a style so an element when a special - other - element gets in view via scrolling; as far as I understand it, the command should be like
$(".sw_4").scroll(function () {
    $(".sw_1").css({
        "position": "fixed"
    });
    console.log("heyho");
});

But it neither logs anything to the console then does something. What do I do wrong?
Thanks

A: How does your html look like? Do you include jquery? I suggest trying waypoints.
http://imakewebthings.com/waypoints/


text:
Q: Calculate new gps coordinates from 1 set of coordinates and distance? so I was wondering if there was existing code/library that allowed me to calculate a new pair of gps coordinates given: distance, a pair of latitude and longituide and bearing.
I hope you guys can give me insight.
cheers!

A: The answer that was given to me was from this link: stackoverflow.com/questions/37348207/find-location-1-km-away-in-180-degree-south-from-my-location/37349396#37349396
Using the following library: https://github.com/JavadocMD/simplelatlng
But the method that does the calculation is below:
/**
     * <p>
     * Calculate the end point of traveling along a great-circle path from a
     * given starting point with a given intitial bearing for a known distance.
     * </p>
     *
     * @param start
     *            the starting point.
     * @param initialBearing
     *            the initial bearing.
     * @param distance
     *            the distance to travel.
     * @param unit
     *            the unit in which distance is measured.
     * @return the end point.
     */
    public static LatLng travel(LatLng start, double initialBearing, double distance,
            LengthUnit unit) {
        double bR = Math.toRadians(initialBearing);
        double lat1R = Math.toRadians(start.getLatitude());
        double lon1R = Math.toRadians(start.getLongitude());
        double dR = distance / LatLngConfig.getEarthRadius(unit);

        double a = Math.sin(dR) * Math.cos(lat1R);
        double lat2 = Math.asin(Math.sin(lat1R) * Math.cos(dR) + a * Math.cos(bR));
        double lon2 = lon1R
                + Math.atan2(Math.sin(bR) * a, Math.cos(dR) - Math.sin(lat1R) * Math.sin(lat2));
        return new LatLng(Math.toDegrees(lat2), Math.toDegrees(lon2));
    }


text:
Q: Find the kernel of a linear transformation Consider the linear transformation of $\mathbb{R}^3$ given by $Ax= (a \cdot x)a + |a|^2x$
a) What are the range (image) and kernel of A?
b) Find the matrix of A in the usual basis $e_j$
The kernel is when Ax=0.  Does this mean that it is when $(a \cdot x)a = -|a|^2x$?
How does one compute the $Im(A)$ in this case and find the matrix of A in the usual basis?

A: $x$ is in the kernel of $A$ when $Ax=0$ which implies that $(a\cdot x)a=-|a|^2x$. But this equality can hold only if $x$ is a multiple of the vector $a$. Plugging in $x=ca$ you can see that $c=0$, and hence $$\ker A=\{0\}.$$ In other words, $A\colon \mathbb{R}^3\to \mathbb{R}^3$ is a one-to-one linear map. But any one-to-one linear map with from a finite dimensional space to itself is onto as well. Thus,
$$\text{Image}(A)=\mathbb{R}^3.$$
To find the standard matrix of $A$, simply evaluate $A$ at $e_i$. More precisely, the $i$-th column of the standard matrix is $Ae_i$. For instance the first column is given by
$$Ae_1=(a\cdot e_1)a+|a|^2e_1=a_1a+|a|^2e_1.$$


text:
Q: Marking assembly as serializable? I'm trying to make a website work with a state server, but I'm having issues where classes need to be marked as [Serializable] to work. Problem is we have tons of classes. It just seems like a red flag to mark all my classes as Serializable.
Any thoughts?

A: Went with Garrison Neely's answer in comment above:

Instead of marking every class as Serializable, look for the ones that are being sent back and forth between your site and state service. Hopefully that's a smaller list. –  Garrison Neely Jul 12 at 20:50


text:
Q: How to use a C++ dll in Unity3D? I am aware of this similar question, but it does not respond to my problem.
I have written two .dlls using Visual Studio 2010. One is in C++, and communicates with an SDK that was written in C++. The other is a C# wrapper for that C++ library, so that it can be used in C# contexts.
My plan was that this would let me use my code in Unity3D, but apparently that is not the case. It seems like Unity3D does not allow me to import .dlls as Assets if they are not a .NET assembly. So I can add my C# wrapper, but not the C++ dll.
This results in a DllNotFoundException whenever I try to access the C++ library. I have tried simply copying the C++ library into the Assets/Plugins folder, but that gives the same results.
Is there a way to do this properly? This is a very vital part of my project setup.

A: The problem is that the DLL is not being found when the p/invoke runtime code calls LoadLibrary(YourNativeDllName).
You could resolve this by making sure that your DLL is on the DLL search path at the point where the first p/invoke call to it is made. For example by calling SetDllDirectory.
The solution that I personally prefer is for your managed code to p/invoke a call to LoadLibrary passing the full absolute path to the native DLL. That way when the subsequent p/invoke induced call to LoadLibrary(YourNativeDllName) is make, your native DLL is already in the process and so will be used.
internal static class NativeMethods
{
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
    internal static extern IntPtr LoadLibrary(
        string lpFileName
    );
}

And then somewhere in your code:
private static IntPtr lib;

....

public static void LoadNativeDll(string FileName)
{
    if (lib != IntPtr.Zero)
    {
        return;
    }

    lib = NativeMethods.LoadLibrary(FileName);
    if (lib == IntPtr.Zero)
    {
        throw new Win32Exception();
    }
}

Just make sure that you call LoadNativeDll passing the full path to the native library, before you call any of the p/invokes to that native library.

A: Note that the DllNotFoundException can be caused by building your Unity DLL in Debug instead of Release!
A simple oversight that can cause a headache.

A: This also happens when Unity can find your DLL, but is not able to find it's dependencies. Obvious fix is to place dependency DLLs into /Plugins as well, or link your dependencies statically.
Less obvious reason is when your DLL depends on Visual Studio runtime library dynamically, i.e. is built with Properties -> C/C++ -> Code Generation -> /MD option. Change it to /MT to link with runtime statically.


text:
Q: Overriding core controllers adminhtml issue This is my xml:
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <mynamespace_mymodule before="Mage_Adminhtml">Mynamespace_Mymodule_Adminhtml</mynamespace_mymodule>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>

and this is my controller:
require_once 'Mage/Adminhtml/Sales/Order/controllers/CreateController.php';

class Mynamespace_Mymodule_Adminhtml_CreateController extends Mage_Adminhtml_Sales_Order_CreateController
{
    public function loadBlockAction(){
        echo 1; exit();
    }
}

I didn't get the echo 1 . What did I do wrong ? thx

A: replace <mynamespace_mymodule> before="Mage_Adminhtml"> with <mynamespace_mymodule before="Mage_Adminhtml">
<admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <mynamespace_mymodule before="Mage_Adminhtml">Mynamespace_Mymodule_Adminhtml</mynamespace_mymodule>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>

also your directory structure is must be same after adminhtml folder Sales/Orders/CreateController.php
require_once Mage::getModuleDir('controllers', 'Mage_Adminhtml') . DS . 'Sales' . DS . 'Orders' . DS . 'CreateController.php';

class Mynamespace_Mymodule_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Sales_Order_CreateController
{
    public function loadBlockAction(){
        echo 1; exit();
    }
}


text:
Q: JQuery multiple click event? There are two div in my page.

In view of above single click event source jQuery is:
$('#test-1000').click(function(){});

But how to achieve two div with a similar to the above statement click events to be monitored are, and how to distinguish between div, which is the click event?

A: Just use $(this) in the callback function to know 'which' element the event fired on.
$('.test').click( function() {
    alert( $(this).attr('id') );
});

A: I'll use a common class attribute to group all the target elements

then
$('.test').click(function(){
    //here this.id will give the clicked div id and this will refer the clicked dom element
    //$(this).data('id') will give 1000/1111
})

A: I prefer to go with data attribute and class approach
HTML code

1

2

js
$('.test').click(function(){
   alert($(this).attr("data"));
});

sample demo

A: Alternatively, if you don't want or can't modify your html, you can use jquery "starts-with" selector.

$("[id^='test']").on('click', function(){
    console.log(this.id);
});

JsFiddle

A: HTML

Js
$('.test').click(function(){
    //here this.id will give the clicked div id and this will refer the clicked dom element
    //$(this).data('id') will give 1000/1111
});

A: Maybe something like:
document.getElementById("test-1000").onclick = function(){});

You can not use the element before it is defined.


text:
Q: Anti-Aliasing with Pixel-by-Pixel filter I've looked around on SO for a while for anti-aliasing algorithms that might work, but they all produce blurry images and/or aren't applicable to my current method.
I've created a pixel-by-pixel filter with Python and PIL that creates a palette of colors (how they're determined isn't important.) The code creates an image like the one below. As you can see, it's very aliased.
http://i.imgur.com/BlGNzmP.png
I've heard that the best way to anti-alias an image is to do it while the image is being drawn, not afterwards; however, I'm not sure if this is possible with my current method, which is to loop through each individual pixel. If a method by which I can anti-alias the image while it is being drawn is possible, please post it here.
Here's the code:
import Image, ImageDraw
from collections import Counter

def avg_color(arr):
    r,g,b = 0,0,0
    for item in arr:
        r += item[0]
        g += item[1]
        b += item[2]
    l = len(arr)
    return (r//l,g//l,b//l)

COLOR_NUMBER = 12

PATH = "test.png"

COLORS = [
(255,255,255),
(0,0,0)
]

im = Image.open(PATH)
rgbim = im.convert('RGB')

size = rgbim.size

nim = Image.new('RGB', size)
draw = ImageDraw.Draw(nim)

for i in range(COLOR_NUMBER-2):
    devs = [[765 for j in range(size[1])] for k in range(size[0])]
    cols = [[765 for j in range(size[1])] for k in range(size[0])]
    ind = []
    for x in range(size[0]):
        for y in range(size[1]):
            r,g,b = rgbim.getpixel((x,y))
            cols[x][y] = (r,g,b)
            for c in COLORS:
                diff = abs(c[0]-r)+abs(c[1]-g)+abs(c[2]-b)
                devs[x][y] = min(diff,devs[x][y])

    h = (0,0)
    for x in range(size[0]):
        for y in range(size[1]):
            if devs[x][y] > devs[h[0]][h[1]]:
                h = (x,y)
    print "Added color",cols[h[0]][h[1]]
    COLORS.append(cols[h[0]][h[1]])

print("Created palette.")
print(COLORS)

for x in range(size[0]):
    for y in range(size[1]):
        r,g,b = rgbim.getpixel((x,y))
        devarray = []
        col = COLORS[0]
        for c in COLORS:
            diff = abs(c[0]-r)+abs(c[1]-g)+abs(c[2]-b)
            devarray.append(diff)
        smallest = 0
        for i in range(len(devarray)):
            if devarray[i] < devarray[smallest]:
                smallest = i
        col = COLORS[smallest]
        draw.point((x,y),fill=col)

print "Finished rough image."

nim.show()


text:
Q: Java execution details in System.out As I remember there is a magic command line option in Java that turns on writing of operations that are currently executed to the console. The output looks like byte code.
-verbose does not match as it prints only class loading, while this option outputs information like memory allocation, setting local variables etc. It was very detailed, like 10 lines for "Hello world".
I didn't find it here https://www.oracle.com/java/technologies/javase/vmoptions-jsp.html or here https://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/java.html.
Also I have found some flags, but most of them only work in openjdk or in the develop mode. Maybe there is a way I can start java.exe on Windows in this develop mode?
Or maybe there is another set of flags that these lists miss?

A: Not quite what you asked, but I'm a big fan of "kill -3" on the java process id - that dumps out all sorts of information about every thread and what state they are in, what locks they hold and what locks they are waiting on, and that sort of thing.

A: On windows use Ctrl-Break to create a thread dump.
To monitor classloading use  -verbose:class for garbage collection -verbose:gc

A: Supported options here. The closest I can find to your description is -verbose:gc, or perhaps -verbose:class.
javap will output bytecode, but it's a static disassembler, and not related to runtime.

A: I've been using jvisualvm quite a bit recently; maybe that would give you what you want? It does profiling of both memory and CPU use, can dump thread stacks, and can even persuade the JVM to list what classloader activity is going on (via the MBean support: go to java.lang→ClassLoading, select Attributes and update Verbose; it still dumps to System.out of course). The great thing about this is that you don't need to anything to enable it (normally); you can just attach to already running JVMs. (If you've got Java 1.5, use jconsole instead.)
Note however that you're unlikely to get a dump of what bytecodes are executed. This is because the HotSpot JIT engine – which has been around for a fair few years now – converts the bytecodes to native instructions before execution so by the time the code is actually executed, there's simply no bytecodes left for the instrumentation to report on. Theoretically you might be able to build a special VM that worked in the old way, but it would be horribly slow (like the bad old days) so why would you really want to?


text:
Q: Como colocar Alert no PHP? CODE:

        //Comando SQL Upadte para Atualizar os dados
        $sql = "UPDATE clientes set nome='$nome',cpf='$cpf',email='$email',setor='$setor',rua='$rua',numero='$numero',telefone='$telefone' WHERE id='$codigo'";
         //Testa o comando SQL
         mysql_query($sql) or die("Não foi possivel exercutar o comando Sql");
         //Mensagem de Sucesso na operação
         echo "O arquivo foi Alterado com sucesso";
         //Fechar a conexão
         mysql_close($conn);
    }
    else
    {
        echo "não houve conexão com o banco";
    }
    ?>
</body>

A: acho que isso resolve:
echo "<script>alert('Mensagem');</script>";

A: Fica assim, sendo duas linguagens que trabalham em lados diferentes, esta é a unica forma directa...
   //Comando SQL Upadte para Atualizar os dados
     $sql = "UPDATE clientes set nome='$nome',cpf='$cpf',email='$email',setor='$setor',rua='$rua',numero='$numero',telefone='$telefone' WHERE id='$codigo'";
     //Testa o comando SQL
     mysql_query($sql) or die("Não foi possivel exercutar o comando Sql");
     //Mensagem de Sucesso na operação
     echo "O arquivo foi Alterado com sucesso";
     //Fechar a conexão
     mysql_close($conn);
}
else
{
    echo "<script>alert('não houve conexão com o banco');</script>";
}
?>

A: Não é muito legal fazer alertas assim, seria mais interessante colocar este aquivo para ser acessado via requisição ajax.
O formulário Html manda via ajax as informações para serem utilizadas na query, e o arquivo php retorna um json, como retorno para o HTML.
Por padrão não tem como dar um alert no php. Dos jeitos abordados anteriormente funcionar, mas não acho seja interessante.


text:
Q: Is it possible to generate a fusion map from an adapted struct? Let A be:
struct A {
  int a;
  std::string b;
  struct keys {
    struct a;
    struct b;
  };
};

I would like to generate a fusion::map from the struct such that it contains the fusion::pairs: fusion::pair<A::keys::a, int> and fusion::pair<A::keys::b, std::string>. Something like
A a;
fusion::make_map<A>(a)

I've tried with BOOST_FUSION_ADAPT_ASSOC_STRUCT
BOOST_FUSION_ADAPT_ASSOC_STRUCT(
    A,
    (int,  a, A::keys::a)
    (std::string, b, A::keys::b)

)
This adapts A to be used as an associative sequence, but I haven't found a way to construct a map from it. In particular, if I iterate over it I get only the values. If I could iterate over the keys that would be really helpful, because then I could zip the values and the keys to build a map, but I haven't found a way to do this yet.

A: I remembered having seen this somewhere in the past.
I've found a blog post that knew the missing link: boost::fusion::extension::struct_member_name.
I've adapted the code from that blog post. I still don't think the code is clean, and have the strong feeling this can be done much more elegantly. However, right now you can do:
struct A {
  int a;
  typedef std::string strings[5];
  strings b;
};

BOOST_FUSION_ADAPT_STRUCT(A, (int, a)(A::strings, b))

int main() {
    using FusionDumping::dump;
    A f = { 42, { "The End Of The Universe", "Thanks For All The Fish", "Fwoop fwoop fwoop", "Don't Panic" } };
    std::cout << dump(f) << "\n";
}

Prints:
STRUCT A
field a int: 42
field b ARRAY [
std::string: The End Of The Universe
std::string: Thanks For All The Fish
std::string: Fwoop fwoop fwoop
std::string: Don't Panic
std::string:
]
ENDSTRUCT

FusionDumping is the namespace that implements the business end of things here. Everything besides the dump(std::ostream&, T const&) function is an implementation detail:
namespace FusionDumping
{
    // everything except the `dump(std::ostream&, T const&)` function is an implementation detail
    using mangling::nameofType;

    template <typename T2> struct Dec_s;

    template <typename S, typename N> struct DecImplSeqItr_s {
        typedef typename boost::fusion::result_of::value_at<S, N>::type current_t;
        typedef typename boost::mpl::next<N>::type next_t;
        typedef boost::fusion::extension::struct_member_name<S, N::value> name_t;
        static inline std::ostream& decode(std::ostream& os, S const& s) {
            os << "field " << name_t::call() << " ";
            Dec_s<current_t>::decode(os, boost::fusion::at<N>(s));
            return DecImplSeqItr_s<S, next_t>::decode(os, s);
        }
    };

    template <typename S>
    struct DecImplSeqItr_s<S, typename boost::fusion::result_of::size<S>::type > {
        static inline std::ostream& decode(std::ostream& os, S const& s) { return os; }
    };

    template <typename S>
    struct DecImplSeqStart_s:DecImplSeqItr_s<S, boost::mpl::int_<0> > {};

    template <typename S> struct DecImplSeq_s {
    typedef DecImplSeq_s<S> type;
    static std::ostream& decode(std::ostream& os, S const& s) {
        os << "STRUCT " << nameofType(s) << "\n";
        DecImplSeqStart_s<S>::decode(os, s);
        return os << "ENDSTRUCT\n";
    };
    };

    template <typename T2> struct DecImplArray_s {
    typedef DecImplArray_s<T2> type;
    typedef typename boost::remove_bounds<T2>::type slice_t;
    static const size_t size = sizeof(T2) / sizeof(slice_t);
    static inline std::ostream& decode(std::ostream& os, T2 const& t) {
        os << "ARRAY [\n";
        for(size_t idx=0; idx<size; idx++) { Dec_s<slice_t>::decode(os, t[idx]); }
        return os << "]\n";
    }
    };

    template <typename T2> struct DecImplVoid_s {
    typedef DecImplVoid_s<T2> type;
    static std::ostream& decode(std::ostream& os, T2 const& t) {
        return os << nameofType(t) << ": " << t << "\n";
    };
    };

    template <typename T2> struct DecCalc_s {
    typedef
        typename boost::mpl::eval_if< traits::is_sequence<T2>, DecImplSeq_s<T2>,
        typename boost::mpl::eval_if< boost::is_array<T2>,
                                    boost::mpl::identity< DecImplArray_s<T2> >,
        DecImplVoid_s<T2>   > >
    ::type type;
    };

    template <typename T2> struct Dec_s : public DecCalc_s<T2>::type { };

    template <typename Data>
    struct Dumper
    {
        Dumper(Data const& data) : data(data) {}
        friend std::ostream& operator<<(std::ostream& os, const Dumper& manip) {
            return Dec_s<Data>::decode(os, manip.data);
        }
    private:
        Data const& data;
    };

    template <typename Data>
        Dumper<Data> dump(Data const& data) { return { data }; }
}

As you can see, there's one more loose end, related to pretty printing the typenames (name mangling and typeid(T).name() are implementation defined). Here's a stock implementation that will work on GCC/Clang:
#ifdef DEMANGLING
#   include <cxxabi.h>
#   include <stdlib.h>

    namespace mangling {
        template <typename T> std::string nameofType(const T& v) {
            int     status;
            char   *realname = abi::__cxa_demangle(typeid(v).name(), 0, 0, &status);
            std::string name(realname? realname : "????");
            free(realname);

            return name;
        }
    }
#else
    namespace mangling {
        template <typename T> std::string nameofType(const T& v) {
            return std::string("typeid(") + typeid(v).name() + ")";
        }
    }
#endif

Full program listing
Integrating it all, see it Live On Coliru
For future reference
#include <typeinfo>
#include <string>
#include <iostream>
#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/is_sequence.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/type_traits.hpp> // is_array, is_class, remove_bounds

#define DEMANGLING

#ifdef DEMANGLING
#   include <cxxabi.h>
#   include <stdlib.h>

    namespace mangling {
        template <typename T> std::string nameofType(const T& v) {
            int     status;
            char   *realname = abi::__cxa_demangle(typeid(v).name(), 0, 0, &status);
            std::string name(realname? realname : "????");
            free(realname);

            return name;
        }
    }
#else
    namespace mangling {
        template <typename T> std::string nameofType(const T& v) {
            return std::string("typeid(") + typeid(v).name() + ")";
        }
    }
#endif

namespace FusionDumping
{
    // everything except the `dump(std::ostream&, T const&)` function is an implementation detail
    using mangling::nameofType;

    template <typename T2> struct Dec_s;

    template <typename S, typename N> struct DecImplSeqItr_s {
        typedef typename boost::fusion::result_of::value_at<S, N>::type current_t;
        typedef typename boost::mpl::next<N>::type next_t;
        typedef boost::fusion::extension::struct_member_name<S, N::value> name_t;
        static inline std::ostream& decode(std::ostream& os, S const& s) {
            os << "field " << name_t::call() << " ";
            Dec_s<current_t>::decode(os, boost::fusion::at<N>(s));
            return DecImplSeqItr_s<S, next_t>::decode(os, s);
        }
    };

    template <typename S>
    struct DecImplSeqItr_s<S, typename boost::fusion::result_of::size<S>::type > {
        static inline std::ostream& decode(std::ostream& os, S const& s) { return os; }
    };

    template <typename S>
    struct DecImplSeqStart_s:DecImplSeqItr_s<S, boost::mpl::int_<0> > {};

    template <typename S> struct DecImplSeq_s {
    typedef DecImplSeq_s<S> type;
    static std::ostream& decode(std::ostream& os, S const& s) {
        os << "STRUCT " << nameofType(s) << "\n";
        DecImplSeqStart_s<S>::decode(os, s);
        return os << "ENDSTRUCT\n";
    };
    };

    template <typename T2> struct DecImplArray_s {
    typedef DecImplArray_s<T2> type;
    typedef typename boost::remove_bounds<T2>::type slice_t;
    static const size_t size = sizeof(T2) / sizeof(slice_t);
    static inline std::ostream& decode(std::ostream& os, T2 const& t) {
        os << "ARRAY [\n";
        for(size_t idx=0; idx<size; idx++) { Dec_s<slice_t>::decode(os, t[idx]); }
        return os << "]\n";
    }
    };

    template <typename T2> struct DecImplVoid_s {
    typedef DecImplVoid_s<T2> type;
    static std::ostream& decode(std::ostream& os, T2 const& t) {
        return os << nameofType(t) << ": " << t << "\n";
    };
    };

    template <typename T2> struct DecCalc_s {
    typedef
        typename boost::mpl::eval_if<boost::fusion::traits::is_sequence<T2>, DecImplSeq_s<T2>,
        typename boost::mpl::eval_if< boost::is_array<T2>,
                                    boost::mpl::identity< DecImplArray_s<T2> >,
        DecImplVoid_s<T2>   > >
    ::type type;
    };

    template <typename T2> struct Dec_s : public DecCalc_s<T2>::type { };

    template <typename Data>
    struct Dumper
    {
        Dumper(Data const& data) : data(data) {}
        friend std::ostream& operator<<(std::ostream& os, const Dumper& manip) {
            return Dec_s<Data>::decode(os, manip.data);
        }
    private:
        Data const& data;
    };

    template <typename Data>
        Dumper<Data> dump(Data const& data) { return { data }; }
}

struct A {
  int a;
  typedef std::string strings[5];
  strings b;
};

BOOST_FUSION_ADAPT_STRUCT(A, (int, a)(A::strings, b))

int main() {
    using FusionDumping::dump;
    A f = { 42, { "The End Of The Universe", "Thanks For All The Fish", "Fwoop fwoop fwoop", "Don't Panic" } };
    std::cout << dump(f) << "\n";
}

A: You should use Associative Iterator interface - it provides result_of::key_of<I>::type metafunciton.
I have found code in my old records, and extracted relevant part.
I used it during implementation of SoA vector (as I understand from chat - you are implementing it too), but eventually switched to just explicit definition of fusion::map. I think I did that in order to have unified interface of normal structure and structure of references (i.e. both are accessed via type tag).
Live Demo on Coliru
namespace demo
{
    struct employee
    {
        std::string name;
        int age;
    };
}

namespace keys
{
    struct name;
    struct age;
}

BOOST_FUSION_ADAPT_ASSOC_STRUCT
(
    demo::employee,
    (std::string, name, keys::name)
    (int, age, keys::age)
)

template<typename> void type_is();

int main()
{
    type_is<as_fusion_map<demo::employee>::type>();
}

Result is:
main.cpp:(.text.startup+0x5): undefined reference to `void type_is<

boost::fusion::map
<
    boost::fusion::pair<keys::name, std::string>,
    boost::fusion::pair<keys::age, int>,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_,
    boost::fusion::void_
>

>()'

Here is full implementation
//             Copyright Evgeny Panasyuk 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// Reduced from larger case, some includes may not be needed

#include <boost/fusion/algorithm/transformation/transform.hpp>
#include <boost/fusion/sequence/intrinsic/value_at_key.hpp>
#include <boost/fusion/include/adapt_assoc_struct.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/view/transform_view.hpp>
#include <boost/fusion/view/zip_view.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/algorithm.hpp>

#include <boost/mpl/transform.hpp>
#include <boost/mpl/vector.hpp>

#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

#include <iostream>
#include <iterator>
#include <ostream>
#include <string>

#include <boost/mpl/push_front.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/iterator.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/fusion/iterator/equal_to.hpp>
#include <boost/fusion/iterator/key_of.hpp>
#include <boost/fusion/iterator/value_of.hpp>

using namespace boost;
using namespace std;

using fusion::at_key;
using fusion::at_c;

// ____________________________________________________________________________________ //

namespace res_of=boost::fusion::result_of;
using namespace boost::fusion;

template<typename Vector,typename First,typename Last,typename do_continue>
struct to_fusion_map_iter;

template<typename Vector,typename First,typename Last>
struct to_fusion_map_iter<Vector,First,Last,mpl::false_>
{
    typedef typename res_of::next<First>::type Next;
    typedef typename mpl::push_front
    <
        typename to_fusion_map_iter
        <
            Vector,
            Next,
            Last,
            typename res_of::equal_to<Next,Last>::type
        >::type,
        fusion::pair
        <
            typename res_of::key_of<First>::type,
            typename res_of::value_of_data<First>::type
        >
    >::type type;
};
template<typename Vector,typename First,typename Last>
struct to_fusion_map_iter<Vector,First,Last,mpl::true_>
{
    typedef Vector type;
};

template<typename FusionAssociativeSequence>
struct as_fusion_map
{
    typedef typename res_of::begin<FusionAssociativeSequence>::type First;
    typedef typename res_of::end<FusionAssociativeSequence>::type Last;
    typedef typename res_of::as_map
    <
        typename to_fusion_map_iter
        <
            mpl::vector<>,
            First,
            Last,
            typename res_of::equal_to<First,Last>::type
        >::type
    >::type type;
};

// ____________________________________________________________________________________ //

// Defenition of structure:

namespace demo
{
    struct employee
    {
        std::string name;
        int age;
    };
}

namespace keys
{
    struct name;
    struct age;
}

BOOST_FUSION_ADAPT_ASSOC_STRUCT
(
    demo::employee,
    (std::string, name, keys::name)
    (int, age, keys::age)
)

// ____________________________________________________________________________________ //
template<typename> void type_is();

int main()
{
    type_is<as_fusion_map<demo::employee>::type>();
}


text:
Q: Rails: Routing for tree-based hierarchy I am working on a very simple blogging engine, no bells or whistles needed, and I've come to the problem of build routes for the arbitrary number of subcategories.
I want to have a post view that displays all posts in the category (posts#index) and a view that displays a specific post (posts#show).
I have the following models
class Category < ActiveRecord::Base
  belongs_to :parent, foreign_key: 'parent_id', class_name: 'Category'
  has_many :children, foreign_key: 'parent_id', class_name: 'Category'
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :category
end

As you can see, the category can have a category as a parent. I'd like to be able to do something along the lines of:
example.com/category1/category2/.../categoryn

rendering posts#index
and
example.com/category1/category2/.../categoryn/post1

rendering posts#show
I've been trying to use globbing, a la:
get '(*categories)' => 'posts#index', as: :posts
get '(*categories)/:id' => 'posts#show', as: :post

but the posts_path keeps globbing up the :id that should be handled by the post_path. If I reverse the routes, then categoryn is treated as the post :id, rather than the bottom category in the tree.
Ruby on Rails: Routing for a tree hierarchy of places is the closest I could find, addressing the use of globbing, but it doesn't deal with the :id problem.
Any help, or even a "You can't do that for these reasons", would be appreciated. If you could point me to a gem that handles this nicely that I could reverse engineer from, that would be awesome.