text:
Q: Passing different elements to a Javascript function with same id I have a jsp file where i am retrieving data from database in the form of a table. My jsp is as below:
<%
ResultSet rs1 = stmt.executeQuery("select * from book where category='Fiction'");
%>

<form name="f1" id="f1" method="post">

        Name of the Book
        Author
        ISBN
        Price
        Publication
        Description

    <%
    while(rs1.next())
    {
    %>

        <%= rs1.getString(1) %>
        <%= rs1.getString(2) %>
        <%= rs1.getString(3) %>
        <%= rs1.getString(4) %>
        <%= rs1.getString(5) %>
        <%= rs1.getString(7) %>
        <input type="button" value="Add to Cart" onclick="cart()"></input>

    <%
    }
    %>

The output of this will be in number of rows. When i click the button 'Add to Cart' it should pass the cell elements to the javascript function and thereby to a servlet through JS function.
the problem i am facing here is, as the id of every 'td' is same, though i click in the second row of he table, only the elements of the first row are passing into the javascript function.
Here is my javascript function:
function cart()
{
    var bname = window.document.getElementById("bname").textContent;
    var isbn = window.document.getElementById("isbn").textContent;
    var price = window.document.getElementById("price").textContent;
    alert(bname);
    alert(isbn);
    alert(price);
}

the above 'alert's are displaying the values of the first rows only though i click the button present in the second row.
I tried so many alternatives online but couldn't solve the problem.

A: *

*Never have the same ID twice in one page

*concat a unique key, preferably the id of the row, to the id of the TD. Use that calculated id in your code. Should be simple

code:
//assuming 0 is the ID index in the row
<td id="bname<%= rs1.getString(0) %>"><%= rs1.getString(1) %>

<input type="button" value="Add to Cart"
           onclick="cart(<%= rs1.getString(0) %>)"></input>

...
...
...

function cart(id) {
    var bname = window.document.getElementById("bname"+id).textContent;
    var isbn = window.document.getElementById("isbn"+id).textContent;
    var price = window.document.getElementById("price"+id).textContent;

    alert(bname);
    alert(isbn);
    alert(price);
}

A: Why not use this, the values you seek are relative to the element that's clicked. Don't need to give id's to any of the elements.
Note that I am passing the button that's clicked to the card function:
 onclick="cart(this)"

Here is the full code.
<!doctype html>

        <meta charset="utf-8" />
        <title>Test the script</title>

Title

<form name="f1" id="f1" method="post">

        Name of the Book
        Author
        ISBN
        Price
        Publication
        Description

        aname1
        bname1
        isbn1
        price1
        pname1
        desc1
        <input type="button" value="Add to Cart" onclick="cart(this)"></input>

        aname2
        bname3
        isbn4
        price2
        pname2
        desc2
        <input type="button" value="Add to Cart" onclick="cart(this)"></input>

A: The best solution would be to use class attributes instead of id:

*

*An id is supposed to identify exactly one element per page.

*A class identifies multiple elements of the same type, or "class," per page.

You can query a subset of the entire DOM (for example the
 that was clicked) for elements with the classes you are interested in. Usually a library like jQuery or Dojo is used to simplify the querying.

If you just want something that works:

*

*HMR's solution is good, but it is a little rigid. It assumes each  (bname, aname, isbn...) exists and placed in a certain order.

*I have modified Itay's solution below for easy copy-pasting. It works by adding a unique prefix (the isbn) to each id to make it unique:

JSP:

    <td id="<%= rs1.getString(3) %>_bname"><%= rs1.getString(1) %>
    <td id="<%= rs1.getString(3) %>_aname"><%= rs1.getString(2) %>
    <td id="<%= rs1.getString(3) %>_isbn"><%= rs1.getString(3) %>
    <td id="<%= rs1.getString(3) %>_price"><%= rs1.getString(4) %>
    <td id="<%= rs1.getString(3) %>_pname"><%= rs1.getString(5) %>
    <td id="<%= rs1.getString(3) %>_desc"><%= rs1.getString(7) %>
    <input type="button" value="Add to Cart"
               onclick="cart('<%= rs1.getString(3) %>_')"></input>

JavaScript:
function cart(prefix)
{
    var bname = window.document.getElementById(prefix + "bname").textContent;
    var isbn = window.document.getElementById(prefix + "isbn").textContent;
    var price = window.document.getElementById(prefix + "price").textContent;
    alert(bname);
    alert(isbn);
    alert(price);
}


text:
Q: Error with Bad Math Delimiter I am struggling with a Bad Math Delimiter error, could I please ask for some help with this issue?
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{setspace}
\usepackage{mathrsfs}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{eurosym}
\usepackage{amstext}
\usepackage{hyperref}
\usepackage{grffile} %Stops the file name of figures appearing
\usepackage{color}
\usepackage{mathabx}
\usepackage{float}
\usepackage{pdfpages}
\DeclareRobustCommand{\officialeuro}{%
  \ifmmode\expandafter\text\fi
  {\fontencoding{U}\fontfamily{eurosym}\selectfont e}}

\title{UCFB Diss}
\author{danrawly}
\date{}

\title{Dissertation}
\author{}
\onehalfspacing
\usepackage{algorithmic}
 \renewcommand{\familydefault}{\sfdefault}
\textheight=23cm
\textwidth=16cm
\topmargin=-2cm
\oddsidemargin=0cm
\parindent=0mm
\pretolerance=2000
\tolerance=3000

\begin{document}

$$t= \dfrac{(\bar{x_1}-\bar{x_2})}{\sqrt{\dfrac{S_1^2}{N_1} +\dfrac{S_2^2}{N_2}}}\)$$

\end{document}

Thank you in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling fragment's onActivityResult from activity to pass data to fragment, method is deprecated I'm trying to pass data I received in activity to fragment in the following manner
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    myFragment.onActivityResult(requestCode, resultCode, data)
}

However, myFragment.onActivityResult(requestCode, resultCode, data) is deprecated. How can I send the data to fragment level without using deprecated code?

A: You have to use a fragment listener instead. Like this:
                parentFragmentManager.setFragmentResultListener(
                "YOUR_REQUEST_KEY",
                viewLifecycleOwner
            ) { requestKey, result ->
                if (requestKey == "YOUR_REQUEST_KEY") {
                    //Do whatever you could previously do in this section in onActivityResult
                }
            }

and when you want to set the result do this:
    val bundle = Bundle()
    //Put your data in bundle here
    setFragmentResult("YOUR_REQUEST_KEY", bundle)


text:
Q: Transaction history issue I have an app, but it is only showing the last 10 transactions in the transaction list. I don't know where the problem is from. See my code
if (_walletViewModel.filteredTransactions.isNotEmpty)
                SizedBox(
                  height: MediaQuery.of(context).size.height,
                  child: ListView.separated(
                    itemBuilder: (context, index) {
                      return WalletTransactionHistoryTile(
                        transaction:
                            _walletViewModel.filteredTransactions[index],
                      );
                    },
                    separatorBuilder: (_, __) => YBox(25.dy),
                    itemCount: _walletViewModel.filteredTransactions.length,
                  ),
                ),


text:
Q: (JAVA) Need to convert DATE to prepared statement for SQL I have been looking and trying solutions provided on the web (and SO) for the last hour on how to use the Date type in Java but I can't seem to get it working. I am using NetBeans 11.2 and I am not used to Java and it is giving me a hard time (no pun intended). It seems that LocalDateTime, Date and Time are deprecated and that I should be using java.time.
To be honest, I don't know what to do anymore. I am trying to build a query with inputs value to save in mySQL database.
The source of the Date is from <input type="date">
SignIn.java (servlet) :
String birthDate = request.getParameter("data_birthdate");

UserDto userDto = null;
UserDao userDao = new UserDao();

try
{
// Tried this
    userDto = userDao.CreateUser(LocalDateTime.parse(birthDate));
// Tried that
    userDto = userDao.CreateUser(Date.parse(birthDate));
// Tried this
    userDto = userDao.CreateUser(Time.parse(birthDate));
}

userDao.java (Dao) :
public void CreateUser(Date dateBirth) throws SQLException {
try {
        connect = db.getConnect();
        ps = connect.prepareStatement(SQL_CreateUser);
        ps.setDate(1, dateBirth);
        ps.executeUpdate();
    }
}

A: You may use LocalDateTime along with PreparedStatement#setTimestamp().  Here is roughly how you would do that:
String birthDate = request.getParameter("data_birthdate");
// assuming your text birthdates look like 1980-12-30 00:30:05
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dt = LocalDateTime.parse(birthDate, formatter);

try {
    connect = db.getConnect();
    ps = connect.prepareStatement(SQL_CreateUser);
    ps.setTimestamp(3, Timestamp.valueOf(dt));
}
catch (Exception e) {
    // handle exception
}

Note carefully the format mask being used in the call to DateTimeFormatter#ofPattern.  You need to replace that with whatever mask actually fits your string dates.


text:
Q: How to check if a cell value is an error or is < 0? I've tried to use the or statement inside an if statement but I´ve got "type mismatch" error. Both Cell.value < 0 and WorksheetFunction.IsError(Cell.Value) return true or false, correct? So, what´s the type mismatch?
Thanks!
For Each Cell In RatioThU
     If Cell.Value < 0 Or WorksheetFunction.IsError(Cell.Value) Then '<--TYPE MISMATCH!
        Cell.EntireRow.Select
           Selection.Font.StrikeThrough = True
     End If
Next

A: An error value in a cell in the selected range is causing the type mismatch on the Cell.Value = 0 check.
Check first for the error condition, then for the cell value like so...
If WorksheetFunction.IsError(Cell.Value) = "True" Then
     Cell.EntireRow.Select
         Selection.Font.Strikethrough = True
ElseIf Cell.Value = 0 Then
    Cell.EntireRow.Select
       Selection.Font.Strikethrough = True
End If

Do you know how to step through code and add a watch? It is very useful for debugging errors like this and something well worth investigating.

A: You must separate the tests:
For Each cell In RatioThU
     If WorksheetFunction.IsError(cell) Then
        cell.EntireRow.Font.Strikethrough = True
    Else
        If cell.Value < 0 Then
            cell.EntireRow.Font.Strikethrough = True
        End If
     End If
Next

Notice Selection is not necessary.


text:
Q: Oracle - Trigger on table that updates different table - permission problem I have a weird problem. I am trying to write a TRIGGER that whenever DEPTNO in table SCOTT.DEPT is updated, then it updates my other Table ( SCOTT.EMP ) with a new DEPTNO.
I got a ORA-01031: insufficient privileges error, which is weird, because I'm logged in as system, I've made this table myself (create .. ) and my other trigger that I wrote is working properly.
Btw. Is this trigger written correctly?
Any help would be appreciated.
CREATE OR REPLACE TRIGGER Trigger1
BEFORE DELETE OR INSERT OR UPDATE OF DEPTNO ON SCOTT.DEPT
FOR EACH ROW
BEGIN
     UPDATE SCOTT.EMP
     SET DEPTNO = :NEW.DEPTNO;
END;

A:
I am logged as System"

You need to be careful with that. SYSTEM is an Oracle owned account, used for maintaining the database, so there are risks to changing its schema.
In this case you have created the trigger in the SYSTEM schema because you didn't prefix the trigger name with anything. Normally triggers are owned by the schema which owns the underlying table, in this case SCOTT.
I suggest you drop the trigger from the SYSTEM schema and re-create it in SCOTT.


text:
Q: Eleventy returning error "Error: Node does not exist: undefined"? Trying to hide a page (which is the only page in a folder) with eleventyNavigation as when I use eleventyExcludeFromCollections: true I get the error:
Error: Node does not exist: undefined

The folder structure is:

*

*products (main folder)

*

*products.json (holds a few options, layout etc.)

*products.njk (parent page only used for dropdown, trying to hide for now )

*product1 (trying to hide as well)

Any idea why I am getting this error when I delete the eleventyNavigation options or when setting eleventyExcludeFromCollections to true or all?
Any advice is appreciated, thanks


text:
Q: INET Building error I have been using omnet++ 5 and inet 3.x and inetmanet 3.x. I have been encountering inet/inetmanet building error for a few days. before that it builds fine but took time for building.
The error is Unhandled event loop exception
Java heap space
I have tried these solutions but error is still there.

*

*I have changed heap size to 2 gb( RAM size is also 2gb) in omnetpp.ini

*I have unchecked c/c++ Build-> Enable parallel build.

Please suggest me a solution for it. Some times when i restart the computer inet builds but took so much time for building. but after that it stopped building with the above error.


text:
Q: PUT Request to REST API using Python For some reason my put request is not working and I am getting syntax errors.  I am new to Python but I have my GET and POST requests working.  Does anyone see anything wrong with this request and any recommendations? I am trying to change the description to "Changed Description"
PUT
#import requests library for making REST calls
import requests
import json

#specify url
url = 'my URL'

token = "my token"

data = {
        "agentName": "myAgentName",
        "agentId": "20",
        "description": "Changed Description",
        "platform": "Windows"
        }

headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}

#Call REST API
response = requests.put(url, data=data, headers=headers)

#Print Response
print(response.text)

Here is the error I am getting.
Traceback (most recent call last):
  line 17, in <module>
    headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data:data}
TypeError: unhashable type: 'dict'

A: Syntax error in because of = sign in your headers dictionary:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", data=data}

It should be:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json", 'data':data}

See data=data is changed with 'data':data. Colon and Single Quotes.
And are you sure you will be sending data in your headers? Or you should replace your payload with data in your put request?
Edit:
As you have edited the question and now you are sending data as PUT request's body requests.put(data=data) so there is no need of it in headers. Just change your headers to:
headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"}

But as you have set your Content-Type header to application/json so I think in your PUT request you should do
response = requests.put(url, data=json.dumps(data), headers=headers)

that is send your data as json.

A: The problem is that you try to assign data to the data element in your dictionary:
headers = { ..., data:data }

That can't work because you can't use a dictionary as a key in a dictionary (technically, because it's not hashable).
You probably wanted to do
headers = { ..., "data":data }


text:
Q: not show link prewiew in telegram open meta data I,m using open graph meta tags and when share links has og meta tags not correct working in Telegram.
like link:
http://yaldayekavir.com/fa/product/223/%D9%85%D8%AD%D8%B1%D8%A7%D8%A8
<meta property="og:description" content=". " /><meta property="og:title" content="محراب" /><meta property="og:type" content="product" /><meta property="og:url" content="http://yaldayekavir.com/fa/product/223/محراب" /><meta property="og:image" content="http://yaldayekavir.com/files/محراب - آبی.jpg" /><meta property="og:image:height" content="150" /><meta property="og:image:width" content="150" />

A: I myself got this problem.
For images of the open graph meta data, you must use the decode url.

A: put prefix="og: http://ogp.me/ns#" in html tag
see this code
<html prefix="og: http://ogp.me/ns#">

A: because your image address (link) is http it must be https
i have this problem and active ssl for my website and change address to https


text:
Q: Python: value that occurs the most in a list I have a two list as follows
x = ['a','a','b','c','b','a']

and
x = ['a','a','b','c','c','d']

I'm trying to find which values occur the most in each of these lists. This is what I have tried.
def unique_values(output,input):
    for i in input:
        if i not in output:
            output.append(i)
k = []
for i in k:
    unique_values(k,x)
    y.remove(i)

I've gotten this far but I cant figure out how to stop the for i in k: before it removes all the values in the list.

A: You can use Counter module from collections, if you want to find the occurrences of each element in the list: -
>>> x = ['a','a','b','c','c','d']

>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

So, the first two elements are most common in your list.
>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)

or, you also pass parameter to most_common() to specify how many most-common elements you want: -
>>> count.most_common(2)
[('a', 2), ('c', 2)]

Update : -
You can also find out the max count first, and then find total number of elements with that value, and then you can use it as parameter in most_common(): -
>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)

>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]

>>> [elem[0] for elem in most_common]
['a', 'c']

A: Here is another solution:
max(zip((x.count(item) for item in set(x)), set(x)))

First, we get a collection containing no duplicate elements using set.
>>> set(x)
{'a', 'c', 'b'}

Then, we count how many times each element is in x. This will return a generator object, you can make it a list to see its values (by using "[ ... ]" instead of "( ... )" ), it would return [3, 1, 2].
>>> (x.count(item) for item in set(x))

Then, we take the counts and pair it with the elements using zip. The number of occurrences first, for the next step. You can see its value by using list( ... ) on it, it would return [(3, 'a'), (1, 'c'), (2, 'b')].
>>> zip((x.count(item) for item in set(x)), set(x))

Finally, we find which of the pairs occurs most times using max.
>>> max(zip((x.count(item) for item in set(x)), set(x)))
(3, 'a')

As for the second value, the solution is a bit lengthier. The above is used within a list comprehension:
>>> [mitem for mitem in zip((x.count(item) for item in set(x)),set(x)) if mitem[0] == max((x.count(item) for item in set(x)))]
[(2, 'a'), (2, 'c')]


text:
Q: IlligalStateException in ListView (no async task or other non-UI thread involved) An (android) application has a global shopping cart. Various UI components can affect the cart, for example adding/removing items from it, all within the UI thread. Whenever the cart-state changes, it emits an event onto a "hub" which broadcasts it to all subscribed Handlers. The handlers, for example, update the Total label or refresh the listview (notifyDataSetChanged).
Under a "stress test" where the user is scrolling through the cart while removing items from it by clicking on them -- I sometimes get the IlligalStateException. Nowhere is the model updated asynchronously.
The app guarantees eventual consistency between the model (cart) and the ListView, just that the propagation of the cart change event involves going through a layer of handlers/queues, so the UI may be temporarily out of sync with the model, until the queued event is processed.
I can think of few possible ways to address this (none tested yet), but none feel particularly attractive:

*

*The listview-adapter might return a dummy (filler) item for out-of-bounds position, expecting a model-update event will "fix" this state.

*Posting the cart-changed event at the front of the handlers queues -- discouraged by the Android SDK doc. The rationale is that I suspect the Listview is redrawn (on scroll) before the enqueued "notifyDataSetChanged" is popped from the queue and processed.

*The adapter caches the global cart state, acting like a
double-buffer. Thus, the Listvew renders of off the adapter's cache,
not the global cart. Feels like a burden though ;)

Any better suggestions greatly appreciated.

A: You can think of implementing copy on write mechanism..Whenever you have to write data make a copy of the the listview data items,modify it and then give the modified list to the listview for rendering..There might be performance hit, you will have to calculate whether it is acceptable...


text:
Q: Unexpected closure with Context import in Android I am trying to import a context into this android file using the Context transfer. But if my message contains "aakash", then this code unexpectedly terminates giving the error as shown after the code.
What do I do ?
    public class messagebody extends BroadcastReceiver{

             Context mContext;
             public messagebody(Context context){
                   this.mContext = context;
                   Log.i(TAG, "yayyyy: " );
              }
             public messagebody(){

          }

            private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
            private static final String TAG = "SMSBroadcastReceiver";

            @Override
            public void onReceive(Context context, Intent intent) {
                 Log.i(TAG, "Intent recieved: " + intent.getAction());

                    if (intent.getAction().equals(SMS_RECEIVED)) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdus = (Object[])bundle.get("pdus");
                            final SmsMessage[] messages = new SmsMessage[pdus.length];
                            for (int i = 0; i < pdus.length; i++) {
                                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                            }
                            if (messages.length > -1) {
                               // Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
                                if(messages[0].getMessageBody().contains("aakash"))
                                {
                                    /*AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
                                    switch (am.getRingerMode()) {
                                        case AudioManager.RINGER_MODE_NORMAL:
                                            //Log.i("MyApp","NORMAL mode");
                                            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                                            Toast toast2=Toast.makeText(mContext, "Vibrate", Toast.LENGTH_LONG);
                                            toast2.show();
                                            break;
                                        case AudioManager.RINGER_MODE_VIBRATE:
                                            //Log.i("MyApp","VIBRATE mode");
                                            am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                                            Toast toast1=Toast.makeText(mContext, "Normal", Toast.LENGTH_LONG);
                                            toast1.show();
                                            break;   */
                                    Toast toast1=Toast.makeText(mContext, "Normal", Toast.LENGTH_LONG);
                                    toast1.show();
                                    }

                                }
                                }
                            }
                        }

    }

The error is as follows :
11-26 15:03:43.150: E/AndroidRuntime(2056): FATAL EXCEPTION: main
11-26 15:03:43.150: E/AndroidRuntime(2056): java.lang.RuntimeException: Unable to start receiver com.example.messages.messagebody: java.lang.NullPointerException
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2236)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.app.ActivityThread.access$1500(ActivityThread.java:130)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1271)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.os.Looper.loop(Looper.java:137)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at java.lang.reflect.Method.invokeNative(Native Method)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at java.lang.reflect.Method.invoke(Method.java:511)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at dalvik.system.NativeStart.main(Native Method)
11-26 15:03:43.150: E/AndroidRuntime(2056): Caused by: java.lang.NullPointerException
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.widget.Toast.<init>(Toast.java:92)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.widget.Toast.makeText(Toast.java:238)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at com.example.messages.messagebody.onReceive(messagebody.java:68)
11-26 15:03:43.150: E/AndroidRuntime(2056):     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2229)

With the mContext changed to context I get a null pointer exception with the new code. The code is
    package com.example.messages;
import com.example.messages.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

    public class messagebody extends BroadcastReceiver{

             Context mContext;
             public messagebody(Context context){
                   this.mContext = context;
                   Log.i(TAG, "yayyyy: " );
              }
             public messagebody(){

          }

            private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
            private static final String TAG = "SMSBroadcastReceiver";

            @Override
            public void onReceive(Context context, Intent intent) {
                 Log.i(TAG, "Intent recieved: " + intent.getAction());

                    if (intent.getAction().equals(SMS_RECEIVED)) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdus = (Object[])bundle.get("pdus");
                            final SmsMessage[] messages = new SmsMessage[pdus.length];
                            for (int i = 0; i < pdus.length; i++) {
                                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                            }
                            if (messages.length > -1) {
                               // Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show();
                                if(messages[0].getMessageBody().contains("aakash"))
                                {
                                    Toast toast3=Toast.makeText(context, "Normal", Toast.LENGTH_LONG);
                                    toast3.show();
                                    AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
                                    switch (am.getRingerMode()) {
                                        case AudioManager.RINGER_MODE_NORMAL:
                                            //Log.i("MyApp","NORMAL mode");
                                            am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                                            Toast toast2=Toast.makeText(context, "Vibrate", Toast.LENGTH_LONG);
                                            toast2.show();
                                            break;
                                        case AudioManager.RINGER_MODE_VIBRATE:
                                            //Log.i("MyApp","VIBRATE mode");
                                            am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                                            Toast toast1=Toast.makeText(context, "Normal", Toast.LENGTH_LONG);
                                            toast1.show();
                                            break;

                                    }

                                }
                                }
                            }
                        }
            }
    }

A: use
Toast toast1=Toast.makeText(context, "Normal", Toast.LENGTH_LONG);
 toast1.show();

instead of
  Toast toast1=Toast.makeText(mContext, "Normal", Toast.LENGTH_LONG);
  toast1.show();

use current BroadcastReceiver Context to show  Toast from BroadcastReceiver instead of any old  Activity or Service Context


text:
Q: Plotting of Principal Component Analysis Results in R On youtube (https://www.youtube.com/watch?v=xKl4LJAXnEA) i stumbled on this plot (see below). This guy performed PCA analysis and came up with a very nice way to plot his results. It seems that his y-variable was categorical.
However mine is numeric. Are there any similar ideas to plot my results in a decent way? I'd love to see groupings. thanks in advance!
The plot;

A: I have seen a similar plot on http://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/112-pca-principal-component-analysis-essentials/
It may be useful !
iris.pca <- PCA(iris [, - 5], graph = FALSE)

fviz_pca_ind(iris.pca,
         geom.ind = "point", # Montre les points seulement (mais pas le "text")
         col.ind = iris$Species, # colorer by groups
         palette = c("#00AFBB", "#E7B800", "#FC4E07"),
         addEllipses = TRUE, # Ellipses de concentration
         legend.title = "Groups"
         )


text:
Q: error syncing protractor after clicking on navigation There's a number of posts about Error while waiting for Protractor to sync with the page, but I think this is something different.
Setup:
I have a form on a page with angular. The form does a POST, which redirects to another page (let's call this the submission page) also with angular. The submission is triggered via an element().click()
I get intermittent Error while waiting for Protractor to sync with the page issues after the submission is triggered. Not every time, maybe 1/4 of the time.

Edit: relevant test code
// fill out form
element(by.css('.submit-btn')).click()
browser.wait(waitForUrl(), 5000)

// errors somewhere around here
expect(element(by.css('h1')).getText()).toMatch('Form submitted')
// errors somewhere around here

function waitForUrl() {
  return browser.getCurrentUrl().then(function(url) {
    return /submitted/.test(url)
  })
}

After digging around, I'm thinking there's a race condition because some test actions are ran before angular is loaded on the submission page.
I've tried browser.waitForAngular() to no avail. browser.ignoreSynchronization works, but since there is angular on the submission page this is not ideal. I'm really hoping browser.waitForAngular() would do what it seems to supposed to do - wait for angular to be loaded, but doesn't seem to do so unless I'm doing this wrong.


text:
Q: Test to compare rank-ordered data I have two result sets of identical search queries run under different parameters, analysis, etc. I will refer to them as RS1 and RS2. RS1 and RS2 may not have the same length, but they are rank-ordered with the first entry in the set being the highest priority. If RS1 is the "desired" set, or perhaps "control set", what statistical measures can I employ to determine how far off RS2 is from RS1?
For example, if the result sets return user ids:
RS1: [2, 4, 6],
RS2: [4, 6, 2]
We can see that RS1 and RS2 are decently similar by inspection.
But in this example:
RS1: [2, 3, 4],
RS2: [2, 6, 7]
is a much "worse" match. Obviously preferences of how important order is, etc matter, but what will be a good starting point? Any resources I could check out?

A: You can compare the medians of the two distributions via Mann-Whitney test.
The test in R is implemented in the wilcox.test function in base R.
The R code to do perform both of these tests is:
n<-100
y<- rgamma(n, shape=1, scale=1)
x<- rgamma(n, shape=2, scale=4)
wilcox.test(y,x, alternative ="less")

use the alternative to specify less than or greater than depending on your setup.  The default is not equal to as the alternative.
Mann-Whitney tests that it is equally likely that a randomly selected value from one sample will be less than or greater than a randomly selected value from a second sample.
If you have the measurements and not only the ranks and the measurements are numeric you could use a Kolmogorov-Smirnov test. ks.test(x,y) in R. To test ranks you could use the cor.test(x, y,alternative ="two.sided", method = "kendall") which tests that the two samples are correlated or not.
If your goal is to measure how close (equivalently how far away) are the two distributions from each other I would use the Kolmogorov-Smirnov test.


text:
Q: MySQL select distinct order by id I have a table like the following:

id category
1  A
2  A
3  B
4  B
5  C
6  C

If I want to select the top 2 distinct categories ordered by id descending, what's the right query in mysql? I tried select distinct category from table order by id desc limit 2 but that gave me the following result:

category
C
C

instead of

category
C
B

A: By top 2, you seem to mean the ones at the end of the list.  Try this:
select category
from t
group by category
order by max(id) desc
limit 2

If you mean the ones with the most rows.
Try this:
select category
from t
group by category
order by count(*) desc
limit 2

You can also include the count(*) in the select list to see what the counts are.


text:
Q: T4 template VS2010 get host assembly I want to get a reference to assembly of a project in which T4 template is. I know I can get path to the project with, for example Host.ResolveAssemblyReference("$(ProjectDir)") and I could maybe add bin\\debug\\{projectName}.dll because my assembly names are named by project name, but that is not always the case and I'm creating reusable template, so I need path to dll or most preferably Assembly instance.
I have also found how to get reference to the Project as explained here in method GetProjectContainingT4File, but then what?
Is there a way to get it?
BTW, I need that reference to access specific types and generate some code from them.

A: Following simple code worked for me (VS 2013):
var path = this.Host.ResolveAssemblyReference("$(TargetPath)");
var asm = Assembly.LoadFrom(path);

Also you can find $(...) properties in project psot build steps editor.

A: Ok, I managed to get the needed reference to assembly @FuleSnabel gave me a hint, although I did't use his suggestion.
Here's a part of my T4 template:
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".output" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="Microsoft.VisualStudio.Shell.Interop.8.0" #>
<#@ Assembly Name="EnvDTE" #>
<#@ Assembly Name="EnvDTE80" #>
<#@ Assembly Name="VSLangProj" #>

<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ include file="T4Toolbox.tt" #>
<#
    Project prj = GetProject();
    string fileName = "$(ProjectDir)bin\\debug\\" + prj.Properties.Item("OutputFileName").Value;
    string path = Host.ResolveAssemblyReference(fileName);
    Assembly asm = Assembly.LoadFrom(path);

    // ....
#>

// generated code goes here

<#+
    Project GetProject()
    {
        var serviceProvider = Host as IServiceProvider;
        if (serviceProvider == null)
        {
            throw new Exception("Visual Studio host not found!");
        }

        DTE dte = serviceProvider.GetService(typeof(SDTE)) as DTE;

        if (dte == null)
        {
            throw new Exception("Visual Studio host not found!");
        }

        ProjectItem projectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
        if (projectItem.Document == null) {
            projectItem.Open(Constants.vsViewKindCode);
        }

        return projectItem.ContainingProject;
    }
 #>

So, to find right path to assembly I had to get reference to the project in GetProject() method and then use project's property OutputFileName with prj.Properties.Item("OutputFileName").Value. Since I couldn't find anywhere what properties project has, I used enumeration and a loop to inspect Properties collection and then found what I need. Here's a loop code:
<#
// ....
foreach(Property prop in prj.Properties)
{
    #>
    <#= prop.Name #>
    <#
}
// ....
#>

I hope this will help someone.


text:
Q: Embed CSS/HTML button into email from scratch Wanting to put button-operated hotlinks to wherever into my emails I attacked the problem using advice from various sources on the web.
Having ZERO previous HTML experience (let alone CSS) the final solution is probably a bit of a dog's dinner but it works!
My only problem is that I think my method of specifying the target URL is a bit suspect and I wonder if it is stable and suitable for all platforms.
The other problem (possibly related) is that the company server is unhappy about the security of the email.
p.s. used Komodo as my HTML editor - menus are in strange places but other than that a nice piece of (free) kit.
Code below:

BUTTON LEGEND


text:
Q: How to change values of a function in Haskell and return this function? I would like to do the following in Haskell:
myFunc 1 = 0
myFunc 2 = 1

changeMyFunc:: (Integer -> Integer) -> Integer -> Integer -> (Integer -> Integer)
changeMyFunc x y z = undefined

-- change value of function x at position y to value z and return this function
-- this would make: (changeMyFunc myFunc 1 5) 1 == 5

This is how far i got it:
changeMyFunc2:: (Integer -> Integer) -> Integer -> Integer -> (Integer -> Integer)
changeMyFunc2 x y z | y == z = myFunc
                | y /= z = myFunc where myFunc y = 12
                | otherwise myFunc

the last line causes: parse error on input '|'
How can i check multiple cases using where?

A: When defining changeMyFunc x, the first step would be to just return the original myFunc x itself. That gets you almost the whole way there.
Then divide that into two cases: one case where x == y and the other case where x /= y, where y is your special input. What should changeMyFunc x return in each case?
Updated hint
Currently you are accepting args x, y, z. Try something with this instead:
changeMyFunc f y z x
    | fill this part in yourself

f is the original function.
y is the special input and z is the special output.
x is the argument for the new changeMyFunc function that you're defining.

See How do you use a function inside arguments in haskell? for more information on higher-order functions.

Think about which args you should be comparing, and what the output should be in each case. (Hint: I already gave part of the answer above.)
Then you can test it with this:
*Main> let successor = (+) 1
*Main> let successor' = changeMyFunc successor 1 1000
*Main> successor' 100
101
*Main> successor' 101
102
*Main> successor' 500
501
*Main> successor' 1
1000

Solution

 changeMyFunc :: (Integer -> Integer) -> Integer -> Integer -> (Integer -> Integer)
changeMyFunc f y z x
  | x == y = z
  | otherwise = f x


text:
Q: How to fetch the MIME type from byte array in Java 6? I have been trying to figure out how to fetch the MIME type from byte array in Java 6, but unfortunately have not been able fetch the MIME type yet.
Can someone help me get out of this?

A: You can use the MimetypesFileTypeMap provided class from Java 6. This class is exclusively used to fetch the MIME type.
Use it to fetch the MIME type as shown below:
byte[] content = ;
InputStream is = new BufferedInputStream(new ByteArrayInputStream(content));
String mimeType = URLConnection.guessContentTypeFromStream(is);

For fetching from File you can use below code:
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mime = mimeTypesMap.getContentType(file);

A: Good working library https://github.com/overview/mime-types
Import (via gradle.kts):
implementation("org.overviewproject:mime-types:0.1.3")

Usage
// input
final var fileName = "somefile.html";
final var content = "<html></html>".getBytes();

final var mimeTypeDetector = new MimeTypeDetector(); // initialize only once, reuse!
final var mimeType = mimeTypeDetector.detectMimeType(fileName, () -> content);

System.out.println(mimeType); // prints: text/html

A: Apache Tika library is proving to be the most accurate in detecting proper MIME type from a byte array in my tests, much better than Java's URLConnection.guessContentTypeFromStream() which has proven not very reliable for me.


text:
Q: session_start() fails silently on a specific script In the most simple code possible
<?php
    $ok = session_start();
    echo var_dump($ok);
?>

starting the session fails, $ok is false and no session cookie is created. Likewise, naming the session using session_name('xxx'); has no effect. The $_SESSION variable also doesn't persist values if set in another script.
Other legacy scripts on the same server that use the session feature work as expected. The same script works fine when run on localhost.
The steps I did during error analysis where:

*

*I removed naming the session and everything else to get the script above (bare minimum example reproduces the error).

*I checked the error log my provider offers, but no entry at all was found

*I made sure that no additional whitespace is present, and all scripts immediately start with session_start().

*In the same script I showed phpinfo() to mark that:

*

*Session Support: enabled

*session.auto_start: Off

*session.use_cookies: 1

*session.use_only_cookies: 1 (disputed, but since other scripts work...)

*I started doubting my sanity.

*I remembered running into "invisible characters" in form of byte-order-marks in text files before and figured, that maybe something like encoding might be a problem (see answer below) ...

What are additional sources for error that could cause these symptoms?

A: The problem was, that the script files were encoded as what Notepad++ calls UTF-8 BOM under Windows.

Converting it to straight UTF-8 in Notepad++ and reuploading the scripts immediately fixed all problems.
So I guess that somewhere in the files a stray byte order mark was left that caused the php installation on the server to not recognize or fail to parse the script file.
Edit: The same root cause was described in much more detail by mario at https://stackoverflow.com/a/8028987/3055288


text:
Q: Removing newline in file in Python (with certain conditions) so I have a utf-8 text file the looks like that:
10/02/2016, 19:08 - tel aviv
10/02/2016, 19:09 - best place in the worlds
10/02/2016, 19:09 - let's see
what do you think?
10/02/2016, 19:10 - yay!
I don't mind
10/02/2016, 19:11 - I care

and my desired text file output is:
10/02/2016, 19:08 - tel aviv
10/02/2016, 19:09 - best place in the worlds
10/02/2016, 19:09 - let's see what do you think?
10/02/2016, 19:10 - yay! I don't mind
10/02/2016, 19:11 - I care

Means in any line without a date in the beginning, I would like to backspace the line to the line before.
What should I do after I recognize the problematic lines? how I can take them to the line before?

A: My quick approach
text = '''
10/02/2016, 19:08 - tel aviv
10/02/2016, 19:09 - best place in the worlds
10/02/2016, 19:09 - let's see
what do you think?
10/02/2016, 19:10 - yay!
I don't mind
10/02/2016, 19:11 - I care
'''
from re import findall as re_findall
new_text = ''
DATE_PATTERN = '[\d]{2}\/[\d]{2}\/[\d]{4}'

for line in text .split('\n'):
    # if line starts by a date
    if re_findall(DATE_PATTERN, line):
        # add a break and the new line
        new_text += '\n' + line + ' '
    else:
        # if not, we just add the line
        new_text += line

print(new_text)
'''
10/02/2016, 19:08 - tel aviv
10/02/2016, 19:09 - best place in the worlds
10/02/2016, 19:09 - let's see what do you think?
10/02/2016, 19:10 - yay! I don't mind
10/02/2016, 19:11 - I care
'''

A: Having your text in a file called input.txt:
10/02/2016, 19:08 - tel aviv
10/02/2016, 19:09 - best place in the worlds
10/02/2016, 19:09 - let's see
what do you think?
10/02/2016, 19:10 - yay!
I don't mind
10/02/2016, 19:11 - I care

This code generates an output.txt file with the desired format:
with open("input.txt", "r") as read_file, open("output.txt", "w") as write_file:
    for idx, line in enumerate(read_file.readlines()):
        if line.strip()[0].isdigit() and idx != 0:
            write_file.write("\n")
        write_file.write(line.replace('\n', ' '))

A: How about this?
import re

def reformat_file(fp, fo):
    with open(fp, 'r') as fin, open(fo, 'w') as fout:
        date_reg_exp = re.compile('(\d+[-/]\d+[-/]\d+)')
        for line in fin:
            if date_reg_exp.findall(line):
                try:
                    _next = fin.next()
                except StopIteration:
                    _next = ''
                if date_reg_exp.findall(_next):
                    fout.write(line)
                    fout.write(_next)
                else:
                    fout.write(line.strip('\n') + ' ' + _next)

Where fp is the filepath of the input file and fo is the desired name and location of the output file

A: you can do like this way using date parser.
from dateutil.parser import parse
def is_date(string):
    try:
        parse(string)
        return True
    except ValueError:
        return False
with open("yourtext.txt", "w") as f:
    for line in f:
        if is_date(str(line).split(' ', 1)[0])==True:
            #first condition
        else:
            #second condition


text:
Q: how do I check how many int digits are inside and reset it to zero? I need to do the same but the variable gram can be any other number but no more or less than 3 characters.
I also need to immediately reset n if the if condition is met
int gram = 123, n = 0; // gram = 241, gram = 333, gram 512. etc

for (int i = 0; i < 10; i++) {

    n = 1000 * n + gram;

    if (n == 123123123) // <--- here I don't know how to write a check
    {

        std::cout << " true:  " << n << std::endl;

        n = 0;
    }

    std::cout << n << std::endl;

}

I was able to do this
    int tik++;
    if (tik % 3 == 2) // But I don't like that the number tik keeps increasing.
    {

        std::cout << " true:  " << n << std::endl;

        n = 0; // <-- I want to get rid of that too
        tik = 0; // <-- I want to get rid of that too
    }

there is another question how to reverse the order of adding numbers to the variable n
I want to add not back but ahead.
 n = 1000 * n + gram;

A: If you know gram is precisely three digits, given your multiply by 1000 and add approach, you can just have an inner loop that runs precisely three times, or a test for i % 3 == 2 to reuse information from the outer loop's loop variable.
If the value isn't fixed, and you need to stop at or above 9 digits, just use the log10 family of functions and trigger on the result being >= 8.0 (log10 of 100,000,000 is 8.0; log10 is a convenient way to count digits in base 10).


text:
Q: Pandas datetime, converting monthly date to month end day Trying to get end of month data with datetime.
my code:
monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(prevdate, format="%B %Y").strftime('%m%d%Y %H:%M')

getting
09012021 00:00

expecting:
09/30/2021 00:00

tried:
monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(monthyear, format="%B %Y")+MonthEnd(1).dt.strftime('%m%d%Y %H:%M')

A: We have a few issues:

*

*We only want to strftime once we have the entire date resolved. For this reason we need parenthesis around our offset computation.

*MonthEnd(1) is not generally what we want to get the end of the current month. We want MonthEnd(0)

*The format string is missing /
All together it can look like:
import pandas as pd
from pandas.tseries.offsets import MonthEnd

month_year = input("Enter Full Month and Year: ")  # Ie September 2021
assess_date = (
        pd.to_datetime(month_year, format="%B %Y") + MonthEnd(0)
).strftime('%m/%d/%Y %H:%M')
print(assess_date)

Program input/ouptut:
Enter Full Month and Year: September 2021
09/30/2021 00:00

The difference between MonthEnd(1) and MonthEnd(0) is that if it is the last day of the month the result will be different:
pd.Timestamp('2021-09-30') + MonthEnd(1)  # 2021-10-31 00:00:00
pd.Timestamp('2021-09-30') + MonthEnd(0)  # 2021-09-30 00:00:00


text:
Q: How to upload multiple files one by one I need to upload a lot of images at once (e.g. 200 small images) through the browser. I have this code:
<?php
if(isset($_POST['Upload_files']) and $_SERVER['REQUEST_METHOD'] == "POST"){

  echo count($_FILES['files']['name']); // Even if I upload more than 20 files, it still displays 20.

  $target_directory = "upload/";
  foreach ($_FILES['files']['name'] as $file_number => $file_name) {
    $file = $_FILES["files"]["tmp_name"][$file_number];
    if (mime_content_type($file) != 'image/png' && mime_content_type($file) != 'image/jpeg')
      { $error[] = 'File '.$file_name.' is not in JPG / PNG format!'; continue; }
    else
      { if(move_uploaded_file($file, $target_directory.$file_name)) {$count_of_upload_file++;}}
  }
}

// If files were uploaded
if($count_of_upload_file != 0){echo 'Your files ('.$count_of_upload_file.' ) were successfully uploaded.';}

// If there was an error
if (isset($error)) {foreach ($error as $display_error) {echo '- '.$display_error.'<br />';}}
?>

<form action="" method="post" enctype="multipart/form-data">
      <input type="file" name="files[]" multiple="multiple" accept="image/*">
      <input type="submit" name="Upload_files" value="Upload files">
</form>

And it works. However my provider set the 'max_file_uploads' to 20 (and I'm not able to change it). (The Uploadify extension is working for more than 20 files, but I'd like to have my own small solution.) So I presume I need to add here something, which instead of 200 files at once uploads 200 files one by one (or twenty by twenty). But I don't know how to do it. (To use AJAX? -- I never used it, so I really don't know.) Thank you!

A: If you don't want to use ajax, you need a loop to receive files
for($i = 0; $i < count($_FILES['files']['tmp_name']); $i++){
    $tmp = $_FILES['files']['tmp_name'][$i];
    $name = md5(microtime());

 if(move_uploaded_file($tmp, "dir/$name.jpg")){
    echo "Uploaded successfully";
 }else{
    echo "failed";
 }
}

In your form you must name all your input fields as files[], example:
<form action="" method="post" enctype="multipart/form-data">
      <input type="file" name="files[]" multiple="multiple" accept="image/*">
      <input type="file" name="files[]" multiple="multiple" accept="image/*">
      <input type="file" name="files[]" multiple="multiple" accept="image/*">
      <input type="submit" name="Upload_files" value="Upload files">
</form>

Or if you want to use ajax here is an example:
Upload multiple image using AJAX, PHP and jQuery


text:
Q: Route not working on laravel 5.4 I am using laravel 5.4 and davejamesmiller laravel breadcrumbs version 3.0.3. Inside routes/breadcrumbs.php i am using Route::currentRouteName() but any Route::... is not returning value. instead it returns null.How can i call Route::currentRouteName() in there?

A: The Route::currentRouteName() method returns the name of a named route. This returns null because you don't have a named route.
To use this method, give the route a name using the name() method on the route.
Route::get('foo/bar',function(){
dd(Route::currentRouteName()); // null
});

Route::get('foo/bar',function(){
dd(Route::currentRouteName()); // baz
})->name('baz');

Then you can call route(Route::currentRouteName()) to get the full url to the route like http://localhost:8000/foo/bar
Or
Call the Request::path() to get the request path of the url like foo/bar


text:
Q: How to run Laravel/Homestead on already setup VirtualBox? I am trying to install laravel/homestead on a VirtualBox using vagrant/Oracle VM VirtualBox.
I realize that I can add Homestead box via the command line like so
vagrant box add laravel/homestead

The problem with that, it creates a Dynamic Size hard drive which makes the VM performance bad and the respond is very slow.
To solve for that, I manually created a VM box with a Fixed size HD using the VM VirtualBox Manager GUI.
Now, I need to run homestead on the box that I manually created.
How do I run Homestead on the the box that I created "devBox"?

A: When you run the vagrant box add laravel/homestead command you are downloading a whole new box to the vagrant box list so you can start using that box but it will be (as I said) a new box, you can't run a box inside another box, you need to run each one separately.
Each box is a brand new virtual machine so you would have 2 virtual machines on your virtualbox, one for laravel homestead and one for devBox


text:
Q: Rails 3.1 Paperclip - better way to organize folder structure for uploaded files? I am using Paperclip to save files for Rails 3.1 app.  Everything works fine, although I am a bit confused by the fact that everything is saved to the Public folder..
I have this kind of structure:
class Photo < ActiveRecord::Base
 belongs_to :photoable, :polymorphic => true
 has_attached_file :photo,  :styles => { :large => "800x600", :medium => "400x300>", :thumb => "100x100>"  }
end

class Project < ActiveRecord::Base
 attr_accessible :projectname, :photos_attributes
 has_many :photos, :as => :photoable
 accepts_nested_attributes_for :photos, :allow_destroy => true
end

Obviously, there can be another models which also has_many :photos, :as => :photoable
Then if I upload a photo, it is  saved to Public/system/photos/1 (or /2 etc.). Everything works fine, but I wonder if there is a better way to organize it (so that the folder structure is a bit more human-readable (has usernames, project names etc.)?
Also correct me if I am wrong, but I thought that the files should go to assets and not Public folder?
Thanks

A: This is what the :path option is for in has_atached_file. Check out the "Storage" section of the README:
https://github.com/thoughtbot/paperclip

The files that are assigned as attachments are, by default, placed in
  the directory specified by the :path option to has_attached_file. By
  default, this location is
  :rails_root/public/system/:attachment/:id/:style/:filename. This
  location was chosen because on standard Capistrano deployments, the
  public/system directory is symlinked to the app's shared directory,
  meaning it will survive between deployments. For example, using that
  :path, you may have a file at

A: Content that is uploaded by users should go into public/system folder, while design elements like stylesheets, images and javascripts should be placed in app/assets corresponding folder.
If you want to add to file path some additional information that is not supported by default (like username), then you should take a look at paperclip interpolations ( https://github.com/thoughtbot/paperclip/wiki/Interpolations )


text:
Q: How to copy the most updated commit in github I don't know the right words so I am having trouble finding the solution.
I git clone a repository in github from my computer. and now there is an updated one in github and I want to copy it to my computer.
when I git clone again, this is the output fatal: destination path 'myFolder' already exists and is not an empty directory.
How can I copy the latest and updated repository in github.
Sorry if this is a duplicate question but I haven't found anything.

A: You use git pull to get the latest commits from a repository.
Docs

A: git pull is the command you should use. In future as well if there are new updates available, you don't have to checkout your code every time. git pull should pull the all the latest code from master branch to your local repository.
hope this clarifies your queries.


text:
Q: Iterating through dictionary keys when the keys point to an array? I made a dictionary where each key references an array.  And I'm trying to apply a .loc command to each array, but I can't seem to figure out how to do this.  Was wondering how this can be done:
#setup:
import pandas as pd
psd = pd.read_csv('psd.csv')
psd.head()

Out[43]:
        id group   band       fp1  ...        fz        cz        pz        oz
0  3407906   Cu-  delta  0.291945  ...  0.230908  0.221589  0.247830  0.229259
1  3407906   Cu-  theta  0.022924  ...  0.026598  0.036143  0.029904  0.025336
2  3407906   Cu-  alpha  0.003124  ...  0.017416  0.015175  0.015207  0.028024
3  3407906   Cu-   beta  0.000573  ...  0.005325  0.006429  0.003628  0.003757
4  3407906   Cu-  gamma  0.000485  ...  0.002627  0.002037  0.000956  0.001303

gp = dict(tuple(psd.groupby('band')))
list(gp.keys())

Out[44]: ['alpha', 'beta', 'delta', 'gamma', 'theta']

for key in gp:
    print(gp[key].head(1))

Out[45]:
        id group   band       fp1  ...        fz        cz        pz        oz
2  3407906   Cu-  alpha  0.003124  ...  0.017416  0.015175  0.015207  0.028024

[1 rows x 32 columns]
        id group  band       fp1  ...        fz        cz        pz        oz
3  3407906   Cu-  beta  0.000573  ...  0.005325  0.006429  0.003628  0.003757

[1 rows x 32 columns]
        id group   band       fp1  ...        fz        cz       pz        oz
0  3407906   Cu-  delta  0.291945  ...  0.230908  0.221589  0.24783  0.229259

[1 rows x 32 columns]
        id group   band       fp1  ...        fz        cz        pz        oz
4  3407906   Cu-  gamma  0.000485  ...  0.002627  0.002037  0.000956  0.001303

[1 rows x 32 columns]
        id group   band       fp1  ...        fz        cz        pz        oz
1  3407906   Cu-  theta  0.022924  ...  0.026598  0.036143  0.029904  0.025336

So far so good, but when I try the following:
for key in gp:
    band = gp[key]
    x_band = band.loc[:,'fp1':'oz']

x_band.head()
Out[49]:
         fp1        f3        f7  ...        cz        pz        oz
1   0.022924  0.019966  0.021740  ...  0.036143  0.029904  0.025336
6   0.028581  0.026947  0.025785  ...  0.028249  0.028188  0.025704
11  0.005078  0.001958  0.003227  ...  0.002071  0.002150  0.002991
16  0.014026  0.030532  0.018575  ...  0.036702  0.027133  0.020489
21  0.002640  0.001335  0.002605  ...  0.001256  0.001974  0.003032

The result as you can see is only for the last key/array, rather than a dictionary of 5 arrays with the band.loc command applied to it.  I could/did just do this manually and ended up with 5 different arrays.  But is there a way to keep it in dictionary format so I don't have to do everything from this step out 5 times?  Happy to clarify, sorry this is weirdly worded.


text:
Q: When buying a video card, what specs should I compare/which are most important? I'm currently deciding on if I should upgrade my current video card or not. I know I will find myself in this situation more times in the future, so I figured I would educate myself.
What should I be looking for as far as specs are concerned and which are most important? From a basic one monitor setup to a multi-monitor gaming PC setup. I would love a hard and fast way of comparing specs. Such as Card A has 123mhz of SpecA and 2gb SpecB, so it will perform better than Card B with 100mhz of SpecA and 1gb of SpecB.
As an example, how would I quantitatively compare the specs of the following cards:

*

*http://www.newegg.com/Product/Product.aspx?Item=N82E16814121660

*http://www.newegg.com/Product/Product.aspx?Item=N82E16814131544
I understand that sites like videocardbenchmark.net exist, but I would like to be able to compare specs even if I don't have access to these types of resources.
TLDR: What video card specs are most important and how can I compare them?
Thanks!

A: Because performance is heavily application-specific, you cannot quantitatively compare two video cards with different GPU architectures based on specs alone.  Different GPU architectures scale differently with various specs such as memory speed, memory size, memory type, and bus width; and the only way to divine the scaling ability is to look at benchmarks.
The only exception to this is if you are comparing two cards which are "obviously" not within the same performance class-for example, comparing a 2 MB S3 ViRGE to a 4 GB Radeon R9 290.  The specs are so incredibly disparate (by an entire level of magnitude) that it's not difficult to guess which card is most likely many generations newer and should have better performance.
But for the two cards you list, you have to refer to benchmarks for the exact or very similar applications that you are going to run--and note that similarity is not just a class of applications (such as "games" or "bitcoin mining") because some applications within the same class may be better-optimized for a particular piece of hardware, or a given piece of hardware may have more mature drivers.
That said, there are several specs you can compare if you're looking at two video cards based on the same GPU architecture.  For example, see the Nvidia and AMD tables at Wikipedia.
GPU architecture/code name
GPU clock speeds

*

*Core (MHz)

*Shader (MHz)

Number of shaders

*

*Unified shaders

*Texture mapping units

*Render output units

Memory

*

*Size (MB or GB)

*Bus type (DDR3, GDDR5, etc.)

*Bus width (bits--e.g., 64-bit, 128-bit, 256-bit)

*Frequency (MHz)

Power consumption

*

*TDP (watts)

There are many other specs that are derived by multiplying two or more of these basic hardware specs, such as memory bandwidth (GB/s) or processing power (GFLOPS).
Generally-speaking, if you're looking for better performance, you want the newest architectures and the highest numbers for all other specs except TDP.  (But sometimes one manufacturer's technology may lag behind that of a competitor.)
Again, performance can be highly application-dependent, as you'll notice if you look the results from any comprehensive benchmark suite for two different cards (especially with different architectures).  While one application may benefit from larger memory, another might perform better with greater bandwidth (memory frequency, bus type, and bus width) or processing power (core frequency and number of shaders).  Depending on your application, improving certain specs may not yield any performance gain whatsoever.
As if divining the computational performance wasn't already difficult enough, most people also factor in the cost, which may include not only the initial purchase price, but also power consumption.

A: I find GPUBoss as an excellent tool for comparing graphics cards.  For example, to compare your two cards:
PowerColor-Radeon-R9-290-vs-ASUS-Geforce-GTX-660
You will see where either card excels with an in-depth comparison on the bottom.  Looking at these statistics you should get a rough idea of all the different aspects involved in comparing one card to another.
There is no clean cut way of comparing graphics cards just by looking at specs, as performance may vary from card to card (with the same clock speed and memory).  Of course this also depends on what your looking for as far as an upgrade goes.  Whether you want overall performance, higher fps in a certain game, or the best performance per $.

A: Considering the cards you have mentioned, I am assuming you intend to use it for gaming. Then best thing to compare in my opinion is game FPS of cards when all other specs are kept same. There are a lot of comparisons out there which have some test rigs built to compare cards. I personally prefer comparing game FPS rather than synthetic benchmarks though I could very well be wrong in doing so.
As far as specifications are concerned, graphics cards have lot more parameters to compare than say CPU or RAM. And quite often, a card will have better RAM but say lesser clock frequency than a similarly priced card. So, its quite confusing to compare two similarly spec'd cards just by looking at specifications.
PS: Unless you plan to bridge it with second card, don't go for Crossfire/SLI supporting cards because they tend to be more expensive.


text:
Q: Java initialize variables "remotely" I need to initialize some variables I receive in an array like (example):
private Map<Long, Object> var1 = null;
private Map<Long, Object> var2 = null;
private Map<Long, Object> var3 = null;
private List<Map<Long, Object>> vars = Arrays.asList(var1, var2, var3);

And I would like to know if I can do this:
private void initializeVars() {
    var1 = new HashMap<Long, Object>();
    var2 = new HashMap<Long, Object>();
    var3 = new HashMap<Long, Object>();
}

But with something like this:
private void initializeVars() {
    for (Map<Long,Object> var : vars) {
        var = new HashMap<Long, Object>();
    }
}

The above code doesn't work because underneath I'm just changing the pointer of the array position from 'var#' to a new HashMap, but what I want to do is access 'var#' and change its pointer.

A: Only solution that comes to my mind is packing it into another light-weight object, like MyMap. That MyMap would hold the actual map inside, and then you could initialize that map, something like this:
private MyMap<Long, Object> var1 = new MyMap<>();
private MyMap<Long, Object> var2 = new MyMap<>();
private MyMap<Long, Object> var3 = new MyMap<>();
private List<MyMap<Long, Object>> vars = Arrays.asList(var1, var2, var3);

private void initializeVars() {
    for (MyMap<Long,Object> var : vars) {
        var.setInnerMap(new HashMap<Long, Object>());
    }
}

It's ugly and bad, but I don't see any different way right now. What you're trying with your way is certainly not possible in Java.

A: First, you only receive an List of null so this could simply be a int countVar = 3, that would be the same.
But if you want to use this list.
private void initializeVars() {
    for (int i = 0; i < list.size(); ++i) {
        list.add(new HashMap<Long, Object>());
    }
}

But of course, var[1|2|3] would still be null.
If you want to be able to do you logic, you would need a wrapper. See Whatz answer for that

A: The closest thing you can get, works with Java 8:
private Map<Long, Object> var1 = null;
private Map<Long, Object> var2 = null;
private Map<Long, Object> var3 = null;
private List<Consumer<Map<Long, Object>>> writers
        = Arrays.asList(m -> var1=m, m -> var2=m, m -> var3=m);

private void initializeVars() {
    for(Consumer<Map<Long,Object>> c: writers) {
        c.accept(new HashMap<>());
    }
}

You don't have a field reference here, as a field reference would work in both directions. Here, we only have a Consumer encapsulating the operation of assigning a new value to the variable. For the initialization procedure, this is sufficient.


text:
Q: Input event listener not working at times I have made a simple API based project wherein whenever the user enter some number in the input, the div below it with the output becomes visible and when the input field is empty the  div gets hidden again as it was in the initial state. The problem is whenever I clear the input field gradually the setup works as expected but if I clear it quickly the div doesn't hide the div at all. Below given is the reference code for the same

let input = document.querySelector("#number-input");
      let fact = document.querySelector(".fact-content");
      input.addEventListener("input", getFact);
      function getFact() {
        let number = input.value;
        if (number != "") {
          let xhr = new XMLHttpRequest();
          xhr.open("GET", "http://numbersapi.com/" + number);
          xhr.onload = function () {
            if (this.status == 200) {
              fact.innerText = this.responseText;
              fact.style.display = "block";
            }
          };
          xhr.send();
        }
        else{
          fact.innerText = "";
          fact.style.display = "none";
        }
      }
@import url('https://fonts.googleapis.com/css2?family=Varela+Round&display=swap');
*{
    margin: 0;
    padding: 0;
    font-family: 'Varela Round', sans-serif;
    box-sizing: border-box;
}
body{
    background-color: #9AD0EC;
}
main{
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.container{
    width: 40%;
    margin: auto;
    line-height: 1.6;
    background-color: #1572A1;
    color: #eee;
    padding: 2rem;
    min-width: 500px;
    border-radius: 5px;
}
.container h1{
    font-size: 1.5em;
}
.container h4{
    font-size: 1.2rem;
}
input{
    padding: 0.5rem;
    border-radius: 5px;
    border: none;
    margin: 10px 0;
    width: 50%;
}
.fact-content{
    display: none;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Number Fact</title>

Get random fact based on numbers

Enter a number and get a random fact

          <input
            type="number"
            id="number-input"
            placeholder="Enter a number..."
          />

A: Consider the case when you have two characters in your input. You delete one character, and initiate an AJAX request for the remaining character. Before that AJAX request completes, you delete the remaining character.
When you delete the final character, the event handler clears and hides the element. But then the previous AJAX request completes, and displays the outdated response in the element.
There are two things you can do here:

*

*When the AJAX request completes, check that the input value is still the same as the number variable. If it's not, discard the response to the AJAX request.

*Switch to using the fetch API, and use an AbortController instance to abort the in-flight request when the input value changes.

let input = document.querySelector("#number-input");
let fact = document.querySelector(".fact-content");
let abortToken = null;

input.addEventListener("input", getFact);

async function getFact() {
  if (abortToken) {
    abortToken.abort("Input changed");
    abortToken = null;
  }

  let number = input.value;
  if (!number) {
    fact.innerText = "";
    fact.style.display = "none";
    return;
  }

  const url = `http://numbersapi.com/${number}`;
  abortToken = new AbortController();
  const { signal } = abortToken;
  try {
    const response = await fetch(url, { signal });
    if (input.value !== number) {
        // The input has been modified.
        return;
    }

    if (!response.ok){
        const errorMessage = await response.text();
        console.error(response.status, response.statusText, errorMessage);
        fact.innerText = "# ERROR #";
        fact.style.display = "block";
        return;
    }

    const text = await response.text();
    fact.innerText = text;
    fact.style.display = "block";
  } catch {
  }
}
@import url('https://fonts.googleapis.com/css2?family=Varela+Round&display=swap');
*{
    margin: 0;
    padding: 0;
    font-family: 'Varela Round', sans-serif;
    box-sizing: border-box;
}
body{
    background-color: #9AD0EC;
}
main{
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.container{
    width: 40%;
    margin: auto;
    line-height: 1.6;
    background-color: #1572A1;
    color: #eee;
    padding: 2rem;
    min-width: 500px;
    border-radius: 5px;
}
.container h1{
    font-size: 1.5em;
}
.container h4{
    font-size: 1.2rem;
}
input{
    padding: 0.5rem;
    border-radius: 5px;
    border: none;
    margin: 10px 0;
    width: 50%;
}
.fact-content{
    display: none;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Number Fact</title>

Get random fact based on numbers

Enter a number and get a random fact

          <input
            type="number"
            id="number-input"
            placeholder="Enter a number..."
          />


text:
Q: Xamarin project with CrossMediaManager can't play local web site can't play I'm using Plugin.CrossMediaManager(Current version) to play VDO or mp3 files.
Try to use URL from local website (IIS) to play them.
I have learned how to use this component and I have set all necessary things.
- Give necessary code to where native platform start.
I have tried with URL form public website: Link to website.
It works well, but when I downloaded that file and copy it into my website (IIS) I can't play it.
This works:
CrossMediaManager.Current.Play("https://archive.org/download/BigBuckBunny_328/BigBuckBunny_512kb.mp4");

But yhis doesn't work:
CrossMediaManager.Current.Play("http://192.168.220.110:1113/SampleVideo_1280x720_1mb.mp4");


text:
Q: what is asp's application object java equivalent? in asp there's an Application object, which is like the Session but it's shared among all sessions...
http://msdn.microsoft.com/en-us/library/ms525360.aspx

You can use the Application object to share information among all users of a given application. An ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories. Because the Application object can be shared by more than one user, there are Lock and Unlock methods to ensure that multiple users do not try to alter a property simultaneously.

I use this object to implement a simple cache for small sets of data...
What is java / jsp equivalent?
thanks a lot...

A: ServletContext is similar to the ApplicationObject. You can use the setAttribute method to add information shared by all users. From within a servlet, you can call getServletContext() to gain access to it. I am not sure however if it provides locking/unlocking functionality.
If you are using Spring or another IoC container, you can easily define a bean that is accessible from all users. I suppose this is a better solution for both worlds.

A: Application scope in JSP is identical to ServletContext.

A: I know of two ways to accomplish this in JSP.

*

*Define a bean in the application scope:
<jsp:useBean id="appCounter" class="com.company.AppCounter" scope="application" />

*Create a singleton class. Example


text:
Q: Gurobi Equivalent of `CPX_PARAM_ALL_MIN` and `CPX_PARAM_ALL_MAX` I am trying to find if there are any equivalents of CPX_PARAM_ALL_MIN and CPX_PARAM_ALL_MAX.
I am trying to port some code from CPLEX to GuRoBi
and there is some code like this
for (int i = CPX_PARAM_ALL_MIN; i <= CPX_PARAM_ALL_MAX; ++i)
{
         stat = CPXgetparamname(env, i, name);
}

while I found out that CPXgetparamname equivalent is GRBgetparamname, I am unable to find the equivalents of CPX_PARAM_ALL_MIN and CPX_PARAM_ALL_MAX

A: Not all features map directly between Gurobi and CPLEX; this is one example. Here, CPLEX parameters are indexed by a number, while Gurobi parameters are indexed by a string (char* in C). If you want to get the full list of Gurobi parameters programmatically, look at the Parameters section in the header file include/gurobi_c.h.


text:
Q: Hydrogen atom and scale transformation for radial variable While solving Schrödinger equation for Hydrogen atom we make a scale transformation for radial variable ($r=\frac{ax}{Z}$; where $a=$ Bohr radius, $x=$ dimensionless variable and $Z=$ atomic number), this turns out to be a very good scale transformation. But my question is how do we know value of Bohr radius in advance, before solving Schrödinger equation? Do we just use Bohr radius that we got from Bohr theory? If we do use Bohr radius from Bohr theory then why is so because it is a classical theory?

A:
this turns out to be a very good scale transformation.

We don't really care that it's a good or bad choice.  We start by choosing a scale factor with just a symbol to move to dimensionless coordinates and follow the math through using it.  The physical problem is solved no matter what we choose (as long as it's not silly like zero).
We can at any point in going through the math (on this or any problem where we apply this technique) choose a value for the scale factor that is convenient and makes doing the math simpler.

But my question is how do we know value of Bohr radius in advance, before solving Schrödinger equation?

We don't.  We solve the problem and then we label the value as the Bohr radius.  That's what happened when Bohr's original model was published - it did not start out being called the "Bohr radius, it became that by convention.
For some problems the scale factor we end up with for mathematical convenience has a straight-forward physical interpretation (a radius, an orbital period, a reduced mass, etc.), but sometimes it's just a constant in the equation because that's how the mathematics works out.

A: Usually when transforming into dimensionless variables one looks at the relevant constants in the problem. For hydrogen atom we have the electron charge $e$,  electron mass $m_e$, Plank constant $\hbar$, permittivity of free space $\epsilon_0$
Then one does dimensional analysis to make scales based on the above constants. And the expression for length scale turns out to be
$$a_0=\frac{4\pi\epsilon_0\hbar^2}{e^2 {m_e}}$$
The extra $4\pi$ is part of the permittivity. And this is exactly the Bohr radius.


text:
Q: Php Session Object Interaction I ask you for advice.
I struggle with session/object interactions....
<?php
class ShoppingCart
{

    public $products

    public function __construct($session) {
        $this->products = $session['products'];
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
        $_SESSION['products'] = $this->products;
    }

}

session_start();
$shoppingCart = new ShoppingCart($_SESSION);
$shoppingCart->addProduct(1);
?>

How would you write similar code?
It's only the stub but I don't like my addProduct method and all this code in general.
Please don't be critical and help me improve it.
Maybe there are some design patterns or examples of such interaction?

A: class ShoppingCart {

    private $products = array();

    public function __construct() {
        if (isset($_SESSION['products'])) {
            $this->products = &$_SESSION['products'];
        }
    }

    public addProduct($id) {
        $this->products[] = new Product($id);
    }
}


text:
Q: What does mongoose.model() do? What does it return? I want to know what mongoose.model() do? Also what does it mean to export it? Am I exporting a collection?
    const mongoose = require('mongoose');
    const schema = mongoose.Schema;

    const userSchema = new Schema({
        firstName: {
            type: String
        },
        lastName: {
           type: String
        },

     })

    module.exports = User = mongoose.model('User', userSchema);

Thanks.

A: mongoose.model compiles a Schema into a Model, then you can use its methods to access the database.
For example:
const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/YOURDB';

mongoose.connect(dbURI, {useNewUrlParser: true}).then(() => {
   console.log(`Mongoose connected to ${dbURI}`);
}).catch((err) => {
   console.log('Mongoose connection error:', err);
});

const yourSchema = new mongoose.Schema({
      name: String,
});

const yourModel = mongoose.model('yourModel', yourSchema);

and with yourModel you can use CRUD methods to use Insert, Read, Update and Delete operations in YOURDB.
You can see here the helper functions for CRUD operations that Mongoose provides.


text:
Q: Saving webpage content using webbrowser IHTMLDocument interface We need to save the complete web page including img, javascript, css and html using ATL webbrowser (IHTMLDocument) control,
using IHTMLDocument2::get_all() method we have saved .html file but now how do we get external files such as .css, javascript and image files
please help us with methods that internet explorer or firefox used to save the web page locally.
Thanks,
Ramanand.

A: I think this will be a rather manual task:
You can get a grip on the stylesheets by using the IHTMLDocument2::styleSheets property. The collection contains IHTMLStyleSheet elements, which in turn have a href-property which you can use to download the file. Scripts you can get via IHTMLDocument2::scripts which gives you a collection containing IHTMLScript elements, which have a src property. Same goes for images: use the src property to obtain a path. Somebody seems to do the same thing as you, have a look here. There are also some hints about handling relative pathes.


text:
Q: how to sort selected data at php to mysql from flutter here is my code at flutter
void initState(){
    var url = "my web";
    String id =  widget.list[widget.index]['id_pemesanan'];
    http.post(url, body: {
        'id_pemesanan': id,
    });
    super.initState();
}

here is the code at my php
<?php
include 'db.php';
$id_pemesanan = $_POST['id_pemesanan'];

$queryResult = $connect->query("SELECT * FROM Odr_Msk_Detail WHERE id_pemesanan = '$id_pemesanan'");

$result=array();

while($fetchData=$queryResult->fetch_assoc()){
    $result[]=$fetchData;
}
echo json_encode($result);
?>

if i change the data at $id_pemesanan to directly my data id in my database, it works, but if i use $id_pemesanan it doesnt shows anything in my listview

A: You can sort your data in ascending or descending order as needed using the Order By clause.
For details you can check the following link:
https://www.guru99.com/order-by-desc-and-asc.html
How to optimize it here:
https://dev.mysql.com/doc/refman/8.0/en/order-by-optimization.html
However as noted by the others, your current code is vulnerable to sql injection, I would recommend reading up on MySQL prepared statements and PHP PDO.
A very nice resource for it:
https://phpdelusions.net/pdo


text:
Q: How to call calling a function inside a Template literal How can I go about calling a function inside a Template literal.
The function syntax in the attempt below shows in the HTML:
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        var html = `

        ${reader.onload = function (e) {
            $('#image_upload_preview').attr('src', e.target.result);
        }}

        `;

        $("#test").append(html);

        reader.readAsDataURL(input.files[0]);
    }
}

$("#multi-file").change(function () {
    readURL(this);
});

Thank you all in advance.

A: This is how you can call a function inside a template literal..
function something() {
    return "better than nothing";
}
console.log(`Something is ${something()}.`);
//=> Something is better than nothing.

A: If I understand your question correctly, you want to define and invoke the function inside the template literal.
Some background:
You can execute an expression in the template literal as follows:
function fun(){
   return 5
}

var someLit=`some function got a value ${fun()}`

So this is the simplest and best usage of a function inside literal. Now what you are trying to do in your example is, evaluate the expression
reader.onload = function (e) {
  $('#image_upload_preview').attr('src', e.target.result);
}

inside the template literal, this binds and event for onload, but the returned value for reader.onload is replaced in that position inside the template literal.
and you see function(){... in the output.
If you don't want to see that function declaration in the output you can immediately invoke the function.
Example:
   (reader.onload = function (e) {
      $('#image_upload_preview').attr('src', e.target.result);
   })();

This will return undefined in the place of the expression. Now if you want to avoid that undefined, you can return some empty string from your function.
  (reader.onload = function (e) {
      $('#image_upload_preview').attr('src', e.target.result);
      return '';
   })();

Now, as you have used this function as an callback for event, immediately invoking the function might not help(as you will not get the e parameter there).
So you can bind the event inside another function like:
(function(){
    reader.onload = function (e) {
          $('#image_upload_preview').attr('src', e.target.result);
       }
    return '';
})();

this will declare the function, which is bind to your onload event and would not leave a trace in your template literal.
Note:
Simply declaring the function outside the template literal and calling it inside literal wherever you want is the best option


text:
Q: Build failed error occurred when try to debug specflow scenarios in VST2017 When i try to debug the test step in feature file  .. I am getting Build failed
VST2017, Specflow 2.3.0, Selenium 3.6
Nunit 2.6
Could someone please help me on this