text:
Q: What is the best approach to implement a versioning feature with content comparison using Hibernate? I'm working on a JSF based web application with backing beans and Hibernate for persistence.
The goal is to implement a feature to compare changes across versions, where some attributes are from "foreign key" objects. In order to get a generic solution, the best way would be to create a kind of database trigger or something.
I know about the @Version annotation, but I don't want only to have a history about the persisted object, but also the associated object.
Anyone already done something like that?
Edit: To specify the question here is more detail information. The application have a lot of business objects, most of them just have simple text attributes like Strings. The main thing the application do is CRUD. I would like to build a feature where users can compare versions older versions of a business object. My first idea was just to have a version column in the tables of the business objects and to save always a new dataset with a new version. But this seems for me like a large overload, to save everything duplicated. And how to keep the associations between versioned objects? Is there an other, lighter aprroach for that? This approach would also imply to change every single database access class and save method.

A: I would solve the problem like this:

*

*business object table, example: EXAMPLE_TABLE
-----------------------------------
|ID         |column 1|column 2|...|
|----------------------------------
|1          |foo     |bar     |...|
|2          |baz     |test    |...|
|...        |...     |...     |...|
-----------------------------------

*history preservation table for each business object table, example: EXAMPLE_TABLE_HISTORY
------------------------------------------------
|ID         |column 1|column 2|...|version|date|
|-----------------------------------------------
|1          |null    |foo     |...|1      |    |
|1          |baz     |test    |...|2      |    |
|...        |...     |...     |...|...    |... |
------------------------------------------------

You can define database-triggers for EXAMPLE_TABLE on each operation (INSERT, UPDATE or DELETE) to copy the current data from EXAMPLE_TABLE to EXAMPLE_TABLE_HISTORY including a version (Column version) and a timestamp (Column date) to preserve a history.
Advantages:

*

*You can easily retrieve all versions of your business object using the ID column in the history preservation table.

*Using triggers you don't have to change your application-code.

A: I think I found what I'm looking for. Event though I wanted to solve it with db triggers, hibernate provides a pretty solution. Hibernate envers creates an audit table for each versioned/annotated entity. All you have to do is to set the annotations in auditable entities. The needed tables will be generated and also the history of related audited entities will be managed. So you can recreate the whole content of your entities.


text:
Q: calling fgets did not work as expected I was trying to manipulate strings,so I used gets. but when I read this, i found that gets is is dangerous and should not be used. so I turn on fgets, but it seems like the program escape the fgets line??? any ideas how to solve it
code:
#include <stdio.h>

int
main (int argc, char *argv[])
{
    char message[200];
    int chx;
    puts("===[0]ENCODE===");
    puts("===[1]DECODE===");

   HERE:
   printf("$>\t");
    scanf("%d", &chx);
   if(chx != (0) && chx != (1)) goto HERE;
    printf("ENTER YOUR MESSAGE TO %s IT:\t", chx == 0 ? "ENCODE":"DECODE");
    fgets(message, sizeof(message), stdin);
    printf("%s", message);
    return 0;
}

execution
arubu@CQ56-LinuxMachine:master$ ./a.out
===[0]ENCODE===
===[1]DECODE===
$>  1
ENTER YOUR MESSAGE TO DECODE IT:
arubu@CQ56-LinuxMachine:master$

gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i combine two Pandas dataframes while keeping columns of both in the new dataframe? In this case, I want to combine revenue_df and total_df.
revenue_df : https://i.stack.imgur.com/652KT.png <br>
total_df: https://i.stack.imgur.com/44j6A.png

I managed to do so using .merge() as shown:

However, the new merged dataframe only has columns from revenue_df and not from total_df. This prevents me from referencing total_df's columns in the merged dataframe.
revenue_df.info() shows this:

Is there a way I can merge both dataframes and get the columns of both dataframe in the merged one?

A: revenue_df.alias('df1').join(total_df.alias('df2'),on = df1['Year'] == df2['Year'],how = 'outer').select('df1.*','df2.*')
Using join we can select all columns from both dataframes.
Also we can restrict which column to be fetched.


text:
Q: Parse.com Android PushService.setDefaultPushCallback not working Using Parse 1.5.1
Hi,
the device receives Push notifications, but the
 PushService.setDefaultPushCallback to call a specific class is not working at all.
Since the app is running in FragmentActivity I had to use getApplicationContext instead of 'this' and run it inside a thread.
Any ideas on how to make this work using FragmentActivity?
The code:
     public class Application extends android.app.Application {

   Parse.initialize(mykey,..
   new Thread(new Runnable() {
        @Override
        public void run() {
              PushService.setDefaultPushCallback(getApplicationContext(), PushActivity.class);
                ParseInstallation.getCurrentInstallation().saveInBackground();
        }
    }).start();


text:
Q: Android: Not getting values of spinner into edittext I have dailog with a EditText and a Spinner, i am implementing as below
spinner1 = (Spinner) dialog.findViewById(R.id.quesspinner);

ArrayAdapter<CharSequence> arrayadapter = ArrayAdapter.createFromResource(activity, R.array.fbquestion,R.layout.textview);

spinner1.setAdapter(arrayadapter);

logo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            spinner1.setVisibility(View.GONE);
            spinner1.performClick();
        }
});

Now i am unable to read the value of Spinner, i want the text in the Spinner to be displayed in my EditText . code seems to be fine for me but itz not working.Any help is appreciated
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
         int Text = parent.getSelectedItemPosition();
           edittext.setText(Text);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    });

A: Use spinner.getSelectedItem() instead of parent.getSelectedItem()

A: Change your code to like this
To show content in EditText before changing the spinner then do like this
spinner1.setAdapter(arrayadapter);
edittext.setText(spinner1.getSelectedItem().toString());

.
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
     String Text = spinner1.getSelectedItem().toString();
     edittext.setText(Text);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

});


text:
Q: Whether it is possible to change the Android manifest attribute dynamically? I need the set the Application attribute dynamically in android , particularly i need set the Name field which is shown below , i need to change it dynamically because i import two library packages each package will contain two different Application class to maintain session variable,but i can able to use any one Application class in imported project, i need to use that both dynamically based on the package user going to use, for that i need to set and change the Application class Name  dynamically in Android Manifest.xml file.

if any one knows the solution means help me out.
Thanks.

A: Your manifest is within your apk, which is signed, so changing it dynamically would invalidate the whole package. My guess is dynamically changing the manifest is not possible.

A: I also agree
Once your Apk is Created it contains your manifest file.And the manifest contains all information about the application,So it is not possible

A: We can't change manifest attribute dynamically
When an app installs, system first checks and collects the manifest file to get all the information about the app like permissions, activities, services, broadcast receivers, content providers.. etc, and based on that info the system reacts to the app in future.
For Example: if some app has request the system to perform some ACTION then the system knows that certain app has an activity that could deal with the ACTION, likewise if a boardcast is fired system knows which app has the related boardcast receivers to notify.. etc
However if we somehow able to edit the manifest file dynamically then also it will be of no use as the system will be unaware of those changes cause it reads the app's manifest file first time only while installing..

A: I agree with K-ballo ..I am not sure i got exactly what your problem is,but i worked on Android before and i am pretty sure that there is no way you are allowed to change the manifest dynamically.so its better if you find a new solution to deal with your problem :)


text:
Q: WordPress $wpdb->get_results() not returning value I'm in the process of looking at a WordPress plugin (never used WordPress before) and am running into an issue trying to execute a very basic SELECT statement against the database.
Ex:
$sql = "SELECT * FROM wp_posts";
$result = $wpdb->get_results( $sql );
var_dump($result);
echo($result);

This doesn't display anything even though my wp_posts table has a couple hundred rows.  Can someone tell me what I'm missing?  Thanks.

A: This may or may not be the issue, but often, prefixes cause trouble and it is not recommended to hardcode tables in.
Secondly, can you output the value of $wpdb? If not, and this is most likely the problem, you don't have access to $wpdb in your scope.
Use global $wpdb if you are executing this within a function.
$sql = "SELECT * FROM $wpdb->posts";
$result = $wpdb->get_results( $sql );


text:
Q: How to calculate the average in this case? (JAVA ) I have a set of numbers that I named age[]. I want to calculate the average of all the elements contained in age[] without calculating the sum separately. Not like this:
int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

That is actually too long to write. Imagine if a have 100 of elements, it'll be too hard.
int age[] = { 20, 17, 19, 22, 18, 18 };
String[] names = { "Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan" };
for (int i = 0; i <= 5; i++) {
    if (age[i] >= 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. And he's from Mars!");
    }
    if (age[i] < 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. He is from Wakanda!");
    }
}

int j = 0;
int avg = (age[j] + age[j++]) / age.length;

System.out.println("Their average age is :" + avg + " years.");

int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

System.out.println("Their correct average age is :" + avg2 + " years.");

That's what I've done but I didn't find the shortcut. Please help me to solve this if possible. Thanks.

A: You could sum the age values while you iterate the array(s). Don't hardcode the length in the for loop. Use an else instead of two if(s). Something like,
int age[]= { 20, 17, 19, 22, 18, 18};
String[] names = {"Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan"};
int total = 0;
for (int i = 0; i < age.length; i++) {
    total += age[i];
    if (age[i] >= 20) {
        System.out.println(names[i] +" is "+ age[i] +" years old. And he's from Mars!");
    } else {
        System.out.println(names[i] +" is "+ age[i] +" years old. He is from Wakanda!");
    }
}
double avg = total / (double) age.length;
System.out.println("Their average age is :" + avg + " years.");

A: One of the simplest ways is to use Java Streams API.
double avg = Arrays.stream(age).average().getAsDouble();

Demo:
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int age[] = { 20, 17, 19, 22, 18, 18 };
        double avg = Arrays.stream(age).average().getAsDouble();
        System.out.println(avg);
    }
}

Output:
19.0

A: Here is a somewhat different way of doing it.

*

*Use IntStream to streams the array indices.

*employ map to print the ages for each individuals

*then calculate the average and

*

*if an average is present, print it

*else print an informatory message

int ages[] =
    {20,17,19,22,18,18};
String[] names =
    {"Ahmed","Sam","Mandi","Amine","John","Rayan"};

IntStream.range(0, ages.length).map(i -> {
    int age = ages[i];
    if (age >= 20) {
        System.out.println(names[i] + " is " + age
                + " years old. And he's from Mars!");
    } else {
        System.out.println(names[i] + " is " + age
                + " years old. He is from Wakanda!");
    }
    return age;
}).average().ifPresentOrElse(
        avg -> System.out
                .println("\nTheir average age is: " + avg + " years."),
        () -> System.out.println("No ages were supplied"));

prints
Ahmed is 20 years old. And he's from Mars!
Sam is 17 years old. He is from Wakanda!
Mandi is 19 years old. He is from Wakanda!
Amine is 22 years old. And he's from Mars!
John is 18 years old. He is from Wakanda!
Rayan is 18 years old. He is from Wakanda!

Their average age is: 19.0 years.


text:
Q: x axes titles on subplots Plotly Python I am trying to add the same titles on the x-axes and y-axes to four gantt charts that are displayed as subplots. I found online figs.update_layout() however, this only presents the title on the first chart, not all. I have found a few answers with R however any help with python would be great
figs = make_subplots(
rows=2, cols=2,
shared_xaxes=False,
subplot_titles =('Plot 1', 'PLot 2', 'PLot 3', 'Plot 4')
)
figs.update_layout(
    title="Plot Title",
    xaxis_title="Miliseconds",
    yaxis_title="Services",
)

for trace in fig_operable.data:
    figs.add_trace(trace, row=1, col=1)
for trace in fig_dynamic.data:
    figs.add_trace(trace, row=2, col=1)
for trace in fig_early.data:
    figs.add_trace(trace, row=1, col=2)
for trace in fig_hmi.data:
    figs.add_trace(trace, row=2, col=2)

figs.update_layout(showlegend=False, title_text="Title of charts")
figs.show()

A: IIUC you are looking for something like
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots

subplot_titles = ['Plot 1', 'Plot 2', 'Plot 3', 'Plot 4']
xaxis_title="Miliseconds"
yaxis_title="Services"
rows = 2
cols = 2
height = 300 * rows

trace = go.Scatter(x=np.linspace(1,100,100),
                   y=np.linspace(1,100,100))

fig = make_subplots(rows=rows, cols=cols,
                    shared_xaxes=False,
                    subplot_titles=subplot_titles
                    )

for i, col in enumerate(subplot_titles):
    r = int(np.ceil(((i+1)/cols)))
    c = i%2+1
    fig.add_trace(trace, row=r, col=c)
    fig.update_xaxes(title_text=xaxis_title, row=r, col=c)
    fig.update_yaxes(title_text=yaxis_title, row=r, col=c)

fig.update_layout(showlegend=False,
                  title_text="Title of charts",
                  title_x=0.5,
                  height=height)
fig.show()

If you need any other doubts you can have a look at the documentation here.


text:
Q: Update the value of a variable from within a Python function as it iterates through a dataframe I'm trying to create a Python function that will iterate through the rows of a Pandas dataframe and execute some simple arithmetic using a variable. But I'd also like to populate the original variable with the product that the function returns.
The goal is to convert the dataframe (which currently contains quarterly annual average percentages) to an approximate dollar figure based on a given starting point ($177.1 in this case). But I can only do that if each subsequent iteration is given an updated base dollar figure.
This version of the function works:
newnum = 177.1
def process_wages(x):
    if type(x) is str:
        return x
    elif x:
        return (x / 400) * newnum + newnum
    else:
        return

newdf.applymap(process_wages)

But I'd like to add a line that might look something like this:
    else:
        return
    newnum = x
newdf.applymap(process_wages)

...which, of course, doesn't work - returning this error:
UnboundLocalError: local variable 'newnum' referenced before assignment

Update: Here's the input dataframe:
    Date    Percent
0   2002Q1  3.5
1   2002Q2  3.6
2   2002Q3  3.1
3   2002Q4  2.6
4   2003Q1  2.9
... ... ...
70  2019Q3  3.0
71  2019Q4  3.0
72  2020Q1  3.3
73  2020Q2  2.9
74  2020Q3  2.7
75 rows × 2 columns

And here's the output I get from the working function (the problem is, of course, that each iteration is working from the same, original, value of newnum):
    Date    Percent
0   2002Q1  178.649625
1   2002Q2  178.693900
2   2002Q3  178.472525
3   2002Q4  178.251150
4   2003Q1  178.383975
... ... ...
70  2019Q3  178.428250
71  2019Q4  178.428250
72  2020Q1  178.561075
73  2020Q2  178.383975
74  2020Q3  178.295425
75 rows × 2 columns

A: global can be used to manipulate a variable outside of a function.

A: Using Maria's tip, I reworked my function to look like this:
newnum = 177.1
def process_wages(x):
    global newnum
    if type(x) is str:
        return x
    elif x:
        newnum = (x / 400) * newnum + newnum
        return newnum
    else:
        return
newstuff = newdf.applymap(process_wages)

...and now I'm able to pass newnum back to the global variable AND to my dataframe.


text:
Q: X11: How to disable the combined display desktop, so screens can be adressed with DISPLAY=:0.x I have an ubuntu 18.04 Desktop Edition installed, to control a setup with three displays.
For this special project, it would be easier to adress the displays one by one, e.g. DISPLAY=:0.1 :0.2 and so on.
Currently I can get it only to work with specifying "--geometry" and crazy offsets.
How do I disable this multi-monitor support on Ubuntu 18.04 Desktop edition?
Is there an easy way, e.g. by deinstalling some package?
BR
Marc

A: OK, just for the record. After digging around a little I found the ZaphodHeads setting ( -> /etc/X11/xorg.conf ), together with the xrandr tool enabled me to find a setting where all monitors work now.
As I have an Intel chipset in my computer this link also was of great help: https://www.systutorials.com/docs/linux/man/4-intel/
Here comes the relevant part of my current /etc/X11/xorg.conf:
Section "Device"
    Identifier  "Intel0"
    Driver      "intel"
    BusID       "PCI:0:2:0"
    Screen      0
    Option      "AccelMethod"       "sna"
    Option      "Monitor-HDMI1"     "HDMI1"
    Option      "ZaphodHeads"       "0:HDMI1"
    Option      "TearFree"  "on"
    Option      "ReprobeOutputs"    "on"
EndSection

Section "Device"
    Identifier  "Intel1"
    Driver      "intel"
    BusID       "PCI:0:2:0"
    Screen      1
    Option      "AccelMethod"       "sna"
    Option      "Monitor-HDMI2"     "HDMI2"
    Option      "ZaphodHeads"       "1:HDMI2"
    Option      "TearFree"  "on"
    Option      "ReprobeOutputs"    "on"
EndSection


text:
Q: Lebesgue integral of $x^{-3/4}$ is finite
Let $X=(0,1]$ and $f(x)=\dfrac{1}{x^{3/4}}$. Show that $A=\int_X f d\mu$ is finite, but $B=\int_X f^2 d\mu$ is infinite, where the integrals are Lebesgue integrals.

For $B$, I bound the integral below by simple functions, taking the values of $f^2$ at $x=1/n, 2/n, \ldots, 1$. The integral over the simple function is $\dfrac{1}{n}\sum_{i=1}^n \dfrac{1}{(i/n)^{3/2}} = n^{\frac12}\sum_{i=1}^n \dfrac{1}{i^{3/2}}>n^{1/2}$, which goes to $\infty$ as $n\rightarrow\infty$.
What about for $A$? I can't see how to bound the function from above to show that the integral is finite.

A: To show that a non-negative measurable function is Lebesgue-integrable, we don't need to bound it from above by a simple function. For a measurable $g \geqslant 0$, the Lebesgue integral of $g$ is defined as
$$\int_X g\,d\mu = \sup \left\lbrace \int_X s\,d\mu : s \leqslant g, s \text{ simple}\right\rbrace.$$
$g$ is then called Lebesgue-integrable if $\int_X g \,d\mu < \infty$.
The existence of a simple function with finite integral that bounds $g$ from above is a sufficient, but not necessary condition for the integrability of $g$.
Most of the time it is simpler to show the integrability of a non-negative measurable function by the monotone convergence theorem, however.
In this case, one can use
$$f_n(x) = \begin{cases} 0 &, x < \frac1n\\ f(x) &, x \geqslant \frac1n \end{cases}$$
which is a monotonic sequence of non-negative bounded measurable functions converging pointwise to $f$.
Since $\sup \int_X f_n\,d\mu < \infty$, the monotone convergence theorem implies that $f$ is integrable and
$$\int_X f\,d\mu = \lim_{n\to\infty} \int_X f_n\,d\mu = \sup_{n\in\mathbb{N}} \int_X f_n\,d\mu.$$

A: Explicitly:
Let $0<p<1$ and $x_n = \frac{1}{\sqrt[p]{n}}$. We have $f(x_n) = n$, of course.
Let $\overline{f} = \sum_{n=1}^\infty (n+1) 1_{[x_{n+1},x_n)}$, then it is easy to verify that $f \le \overline{f}$ on $(0,1]$.
The monotone convergence theorem gives
\begin{eqnarray}
\int \overline{f} &=&  \sum_{n=1}^\infty (n+1) \int 1_{[x_{n+1},x_n)} \\
& =& \sum_{n=1}^\infty (n+1) (\frac{1}{\sqrt[p]{n}} - \frac{1}{\sqrt[p]{n+1}}) \\
& =& \sum_{n=1}^\infty \left( \frac{1}{\sqrt[p]{n}(n+1)^{-1}} - \frac{1}{\sqrt[p]{n+1}(n+1)^{-1}} \right) \\
& \le & \sum_{n=1}^\infty  \left( \frac{1}{\sqrt[p]{n}n^{-1}} - \frac{1}{\sqrt[p]{n+1}(n+1)^{-1}} \right)\\
&=& 1
\end{eqnarray}
Furthermore, since $0 \le f \le \overline{f}$, we have $0 \le \int f \le \int \overline{f} \le 1$.


text:
Q: get value of field of table in android on press of button I am creating an application where there is table whose data is obtain from server using JSON and is populated on screen. Also i have added a button in the beginning of the table and when the user presses the button, the value of first row and first column should store inside a variable.
i am not storing value in any database, just fetching the value from the server and then displaying it on the screen.
In the screenshot you can see buttons and the table. As soon users presses first button("Add to basket"), it should store the value of product_code of that row only(Only product_code) in to a string variable.
Please suggest me some ways by which i can do that. I am not able to get any answer.
sorry for my bad english

here is my code
public class FancyStock extends Activity implements View.OnClickListener {

    String data = "";
    TableLayout tl;
    TableRow tr;
    TextView label;
    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fancystock);

        tl = (TableLayout) findViewById(R.id.main_table);

        final GetDatafromDB_fancystock getdb = new GetDatafromDB_fancystock();
        new Thread(new Runnable() {
            public void run() {
                data = getdb.getDataFromDB();
                System.out.println(data);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<Users_fancystock> users = parseJSON(data);
                        addData(users);
                    }
                });

            }
        }).start();
    }

    public ArrayList<Users_fancystock> parseJSON(String result) {
        ArrayList<Users_fancystock> users = new ArrayList<Users_fancystock>();
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                Users_fancystock user = new Users_fancystock();
                user.setId(json_data.getInt("id"));
                user.setProduct_code(json_data.getString("product_code"));
                user.setShapes(json_data.getString("shaps"));
                user.setPair(json_data.getString("pair"));
                user.setCarats(json_data.getString("carats"));
                user.setColor(json_data.getString("color"));
                user.setClarity(json_data.getString("clarity"));
                user.setService(json_data.getString("service"));
                user.setPolish(json_data.getString("polish"));
                user.setSymetric(json_data.getString("symetric"));
                user.setTables(json_data.getString("tables"));
                user.setMeasurements(json_data.getString("measurments"));
                user.setFlourscne(json_data.getString("flourscne"));
                user.setDescription(json_data.getString("description"));
                user.setCerticated(json_data.getString("certificated"));
                user.setCcode(json_data.getString("ccode"));
                user.setCut(json_data.getString("cut"));
                user.setTotal(json_data.getString("total"));
                user.setFile(json_data.getString("file"));
                users.add(user);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return users;
    }

    void addHeader(){
        /** Create a TableRow dynamically **/
        tr = new TableRow(this);

        TextView add = new TextView(this);
        add.setText("Add");
        add.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        add.setPadding(5, 5, 5, 5);
        add.setBackgroundColor(Color.parseColor("#BDB76B"));
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(add,params);
        tr.addView((View)Ll);

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText("Product code");

        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(5, 5, 5, 5);
        label.setBackgroundColor(Color.parseColor("#BDB76B"));
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(label,params);
        tr.addView((View)Ll);  // Adding textView to tablerow.

        /** Creating Qty Button **/
        TextView shapes = new TextView(this);
        shapes.setText("Shapes");
        shapes.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        shapes.setPadding(5, 5, 5, 5);
        shapes.setBackgroundColor(Color.parseColor("#BDB76B"));
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(shapes,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

        TextView pair = new TextView(this);
        pair.setText("Shapes");
        pair.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        pair.setPadding(5, 5, 5, 5);
        pair.setBackgroundColor(Color.parseColor("#BDB76B"));
        Ll = new LinearLayout(this);
        params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 5, 5, 5);
        //Ll.setPadding(10, 5, 5, 5);
        Ll.addView(pair,params);
        tr.addView((View)Ll); // Adding textview to tablerow.

        // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }

    @SuppressWarnings({ "rawtypes" })
    public void addData(ArrayList<Users_fancystock> users) {

        addHeader();

        for (Iterator i = users.iterator(); i.hasNext();) {

            Users_fancystock p = (Users_fancystock) i.next();

            /** Create a TableRow dynamically **/
            tr = new TableRow(this);

            Button btn = new Button(this);
            btn.setText("Add to Basket");
            // btn.setTextSize();
            btn.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
            // btn.setTag(mLinks.get(index));
            btn.setOnClickListener(this);
            LinearLayout Ll = new LinearLayout(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 2, 2, 2);
            params.width=200;
            params.height=60;
            // btn.setLayoutParams(new LinearLayout.LayoutParams(10, 100));
            Ll.addView(btn,params);

            tr.addView((View)Ll);

            /** Creating a TextView to add to the row **/
            label = new TextView(this);
            label.setText(p.getproduct_code());
            label.setId(p.getId());
            label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            label.setPadding(5, 5, 5, 5);
            ////label.setBackgroundColor(Color.parseColor("#BDB76B"));
             Ll = new LinearLayout(this);
             params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 2, 2, 2);
            //Ll.setPadding(10, 5, 5, 5);
            Ll.addView(label,params);
            tr.addView((View)Ll); // Adding textView to tablerow.

            /** Creating Qty Button **/
            TextView place = new TextView(this);
            place.setText(p.getShapes());
            place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            place.setPadding(5, 5, 5, 5);
            //  place.setBackgroundColor(Color.parseColor("#BDB76B"));
            Ll = new LinearLayout(this);
            params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 2, 2, 2);
            //Ll.setPadding(10, 5, 5, 5);
            Ll.addView(place,params);
            tr.addView((View)Ll); // Adding textview to tablerow.

            label = new TextView(this);
            label.setText(p.getpair());
            label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            label.setPadding(5, 5, 5, 5);
            ////label.setBackgroundColor(Color.parseColor("#BDB76B"));
            Ll = new LinearLayout(this);
            params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 2, 2, 2);
            //Ll.setPadding(10, 5, 5, 5);
            Ll.addView(label,params);
            tr.addView((View)Ll); // Adding textView to tablerow.

            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        }
    }
    public void onClick(View v)
    {
        //  startActivity(f1);

    }

}

A: In your addData() function you must set the tag value with that button and this tag value you must set the i integer, and in onclick first you get tag and parse to integer and then get that index value from arraylist    ArrayList in which you already populate record from JSON. you will get object of fancystock from that index and that object contain record of you selected row.
tell me if you understand this and solve this problem :)
Updated//*****************************************************//
    ArrayList<Integer> users=new ArrayList<Integer>();
   for(int i=0;i<users.size();i++){
       Button b=new Button(this);
       b.setTag(i);

   }

in onClickListner
    int i=(Integer)b.getTag();
    Users_fancystock rowRecord= users,get(i);

now this rowrecord will contain all values of row of your desired one


text:
Q: C# Most elegant way to convert string array to dictionary with different keys I have a collection of string arrays (result of splitting CSV to rows and then delimiting)
{31001, 2014-01-01, 24:00:00},{31001, 2014-01-02, 24:00:00},{31001, 2014-01-03, 24:00:00} ...
Now I need to convert it to list of dictionaries, where each dictionary element will have custom key depending on arrays element index. So I want to achieve something like this:
{
 {"Index":"31001", "Date":"2014-01-01", "Time":"24:00:00"},
 {"Index":"31001", "Date":"2014-01-02", "Time":"24:00:00"},
 {"Index":"31001", "Date":"2014-01-03", "Time":"24:00:00"},
 ...
}

I can't use models for this

A: Assuming you will have duplicate keys you could use something like
List<KeyValuePair<string,Tuple<string,string>>

where the key is the Index and the rest of the data belongs in the Tuple (Date,Time,..etc).
If you will have more data you couls simply use a List<KeyValuePair<string,List<string>>>

A: You could do it with an anonymous object.
this way would result in objList having all the rows with the properties Index,Date and Time. whilst not using named classes.
(please note I'm still learning if I don't name things right)

List<Object> objList = new List<object>();

foreach(var line in lines)
{
    var fields = line.Split(',');
    objList.Add(new {
        Index = fields[0],
        Date = fields[1],
        Time=fields[2]
     });
 }


text:
Q: how to add dynamic properties to entities at run time I'm using Dynamic Linq to select a few fields from a database query
Lets say I have following class
Class User
 Property LastName as string
 Property Email as string
End Class

But I want to call the query like this
dim q= MyContext.Set("User").Select("new (LastName, FirstName)")

I obviously get an error

System.Linq.Dynamic.Core.Exceptions.ParseException: 'No property or field 'FirstName' exists in type 'User''

Even though I have the field in the database
So the question is: How can I tell EF at run time, that the User Class has a field FirstName. Even though it was not declared in code?
I looked at all the documentation about OnModelCreating, but can't seem a way to add a new property, only configure existing/known properties.
any ideas?
Thanks in advance!
UPDATE
I got a freelancer to write me some code, but its not really working (he just took the money before i had time to test it)
this is what I added to my OnModelCreating
Dim asm = Assembly.GetAssembly(GetType(FieldTypes))
            Dim asb = AppDomain.CurrentDomain.DefineDynamicAssembly(New AssemblyName(asm.FullName), AssemblyBuilderAccess.Run)
            Dim modb = asb.DefineDynamicModule(t.Module.Name)
            Dim builder = modb.DefineType("Dynamic" & t.Name, TypeAttributes.Public Or TypeAttributes.Class, t)
            builder.DefineDefaultConstructor(MethodAttributes.Public)
            Dim tbl = t.GetSchemaTable.Table
            Dim newcols = dbcols.Where(Function(x) x.ObjectName = tbl)
            For Each column In newcols
                If t.GetProperty(column.Name) Is Nothing Then
                    Dim dt As Type
                    Select Case column.TypeName
                        Case "int" : dt = GetType(Integer)
                        Case "nvarchar" : dt = GetType(String)
                        Case "datetime2" : dt = GetType(Date)
                        Case "bit" : dt = GetType(Boolean)
                    End Select
                    CreateAutoImplementedProperty(builder, column.Name, dt)
                End If
            Next
mthd.MakeGenericMethod(builder.CreateType).InvokePlus(modelBuilder)

and here is the function used
Private Sub CreateAutoImplementedProperty(ByVal builder As TypeBuilder, ByVal propertyName As String, ByVal propertyType As Type)
        Dim fieldBuilder = builder.DefineField(String.Concat("m_", propertyName), propertyType, FieldAttributes.Private)
        Dim propertyBuilder = builder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.HasDefault, propertyType, Nothing)
        Dim propertyMethodAttributes = MethodAttributes.Public Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig
        Dim getterMethod = builder.DefineMethod(String.Concat("get_", propertyName), propertyMethodAttributes, propertyType, Type.EmptyTypes)
        Dim getterILCode = getterMethod.GetILGenerator()
        getterILCode.Emit(OpCodes.Ldarg_0)
        getterILCode.Emit(OpCodes.Ldfld, fieldBuilder)
        getterILCode.Emit(OpCodes.Ret)
        Dim setterMethod = builder.DefineMethod(String.Concat("set_", propertyName), propertyMethodAttributes, Nothing, New Type() {propertyType})
        Dim setterILCode = setterMethod.GetILGenerator()
        setterILCode.Emit(OpCodes.Ldarg_0)
        setterILCode.Emit(OpCodes.Ldarg_1)
        setterILCode.Emit(OpCodes.Stfld, fieldBuilder)
        setterILCode.Emit(OpCodes.Ret)
        propertyBuilder.SetGetMethod(getterMethod)
        propertyBuilder.SetSetMethod(setterMethod)
    End Sub

But if this code runs, then I lose my debugging in VS. Trying to get the value of variables in watch/immediate windows gives me the following error:

error BC31091: Import of type 'FieldTypes' from assembly or module
'MyClass.dll' failed.

If I comment out this code. Everything is back to normal. What am I doing wrong?
Thanks!

A: If you just want to construct a new type which has that property, you can use the DynamicClassFactory from System.Linq.Dynamic.Core
You can use this like:
var props = new DynamicProperty[]
{
  new DynamicProperty("FirstName", typeof(FirstName))
};

var type = DynamicClassFactory.CreateType(props);
var dynamicClass = Activator.CreateInstance(type) as DynamicClass
dynamicClass.SetDynamicProperty("Name", "Test");

See https://github.com/zzzprojects/System.Linq.Dynamic.Core/blob/master/src/System.Linq.Dynamic.Core/DynamicClassFactory.cs#L172


text:
Q: Explicit expression for recursively defined functions Consider a function $w(i)$, $i \in \mathbb{N}$, defined recursively by:
$w(0)=w(1)=1$, and
$w(i)={i}^{n}-\sum_{j=1}^{i-1}{i \choose j}w(j)$ for  $i>1$.
Is it possible to write $w(i)$ out explicitly as a function of $i$ (i.e., with only $i$ on the right hand side), for $i>1$ ?
In general, given a recursively defined total computable function say, $f(n)$, is it always possible, in principle, to write out $f(n)$ explicitly as a function of $n$, for $n$ large enough? I suspect it's impossible. If so, what is the real reason that prevents us from doing so?
Another well known example that comes to my mind is:
$f(0)=f(1)=c$, and
$f(i)=5f(i-1)(1-f(i-1))$
where we can choose some value of $c \in (0,1)$ so that the trajectory of $f(i)$ becomes chaotic in $(0,1)$. If we could really express any recursively defined total computable function explicitly, then we could write out the chaotic trajectory in a finite, flat and non-dynamic formula, which seems strange to me. (or can we?)

Edit: Thank you very much for all the answers. They are really helpful.
@Joel: Is the recursive formation essential when the resulting recursive function doesn't grow faster than it's component functions ${g}_{i}$ (in your notation)? i.e., is it true that given ${g}_{i}$ and recursive function $f$ defined on them, as long as $f$ doesn't grow faster than the fastest of ${g}_{i}$, the recursive formation can be dispensed with?
@Carl: By "...it is not possible to come up with a completely explicit form for every computable function, in some fixed signature" , did you mean to write out the functions symbolically using finite, fixed set of symbols? In @Joel's interpretation, he didn't distinguish between we being able to symbolically write out exponential functions as, say ${2}^{n}$, and just taking the recursive function on multiplication as another "known" basic function ${g}_{i}$. Of course, one may just dismiss ${2}^{n}$ as a "shorthand" for the whole recursive formation, but I do feel they are not quite the same ("${2}^{n}$" is closer to what I had in mind by "explicit". I'd like to know if the distinction makes any sense in any sense).
Another question I have concerns about this "...because then by enumerating all possible forms we would get a numbering ϕ as in the theorem" But just because we can write a completely explicit form for each computable function doesn't mean we can enumerate these forms effectively, does it? If we can't, this does not contradict the theorem. Can you be more specific about this? Thanks!

A: The class of primitive recursive functions is the smallest class of functions containing the basic primitive recursive functions (zero, successor, projection) and closed under the two operations:

*

*composition: if $h$ and $g_1,\ldots,g_k$ are primitive recursive, so is the function  $$\vec x\mapsto h(g_1(\vec x),g_2(\vec x),\ldots,g_k(\vec x)).$$

*primitive recursion: if $h$ and $g$ are primitive recursive, then so is the function $f$ defined by $$f(0,\vec x)=h(\vec x),$$ $$f(n+1,\vec x)=g(n,\vec x, f(n,\vec x)).$$

This class is extremely robust and includes all of the functions that you mention in your question (but it falls short of the class of all Turing computable functions).
I interpret your question as being about the extent to which we might hope to eliminate the recursion scheme, and still arrive at the same class of functions.
One easy observation, of course, is that we cannot simply eliminate the recursion scheme as is and still get all primitive recursive functions. For example, even if we add addition and multiplication as basic functions, then the composition scheme will remain inside the class of polynomial functions. But we can easily define the exponential function $n\mapsto 2^n$ by recursion over that class, and this does not have polynomial growth.
More generally, let us consider whether we might add finitely many additional, powerful primitive recursive functions $g_1,\ldots,g_k$ as basic, and then close only under composition. This interpretation of the question would be: can we arrange that this class is closed under definition by recursion? In other words, is every function definable by recursion using those functions and their compositions already expressible as a term in the language using only those functions (that is, as a composition)?
The answer to this more general version of the question is still no. For any finitely many primitive recursive functions $g_1,\ldots,g_k$, the closure of it under composition is strictly smaller than the closure of it under composition and definition by recursion. Specifically, there will be a primitive recursive function $f$, defined by one or more recursions over those $g_i$ and the usual basic functions, which has a higher growth rate than any individual term in those functions. This can be proved by using a high enough level function $A_n$ of the Ackermann function, because whenever a collection of functions is dominated by $A_n$, then all terms in those functions are dominated by $A_{n+1}$.

A: With regard to the general question, I defer to Joel Hamkins's answer.  For your specific function, though, the first few cases give
$$\begin{align}
w(2) &= 2^n - 2 \\\
w(3) &= 3^n -3\cdot 2^n + 3\\\
w(4) &= 4^n - 4\cdot 3^n + 6\cdot 2^n - 4\\\
w(5) &= 5^n - 5\cdot 4^n + 10\cdot 3^n - 10\cdot 2^n + 5
\end{align}$$
This suggests the explicit formula (where by "explicit" I just mean that the function $w$ doesn't appear on the right hand side)
$$w(i) = \sum_{j=0}^{i-1} (-1)^j(i-j)^n{i \choose j}$$
which I suspect (without taking time to verify) can be proved by straightforward induction.
A minor additional note:  The OP's second example does not have chaotic trajectories.  Because the coefficient 5 is greater than 4, the typical trajectory quickly escapes the unit interval and henceforth heads for $-\infty$.
Added 12/19/11:  An elementary mathoverflow question that was opened and closed yesterday made me realize there's an interpretation for the function $w(i)$ that makes it easy to see the equivalence of the OP's recursive formula and the "explicit" formula I came up with:  The function $w$ counts the number of maps from a set of $n$ objects onto a set of $i$ objects (with $n$ assumed greater than or equal to $i$).  The OP's recursive formula does the count by starting with the number of all maps ($i^n$) and subtracting the number that are mappings onto subsets of size $j$ for $j=1$ to $i-1$.  My explicit formula is an inclusion-exclusion count of all maps (not necessarily onto) from a set of size $n$ to sets of size $i-j$.  The only little mystery from this point of view is why the equivalence works for all $n$, not just $n\ge i$.

A: There is an easy inversion formula for $$a(k)=\sum_{j=0}^k\Big({k\atop j}\Big)b(j)\, ,$$
namely,
$$b(k)=\sum_{j=0}^k  (-1)^{k-j}\Big({k\atop j}\Big)a(j)\, ,$$
and in your case ($a(k):=k^n$) this produce the formula shown by Barry. You can see and prove it in several ways: The inverse matrix of the triangular matrix whose entries are the binomial coefficients. Or an identity between suitable generating functions. Also, as an instance of the inclusion-exclusion formula. I'm quite sure you may find nice hints in  Concrete Mathematics  by Graham, Knuth, and Patashnik.

A: To follow up on Joel Hamkins' answer, the fundamental obstruction here is totality. Explicit definitions are always going to give total functions. The reason that recursion is so powerful for defining functions is that it is possible to make partial functions, e.g.
$$
f(0) := 0 \qquad f(2n+2) := f(2n) \qquad f(2n+1) := f(2n+3)
$$
The following is a standard theorem.

Theorem. Let $C$ be a countable system of total computable functions $\mathbb{N} \to \mathbb{N}$ with the property

*

*There is a numbering $\phi_i\colon \mathbb{N} \to C$ such that every $f \in C$ is of the form $\phi_i$ for at least one $i$, and there is a uniform way to compute $\phi_i(j)$ given just $i$ and $j$.

  Then $C$ does not include all total computable functions from $\mathbb{N}$ to $\mathbb{N}$.
Proof. Diagonalization.

In the context of this question, the philosophical meaning of this theorem is that it is not possible to come up with a completely explicit form for every computable function, in some fixed signature, because then by enumerating all possible forms we would get a numbering $\phi$ as in the theorem.
The closest we can hope for in terms of an explicit form for all total computable functions is something like Kleene normal form, but this still includes an unbounded search. Kleene's normal form theorem says that there is a primitive recursive function $U$ and a primitive recursive relation $T$ such that for every computable function $f$ there is an $e$ such that for all $i$,
$$
f(i) \simeq U(\mu s . T(e,i,s)).
$$
where $\mu$ is the unbounded search operator.


text:
Q: How do I manage profiles using SimpleMembership? I have an ASP.NET MVC 4 site based off the internet template. I am using the SimpleMembership which i set up with that template.
I can modify the Users table which has been creted for me but I am unsure as to the "correct" way to modify the extra fields I have added. I want Fullname, Email etc and have added them to the user table but there appears no way to update through the SimpleMembership WebSecurity.* static methods.
Are you supposed to just update those properties yourself using EF outside of the SimpleMembership API?

A: if you look right around line 273 of the accountcontroller you'll find this line
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });

Looks like even OOTB they (MS) are doing just as you suggested and using EF to update.
I too, am looking for the "correct" way of updating and accessing these properties.
Edit:
Here's my solution (I'm happy if someone says there's an OOTB way to do this).
wrap UserProfile (the .net Entity from SimpleMembership) in a session class.
public static class sessionHelpers {
     public static UserProfile userProfile
        {
            get
            {
                if (HttpContext.Current.Session["userProfile"] != null)
                {
                    return HttpContext.Current.Session["userProfile"] as UserProfile;
                }
                else
                {
                    using (UsersContext db = new UsersContext())
                    {
                        HttpContext.Current.Session["userInfo"] =
                        db.UserProfiles.Where(x => x.UserName ==
                            HttpContext.Current.User.Identity.Name).FirstOrDefault();

                   return db.UserProfiles.Where(x => x.UserName ==
                       HttpContext.Current.User.Identity.Name).FirstOrDefault();
                    }
                }
            }
            set { HttpContext.Current.Session["userProfile"] = value; }
        }
}

From this you can access the profile table by doing
string foo = sessionHelpers.userProfile.FIELDNAME;

where sessionHelpers is my wrapper class. The if block just ensures that if it hasn't been set in the current session that accessing it will attempt to get it.

A: 1 - You need to enable migrations, prefereably with EntityFramework 5
2 - Move your
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "EmailAddress", autoCreateTables: true);

to your Seed method in your YourMvcApp/Migrations/Configuration.cs class
    protected override void Seed(UsersContext context)
    {
        WebSecurity.InitializeDatabaseConnection(
            "DefaultConnection",
            "UserProfile",
            "UserId",
            "UserName", autoCreateTables: true);

        if (!Roles.RoleExists("Administrator"))
            Roles.CreateRole("Administrator");

        if (!WebSecurity.UserExists("lelong37"))
            WebSecurity.CreateUserAndAccount(
                "lelong37",
                "password",
                new {Mobile = "+19725000000", IsSmsVerified = false});

        if (!Roles.GetRolesForUser("lelong37").Contains("Administrator"))
            Roles.AddUsersToRoles(new[] {"lelong37"}, new[] {"Administrator"});
    }

Now EF5 will be in charge of creating your UserProfile table, after doing so you will call the WebSecurity.InitializeDatabaseConnection to only register SimpleMembershipProvider with the already created UserProfile table, also tellling SimpleMembershipProvider which column is the UserId and UserName. I am also showing an example of how you can add Users, Roles and associating the two in your Seed method with custom UserProfile properties/fields e.g. a user's Mobile (number) and IsSmsVerified.
3 - Now when you run update-database from Package Manager Console, EF5 will provision your table with all your custom properties
For additional references please refer to this article with sourcecode:
http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/

A: They made it easy to modify the profile with SimpleMembership.  SimpleMembership is using the code first EF model and the user profile is defined in the file AccountModels.cs that is generated as part of the Internet template for MVC 4. Just modify the class UserProfile and add the new fields in the class definition.  For example, adding a field for email would look something like this:
[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

Here is an example on how you would access the email field:
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var email = user.Email;

Here is what the database looks like after adding the email field.

There is a good blog that describes some of the changes in SimpleMembership here. You can also find more detailed information on customizing and seeding SimpleMembership here.

A: You need to add them to your Database ( done according to description )
add them to the view ( edit , add , delete , and view ) unless modified
add them to your model in UserProfiles
Then it will work.


text:
Q: How do I find the instance to which a method belongs? // minified base class code (if the uncompressed code is needed, I'll post it)
    function Class(){}Class.prototype.construct=function(){};Class.extend=function(c){var a=function(){arguments[0]!==Class&&this.construct.apply(this,arguments)},d=new this(Class),f=this.prototype;for(var e in c){var b=c[e];if(b instanceof Function)b.$=f;d[e]=b}a.prototype=d;a.extend=this.extend;return a};
// custom event class
var Event = Class.extend({
    handlers: [],
    // stores the event handler
    subscribe: function(handler, thisObj) {
        this.handlers.push([handler, thisObj]);
    },
    // calls the event handlers
    fire: function() {
        for(i in this.handlers) {
            var handler = this.handlers[i];
            handler[0].apply(handler[1]);
        }
    }
});
var Class2 = Class.extend({
    myEvent: new Event(), // the event
    test: function() { // fires the event
        this.myEvent.fire(this);
    }
});
var Class3 = Class.extend({
    construct: function(model) {
        this.name = "abc";
        model.myEvent.subscribe(this.handler, this); // subscribe to the event
    },
    handler: function() {
        alert(this.name); // alerts 'abc'
    }
});
var instance1 = new Class2();
var instance2 = new Class3(instance1);
instance1.test();

The only way to make the event handler code to work with the good 'this' is by adding a new argument ('thisObj') to the 'subscribe' method? Is there a better way to do this?

A: The behaviour you're getting is due to the fact that when you pass a "method" to a function, the receiving function has no idea it's a method. It's just a block of javascript that needs to get executed.
Prototype gets around this issue with the bind method

*

*http://api.prototypejs.org/language/function/prototype/bind/
You can get similar behaviour (I didn't look at the implementation details of bind) by using a closure.
var Class3 = Class.extend({
    construct: function(model) {
        this.name = "abc";
        //model.myEvent.subscribe(this.handler, this); // subscribe to the event
        var self = this;
        model.myEvent.subscribe(function() {self.handler()});
    },
    handler: function() {
        alert(this.name); // alerts 'abc'
    }
});

Or apply some similar functionality to the subscribe method of your custom event class.
EDITED To reflect CMS's observations. Thanks!


text:
Q: How to make GridView touchable inside ListView? I'm trying to implement grid view inside list view. I want to disable touch of List View and want to perform touch event on Grid View. How to do it?
I need to do this because i have implemented my calendar within grid view and i have inflated my grid view within list view.
I am using below custom List activity to disable scrolling and touch event but still it gets my touch as I am getting log as true value for "ListViewTouch" and "ListViewDispatchTouch".
public class ScrollDisabledListView extends ListView {

private int mPosition;

public ScrollDisabledListView(Context context) {
    super(context);
}

public ScrollDisabledListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ScrollDisabledListView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    Log.d("ListViewTouch", "true");
    return true;
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.d("ListViewDispatchTouch", "true");
    final int actionMasked = ev.getActionMasked() & MotionEvent.ACTION_MASK;

    if (actionMasked == MotionEvent.ACTION_DOWN) {
        // Record the position the list the touch landed on
        mPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
        return super.dispatchTouchEvent(ev);
    }

    if (actionMasked == MotionEvent.ACTION_MOVE) {
        // Ignore move events
        return true;
    }

    if (actionMasked == MotionEvent.ACTION_UP) {
        // Check if we are still within the same view
        if (pointToPosition((int) ev.getX(), (int) ev.getY()) == mPosition) {
            super.dispatchTouchEvent(ev);
        } else {
            // Clear pressed state, cancel the action
            setPressed(false);
            invalidate();
            return true;
        }
    }

    return super.dispatchTouchEvent(ev);
}

A: Try adding this attribute to the ListView in your layout file: android:clickable="false".

A:  android:descendantFocusability="blocksDescendants"

Add this in your gridview's XML file. That should do it.
Like this:
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/reminderItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"

        android:descendantFocusability="blocksDescendants"

        android:padding="0dp">


text:
Q: How to use .format() string in a MySQL statement? I'm trying to format a MySQL statement with today's data, as well as 7 days back. I'm pretty sure the date is in the correct format, so I don't think that's the issue.
The error report is:
 Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
      result = self._query(query)
    Traceback (most recent call last):
         AttributeError: 'int' object has no attribute 'format'

e.g.
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))

cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)

A: Using prepared statements (safe way):
qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

cursor.execute(qry, [today, week_ago])

Using .format() which leaves you at risk for sql injections (if you pass user input to .format() e.g.)
qry = """
    SELECT *
    FROM db
    WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()

today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d'))  # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d'))  # Convert to string

qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)


text:
Q: Parsing JSON result with Gson I have an InputStreamReader reader that contains this JSON file:
http://barcelonaapi.marcpous.com/bus/nearstation/latlon/41.3985182/2.1917991/1.json
Also, I have a class Station that contains ID, streetName, city, utmX, utmy, lat, lon as members.
What should i do, if I want parse the JSON file with GSon, to return an List<Station>?
I tried this :
gson.fromJson(reader, new TypeToken<List<Station>>(){}.getType());

But it raised an IllegalStateException (Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2).
How to extract only data which interests me (members of my Station class)?
Is it possible with GSon, or I need to use the JSON standard API provided by Android SDK (with JSONObject and JSONArray)?

A: You're close, but in this case you can't directly map to a List<Station> because it is wrapped in json object (2 layers deep) that also contains some other fields. That's basically also what the error is trying to tell you: you're instructing Gson to map to an array/list of items (in json: [...]), but instead it encountered an object (in json: {...}).
The quickest solution is to create a POJO that reflects this json response. For example:
public class Response {
    @SerializedName("code") public int mCode;
    @SerializedName("data") public ResponseData mData;
}

public class ResponseData {
    @SerializedName("transport") public String mTransport;
    @SerializedName("nearstations") public List<Station> mStations;
}

Now you can map the json to the above Response and get the List<Station> from the result:
Response response = gson.fromJson(reader, Response.class);
List<Station> stations = response.mData.mStations;
// do something with stations...

If you like to do something a little more advanced, you can take a look into writing a custom deserialiser or type adapter.


text:
Q: image not resizing in twitter bootstrap responsive page design I have a web page which is designed using twitter bootstrap along with it's responsive css inclusion to make everything responsive on different window sizes.But the image in the following codes not re-sizing itself when browser resized, so is not showing responsiveness

media name

    In css file styles are -
    .media-link
    {
            float:left;
        border:1px solid #ccc;
        display:inline-block;
        color:#3B5998;
        cursor:pointer;
        margin-right:5px;
    }
    .mod-picture{
        margin-right:10px;
        border:0;
        display:block;
        margin:3px;
    }

but if i remove float:left; and display:inline-block; styles from media-link class then image is resizing on browser window size changes.But i can't remove these two properties because next content with class "media-container" need to be appear on right.I tried in many ways like adding float:left in the div before link but failed.Please suggest me.

A: If you are using bootstrap 3, then you may need to add the class 'img-responsive' to your 'img' tag.

A: You can take styles from Bootstrap 3 and apply for your code:

.media-link{
  //nothing styles
}

.mod-picture{
  // max width of image
  max-width: 50%;
  float: left;
  display: block;
  border:1px solid #ccc;
}

A: If you are using bootstrap 3 which you should. Then just add class img-responsive to img tag. and That's all to make it responsive.
Here is CDN link for bootstrap3 css. You don't even need to add bootstrap-responsive css.
//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"
In case bootstrap 2.3 existing problem use this-

      media name

.mod-picture{
  width:40%;
  padding:5%;
  max-width: 200px;
  height:auto;
  float:left;
}
 .media-container{
   display:inline-block;
 }


text:
Q: Logic regarding some code to find everything not in a table? So, what I've written below does this (to my knowledge and how it's outputting):
1) I've found where Zip, City, State, and Bank Name match. ~ 3786 records
2) I've combined that with where just City, State, Name matches (minus Zip). ~4390 records
Combined I have 8176 records.
What I'm trying to find next is the rest of the table (18,288 records total, so roughly 10,000 left over) that didn't get picked up in those 2 queries equaling 8,176.
Any idea on how to find that?
My BM_BNKA_FLATFILE_FEDACHDIR2018_ZIP_5_010 table is just splitting out a table, acting as the source table for all 18,288 records.
My BM_BNKA_FLATFILE_SWIFT_US_LPAD_SMALLZIP_SPLIT_CITY_STATE table is acting as another source table, where I formatted Columns correctly.
My BM_BNKA_FLATFILE_FEDACHDIR2018_NDIST_BIC_ZIP_5_030 combines those two tables above on Zip, State, City, Name and filteres where BIC is not null. Bic is just a bank code.
SELECT SWIFT_US.BIC,
       FED_ACH_5ZIP.RoutingNumber,
       FED_ACH_5ZIP.BankName,
       FED_ACH_5ZIP.BankCity,
       FED_ACH_5ZIP.BankStateCd,
       FED_ACH_5ZIP.BankZip_5,
       'Second Pass' AS Phase
FROM dbo.BM_BNKA_FLATFILE_FEDACHDIR2018_ZIP_5_010 AS FED_ACH_5ZIP
LEFT OUTER JOIN dbo.BM_BNKA_FLATFILE_SWIFT_US_LPAD_SMALLZIP_SPLIT_CITY_STATE AS SWIFT_US
        ON FED_ACH_5ZIP.BankName = SWIFT_US.INSTITUTION_NAME
        AND FED_ACH_5ZIP.BankCity = SWIFT_US.CITYNEW
        AND FED_ACH_5ZIP.BankStateCd = SWIFT_US.STATENEW
/*AND FED_ACH_5ZIP.BankZip_5 = SWIFT_US.ZIPNEW    */
WHERE (SWIFT_US.BIC IS NOT NULL)
AND FED_ACH_5ZIP.RoutingNumber NOT IN
                        (SELECT RoutingNumber
                         FROM BM_BNKA_FLATFILE_FEDACHDIR2018_NDIST_BIC_ZIP_5_030)

UNION ALL

SELECT *, 'First Pass' AS Phase
FROM BM_BNKA_FLATFILE_FEDACHDIR2018_NDIST_BIC_ZIP_5_030

A: I guess you need a simple EXCEPT clause -
SELECT *
FROM BM_BNKA_FLATFILE_FEDACHDIR2018_ZIP_5_010

EXCEPT

(
SELECT SWIFT_US.BIC,
       FED_ACH_5ZIP.RoutingNumber,
       FED_ACH_5ZIP.BankName,
       FED_ACH_5ZIP.BankCity,
       FED_ACH_5ZIP.BankStateCd,
       FED_ACH_5ZIP.BankZip_5,
FROM dbo.BM_BNKA_FLATFILE_FEDACHDIR2018_ZIP_5_010 AS FED_ACH_5ZIP
LEFT OUTER JOIN dbo.BM_BNKA_FLATFILE_SWIFT_US_LPAD_SMALLZIP_SPLIT_CITY_STATE AS SWIFT_US
        ON FED_ACH_5ZIP.BankName = SWIFT_US.INSTITUTION_NAME
        AND FED_ACH_5ZIP.BankCity = SWIFT_US.CITYNEW
        AND FED_ACH_5ZIP.BankStateCd = SWIFT_US.STATENEW
/*AND FED_ACH_5ZIP.BankZip_5 = SWIFT_US.ZIPNEW    */
WHERE (SWIFT_US.BIC IS NOT NULL)
AND FED_ACH_5ZIP.RoutingNumber NOT IN
                        (SELECT RoutingNumber
                         FROM BM_BNKA_FLATFILE_FEDACHDIR2018_NDIST_BIC_ZIP_5_030)

UNION ALL

SELECT *
FROM BM_BNKA_FLATFILE_FEDACHDIR2018_NDIST_BIC_ZIP_5_030
)


text:
Q: VSCode Golang dlv debug error for version mismatch On MacOS, brew upgrad-ed upgraded golang to version 1.14. Able to run unit test but debug fails with message
# errors
compile: version "go1.12.13" does not match go tool version "go1.14.2"
# unicode/utf16
compile: version "go1.12.13" does not match go tool version "go1.14.2"
# unicode/utf8
compile: version "go1.12.13" does not match go tool version "go1.14.2"
# internal/race
compile: version "go1.12.13" does not match go tool version "go1.14.2"
# container/list
....

go env output shows go version as 1.14.2

A: Fixed. Had a stale go bin reference in VSCode User settings.


text:
Q: Is there a possibility to make from one long column two small in R? Hope you have a nice day.
Today I was trying two make from one big column two small ones in R. However, I haven't found a way how to make it.
I have something like this (however, it is way bigger)
name3 <- c(1, 2, 3, 4, 5, 6)
df1 <- data.frame(name3)
print(df1)

I want to do something like this. My intention is just take the total number of variables and divide it into two equal groups.
 name <- c(1, 2, 3)
 name1 <- c(4, 5, 6)
 df <- data.frame(name, name1)
 print (df)

Thanks in advance!

A: One way to do it, you can first write this as a matrix in which you specify the number of columns
than transform the matrix to dataframe
from a dataframe you can convert each column to a vector
This is how I did it
name3 <- c(1, 2, 3, 4, 5, 6)

df <- as.data.frame(matrix(name3, ncol = 2))

name1 <- df$V1
name2 <- df$V2

A: Trying to accomplish this as close to base r as possible, this would be my method if the order of the sub vector don't matter:
# needed for index function
library(zoo)

# simple function to calculate even / odd
is.even <- function(x) x %% 2 == 0

# define my vector of values
name3 <- c(1, 2, 3, 4, 5, 6)

# split vector by even or odd index.
split(name3,f= is.even(index(name3)) )

Result:
$`FALSE`
[1] 1 3 5

$`TRUE`
[1] 2 4 6


text:
Q: how to retrieve/parse results from ansible k8s modules using with_items on multiple fields Team,
My task is running fine with json output but I just want to look for pod name and namespace instead of outputting the whole pod json output. so, i am using debug to pull the pod name but not sure how to pull all pods names along side namespace..
any hint? I am not able to understand from here: extracting a variable from json output then debug and register the outout with ansible
      - name: "Get a list of all pods from any namespace"
        k8s_facts:
          kind: Pod
          namespace: webhook
          kubeconfig: $WORKSPACE
          verify_ssl: no
        register: pod_list
      - debug:
          var: pod_list

      - name: list names and namespaces
        debug:
          msg: "{{ pod_list.resources[0].metadata.name }}"

output:
TASK [3_validations_on_ssh : list names and namespaces] *******************************************************************************************************************************
ok: [target1] => {
    "msg": "k8s-webhook-auth-xxxx1"
}

sample output snippet that looks for a pod is below: similarly it continues for other pods in pod_lsit

TASK [3_validations_on_ssh : debug] *****************************************************
ok: [target1] => {
    "pod_list": {
        "changed": false,
        "failed": false,
        "resources": [
            {
                "apiVersion": "v1",
                "kind": "Pod",
                "metadata": {
                    "creationTimestamp": "2019-10-11T18:44:04Z",
                    "generateName": "k8s-webhook-auth-",
                    "labels": {
                        "app": "k8s-webhook-auth",
                        "controller-revision-hash": "666c6cb69d",
                        "pod-template-generation": "20",
                        "release": "k8s-webhook-auth"
                    },
                    "name": "k8s-webhook-auth-xxxx1",
                    "namespace": "webhook",
                    "ownerReferences": [
                        {
                            "apiVersion": "apps/v1",
                            "blockOwnerDeletion": true,
                            "controller": true,
                            "kind": "DaemonSet",
                            "name": "k8s-webhook-auth",
                            "uid": "1e9-8e9b-ac1f6b4ea082"
                        }
                    ],
                    "resourceVersion": "47592900",
                    "selfLink": "/api/v1/namespaces/webhook/pods/k8s-webhook-auth-5jx6w",
                    "uid": "1e9-8e9b-ac1f6b4ea082"
                },

expected output:
k8s-webhook-auth-xxxx1 webhook
k8s-webhook-auth-xxxx2 webhook
k8s-webhook-auth-xxxx3 webhook

A: I think you would need a loop to get the exact output you are looking for, but that means it won't be in a single "message", but rather one message per pod, for example:
 - debug:
    msg: "{{ item.metadata.name }} {{ item.metadata.namespace }}"
  loop: "{{ pod_list.resources }}"

The other option is to create a new object with the data you need. I'll give 2 examples below but there's a lot of different options. These examples use debug to show the output, but you would probably want to use set_fact:
 - debug:
    var: pod_list | json_query('resources[].[metadata.name, metadata.namespace]')

 - debug:
    var: pod_list | json_query(query)
  vars:
    query: 'resources[].{name: metadata.name, namespace: metadata.namespace}'

Edit: more examples
To limit output in loops, check out the loop control documentation. Here's an example using the pod name:
- debug:
    msg: "{{ item.metadata.name }} {{ item.metadata.namespace }}"
  loop: "{{ pod_list.resources }}"
  loop_control:
    label: "{{ item.metadata.name }}"

To assign output to a new variable use set_fact. Be wary that if combined with a loop, your result will be a list of multiple objects. Here's an example using one of the debug tasks above:
- set_fact:
    pods: "{{ pod_list | json_query(query) }}"
  vars:
    query: 'resources[].{name: metadata.name, namespace: metadata.namespace}'

- debug:
    var: pods


text:
Q: How can you change ./configure to use a specific binary over /usr/bin? Running macOS Catalina 10.15.6.
My question is more related to compilation with GNU tools, so it may be more suited for a different SE site — I'll be happy to close and ask somewhere else if that's the case.
I'm trying to compile software (namely wine-6.0) and the compilation requires bison, for which there's already an executable in /usr/bin. However, bison needs to be version >3.0 to compile the program and the binary in /usr/bin is version 2.7.6. I compiled bison 3.7.6 and I was gonna just move the new bison 3.7 binary into /usr/bin but due to the filesystem protection of macOS, I can't just replace /usr/bin/bison. I'd have to restart my mac in recovery mode to disable the filesystem lock, but I have something open that can't stop running at the moment.
Using ./configure --enable-win64 gives the following error:
checking for bison... bison
checking whether bison is recent enough... no
configure: error: Your bison version is too old. Please install bison version 3.0 or newer.

To fix it, I thought modifying PATH would work; I moved the bison 3.7.6 binary to /usr/local/bin/bison and did export PATH=/usr/local/bin:$PATH before ./configure but it doesn't work; it still just errors about not having bison >3.0 (the same error as before I tried to mess with bison):
checking for bison... bison
checking whether bison is recent enough... no
configure: error: Your bison version is too old. Please install bison version 3.0 or newer.

The weird thing is, just trying to run bison uses the right binary.
$ bison -V
bison (GNU Bison) 3.7.6
Written by Robert Corbett and Richard Stallman.
...

$ which bison
/usr/local/bin/bison

I also tried messing with the configure.ac file a little, but the problem is I don't really know what I'm doing there. Editing the config file and rerunning autoconf and using ./configure then still doesn't work.
Ultimately, my question is: how do I ensure ./configure uses the correct bison binary?

A: My problem was that the bison install was bad.
I compiled bison from source with configure --prefix=/usr/local instead of letting brew decide where to put everything and then made sure PATH was correct when using configure to gen the makefile for the wine compilation, and it worked.
The problem arose from the wine configure script just checking the exit code of running Bison on an empty file to verify the version. Because bison was failing due to a broken install, it was giving the error exit code, causing the configure script to believe bison was an insufficient version.


text:
Q: how expensive are the postgres WITH RECURSIVE? I have a product system that each category can have multiple subcategory layers if there aren't any products attached to them, and we can attach as many products as we want to a category if there aren't any sub-categories attached to it like the example below:
PS: I deleted other columns/constraints from the two tables for simplicity
      CREATE TABLE categories (
        id serial PRIMARY KEY,
        name VARCHAR NOT NULL,
        parent_id INT
    );
    CREATE TABLE products (
        id serial PRIMARY KEY,
        name VARCHAR NOT NULL,
        category_id serial,
        CONSTRAINT fk_category FOREIGN KEY(category_id) REFERENCES categories(id)
    );
INSERT INTO categories (
    id,
    name,
    parent_id
)
VALUES
    (1, 'Electronic Devices', NULL),
    (2, 'lap-top', 1),
    (3, 'smart-phones', 1),
    (4, 'headphones', 1),
    (5, 'desctops', 1),
    (6, '16inc laptops', 2),
    (7, '13inc laptops', 2),
    (8, 'smart phones', 3),
    (9, 'phablets', 3),
    (10, 'wireless headphones', 4),
    (11, 'wired headphones', 4),
    (12, 'onear headphones', 10),
    (13, 'large headphones', 10);

INSERT into products (
    id, name, category_id
) VALUES
    (1, 'mac-book-16 model 1', 6),
    (2, 'mac-book-16 model 2', 6),
    (3, 'mac-book-16 model 3', 6),
    (4, 'mac-book-13 model 1', 7),
    (5, 'mac-book-13 model 2', 7),
    (6, 'mac-book-13 model 3', 7),
    (7, 'mac-book-13 model 4', 7),
    (8, 'iphone 10', 8),
    (9, 'iphone 11', 8),
    (10, 'iphone 12', 8),
    (11, 'iphone 13', 8),
    (12, 'iphone 14', 8),
    (13, 'iphone 10 pro max', 9),
    (14, 'iphone 11 pro max', 9),
    (15, 'iphone 12 pro max', 9),
    (16, 'iphone 13 pro max', 9),
    (17, 'iphone 14 pro max', 9),
    (18, 'galegxy note 8', 9),
    (19, 'galegxy note 9', 9),
    (20, 'galegxy note 10', 9),
    (21, 'some headphones', 12),
    (22, 'samsung galexypods', 12),
    (23, 'apple earpods', 12),
    (24, 'apple earpod pro', 13);

Let's say I want to get all the products related to "Electronic Devices" how I'm planning to do it like below:
WITH RECURSIVE products_in_category AS (
    SELECT
        p.*,
        c.parent_id
    FROM
        products p
    INNER join categories c on c.id = p.category_id
    WHERE
        category_id = 1
    UNION
        SELECT
            p2.*,
            c2.parent_id
        FROM
            products p2
        INNER join categories c2 on c2.id = p2.category_id
        INNER JOIN products_in_category s ON s.category_id = c2.parent_id
) SELECT
    *
FROM
    products_in_category limit 25;

I'm expecting to see all 24 rows in products, but I'm getting 0.
A: Is it possible with WITH RECURSIVE? , if it is how?
B: Is it a good way to do it this way(I do create indexes on my id fields)? is it scaleable (when we have 500 categories & 10k products for example)? if not what are the alternatives?

A: To answer the indirect question of "why doesn't this work"...

First, you should only recurse that part of the structure that needs it; the categories in your case

*

*build the tree of categories first, inside the recursive CTE

*join the products to it outside of the CTE

Second, your expected results don't need a recursive query, just a join.
SELECT
  p.*,
  c.parent_id
FROM
  products   p
INNER join
  categories c
    ON c.id = p.category_id

To get all products within an arbitrary category (and its children categories)...
WITH RECURSIVE
  recursed_category AS
(
  SELECT
    id     AS root_category_id,
    name   AS root_category_name,
    id     AS category_id,
    name   AS category_name
  FROM
    categories

  UNION ALL

  SELECT
    p.root_category_id,
    p.root_category_name,
    c.id,
    c.name
  FROM
    recursed_category   AS p  -- parent
  INNER JOIN
    categories          AS c  -- child
      ON c.parent_id = p.category_id
)
SELECT
  c.*,
  p.id    AS product_id,
  p.name  AS product_name
FROM
  recursed_category   AS c  -- category
INNER join
  products            AS p  -- product
    ON c.id = p.category_id
WHERE
  c.root_category_id = ???

This builds multiple trees, one for each category, and travels to every child node of each category.
Then in the WHERE clause you can specify which one you're actually interested in.
As SQL is Declarative, the optimiser willl apply the outer WHERE clause to the CTE, and not build all the trees then throw some of them away.
Then, it's the simple query again; just take the category tree and join the products on, in the outer query.
NOTE: This expressly starts at a category and browses down.  If you wanted to know which categories a product is in, do NOT use this.  Make your recursive CTE similarly, but start at the children and browse up.  Otherwise, the optimiser won't be able to push the where clause up to the CTE.

A: In this example as you can see on my Git Repos also :
https://github.com/WalterMatsuda/WITH-RECURSIVE-x-SELECT
The difference of the same operation made with a LOOP and subqueries is :
In a 1000000 Rows tables with 5 levels of hierarchy
For Loops and subqueries
Query OK (execution time: 15.359 sec; total time: 15.422 sec)
For With Recursive
Query OK (execution time: 62 ms; total time: 125 ms)

Both returning 1667 values .
You can try a more efficient looping logic than the most easier, but WITH RECURSIVE is made to use recursion.
Loops in other hand when you dont need to access multiple level,only want to repeat something withouth going to another conditional repetition is more efficient than Recursion.
So both should be used in their proper roles.


text:
Q: what tools to use to find c++ bug when compile for release. boost::asio, cmake. vs2012. crossroads / 0mq I have having some sort of memory or winsock issue that only occurs when c++ code is compiled in release mode.
Evidence that its a memory issue:
A previous unknown bug was fixed, by commenting out two lines of code. These two lines of code seem harmless. they were left overs from old versions. This indicates that somewhere I am using un-initialized memory. XS_Client is used as a base class.
        class XS_Client
        {
        private:

            /* these two lines of comments fixed the bug */
            /***********************************************
            enum { max_length = 1024 };
            char data_[max_length];
            **********************************************/

            void * context_;
            void * socket_;
            boost::thread t_;
            volatile bool should_run_;
        public:
            XS_Client(void *context, short type, const std::string &address)
            : context_(context), socket_(XS_Socket::NewSocket(context_,type))
            {
                XS_Socket::Connect(socket_,address);
        #ifdef _OUTPUTD
                std::cout << address << " XS_Client: " << GetCurrentThreadId() << std::endl;
        #endif
                boost::thread   t(boost::bind(&XS_Client::thread_func, this));
                t_.swap(t);
            }

            void SetSockOpt(int option, const void *optval,size_t optvallen)
            {
                int rc = xs_setsockopt(socket_,option,optval,optvallen);
                if ( rc != 0 )
                    std::cout << "xs_setsockopt error: " << xs_strerror(errno) << std::endl;
            }

            virtual ~XS_Client()
            {
                if ( should_run_ )
                    Stop();
            }

            void thread_func() {
                /* Create an empty message */
                xs_msg_t msg;

                while (should_run_)
                {
                    //int bytes_recvd = xs_recv(socket_,data_,max_length,0);
                    int rc = xs_msg_init (&msg);
                    if ( rc != 0 )
                        std::cout << "xs_msg_init error: " << xs_strerror(errno) << std::endl;
                    assert (rc == 0);
                    /* Block until a message is available to be received from socket */
                    int bytes_recvd = xs_recvmsg (socket_, &msg, 0);

        #ifdef _DEBUG
                    std::cout << "received " << bytes_recvd << std::endl;
        #endif;

                    if ( bytes_recvd == -1 )
                    {

                        if ( xs_errno() == ETERM )
                        {
                            should_run_ = false;
                            std::cout << "ETERM received" << xs_strerror(errno) << std::endl;
                            break;
                        }

                        if ( !should_run_ )
                            xs_msg_close (&msg);
                        else
                        {
                            std::cout << "receive error!" << xs_strerror(errno) << std::endl;
                            boost::this_thread::sleep(boost::posix_time::milliseconds(100u));
                        }
                    }
                    else
                    {

        #ifdef _DEBUG
                        //std::cout << "received " << xs_msg_data(&msg) << std::endl;
        #endif;
                        OnMsg(xs_msg_data(&msg),bytes_recvd);

                        /* Release message */
                        xs_msg_close (&msg);
                    }

                }

                int rc = xs_close (socket_);
                if ( rc != 0 )
                    std::cout << "xs_close error: " << xs_strerror(errno) << std::endl;

                Cleanup();
            }

            virtual void OnMsg(const void *msg, int bytes_recvd)
            {
                std::cout << "virtual void OnMsg received " << bytes_recvd << std::endl;
            }

            virtual void Stop()
            {
                should_run_ = false;
                t_.timed_join(boost::posix_time::milliseconds(2000));
            }

            virtual void Cleanup()
            {
            }

        };

Evidence that its a windows/socket issue:
The real bug is that my tcp socket (localhost) never gets data. However this only occurs when I am using both boost::asio and crossroads/0mq in same process. Also, the bug does not occur if I start the process through the debugger.
So when I compile in "realesewithdebuginfo" mode the bug only occurs when not in the debugger. same exact compiled code.
question1: what tool is recommended for c++ code analysis and/or windows api call analysis? Also, the problem is not easily recreated, so a static analysis may be best. i use lots of templates, boost::asio::udp, multiple treading libraries. multiple socket/io libraries.
question2: what is available on the windows side to see if I am causing a deadlock due to socket i/o mis-us-sages by external libraries?
tyvm4yh

A: The main difference between running under a debugger and not is the debug heap. To switch the debug heap off, you can use the _NO_DEBUG_HEAP environment variable. You can set this globally, but you're much better off doing it just for your debugging runs, as in this answer:
https://stackoverflow.com/a/1060929/1618406
If this reproduces the bug, but you're having difficulty actually debugging (because of the optimised code), I'd just temporarily disable optimisations for your release build. Just don't forget to switch them back on again...
Pretty much every time, switching the debug heap off and disabling optimisations has let me reproduce this kind of bug in the debugger, and then debug it without too much hassle.
Additionally, if you use Windows 7, you may find the Program Compatibility Assistant is stepping in and doing something that makes your program work, even though it shouldn't:
http://www.virtualdub.org/blog/pivot/entry.php?id=319
You can supposedly disable this in your program's manifest, but I prefer to have it disabled using the Group Policy Editor, e.g.:
http://www.howtogeek.com/howto/4161/disable-program-compatibility-assistant-in-windows-7-and-vista/
Disabling the Program Compatibility Assistant is highly recommended if you ever run your program outside the debugger...


text:
Q: Allow users to download when authorised A quick question really. I'm creating a website that holds files, and when that user has purchased the file, the file will then download.
The only problem is, is that the directory is protected with .htaccess permissions in order to stop unauthorised downloading of files. So obviously, when a user clicks the link to download the file, they are presented with the .htaccess username password combination.
Is there a better way to manage this?
Thanks,
James.

A: *

*Store your files outside the document root.

*Have your own custom login mechanism

*Serve the file with php after you check whether the user is logged in, either with readfile(), or better if it's installed or you can install it, with mod_xsendfile (which takes a load off PHP).

A: Don't use HTACCESS, put the files outside of webroot and serve them them via code.
See:
Allow users to download files outside webroot


text:
Q: Truncating /r and returns Failed opening required I haven't had an issue (that I'm aware of) of including PHP files in a different directory. What is this PEAR and why is it trying to be included? Why is it printing \scripts equests and not scripts\requests

Path : \WebDevProject\scripts equests.php

Warning: require(\WebDevProject\scripts equests.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\WebDevProject\userrequest.php on line 1

Fatal error: Uncaught Error: Failed opening required '\WebDevProject\scripts equests.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\WebDevProject\userrequest.php:1 Stack trace: #0 {main} thrown in C:\xampp\htdocs\WebDevProject\userrequest.php on line 1

ANSWER:
<?php $path = "\\WebDevProject\\scripts\\requests.php"; echo "Path : $path"; require $path;?> Double \ to escape the slash, and needs a file include such as <?php include ("scripts/userregister.php"); ?>

A: <?php $path = "\\WebDevProject\\scripts\\requests.php"; echo "Path : $path"; require $path;?>

Double \ to escape the slash, and needs a file include such as
<?php include ("scripts/userregister.php"); ?>


text:
Q: Material-UI Expansion Panel not obeying controled expansion I want the first of the three expansion panels to be open but still only allow one panel at a time to be open. Currently I can either have the first panel open OR have the panels controlled to be open one a time, but not both. But this what I need.
I also need the jsx to be rendered with a loop. This loop seems to be be causing the issue because this works without a loop.
The 2nd and 3rd drawers works as they should here.
I've tried passing the the props directly like in the docs but this did not work. Currently I am trying to pass them in dynamically so only the proper props ones go with each panel, with each iteration of the loop. It looks like this:
function setAttributes(i) {
   return [
     { defaultExpanded: true },
     { expanded: expanded === `panel2` },
     { expanded: expanded === `panel3` }
   ]
  }

return (
<div className={`${classes.root} accordion`}>
  {Object.values(props.drawers).map((drawer, i) => {
    return (
      <ExpansionPanel
        key={i}
        //set attributes here
        {...setAttributes(i)[i]}
        onChange={handleChange(`panel${i + 1}`)}
        className="expansion-panel"
      >
        <ExpansionPanelSummary
          className="expansion-panel-inner"
          expandIcon={<ExpandMoreIcon />}
          aria-controls={`panel${i + 1}bh-content`}
          id={`panel${i + 1}bh-header`}
        >
          <Typography className={`${classes.heading} panel-heading`}>
            {' '}
            {drawer.heading}
          </Typography>
          <Typography className={classes.secondaryHeading} />
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          <Typography>{drawer.text}</Typography>
        </ExpansionPanelDetails>
      </ExpansionPanel>
    )
  })}
</div>

)
I've tried looking at what props are attached after render but its' not super clear; it's not as easy as looking for an added class. It's unclear to me if the proper props are getting added to each panel. I also tried making the first object inside setAttributes { defaultExpanded: true, expanded: expanded === "panel1" }, but this just disables the default expansion.
A demo shows the problem.
I want the first panel open on load, then after that only one panel, whichever is clicked, to be open, and only that one.

A: If I'm understanding your issue, you should be able to just set the default value.
const [expanded, setExpanded] = React.useState("panel1");

And if you want to make it so you can't collapse a panel by clicking it again:
const handleChange = panel => (event, isExpanded) => {
    setExpanded(panel);
};


text:
Q: iPhone CPScatterplot How to make a smooth line in CPScatterplot .To make scatterplot like a curve chart.
i use this code
CPScatterPlot.dataSource = self;

CPScatterPlot.dataLineStyle.lineWidth = 3.0f;

A: For future reference, this feature has now been addressed in Core Plot issue #156. As of 0.9 it has not been merged however a diff is available at http://code.google.com/p/core-plot/issues/detail?id=156

A: Core Plot only draws straight line segments between your data points. You can insert extra points between your existing data, but you have to calculate the values yourself to get the desired curve. If you insert enough points, it will appear to be a smooth curve.

A: Try this one May be Helped.
CPScatterPlot *Cps = [[[CPScatterPlot alloc] initWithFrame:graph.defaultPlotSpace.bounds]autorelease];
Cps.identifier = @" ";
Cps.dataLineStyle.lineWidth = 1.0f; // if u want smooth the line
//Cps.dataLineStyle.lineColor = [CPColor blueColor]; // if u want color the line
Cps.dataSource = self;
[graph addPlot:Cps];