Q: jsTree select Node which is not in DOM yet I have an jsTree, data comes from HTML
$("#tree_container").jstree();

Now I want to implement deep linking on the tree elements. I am getting the class and data-id from URL parameters and now I want to select the correspondent node.
var id=$("#tree_container").find("li."+get_class+"[data-id='"+get_id+"']").attr("id");
if(id!=undefined && id!=0) {
                treeElem.jstree(true).select_node(id);
            }

This only works if the node is already in the DOM Tree.
(sub-Trees are getting inserted in if the parent node is clicked)
If the node I want is not in the tree ... id is undefined and the select fails.
Thing is, if I put in the id (like "#j1_6") in directly the node is found even if it is not in the DOM tree. It only work with the Id in that format, I try putting other selectors in or even elements ($(".class[data-id='1']"), nothing worked.
My problem is that I do not know how to get the id of the node if it is not in the DOM Tree yet. I did not find a api function or anything to do that.
====== UPDATE ======
I found a workaround ...
When building the HTML tree I now combine the class and data-id to make up the html id of the element (li).
So I have controll over the ids and know them and just do:
treeElem.jstree(true).select_node("#"+get_type+"_"+get_id);
so yeah, as I said for me it is just a workaround...


Q: Store a custom Array List in Shared Preference I want to store a Custom Array List in a Shared Preference , so that I can read the List when I open my app the next time.
I looked at many tutorials and answers but I could not really understand it.
list_addr.java
public class list_addr {

public String title;
public String detail;

public list_addr( String title, String detail) {
    super();

    this.title = title;
    this.detail=detail;

}

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDetail() {
    return detail;
}
public void setDetail(String detail) {
    this.detail = detail;
}

@Override
public String toString() {
    return title + "\n" ;
}

}

list_adapter.java
enterpublic class list_addr_adapter extends ArrayAdapter<list_addr> {

Context context;
int layoutResourceId;

public list_addr_adapter(Context context, int layoutResourceId, List<list_addr> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    //  this.listener=callback;
}

/*private view holder class*/
private class ViewHolder {

    TextView txtTitle;
    TextView txtDetail;
    ImageView imageview;
    CheckBox checkbox;

}
ViewHolder holder = null;

public View getView(final int position, View convertView, ViewGroup parent) {
    final list_addr lists = getItem(position);
    final int pos=position;

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.items_sav_addr2, null);
        holder = new ViewHolder();
        holder.txtTitle = (TextView) convertView.findViewById(R.id.textTitle);
        holder.txtDetail = (TextView) convertView.findViewById(R.id.detail);
        holder.imageview = (ImageView) convertView.findViewById(R.id.imageview);
        holder.checkbox=(CheckBox)convertView.findViewById(R.id.chkitem);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.txtTitle.setText(lists.getTitle());
    holder.txtDetail.setText(lists.getDetail());

        return convertView;
    }

}

This is how I inflate the list view -
 listView1 = (ListView) findViewById(R.id.listView);
    list_adapter_invoice adapter = new list_adapter_invoice(this,
            R.layout.items_row, MyAdaptertwo.rowitems);

    listView1.setAdapter(adapter);

A: You can only save primitive types in shared preference . If you need to save an ArrayList then you can save it as a String which is Comma seperated . At the time of fetching this use split(",") on this String And you will get a String [] of it .
And if you want to save a list of Object then i Suggest to use a Singleton Class for it . Here is example of Singelton Class .Try this it you want .
public class ReferenceWrapper {
private Context context;
private static ReferenceWrapper wrapper;
private ArrayList<Object> list;

private ReferenceWrapper(Context context) {
    this.context = context;
}

public static ReferenceWrapper getInstance(Activity activity) {
    if (wrapper == null) {
        wrapper = new ReferenceWrapper(activity);
    }
    return wrapper;
}

public ArrayList<Object> getList() {
    return list;
}

public void setList(ArrayList<Object> list) {
    this.list = list;
}

}
And use it like this
ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
    wrapper.setList(yourArrarlist);

And get It in any activity
ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
ArrarList<Object> list= wrapper.getList(yourArrarlist);

It will return the same ArrayList list you saved recently . Because its only one object is Created
.Let me know if it helps

A: Answer is about write object in File instead of SharedPreference. Hope this may help
    try {
        ArrayList<List_addr> addrList = new ArrayList<>();
        addrList.add(new List_addr("Bangalore", "Its a City"));
        addrList.add(new List_addr("Delhi", "Its also a City"));

        //write object into a file
        FileOutputStream fos = openFileOutput("addrList", Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(addrList);
        oos.close();

        //read object from the file
        FileInputStream fis = openFileInput("addrList");
        ObjectInputStream ois = new ObjectInputStream(fis);
        ArrayList<List_addr> readAddrList = (ArrayList<List_addr>) ois.readObject();
        ois.close();

        for (List_addr address : readAddrList) {
            Log.i("TAG", "Name " + address.getTitle() + " City " + address.getDetail());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

Important : Please mind @MeetTitan answer comments.

A:          Step 1:

           Put string array set into the shared preference.
           pref.putStringSet(String key, Set<String> values);

         Step 2:

           Convert array list of pojo into set.
           Set<String> set = new HashSet<String>(list);

         Set 3:

           Retrive using the getStringSet.

A: To save arraylist in shared preferences do the following
 // Create List of address that you want to save
    ArrayList addressList = new ArrayList();
    addressList.add(new list_addr());
   addressList.add(new list_addr());
    SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
    //save the user list to preference
    Editor editor = prefs.edit();
    try {
    editor.putString("addressList", ObjectSerializer.serialize(addressList));
    } catch (IOException e) {
    e.printStackTrace();
    }
    editor.commit();

and then to retrieve arraylist use this
ArrayList addressList = new ArrayList();
// Load address List from preferences
SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
try {
addressList = (ArrayList) ObjectSerializer.deserialize(prefs.getString("addressList", ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}

And this is the link for objectSerializer class
Object Serializer


Q: How to keep a user signed in on an Electron app using Auth0? There seem to be no complete explanations of how to do this, or even enough fragments for me to piece together what I have to do. After about 16 hours of studying, I am at wit's end.
It seems like I can't use SSO, and I also can't use PKCE because there is no working example anywhere on the web. There is a github repo with an example implementation, but it does not function and after 2 hours playing with it I cannot determine what I need to do to move forward this way.
Thanks for any help.

A: You can add offline_access to your scope (e.g. "scope": "offline_access openid something:else",) and this will yield you a refresh_token.
Auth0 currently supports unlimited refresh_token usage, so when your access_token expires (you either can track expiration time manually using "expires_in": 86400 value in respones or react on 401 response from api) - you can send your refresh token to OAuth2 api endpoint and receive new access token back. They have few descent articles about this matter and what you need to configure for your clients and API as well as what not to do (depending on your client security assumptions).
Take a note - you must secure refresh_token properly - store it in some reliable store and prevent any external scripts from accessing it. I assume with electron app you can do it more reliable than with a public website.


Q: How to check if checkbox is checked in gridviewrow I need help with this code where I check every row in GridView if the CheckBox is checked or not. But there is still false. Can you help me, please?
<asp:GridView ID="GridView1" CssClass="tabulka" runat="server" AutoGenerateColumns="false" />
        <Columns>
            <asp:TemplateField HeaderText="Placení">
                <ItemTemplate>
                    <asp:CheckBox ID="Poslano" runat="server" Text="Vyřešeno"  />
                    <asp:HiddenField ID="id" runat="server" Value='<%# Eval("id").ToString() %>' />
                </ItemTemplate>
            </asp:TemplateField>

         </Columns>
        <FooterStyle BackColor="#CCCCCC" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
    </asp:GridView>

protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            if (((CheckBox)gvRow.FindControl("Poslano")).Checked) // here is a problem - still false
            {
                Tabor tab = new Tabor();

                tab.Id = Convert.ToInt32(((HiddenField)gvRow.FindControl("id")).Value); // here is good value

            }
        }
    }

A:     Pleae check with below code

   foreach(var gvItem in GridView1.Items)
    {
      CheckBox chkItem = (CheckBox) gvItem.FindControl("Poslano");
      if (chkItem.Checked)
     {
       //Do stuff
     }
    }


Q: calculate a rolling median on a dataframe that has a non-unique date index I have the following dataframe, which has a non-unique index using dates:
                column
2019-01-07         NaN
2019-01-08         NaN
2019-01-08        0.02
2019-01-09       31.45
2019-01-10         NaN
2019-01-10       71.87
2019-01-10       90.18
2019-01-11         NaN
2019-01-12       12.67
2019-01-12        5.68
2019-01-12       11.23
2019-01-12       21.67
2019-01-12       14.77
2019-01-12        5.18
2019-01-13       14.38
2019-01-13         NaN
2019-01-13       71.13
2019-01-13       20.02
2019-01-13      103.10
2019-01-14         NaN
2019-01-15       32.48
2019-01-16       37.37
2019-01-16       31.05
2019-01-16        7.00
2019-01-17         NaN
2019-01-17       39.65
2019-01-18       23.68
2019-01-18        0.08
2019-01-18       41.35
2019-01-19         NaN
2019-01-19       45.85
2019-01-19        3.98
2019-01-19        4.60
2019-01-19         NaN
2019-01-19         NaN
2019-01-20        3.60
2019-01-20        5.03
2019-01-20       15.70

My aim is to calculate a 7 day rolling median using all the values for each date, but ignoring the NaN values.
The resulting dataframe should have a unique date index with the rolling median as a column value for that date, similar to the following:
                column
2019-01-13       17.40
2019-01-14       17.40
2019-01-15       20.85
2019-01-16       20.85
2019-01-17       20.02
2019-01-18       20.85
2019-01-19       31.05
2019-01-20       19.69

I am not sure how to easily achieve this using pandas, so if anyone can provide an answer or point me in the right direction, it will be very much appreciated.
EDIT
To make things clearer, I will explain how the median needs to be calculated for a single date.
Using the date of 2019-01-13, the rolling median will need to use all the values, excluding the NaN values, from the 7 days up to the 13th. This means that the values that need to be included in the median calculation for the 13th are 0.02, 31.45, 71.87, 90.18, 12.67, 5.68, 11.23, 21.67, 14.77, 5.18, 14.38, 71.13, 20.02, 103.10. The resulting median for the 13th would be 17.4.
Hope that helps.

A: A rolling object is iterable, which allows for a solution like this:
# drop NAs and group by date into lists of values
df_per_date = df.dropna().groupby('date').apply(lambda g: g.value.to_list())

# compute medians across windows ('sum' concatenates multiple lists into one list)
medians = [np.median(window.agg(sum)) for window in df_per_date.rolling(5)]

# result
medians = pd.Series(index=df_per_date.index, data=medians)

medians

By the way, I loaded the data like this:
# load the data
df = pd.read_csv(pd.io.common.StringIO("""
2019-01-07         NaN
2019-01-08         NaN
2019-01-08        0.02
2019-01-09       31.45
2019-01-10         NaN
2019-01-10       71.87
2019-01-10       90.18
2019-01-11         NaN
2019-01-12       12.67
2019-01-12        5.68
2019-01-12       11.23
2019-01-12       21.67
2019-01-12       14.77
2019-01-12        5.18
2019-01-13       14.38
2019-01-13         NaN
2019-01-13       71.13
2019-01-13       20.02
2019-01-13      103.10
2019-01-14         NaN
2019-01-15       32.48
2019-01-16       37.37
2019-01-16       31.05
2019-01-16        7.00
2019-01-17         NaN
2019-01-17       39.65
2019-01-18       23.68
2019-01-18        0.08
2019-01-18       41.35
2019-01-19         NaN
2019-01-19       45.85
2019-01-19        3.98
2019-01-19        4.60
2019-01-19         NaN
2019-01-19         NaN
2019-01-20        3.60
2019-01-20        5.03
2019-01-20       15.70
""".strip()), sep='\s+', names=['date', 'value'], parse_dates=['date'])

A: If the data is not too long, cross merge can work:
df['key'] = 1
df = df.reset_index()

(df.merge(df, on='key', suffixes=['','_'])
   .loc[lambda x: x['index'].ge(x['index_']) &
                  x['index'].sub(x['index_']).le('7D')]
   .groupby('index')['column_'].median()
)

Output:
index
2019-01-07       NaN
2019-01-08     0.020
2019-01-09    15.735
2019-01-10    51.660
2019-01-11    51.660
2019-01-12    13.720
2019-01-13    17.395
2019-01-14    17.395
2019-01-15    20.020
2019-01-16    21.670
2019-01-17    21.670
2019-01-18    20.845
2019-01-19    20.020
2019-01-20    21.850
Name: column_, dtype: float64


Q: Error LNK1104 when upgrade from VS2008 to VS2010 My project make C dll deployment in Matlab.
After upgrade from VS C++ 2008 to VS C++ 2010 project, I got this error:
LINK : fatal error LNK1104: cannot open file 'mfc90d.lib'

After searching for solution, I think it should reference to 'mfc100d.lib'. But I don't know HOW to reference.
I tried to reference 'mfc90d.lib', and 'mfc100d.lib'. After that, the error gone, and the other replaced.
LINK : fatal error LNK1104: cannot open file 'mfcs90d.lib'

Even when I put 'mfcs90d.lib' in library paths, nothing happen. The error still there.
Does anyone meet that problem? And how you solve that?
Thank you!


Q: returning and passing 2 one dimensional arrays from a function to another in c++ I have around 5 functions which exchange data among each other, each fuction has to return an array and around two integers. I went through "tuple" but we cant club integers and arrays together and im not very comfortable with "struts".
If i could please be guided of ways of doing the same or passing and returning two arrays ( the integers can be put in an array).
Thank You

A:
returning and passing 2 one dimensional arrays

In C++, you can only return a single value. You cannot return multiple values, and the value that you return cannot be an array.

im not very comfortable with "struts" [sic]

I assume you mean structs. Well, now is the time to become comfortable, because a struct (also known as class) is great way to combine multiple values - even arrays - into a single object that can be returned.

Another option is to pass the function multiple references (or iterators or pointers) to objects that the function can modify instead of returning them.


Q: Google sheets API limits for SAAS applications We want to develop an API integration for Google Sheets in our SAAS platform, we have around 1000 users and each user in our platform will be connecting their own Google Account to the integration.
I see the API limits are 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user.
What I'm not 100% clear on is if these limits apply to our platform integration as a whole (all users on our platform) or the limits apply to each connected Google Account?
I'm assuming the API limit applies to each individual connected Google Account in our integration so each user in our platform will have their own individual requests limits?
I want to be sure though because the alternative of having only 100 requests per 100 seconds is not very scalable across 1000 users in our platform.
Any clarification on this would be highly appreciated!

A: The way the API limits would work for you is that:
Every user would have a limit of 100 requests per 100 seconds per user, since you are performing these requests on the behalf of the user.
If you application was performing these requests instead, then you would reach the 500 requests per 100 seconds.
Hope this clarifies it!


Q: Selecting only first match with CSS document.querySelector("h2") returns only the first element that matches that class selector.
Could this be done in CSS? It is not like doing: h2:first-child as this would select every
 that is the first element of its parent...
Take for example this:

Title

Sub

Title2

Blabla

Introduction

Blabla

Methods

Conclusions

Bla

I know there are ways to select only that
 containing "Sub", but could I ask like in querySelector: get all of them and filter the first, the second or the third one...?


Q: How do you configure static DHCP (based on MAC addresses) on Adtran NetVanta 3200? we have an Adtran NetVanta, and I was wondering how (if possible) to configure static DHCP entries for specific devices on the network?  The NetVanta 3200 is running OS v15.08.00.  Thanks!

A: ip dhcp-server pool "name"
  dns-server H.H.H.H
  default-router H.H.H.H
  host N.N.N.N S.S.S.S
  hardware-address XX:XX:XX:XX:XX:XX ethernet


Q: Can schema be upgraded to Exchange 2010 SP2 before installing Exchange SP1? It seems there's no Exchange 2010 with SP2 integrated available on MSDN so I thought I would just download Exchange 2010 with SP1 and do schema in Active Directory and then before even installing Exchange I would update it again to SP2. I think this should work but maybe someone already done it before and knows if there's any issues that may come up because of this? Or should I go the long way and expand schema to SP1, install Exchange on 4 servers and then do the expanding to SP2?

A: Use this Package:
http://www.microsoft.com/en-us/download/details.aspx?id=28190
This is the full package (integrated SP2), as per the "Additional Info":

This Exchange Server 2010 SP2 software may be used to perform a new
  installation or to update an existing Exchange Server 2010
  installation to Service Pack 2 (SP2) level.

A: Exchange 2010 service packs are actually full installers, you can download Exchange 2010 SP2 and install it on new servers; the ISO images on MSDN are there only for convenience, but are functionally equivalent to the standard service pack download.
Just download Exchange 2010 SP2 from here and run the installer from it; it will be much more quick and clean than installing SP1 and then updating to SP2.


Q: Setting state object dynamically using the data returned using Promise.all and fetch API : React+Typescript I am using fetch API and promise.all for a scenario where I am passing an array of URL'S from where I am fetching the data. The data retrieved from all the above URL'S needs to be set to the state object.
Say I have an array of 5 URL's , the result returned by these must be
assigned to the 5 different values inside my state object.
Using React along with typescript.
Help would be appreciated.
This is what I have tried so far
import * as React from 'react';

const urls = [ 'http://localhost:3001/url1',
               'http://localhost:3001/url2',
               'http://localhost:3001/url3',
             ]

interface IState {
     test: [],
     result: [],
     returnVal: []
}

export default class App extends React.Component<{},IState> {

  constructor(props:any)
  {
    super(props);
    this.state = {
       test: [],
       result: [],
       returnVal: []
  }

  checkStatus(response:any) {
    if (response.ok) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(new Error(response.statusText));
    }
  }

  parseJSON(response:any) {
    return response.json();
  }

  setData(data:any){
    Object.entries(this.state).forEach(([key], index) => {
      this.setState({ [key]: data[index] })
    });
  }

  componentDidMount()
  {
    Promise.all(urls.map(url =>
          fetch(url)
            .then(this.checkStatus)
            .then(this.parseJSON)
            .catch(error => console.log('There was a problem!', error))
        ))
        .then(data => {
           this.setData(data);
        })
  }

  render() {
    return(
      //some rendering code
    )
  }
}

Need to set the data returned from promise to the state object variables.

A: Promise.all(urls.map(url =>
      fetch(url)
        .then(this.checkStatus)
        .then(this.parseJSON)
 ))
 .then(jsons => {
    var newState = {};
    var index = 0;
    for(var key in this.state)
       newState[key] = jsons[index++];
    this.setState(newState);
})


Q: Simple Function to latch_setbit_resetbit I have 32-bit MCU. The port uses 32 digital IO functionality.STM32F469/479  Series.
I am looking for a sample code to Latch a particular bit/particular pin in PORTA
Set/RESET function particular bit In port A.
Can some one guide me on how it can be done using AND/OR/XOR operation?


Q: Area of a part of a cylinder contained in a ball How can one calculate area of the part of a cylinder $x^2+y^2=r^2$ which is contained inside this ball : $(x-r)^2 + y^2 + z^2 \le 4r^2$?
I've read a little about surface integrals, but I don't know how and if to apply it here.

A: The infinite cylinder can be parametrized by
$$(\phi,z)\mapsto (r\cos\phi, r\sin\phi, z)\qquad(-\pi\leq\phi\leq\pi, \ -\infty<z<\infty)\ .$$
The condition $(x-r)^2+y^2+z^2\leq 4r^2$ puts a bound on the length of the stalk  erected on the point $(r\cos\phi, r\sin\phi,0)$:
$$(r\cos\phi-r)^2+r^2\sin^2\phi +z^2\leq 4r^2\ ,$$
or
$$z^2\leq 2r^2(1+\cos\phi)=4r^2\cos^2{\phi\over2}\ .$$
It follows that this stalk ranges from $z=-2r\cos{\phi\over2}$ to $z=2r\cos{\phi\over2}$, so that the intended part $S$ of the cylinder has the parametric representation
$$(\phi,z)\mapsto (r\cos\phi, r\sin\phi, z)\qquad(-\pi\leq\phi\leq\pi, \ -2r\cos{\phi\over2}<z<2r\cos{\phi\over2})\ .$$
It follows that
$${\rm area}(S)=\int_{\hat S} r\>{\rm d}(\phi,z)=r\int_{-\pi}^\pi 4r\cos{\phi\over2}\ d\phi=16r^2\ .$$


Q: Where's the time travel in Mannequin 2: On the Move? I've just watched an episode of American Dad and Stan was saying he hates all movies with a time travelling premise except for Mannequin 2.
I couldn't see any time travel in the synopsis. Is there any?

A: There are two elements of time-travel within the film. In the first few minutes of the film, a character (the Princess) is turned into a statue through the use of a magical necklace. 1000 years later, she is turned back into a real person. Although this isn't "time-travel" per se (she went the long way around) the use of magical artificial hibernation to prevent her from aging could be considered a way of time travelling through time.
Shortly afterwards, we find that the main protagonists from the medieval period (the Prince and the Duke) are reincarnated in the present day as a shop boy and a local aristocrat. Again, not time-travel per se, but easily confused as such.


Q: Encryption on USB - Mac & Windows partitions I have a  64GB USB stick which I want to use on both my (Mountain Lion) iMac and my (work) Windows 7 laptop.  I don't want to or need to share files across platforms and require the following structure:
Partition 1 - Mac OSX Journaled case-sensitive Encrypted
Partition 2 - Windows FAT 32 (not encrypted)
Each method I have tried doesn't work as it appears that to allow encryption on the Mac partition, the root partition scheme needs to be GUID.  Doing this means my windows machine can't see the (FAT32) windows partition.
If I set the partition scheme to MBR, disk utility doesn't show the option to format the Mac partition as encrypted.
It may be that there's just not a solution to this and I'll need to carry 2 USB sticks or get into sparse disk images, but confirmation of this would be useful. I've read similar posts on the stack exchange & elsewhere but none seem to cover the exact same set-up.
Many thanks for any help

A: If you don't actually require case-sensitivity, Truecrypt is a free and open-source encryption system that will allow you to do either encrypt an entire volume using the Mac OS Extended filesystem or make a encrypted file container (basically an encrypted folder) that can be used to save files as if it were a separate volume.
You will need to download the program from the link above and install it. The Truecrypt program itself will allow you to create encrypted volumes/file containers and mount the encrypted volumes or file containers to your system to use them.

A: You should be able to create a hybrid GPT+MBR partition table to let both OSes see their volumes. Hybrid partition table aren't standard (they try to comply with the important bits of two different -- conflicting -- standards), so there are some potential gotchas. This page from Rod Smith has a good explanation, and covers how to use his gdisk tool to create them. You might also be able to use the (simpler but less flexible) gptsync tool, which simply clones the GPT table into an MBR -- but I'm not sure if it's smart enough to deal with an encrypted partition.
BTW, I'm not clear on why a GPT-only setup isn't working. According to Microsoft, Windows 7 should be able to use a GPT-formatted disk:

Q.    Can Windows 7, Windows Vista, and Windows Server 2008 read, write, and boot from GPT disks?
A.    Yes, all versions can use GPT partitioned disks for data. Booting is only supported for 64-bit editions on UEFI-based systems.

...so there may be something else going on.


Q: React - passing data between components This is my first try at a simple React application. Working with the Openweather API and AXIOS. I took Stephen Grider's course on Udemy and I'm trying to create something on my own now, but I still have problems when passing data between components. I have a SearchBar component and I'd love to be able to pass the input value to the parent component's state, so I can then update it with each search and render it into the DOM. However, I keep running into errors. I tried passing a function as a prop to my SearchBar component but I'm getting errors:

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component.
citySearch is not defined

This is confusing to me, as I tried to copy the exact steps from the course, where it seems to be working just fine. But again, I'm very new to this so it is probably just me making some sort of a rookie mistake. Any tips would be much appreciated.
Check my code below:
App.js
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });

      this.citySearch('London');
  }

  citySearch(city){
    this.setState({city})
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

SearchBar component:
import React, { Component } from 'react';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      city: ""
    };
  }

  render() {
    return (
      <input
        value={this.state.city}
        onChange={this.onHandleChange}
        className="form-control mt-3"
        placeholder="Enter a city name..."
        type="text"
      />
    );
  }

  onHandleChange(city) {
    this.setState({ city });
    this.props.onSearchTermChange(city);
  }
}

export default SearchBar;

A: You just setState in constructor. If you want to make a call you can put it in componentWillMount() or componentDidMount()
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }
  }

  citySearch(city){
    this.setState({city})
  }

  componentWillMount(){
    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });

      this.citySearch('London');
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

A:
setState(...): Can only update a mounted or mounting component. This
  usually means you called setState() on an unmounted component. This is
  a no-op. Please check the code for the App component.

This is because of your axios call inside the constructor. Put your axios call in componentDidMount should resolve it

citySearch is not defined

It is because React cannot find citySearch function. You should change
<SearchBar onSearchTermChange={citySearch} />
to
<SearchBar onSearchTermChange={this.citySearch} />
In order to use citySearch this way, you should also bind citySearch in your constructor
In summary:

import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    this.citySearch = this.citySearch.bind(this)
  }

  componentDidMount() {
    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  citySearch(city){
    this.setState({city})
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={this.citySearch} />

    );
  }
}

export default App;

Don't call setState in your constructor, you can just initialize your state like your did. So the original setState in your constructor should be deleted.

UPDATE
To search again everytime you call citySearch.

import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    this.citySearch = this.citySearch.bind(this)
  }

  componentDidMount() {
    axioSearch();
  }

  axioSearch(city) {
    let city = city || this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  citySearch(city){
    this.axioSearch(city);
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={this.citySearch} />

    );
  }
}

export default App;

A: First, you should not make your axios calls in the constructor. The component is not yet mounted at this point. Do this in a componentDidMount to ensure that the component is already mounted.
Secodly, you did not bind citySearch to the App class. So in the SearchBar component, it does not know that the citySearch Method should be called from the App class. It is advisable to do this binding in the App class constructor for optimization reasons.
Lastly, I will advise you to write React in a more functional way leveraging state management frameworks like Redux or Flux
The code below should work
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }
    this.citySearch = this.citySearch.bind(this);
    this.citySearch('London');
  }

  citySearch(city){
    this.setState({city})
  }

  componentDidMount() {
    //Axios call
    let {city, country} = this.state;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

For the searchBar component, you didn't bind onHandleChange in the SearchBar component. This will throw errors. You should do this in the searchBar constructor
constructor() {
     ...
     this.onHandleChange = this.onHandleChange.bind(this) //Very important you do this
  }

A: To pass data from child components to the parent component you have to use a callback method.
Check this out. (About how to pass data from parent to child and child to parent).
I know that I'm not touching your code here (I'm sorry), but if you're interested in a different approach this works.
https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17


Q: Not able to hide ARSLineProgress in iOS 15 I am new in swift and I am not able to hide ARSLineProgress in iOS 15. Its was working fine below iOS 15.
My code is like this
ARSLineProgress.hide()

The hide() function contain
public static func hide() {
ars_hideLoader(ars_currentLoader, withCompletionBlock: nil)
}

I have download pod file from this page
https://github.com/soberman/ARSLineProgress

Did someone face the same issue

A: This has been fixed on the following PR
https://github.com/soberman/ARSLineProgress/pull/36
The fix is to add CATransaction.commit() to the hide function.  This was not my work.
func ars_hideLoader(_ loader: ARSLoader?, withCompletionBlock block: (() -> Void)?) {
    guard let loader = loader else { return }

    ars_dispatchOnMainQueue {

        let currentLayer = loader.emptyView.layer.presentation()

        let alpha = Double(currentLayer?.opacity ?? 0)
        let fixedTime = alpha * ars_config.backgroundViewDismissAnimationDuration

        CATransaction.begin()
        CATransaction.setCompletionBlock(block)
        let alphaAnimation = CABasicAnimation(keyPath: "opacity")
        alphaAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
        alphaAnimation.fromValue = alpha
        alphaAnimation.toValue = 0
        alphaAnimation.duration = fixedTime
        alphaAnimation.isRemovedOnCompletion = true

        loader.emptyView.layer.removeAnimation(forKey: "alpha")
        loader.emptyView.alpha = 0
        loader.emptyView.layer.add(alphaAnimation, forKey: "alpha")

        let scaleAnimation = CABasicAnimation(keyPath: "transform")
        scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
        scaleAnimation.fromValue = CGAffineTransform(scaleX: 1, y: 1)
        scaleAnimation.toValue = CGAffineTransform(scaleX: ars_config.backgroundViewDismissTransformScale,
                                                   y: ars_config.backgroundViewDismissTransformScale)
        scaleAnimation.duration = fixedTime
        scaleAnimation.isRemovedOnCompletion = true

        loader.backgroundView.layer.removeAnimation(forKey: "transform")
        loader.backgroundView.layer.add(scaleAnimation, forKey: "transform")

        CATransaction.commit()
    }

    ars_dispatchAfter(ars_config.backgroundViewDismissAnimationDuration) {
        ars_cleanupLoader(loader)
    }
}


Q: Translate C++ in Mathematica 10.0.2 By translating the following program written in C ++
#include <iostream>
#include <math.h>

using namespace std;

inline int gcd (int a, int b)
{
    if(a==0) return b;
    return gcd(b%a,a);
}

double sol(const int n)
{
    const double p=n/(double)(n+1);
    double ans=0;
    int all=(n+1)*(n+1);
    for(int i=0;i<=n;++i)
        for(int j=0;j<=n;++j)
            for(int a=0;a<=n;++a)
                for(int b=0;b<=n;++b)
                    if( (i!=a || j!=b ) && (i*b!=a*j))
                    {
                        int u=a-i,v=b-j,cnt=0;
                        for(int x=0;x<=n;++x)
                        {
                            int t=(x-i)*v+j*u;
                            // y * u > t
                            if(u==0)
                                cnt+=t<0?n+1:0;
                            else if(u>0)
                                cnt+=t<0?n+1:n-min(t/u,n);
                            else
                                cnt+= t<0?min((t+1)/u,n) +1:0;
                        }
                        if(cnt!=0)
                            ans+=(i*b-a*j)*pow(p,all-abs(gcd(u,v))-cnt-1)*(1-pow(p,cnt));
                    }
    return ans/(2*all);
}
int main()
{
    cout << sol(1) << "\n" ;
    cout << sol(5) << "\n" ;
    cout << sol(10) << "\n" ;
}

In Mathematica like this (absolutely the same instructions)
f[n_] := Module[
  {p = n/(n + 1), ans = 0., all = (n + 1) (n + 1), i, j, a, b, x, u,
   v, cnt, t},
  For[i = 0, i <= n, ++i,
   For[j = 0, j <= n, ++j,
    For[a = 0, a <= n, ++a,
     For[b = 0, b <= n, ++b,
      If[(i != a || j != b) && (i b != a j),
       u = a - i;
       v = b - j;
       cnt = 0;
       For[x = 0, x <= n, ++x,
        t = (x - i) v + j u;
        Which[
         u == 0, cnt += If[t < 0, n + 1, 0],
         u > 0, cnt += If[t < 0, n + 1, n - Min[t/u, n]],
         True, cnt += If[t < 0, Min[(t + 1)/u, n] + 1, 0]
         ];
        ];
       If[cnt != 0,
        ans += (i b - a j)*
          Power[p, all - Abs[GCD[u, v]] - cnt - 1]*(1 - Power[p, cnt])]
       ]]]]];
  Return[ans/(2 all) // N]
  ]

I obtain the same result with n = 1 but different results whith n != 1.
Somebody can explain where I am wrong ?
Thanks for help

A: In C, a/b for integers a and b does something different than in Mathematica.
To translate the code faithfully, we could use IntegerPart[t/u] and IntegerPart[(t+1)/u], or as Szabolcs points out, Quotient[t, u] and Quotient[t+1, u].
With this modification, the results are
f[1]
f[5]
f[10]

(* 0.1875
   9.76895
   55.0301 *)

which is in line with what  is printed by the C code.


Q: A Complete Guide For Transition From Single to Multiple Partition Ubuntu 20.04 Server On Already Installed System Using LVM The title is my request.  I have been reading for hours and I have found tutorials for moving /home to a partition and /tmp to a partition. But none for converting all recommended directories into partitions for Ubuntu Server.  One tutorial got close, but then ignored the obviously necessary step of copying data from prior directories to new partitions.
Anyway, after many hours, I still have not yet found a tutorial that covers my rather common situation.
Situation:
I installed Ubuntu Server on Prod & Test servers (vps & virtualbox, respectively), did some work.  While reading server hardening tutorials, I realized that it is best practice to have /boot /home /swapfile /tmp /usr and var... /opt? all on separate partitions for resource management and security reasons.
The correct way to create the above mentioned partitions is by using LVM
However, none of tutorials discuss / recommend partition sizes (proportionally, as obviously different systems have different disk space available, mine is 80GB on / )
Additionally, some tutorials mention the necessary changes to /etc/fstab and some don't.
My goal is to convert my 80GB single partition setup into multiple partitions and then secure the partitions against common attacks and exploits using: a combination of nodev,noexec,nosuid in /etc/fstab
I can spend days testing and failing different configurations in virtualbox... Or some handsome and/or beautiful "Ubuntu Server Partitioning Guru" can publish an easy to follow (intermediate user target audience) definitive guide as I have described above and become Internet Famous as many users hosting their own projects on vps will forever love & adore you.  :-)
UPDATE
I originally did not publish the primary server hardening guide becuse I didnt want this post to become a "debate" over this guy's very thorough piece of work.  However, in hindsight I think it would be helpful for folks looking to answer this post, to see the actual security benefits that I am trying to achieve.
https://linoxide.com/ultimate-guide-secure-ubuntu/

A: I think usually separating things into different file systems doesn't help/improve security. If someone breaks into the system while it's running, anyway everything is mounted and there is no logical difference to having everything in one file system. What reasons were given in the material you studied?
That said, it can help performance (different file systems or different hardware beneath these mount points) and shorten how long a disaster recovery takes (e.g. if only the SSD that held /var went up in smoke, you only have to restore that backup and the rest stays running).
You were asking about recommended partition sizes:

*

*For / you're good with 15-20 GB. I've never needed more for a server (running a web server + mail server).

*swap I usually put on its own volume / partition which has the same size as the RAM - simply so that suspend-to-disk can work. People used to recommend 2xRAM size, but with nowadays' RAM sizes, when you run into a situation where you need a serious amount of swap, you're anyway in trouble. You'll notice it from a massive slowdown, and you should then quickly increase the available RAM.

*/boot just needs 500 MB, which gives it space for 8+ kernel+initrd versions. Make sure to run apt autoremove frequently, to keep it trimmed after kernel upgrades.

*I would keep /usr and /opt as directories on /, just don't see a benefit in moving them to their own filesystems.

*As described in this hardening guide, having a separate volume for /tmp does make sense, as it allows you to make that world-writable directory more restricted - both in how much space it can use of the totally available space, and what can be done with the files that are stored there. The guide recommends to use the nodev, nosuid and noexec options when mounting the filesystem. The guide only gives the mount commands for "one-time use". Translating this into a line in /etc/fstab would mean that you place nodev,nosuid,noexec into the 4th (options) column of the line where you mount the dedicated /tmp volume onto /tmp.

*That leaves us with /home and /var - that's usually the "important" stuff. On my servers /home is pretty much empty, but /var holds public_html, the logs, the databases, etc. So I keep /home as a directory on /, but /var definitely gets its own volume, and is backed up most frequently. Give it all remaining space after the above was done.

Then you asked how to make the transition:

*

*In the running system, where everything is on /, attach the new disk (VDI file, ...), prepare it with pvcreate, lvcreate and then the file systems of your choice (mkfs.ext4 for example).

*Then make temporary mount points under /mnt, e.g. /mnt/newroot, /mnt/newvar, ... and mount the file systems there.

*Then use rsync -xaP <source>/ <destination>/ for each of your file systems. The '-x' option will prevent rsync from crossing file system boundaries, i.e. if you do rsync -xaP / /mnt/newroot/ it won't also copy /var, /home or even all the new filesystems mounted under /mnt. '-a' will make sure permissions etc. will be taken over without modification, and '-P' shows progress. For details, please refer to man rsync.

After that's done, edit the /mnt/newroot/etc/fstab and make sure you list all file systems at the appropriate mount points. If you've gotten that far, this shouldn't be too hard (as you chose all the /dev/mapper/... names, file systems, etc.).
You will also have to use grub-install and maybe update-grub to make the new disk bootable, but there I'm not so sure about the exact procedure. With VMs you can easily try it out and if it doesn't boot, attach the old disk again and fix it.
For reference, here is a shell session that gives you some specific commands on the partitioning + LVM + formatting + referencing in fstab topics. Please note that you most likely will have to modify them, for example if your device isn't /dev/sda, if you want different file systems, etc. - it's merely an example.
# After using fdisk to create one partition that covers the whole device,
# it looks like this:
root@ubuntu:~# fdisk -l /dev/sda
Disk /dev/sda: 100 GiB, 107374182400 bytes, 209715200 sectors
Disk model: VBOX HARDDISK
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 18ACB4C9-3F33-7041-8BEB-D819F138A809

Device     Start       End   Sectors  Size Type
/dev/sda1   2048 209715166 209713119  100G Linux LVM

# Create a physical volume for LVM
root@ubuntu:~# pvcreate /dev/sda1
  Physical volume "/dev/sda1" successfully created.

# Create a volume group with the name "vg1" for LVM that will
# hold all our logical volumes
root@ubuntu:~# vgcreate vg1 /dev/sda1
  Volume group "vg1" successfully created

# Create the logical volumes as described above
root@ubuntu:~# lvcreate --name root --size 20G vg1
  Logical volume "root" created.
root@ubuntu:~# lvcreate --name swap --size 8G vg1
  Logical volume "swap" created.
root@ubuntu:~# lvcreate --name boot --size 500M vg1
  Logical volume "boot" created.
root@ubuntu:~# lvcreate --name tmp --size 5G vg1
  Logical volume "tmp" created.

# Have a look at the logical volumes
root@ubuntu:~# lvs
  LV   VG  Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  boot vg1 -wi-a----- 500.00m
  root vg1 -wi-a-----  20.00g
  swap vg1 -wi-a-----   8.00g
  tmp  vg1 -wi-a-----   5.00g

# Have a look at the volume group and see how much space is left
root@ubuntu:~# vgs
  VG  #PV #LV #SN Attr   VSize    VFree
  vg1   1   4   0 wz--n- <100.00g <66.51g

# Use the remaining space for the last logical volume, var
root@ubuntu:~# lvcreate --name var --size 66.5G vg1
  Logical volume "var" created.

# Have another look at the volumes
root@ubuntu:~# lvs
  LV   VG  Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  boot vg1 -wi-a----- 500.00m
  root vg1 -wi-a-----  20.00g
  swap vg1 -wi-a-----   8.00g
  tmp  vg1 -wi-a-----   5.00g
  var  vg1 -wi-a-----  66.50g

# Format all volumes with ext4 file system
for i in /dev/mapper/vg1-*; do mkfs.ext4 $i; done
# Turn vg1-swap into swap space
mkswap /dev/mapper/vg1-swap

# Create fstab entries that look like this
/dev/mapper/vg1-root    /       ext4    defaults                0       1
/dev/mapper/vg1-boot    /boot   ext4    defaults                0       2
/dev/mapper/vg1-var     /var    ext4    defaults                0       2
/dev/mapper/vg1-tmp     /tmp    ext4    nosuid,nodev,noexec     0       0
/dev/mapper/vg1-swap    none    swap    sw                      0       0


Q: Getting average of sums Example collection:
List<Product> list = new List<Product>();
list.Add(new Product { Id = 1, Good = 50, Total = 50 });
list.Add(new Product { Id = 2, Good = 18, Total = 30 });
list.Add(new Product { Id = 2, Good = 15, Total = 30 });
list.Add(new Product { Id = 1, Good = 40, Total = 50 });
list.Add(new Product { Id = 3, Good = 6, Total = 10 });
list.Add(new Product { Id = 1, Good = 45, Total = 50 });
list.Add(new Product { Id = 3, Good = 8, Total = 10 });

Number of products is unknown. What I need as a result is to get a percentage for each distinct product good/total, and then an average for all products. In this case:
Product Id=1, GoodSum = 50 + 40 + 45 = 135, TotalSum = 50 + 50 + 50 = 150, Perc = 135/150
Product Id=2, GoodSum = 18 + 15 = 33, TotalSum = 30 + 30 = 60, Perc = 33/60
Product Id=3, GoodSum = 6 + 8 = 14, TotalSum = 10 + 10 = 20, Perc = 14/20

Avg = Avg(135/150 + 35/60 + 14/20) = Avg(0.9 + 0.55 + 0.7) = 2.15 / 3 = 7.17

Can we do this with Linq, I am only interested in Linq solution.

A: Something like this?
var groups = list.GroupBy(l => l.Id)
                 .Select(g => new {
                                      Id = g.Key,
                                      GoodSum = g.Sum(i=>i.Good),
                                      TotalSum= g.Sum(i=>i.Total),
                                      Perc = (double) g.Sum(i=>i.Good) / g.Sum(i=>i.Total)
                                  }
                        );

 var average = groups.Average(g=>g.Perc);

Note that your answer for Avg should be 0.717 not 7.17.

A: Try this :
var avg = list.GroupBy(G => G.Id)
              .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum)))
              .Average();


Q: Getting DIV ID on AJAX loaded content I have div with unique id and I'm trying to get that div id with jQuery

Quantity

Everything works good, but after loading div with ajax - I just can't get id from loaded div.
$('.quantity').click(function() {
    $.post('quantity.php', { id: $(this).attr('id') }, function(output) {
        $(this).html(output);
    });
});

Any ideas?

A: This should work
$('.quantity').click(function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) {
        $(that).html(data);
    });
});

But this is how i'd write it
<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity

$('.quantity').on('click', function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    });
});

And for dynamic divs
<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity

$(document).on('click', '.quantity', function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    });
});

A: The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code:
$(document).on('click', '.quantity', function(){
    var id = $(this).attr('id');

    $.post('quantity.php', { quantityId: id }, function(data){
        $('#'+ id).html(data);
    });
});

UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method.


Q: Align text below input I have a text-input with a list below.
I now want the list to start exactly under the input on the left side.
Here is a jsFiddle.
CSS / HTML / Demo

body {
  text-align: center;
}
#underbox li {
  display: inline-block;
  text-decoration: underline;
}
<input type="text" style="width: 200px;" />

Test

Next

A: Change your styles to:
body{
    text-align: center;
}
input {
    width: 200px;
}
ul {
    text-align: left;
    margin: 0 auto;
    padding: 0;
    width: 200px;
}
#underbox li{
    display: inline-block;
    text-decoration: underline;
}

input and ul => same width /
ul => text-align: center; margin: 0 auto (for set position to center); padding: 0 (disable default style);
jsfiddle

A: something like this:
#underbox {

    width: 200px;
    margin: 0 auto;
    padding: 0;
    list-style-type: none;

}
#underbox li {
    margin-right: 5px;
    text-decoration: underline;
    text-align: left;
    float: left;

}

A: Try to add style to the ul element like that: http://jsfiddle.net/csdtesting/j6f8L7Lp/

body {
  text-align: center;
}
#underbox li {
  display: inline-block;
  text-decoration: underline;
}
ul#underbox {
  padding: 0;
  list-style-type: none;
  margin: 0;
}
<input type="text" style="width: 200px;" />

Test

Next


Q: Create -help- module for web application What is the best solution for create and merge help for my web application ,
I want create HTML help for entire solution and help for each page,
Is there any module for this purpose?

A: You can use SandCastle. It is now maintained as part of SandCastle Help File Builder or SHFB.

http://shfb.codeplex.com/

SandCastle depends on Microsoft Help Workshop, which you have to download separately.
If you want to just create your own help system and not product API documentation, then just use the HTML Help Workshop on its own. It very simple, to use. Just create HTML pages for each help section and compile. Read the documentation.
HTML Help is also available as part of the Visual Studio SDK.

Reference:
  http://msdn.microsoft.com/en-us/library/windows/desktop/ms670169(v=vs.85).aspx
Download:
  http://www.microsoft.com/en-us/download/details.aspx?id=21138

Important:
As of March 2012 there is no HTML Help Workshop 1.4. VS 2010 doesn't use MS Help2 format so there is no Help2 compiler available for it. Starting with VS 2010, the new MS Help Viewer format is used.

Reference:
  http://msdn.microsoft.com/en-us/library/vstudio/hh492077.aspx
MS Help Viewer SDK for Visual Studio:
  http://msdn.microsoft.com/en-us/library/dd627473.aspx

Hope that helps.
I would suggest you to use SandCastle (SHFB), because you get best of all worlds. You can create compiled HLP2 files, Help Viewer Content and also a simple online HTML help.


Q: Any C++ library for Johansen co-integration test? Any Ideas ? Will be highly appreciated.

A: Assuming you mean this test, I think I found a library that will help you.  Check out the Gnu Regression, Econometrics and Time-series Library.


Q: Swift dismissing view with clunky animation I simply have a ViewController that I would like to dismiss. And this is my dismissAction:
@objc private func dismissView(){

    self.dismiss(animated: true, completion: nil)

    UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)
    let dataSourceArray = UserDefaultsService.shared.getDataSourceArray()
    //  update datasource array in MainVC
    self.dismissWishlistDelegate?.dismissWishlistVC(dataArray: dataSourceArray, dropDownArray: self.dropOptions, shouldDeleteWithAnimation: false, wishlistToDelete: self.wishList)

}

Proble:
The dismiss  animation is very clunky and not fluent at all. I found out that if I remove everything in the function but only call self.dismiss it is working perfectly fine. What is the issue here? Any idea on how I can fix this?

A: You can try to light-weight load in main thread by
DispatchQueue.global().async {
   UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)
}

And instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line


Q: Update recyclerview on Edittext text change I have a Edittext and a recyclerview below it in fragment. The recyclerview row item has a textview. I have set the adapter and everything is working fine. I would like to change each item of the recyclerview with text in edittext and somehow it's not working. I tried with  itemArrayAdapter.notifyDataSetChanged() on getListForRv() method.
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_fonts, container, false);

    itemList = new ArrayList<FontItem>();

    EditText editText = view.findViewById(R.id.edit_text);
    itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList);

    recyclerView = (RecyclerView) view.findViewById(R.id.font_list);

    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(itemArrayAdapter);
    getListForRv(10);

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            getListForRv(90);
        }

        @Override
        public void afterTextChanged(Editable s) {
            getListForRv(90);

        }
    });

    return view;
}

private void getListForRv(int k) {
    for (int i = k; i < 1000; i++) {
        itemList.add(new FontItem("Item " + i));
    }
    itemArrayAdapter.notifyDataSetChanged();
}

A: call your getListForRv() on edit text afterTextChanged methode.

A: notifyDataSetChanged will refresh all itemview, if you want to synchronize all edittext
I have two  solution:

*

*databinding : you can use ObservableField

*Create a listener and make sure all item keep the listener,when editext was changed, call the listener then all itemview will accept the change

A: Finally I managed to solve this by doing the following, don't know if it's a bad practice but works for me:
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fonts, container, false);

        itemList = new ArrayList<FontItem>();

        EditText editText = getActivity().findViewById(R.id.edit_text);
        itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList);

        recyclerView = (RecyclerView) view.findViewById(R.id.font_list);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(itemArrayAdapter);
        getListForRv(10);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.setAdapter(itemArrayAdapter);
                getListForRv(90);
                itemArrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        return view;
    }

    private void getListForRv(int k) {
        if (!itemList.isEmpty())
            itemList.clear();
        for (int i = k; i < 1000; i++) {
            itemList.add(new FontItem("Item " + i));
        }
    }


Q: Why my pycharm can not debug forever? My computer version is Win7.
And what ever .py I debug, this pycharm will show me en error like this:

ValueError: bad marshal data (string ref out of range)
So what's wrong with pycharm, I tried to user newest version of pycharm but I helpless, the same error will show again.
I used to reinstall my win7 (becauser I have Shadow Mode software) and it work for a period.
Is there body have a good solution?

A: I don't think the problem is directly related to the pydev debugger in this case... my bet is that for some reason you're having corrupted .pyc files (don't know why thought).
Try cleaning your .pyc files from your pycharm installation and your own files and run it again (you may try running with pydev which has the same debugger backend if you want to see if you reproduce the issue there).


Q: How to call Geowebcache tile openlayers Can anyone provide the solution, how to call GeoWebCache tiles in openlayers as i have 20GB of tiles created in gwc folder.

A: If Geoserver with GWC is running on your server, then it's as simple as using
http://example.com/geoserver/gwc/service/wms

instead of
http://example.com/geoserver/wms

for the WMS url in your JavaScript OpenLayers code. In other words, add /gwc/service/wms in between the path to your GeoServer instance and the WMS call

A: Another way to do it is by setting the WMS request tiled propery to "true", without adding /gwc/service/wms
var layerX  = new OpenLayers.Layer.WMS("layerX", http://example.com/geoserver/wms?",{
//WMS parameters
layers : 'layerX',
transparent : true,
format : 'image/png',
tiled : true // <-- Here
},
{
//Open Layer parameters
});


Q: In React, what is a better place to store big data arrays? I'm building an interactive plot in React where the user can select multiple variables and add them to a single plot. Each of these "variables" represent scientific data and are stored as arrays with 100k to 3 million elements.
I don't feel very inclined to store these variables in the React state as their contents never change and I'd prefer to control when the UI needs to re-render manually instead of letting React automagically traverse these arrays trying to find out if they have changed, which renders my application unresponsive.
Is there any preferred way of storing this data and sharing it with React? Right now I just store everything in a global variable.

A: There aren't many places you can store it though. If the data never changes, there's no downside in storing it in state, no changes means no re-renders. It sounds like there's quite a bit of it, so you can't store it in local storage due to limits. If you build a data set inside React by doing a bunch of API calls, revisit the API itself - it should return the data you care for, rarely a bunch of data segments you have to splice together yourself.


Q: Proxy in development mode of React won't redirect I'm building an app with create-react-app.
I have local Apache server running on port 80 to execute my backend API PHP scripts.
I have added
"proxy": "http://localhost:80" to my package.json,
but on this axios requests:
 getAllCategories = () => {
      const url = process.env.PUBLIC_URL+`/api/api/categories/categories.php`;
      axios.get(url)
        .then(res => {
        const categories = res.data.data;
        this.setState({ categories });
      }).catch(err => {
        console.log('Axios fetch error:',err);
      })
    }

My request are directed to
Request URL: http://localhost:3000/api/api/categories/categories.php

according to Chrome Devtools and I'm not getting the data required.
In the build mode on remote server everything works fine with those paths indicated.
How can I configure proxy in dev mode to access my API files?

A: Have you tired path like this?
axios.get(`/api/api/categories/categories.php`)
...

A: If you are using create-react-app install http-proxy-middleware  as a dev dependency and in your src folder create a file called setupProxy.js (it must be spelt exactly like that).
In that file:
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:80' }));
};

You will need to restart the app for it to take effect.
Your api calls should not need the process.env


Q: Update table field by summing field from another table I am trying to update a table filed taking value from another table by summing a field based on EmpID.
In tblEmpInfo EmpID is primary key. I have saw few post on this site but couldn't adopt to my file. Here is my code till yet.
UPDATE tblEmpInfo AS c
INNER JOIN (SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID)  AS x ON c.EmpID = x.EmpID
SET c.ProfidentFund = x.total;

Above code give me following warning and do not update value to tblEmpInfo

tblEmpInfo screenshot.

tblTransactions screenshot.

And my expected output.

A: You can try the below -
UPDATE  c
SET c.ProfidentFund = x.total
from tblEmpInfo AS c
INNER JOIN
(SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID)  AS x
    ON c.EmpID = x.EmpID


Q: Self Join using a Group By clause getting "Invalid Identifier" error I'm trying to put together a Self Join using a Group By clause to see which person is getting paid the highest in their respective jobs but I keep getting this error
00904. 00000 -  "%s: invalid identifier"
Below is my code that I am currently trying to fix:
Select a.*,b.sal
From EMP a,(Select job,MAX(sal)
            From EMP
            Group By job) b
Where a.empno = b.empno

I did some research and I couldn't find anything that pertained to what I am doing (maybe becayse what I am doing is too simple?) but nonetheless I am looking for anything that will point me in the right direction.  Thanks in advance.

A: You don't have a column called empno that you are returning in the subquery. I think you want something like this which will return the max(sal) for each employee based on the job:
Select a.*, b.sal
From EMP a
inner join
(
  Select job, MAX(sal) sal
  From emp
  Group By job
) c
   on a.job = b.job

A: Try this instead:
Select a.*
From EMP a
INNER JOIN
(
   Select job, MAX(sal) MaxSal
   From EMP
   Group By job
) b ON a.job = b.job AND a.sal = b.MaxSal


Q: Constants of motion for Droop equation There is an important ODE system in biochemistry, Droop's equations:
$$s'=1-s-\frac{sx}{a_1+s}$$
$$x'=a_2\big(1-\frac{1}{q}\big)x-x$$
$$q'=\frac{a_3s}{a_1+s}-a_2(q-1)$$
Relatively easy one finds a constant of motion $e^t(\frac{xq}{a_3}+s-1)$.
How to find another constant of motion? Do you have any idea how to present this system in the Hamiltonian or Lagrangian form?

A: A complete global analysis of the Droop equations is carried out in

Lange, Kenneth;
  Oyarzun, Francisco J., The attractiveness of the Droop
  equations, Math.
  Biosci. 111, No. 2, 261-278 (1992).
  ZBL0762.92021.

The authors show that solutions are globally stable, in the sense that they converge to one of two fixed points (5) or (6) in their paper, depending on the positivity of $a_2 a_3 - a_2 - a_3 - a_1 a_2$; see Theorems 1 and 2. Authors use comparison arguments, a Lyapunov function, the Poincaré-Bendixson theorem, and the Bendixson-Dulack theorem to conclude this. Moreover, the vector field associated with the limiting 2-dimensional Droop system on the set $\{ a_3^{-1} x q + s - 1 = 0 \}$ is neither Hamiltonian nor is it conservative.


Q: findViewById retrurns wrong element? I can't understand why findViewById returns the wrong element, here is the class:
public class EventDetailsFragment extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_details);
        Log.d("First", findViewById(R.id.tuxtView1).getClass().toString());
        Log.d("Second", findViewById(R.id.tuxtView2).getClass().toString());
        Log.d("Third", findViewById(R.id.imageView1).getClass().toString());
    }
}

And here is the xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">

    <RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="0dp"
    android:layout_height="175dp"
    android:layout_gravity="center_horizontal"
    android:layout_weight="1"
    android:background="#fff"
    android:gravity="right" >

        <ImageView
        android:id="@+id/imageView1"
        android:layout_width="110dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:src="@drawable/ic_event_image" />

        <TextView
        android:id="@+id/tuxtView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp" />
        <TextView
        android:id="@+id/tuxtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tuxtView2"
        android:layout_toRightOf="@+id/imageView1"
        android:textColor="#555"
        android:textSize="20dp" />

    </RelativeLayout>

</LinearLayout>

The logcat ouput is:
12-26 23:43:20.249: D/First(6789): class android.widget.TextView
12-26 23:43:20.249: D/Second(6789): class android.widget.ImageView
12-26 23:43:20.249: D/Third(6789): class android.widget.TextView

So the point is, why do I get a imageview with id R.id.tuxtView2 and a textview with id R.id.imageView1. The application crashes if I want to assign a text value to R.id.tuxtView2, casted as a TextView.

A: Try to reload your project, maybe something wrong with R.java, or verify you are calling the good file with setContentView.
By refreshing/cleaning your project the R.java file will be reloaded and will find the named widgets.

A: I copied your code and made a dummy app. I got these results:
12-27 00:03:48.332: D/First(9165): class android.widget.TextView
12-27 00:03:48.332: D/Second(9165): class android.widget.TextView
12-27 00:03:48.332: D/Third(9165): class android.widget.ImageView

Apparently there is nothing wrong with the code

A: I've tried almost everything here, but nothing worked until I added a new component to the activity and, after running, noticing that the new component didn't show. It suggested my app wasn't updating with the runs. It worked by manually uninstalling the old version of the app an then running again.


Q: strange Java compilation error with typed interface I have come across a very strange compilation error.  At first I thought it was a bug in IntelliJ, but now I've tried with Eclipse and see the same thing.
I have the following interface:
public interface PluginDriver<T extends Plugin> {
   PluginBuilder<T> getBuilder();
   Set<PluginParam> getParams();
   Set<String> getStrings();
}

where Plugin is an abstract class:
public abstract class Plugin

and we also have a POJO as follows:
public class PluginParam { ... }

Now I have a DriverManager to return an instance of a PluginDriver, and here I will try to use that:
PluginDriver driver = DriverManager.getDriver(transformer.getPlugin());
PluginBuilder builder = driver.getBuilder();
for (PluginParam o : driver.getParams()) {
    //type mismatch - cannot convert from element type Object to PluginParam
}
for (String s : driver.getStrings()) {
    //type mismatch: cannot convert from element type Object to String
}

The for loop commands don't compile, for reasons that I don't understand.  The interface specifies concrete return types for those methods, not type T.
Now, if I change the following line:
PluginDriver<Plugin> driver = DriverManager.getDriver(transformer.getPlugin());

everything suddenly plays nicely.
Similarly, if I remove the type arguments from the interface, it will work.
I could understand that the getBuilder() method might not work if we hadn't correctly typed the PluginDriver.
But how could it possibly complain about the getStrings() method?
==EDIT
This is not a duplicate of Combining Raw Types and Generic Methods, since that question refers to a method with typed parameters.  The method I'm asking about is untyped.

A: The JLS says,
"The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C."
http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.8
When you declared a variable of the raw interface type, you forced the member methods to have raw types also. That's what screwed up the class cast.
The documentation rules.

A: Here:
PluginDriver driver = DriverManager.getDriver(transformer.getPlugin());

You are creating a raw type. Bad idea.
Can lead to all sorts of problems - see here.
Thus the answer is simple: never do that! When you are using generic types, then make sure that you have a "generic" on (one/both) sides of your declaration/definition!


Q: How to change the colors of xdebug output? The red and yellow standard colors of xdebug can hurt your eyes after a few hours.
http://www.designified.com/blog/article/76/restyling-xdebug-output describes how to replace the style with javascript requiring jquery.
I was looking for a more straight forward way and finally found one.

A: The solution is the !important tag, it overrides the existing style values. Use the following css code to avoid eye cancer when using xdebug:
.xdebug-error {
    font-size: 12px !important;
    width: 95% !important;
    margin: 0 auto 10px auto !important;
    border-color: #666 !important;
    background: #ddd !important;
}

.xdebug-error th, .xdebug-error td {
    padding: 2px !important;
}

.xdebug-error th {
    background: #ccc !important;
}

.xdebug-error span {
    display: none !important;
}

.xdebug-error_description th {
    font-size: 1.2em !important;
    padding: 20px 4px 20px 100px !important;
    background: #ccc no-repeat left top !important;
}

.xdebug-error_callStack th {
    background: #666 !important;
    color: #ddd !important;
}

A: Have a nice xdebug!
Yes you can. Try this css below.
table.xdebug-error {
  width: auto;
  background: white;
  border: none;
  border-spacing: none;
  border-collapse: collapse;
  box-shadow: 0px 3px 10px 0px black;
  position: fixed;
  top: 0px;
  right: 0px;
  z-index: 8888;
  font: 14px verdana;
  transform-origin: top right;
  transform: scaleX(0.4);
  opacity: 0.3;
  transition: all 200ms ease;
}
table.xdebug-error caption,
table.xdebug-error th,
table.xdebug-error td {
  text-align: left;
  vertical-align: middle;
}
table.xdebug-error a img {
  border: 0;
}
table.xdebug-error :focus {
  outline: 0;
}
table.xdebug-error pre {
  margin: 0;
}
table.xdebug-error tbody tr td,
table.xdebug-error tbody tr th {
  border: none;
  border-bottom: 1px solid rgba(0,0,0,0.2);
  font-weight: normal;
}
table.xdebug-error tbody tr td {
  padding: 3px !important;
  vertical-align: top;
}
table.xdebug-error tbody tr th {
  padding: 13px !important;
}
table.xdebug-error tbody tr td:nth-of-type(1) {
  width: 5% !important;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] {
  font-weight: normal;
  background: steelblue;
  color: white;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] span {
  display: none;
}
table.xdebug-error tbody tr font[color='#00bb00'] {
  color: #005e00;
}
table.xdebug-error tbody tr td small {
  display: none;
}
table.xdebug-error tbody tr td i {
  padding-left: 12px;
}
table.xdebug-error:hover {
  transform: none;
  opacity: 1;
}

CONS:

*

*Depending on your other css defs, you may have to fiddle a bit until it looks as promised.

*It's not as beautiful as a Laravel/Symfony error

PROS:

*

*You can see the actual page, despite the error. (Message will be dimmed and pushed on the right side, appearing on mouse hover.)

*It's nothing more than CSS

*You can even add it to your page via CSS Live Editor Plugin or something similar; therefore, no need to add to your own code

*It won't break your styling, won't stuff a whole lot of text into a tiny container where the error happened, etc. - because it's position:fixed.

*Pleasant to the eye - you'll end up throwing errors just to see it again :)

A: Another option is to disable xdebug from overloading var_dump.
In the php.ini [XDebug] section add xdebug.overload_var_dump=0
Formatting the output is then up to you; one such way could be wrapping var_dump in your own debug function that prints <pre> tags.

A:
// notice the line height, the padding(cellspacing), monospace font, font size, making readability better at least for me.
//
// A FILENAME : xdebug_stack_trace.css
//
// This is how the xdebug_stack_trace.css is called from the index.php page
//
// <style><?php require_once("./resources/css/xdebug_stack_trace.css");?></ style>
//
// notice that on the line above there is a space between the slash
// and the 'style', on the ending 'style' tag, otherwise the display
// get all messed up when this page gets loaded.
//
// make sure that when you copy the 'style' line from here to the
// index page, that you remove the extra space at the ending 'style'
// tag of the index page.
// +---------+---------+---------+---------+---------+---------+---------+
// orange/black td header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error th
{
    font-family:monospace;
    font-weight:normal;
    font-size:15px;
    padding: 6px 6px 6px 6px;
    border:1px solid black;
    background: #FFCC99;    // orange
    color:#000000;          // black
}
// +---------+---------+---------+---------+---------+---------+---------+
// black/white th header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error > tr:first-child > th:first-child,
.xdebug-error > tbody > tr:first-child > th:first-child
{
    line-height:1.6em;
    padding: 10px 10px 10px 10px;
    border:1px solid #000000;
    background: #000000;          // black
    color:#FFFFFF;
}
// +---------+---------+---------+---------+---------+---------+---------+
// green/black td content one or more lines
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error td
{
    font-size:14px;
    padding: 6px 6px 6px 6px;
    border:1px solid green;
    background: #D1FFE8;          // light green
}
// +---------+---------+---------+---------+---------+---------+---------+


Q: Fails to get IP address after temporary cable disconnect When I boot my Mac up with a network cable plugged in (connected to my router), the network works fine. But after the connection has been physically separated once (and the cable reinserted), it fails to get an IP address from the router (via DHCP). Mac OS just assigns a seemingly random IP address, and I can't access the internet anymore. After a reboot (with the cable plugged in), it works again.
This seems to be a Mac-only, cabled-only problem. WiFi works fine, and every other computer I tried (Windows & Linux notebooks) doesn't have the problem.
I'm using OS X Lion, and the Router is a D-LINK DIR-615, if it matters.


Q: Why Azure takes so long to setup a Load Balancer? I have set up an application gateway in almost five different regions in Azure and every time Azure take around 15-20 mins to complete the setup.
Whereas AWS will do it in a couple of minutes, why Azure requires such a long time?

A: You should try using Application Gateway V2, its a lot faster to create. updates are almost instantaneous (well, at least compared to V1). But I believe V1 is using windows VM's underneath, so it creates a set of vms for you, then it configures them. Each update would be a "sliding window" update, with 1 vm being recreated at a time.
As far as I know.

A: Application Gateway is a layer 7 load balancer which, as far as I understand, is a Windows VM (or collection of Windows VMs, depending on selected size) under the covers, which take some time to come up and be configured. In my experience, this time is usually around 15-30 minutes, depending on region and local time of day, capacity, etc.
Azure Load balancers on the other hand are layer 4 load balancers, which typically take in the order of 1-2 minutes to come up.

A: So, yes talking about the load balancer if you say it normally takes less than a minute to get deployed. But coming onto the Application gateway yeah it takes 15-20 minutes every time the reason being:

*

*Configuration Settings: Microsoft has the set of the vacant load balancers ready at their backend and when they receive a request to deploy a particular load balancer in any region, they just assign it an IP as requested by the user and it gets deployed within a minute. But coming onto the Application gateway, azure need to start deploying the load balancer [App Gateway in this case] from the scratch, need to attach it to the VNET so deployed and making it ready for the backend pools IP Address configuration and all, which basically take time about [15-20 minutes]. Now, Azure has brought up the V2 of the Application Gateway, a lot faster to create usually 5 minutes. And also talking about updates they are also really quick and instantaneous.

*Subscriptions: Secondly, the reason that it takes time is subscription. Suppose, you have the MSDN, free subscription in your Azure account. And another individual sitting at any different place is using the enterprise applications subscription [basically a pay as you go] in his azure account. Now, both of you raise a request to deploy an Application gateway in the same region at the same time then, Microsoft will give the person request with the enterprise subscription the higher priority than your free subscription request. Which is another reason that it results in a delay. As I am using the enterprise edition so it takes 2 minutes for a VM to deploy which gets deployed in 5-6 minutes if using the free subscription!
Thanks!


Q: How to use transactions in DotNetNuke? I'm trying to do the most simple thing and apply a transaction to the CreatePortal method.
If I'm using TransactionScope - It promotes to DTC for some unknown reason - BAD.
using (var ts = new TransactionScope())
{
    var portalController = new PortalController();

    var portalId =
        portalController.CreatePortal(
                    "TESTTESTTEST",
                    string.Empty,
                    string.Empty,
                    "TESTTESTTEST_" + new Random().Next(999999),
                    UserController.GeneratePassword(),
                    "TESTTESTTEST_" + new Random().Next(999999) + "@something.com",
                    string.Empty,
                    string.Empty,
                    Globals.ApplicationMapPath + "/Portals/_default/",
                    "Default Website.template",
                    "Portals/TESTTEST",
                    "TESTTESTTEST",
                    string.Empty,
                    string.Empty,
                    false);

    ts.Complete();
}

If I'm using DataProvider.Instance().GetTransaction and performs RollbackTransaction at the end - IT DOES NOT ROLLBACK, which means that the transaction didn't even work.
var t = Data.DataProvider.Instance().GetTransaction();

var portalController = new PortalController();

var portalId =
    portalController.CreatePortal(
                "TESTTESTTEST",
                string.Empty,
                string.Empty,
                "TESTTESTTEST_" + new Random().Next(999999),
                UserController.GeneratePassword(),
                "TESTTESTTEST_" + new Random().Next(999999) + "@something.com",
                string.Empty,
                string.Empty,
                Globals.ApplicationMapPath + "/Portals/_default/",
                "Default Website.template",
                "Portals/TESTTEST",
                "TESTTESTTEST",
                string.Empty,
                string.Empty,
                false);

Data.DataProvider.Instance().RollbackTransaction(t);

So, How to use transactions in DotNetNuke?

A: When you create a transaction through the GetTransaction method, the DataProvider just creates a new connection and gives you the transaction.  You would then need to manually use that transaction to perform whatever action you're going to take against the database.  There isn't a way to pass that transaction so that it gets used by, for example, CreatePortal, or any other built-in DNN function.  That functionality appears to be just for any additional database access you might make.
In terms of how to wrap a call from the DNN core in a transaction, I don't think you can.  The cleanest solution I know to recommend (which, unfortunately, still isn't very clean) is to manually call the stored procedure, using a transaction, rather than going through the controller class.
What's your use case, maybe I can recommend a solution that solves the problem some other way...

A: I was able to use Transactions in DNN with the help of this article.
It doesn't apply to your case, but will help others trying to leverage transactions in DNN.


Q: Azure Mobile Service Single Sign on Microsoft Account I have implemented single sign on using the WL api, but I only recently realized that I need to call mobileService.login on top of that to use the nice authentication features of Azure Mobile Services.
I followed this tutorial
http://www.windowsazure.com/en-us/develop/mobile/tutorials/single-sign-on-windows-8-js/#add-authentication
and added this piece of code:
var login = function () {
    return new WinJS.Promise(function (complete) {
        WL.init();

        WL.login({ scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"] }).then(function (result) {
            session = result.session;

            WinJS.Promise.join([
                WL.api({ path: "me", method: "GET" }),
                mobileService.login("microsoftaccount", session.authentication_token)
            ]).done(function (results) {
                var profile = results[0];
                var mobileServicesUser = results[1];

                var title = "Welcome " + profile.first_name + "!";
                var message = "You are now logged in as: " + mobileServicesUser.userId;
                var dialog = new Windows.UI.Popups.MessageDialog(message, title);
                dialog.showAsync().done(complete);
            });
        }, function (error) {
            session = null;
            var dialog = new Windows.UI.Popups.MessageDialog("You must log in.", "Login Required");
            dialog.showAsync().done(complete);
        });
    });
}

however on this line
mobileService.login("microsoftaccount", session.authentication_token)

my session.authentication_token is undefined. (I have an access_token)
If I don't pass the token, I am prompted to sign in every time I launch the app, which defeats the purpose of the integrated sign on.
Any ideas?

A: To get the authentication token, you need to pass the redirect URI to the call to WL.init:
WL.init({
    redirect_uri: "<< INSERT REDIRECT DOMAIN HERE >>"
});

Where the redirect domain must be the same as the one in your Live Connect application.


Q: Axios promise value render always 'undefined' Inside a componentDiMount function of a child component, I'm using an external function (getResults) to populate a state value. This getResults function, call an external API with axios.
Here is my code:
  componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
    });

After reading many, many posts I see that my problem seems to be the axios delay to generate the results. To resolve my problem, I have tested many solutions without success: check the rendered value in the render section...
How can I resolve this problem? Do I modify an element in the componentDiMount function or directly in the external getResults function ?
Thanks for your help.

A: Normally, in an axios request, the data comes in results.data
Also, because you don't return anything inside .map, it will just be an array of undefined.
You need to return inside .map
componentDidMount() {
    const cluster = '...';
    const index= '...';
    const field= '...';
    const paragraphs = uuids.map(uuid => {
      // Get the results.
      // ADDED RETURN INSIDE .map
      return getResults(cluster, index, field, uuid, 'source')
        .then(results => {
        // Get value with console.log OK.
        console.log(results);
        // Return a undefined value...
        return results;
      })
      .catch(error => {
        console.error(error);
      });
  });

And if you want to get the data from paragraphs, you need to use Promise.all or async/await for it to work.


Q: Can't connect to the wifi network First it was note even showing the wifi icon,but I somehow searched google and it started showing the icon. I don't know whether the wifi driver was installed or not. I don't know any coding:)  I just ran lshw -C network and found this.
WARNING: you should run this program as super-user.
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: enp3s0
       version: 06
       serial: ec:a8:6b:f2:58:57
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 firmware=rtl8168e-3_0.0.4 03/27/12 latency=0 link=no multicast=yes port=MII
       resources: irq:18 ioport:d000(size=256) memory:f2104000-f2104fff memory:f2100000-f2103fff
  *-network:0 DISABLED
       description: Wireless interface
       physical id: 1
       bus info: usb@1:1.3
       logical name: wlx00e04c818802
       serial: 00:e0:4c:81:88:02
       capabilities: ethernet physical wireless
       configuration: broadcast=yes driver=r8188eu multicast=yes wireless=unassociated
  *-network:1
       description: Ethernet interface
       physical id: 2
       bus info: usb@1:1.4
       logical name: enx026d525c8ecc
       serial: 02:6d:52:5c:8e:cc
       capabilities: ethernet physical
       configuration: broadcast=yes driver=ipheth ip=172.20.10.5 link=yes multicast=yes
WARNING: output may be incomplete or inaccurate, you should run this program as super-user.

I am using realtek rtl8188eu  802.11n wifi chipset.with adnet external usb wifi adapter.
It is showing network0 DISABLED.
Is the wifi driver recognized? I am using ethernet from mobile hotspot now. Please help me I need to attend my online classes.

A: I am not sure which linux distro you use, but I am on 16.04 and the below works perfectly for Ubuntu 16.04
Steps:
cd to Downloads and then clone this repo using:
git clone https://github.com/quickreflex/rtl8188eus
Then
cd rtl8188eus
nano Makefile

Scroll down to the line that says
export TopDIR ?= $(srctree)/drivers/net/wireless/rtl8188eus

For me it is on the 151st line, it might not be the same for you.
Change the line to:
export TopDIR ?= $ ~/Downloads/rtl8188eus
Then do:
make
sudo make install
sudo modprobe 8188eus

You might have to restart to get the wireless working.


Q: Round to nearest 7.5 with limited mathematical functions I am working with a piece of software with limited mathematical functions and I need to round a double value to the nearest multiple of 7.5.
Values will be in the range 0 to 360 (of type double).
I believe I can use the formula:
$$Round(x/7.5)*7.5$$
but the software doesn't have a round function (that I can find at least!)
The functions I have available are:

*

*Standard add, subtract, multiply and divide.

*Brackets are permitted

*ABS(x) - returns absolute value of x

*COS SIN TAN and their inverse

*EXP(x) - returns e to power x

*INT(x) - returns x rounded down to nearest integer (i.e truncates x)

*LN(x) - returns the natural base logarithm of x

*LOG(x) - returns the base 10 logarithm of x

*MOD(x,y) - returns the remainder of x divided by y

*SQRT(x) - returns the square root of x

They all accept integers or doubles and return appropriate values types.
So is it possible to round to the nearest 7.5 with only these functions?

A: Note that $\mathrm{round}(x) = \mathrm{int}(0.5+\mathrm{abs}(x)) \frac{x}{\mathrm{abs}(x)}$ when $x\neq 0$. Since your $x$ is nonnegative, the formula simplifies to $\mathrm{round}(x) = \mathrm{int}(0.5+x)$ and also holds for $x=0$. So, $7.5 \; \mathrm{round}(\frac{x}{7.5}) = 7.5 \; \mathrm{int}(0.5 + \frac{x}{7.5})$


Q: Identifying $k[x_1,x_2,y_1,y_2]^{\epsilon}$ with $k[x,y]\wedge k[x,y]$ Suppose the symmetric group $S_2$ of order 2 acts on $k^4=Spec \;k[x_1, x_2, y_1, y_2]$ by the following: for $\sigma\not=e$,
$$\sigma\circ(x_1, x_2, y_1, y_2)=(x_2,x_1,y_2,y_1).$$
That is, the nontrivial element in $S_2$ swaps the indeterminants $x_1$ and $x_2$, and $y_1$ and $y_2$, simultaneously.
Let $k[x_1, x_2,y_1, y_2]^{\epsilon}$ denote the vector subspace of $k[x_1, x_2,y_1, y_2]$ consisting of $S_2$-alternating polynomials, and let $k[x,y]\wedge k[x,y]$ denote the $2^{nd}$ exterior power of the vector space $k[x,y]$ of polynomials in $2$ variables.

Then how is $k[x_1, x_2,y_1, y_2]^{\epsilon}$  identified with $k[x,y]\wedge k[x,y]$?

$\mathbf{Examples}:$ Some examples of polynomials in $k[x_1, x_2,y_1, y_2]^{\epsilon}$ include the following:
$$g_1 = x_1-x_2,\; g_2= x_1-x_2+y_1-y_2, \;\mbox{ and } \;g_3 = (x_1 + x_2)(x_1-x_2)$$
since $g_i(x_2,x_1,y_2,y_1)=-g_i(x_1,x_2,y_1,y_2)$. This basically means when you swap the $x_i$'s and the $y_i$'s, the polynomial only changes by a sign.
At the moment, this identification is not obvious to me.
$$
$$

A: Hints:

*

*We have an isomorphism $A:=k[x_1,x_2,y_1,y_2]\cong k[x_1,y_1]\otimes_k k[x_2,y_2]=B$.

*The action $\tau:A\to A:p\mapsto -\sigma p$ is a vector space homomorphism.

*The action of $\tau$ on $B$ is generated by $p(x_1,y_1)\otimes q(x_2,y_2)\mapsto -q(x_1,y_1)\otimes p(x_2,y_2)$.

*If $\varphi\in \mathrm{End}(V)$ is a linear map, $V/\mathrm{Im}(I-\varphi)\cong \mathrm{Ker}(I-\varphi)= V_1$, where $V_1$ is the eigenspace corresponding to the eigenvalue $1$ (i.e. the fixed points of the transformation).

(I'm going on the definition that $\bigwedge^2 V:= V\otimes V/I$, where $I$ is the subspace spanned by those elements of the form $v\otimes w+w\otimes v$ with $v,w\in V$.)