Q: How to join surfaces together to form a 3D image in Python? I wish to achieve something very similar to this question: How to join these two 3D lines together with a surface in Python's matplotlib
There is an answer towards the bottom which is exactly the picture I would like to obtain, however, the surfaces I am dealing with are arbitrary and as a result I am unable to parametrize them. I have multiple 2D curves (each at a specific z level) and I wish to "connect" these, in part so it is visually obvious when the "width" of one closed surface is increasing as z increases.
Does anyone know how I might achieve this? Thanks.

A: I'm not sure if this is want you want but if you want to project two 2d-profiles of the 3d-surface you can use offset=z in the contour plot, where z is where in the z-axes you want to plot the profiles. Here is an example: https://matplotlib.org/3.3.1/gallery/mplot3d/contour3d_3.html


Q: lightning:helptext popup not working If the lightning component is opened through VF page I am unable to view lightning helptext popup. below is the VF that I am using.
    <apex:page sidebar="true" showHeader="true">
<apex:includeLightning />

</apex:page>

CreateTemplateLC has lightning:helptext. If I open this page using a normal custom button with this VF page, helptext is breaking the page. Please refer below screenshot.

If I open the same page using lightning component button, lightning:helptext popup is working without any issues. below are the lightning component and controller used to open CreateTemplateLC Component.
markup :
<aura:component implements="force:lightningQuickAction,force:hasRecordId,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName,flexipage:availableForAllPageTypes"
            access="global">
<aura:attribute name="recId" type="String"/>
<aura:attribute name="sObjectName" type="String" />
<aura:attribute name="uiContext" type="String"/>

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<lightning:button label="Create template" onclick="{! c.handleClick }"/>

Controller: has all functions required. I am firing below event to open the page component on handleClick function.
var evt = $A.get("e.force:navigateToComponent");
    evt.setParams({
        componentDef : "nameSpace:CreateTemplateLC",
        componentAttributes: {
UserContext: context,
            recId : id
        }
    });
    evt.fire();

And the result is as below snapshot. While I am opening through above lightning component, it's working fine.

Please let me know how to get this working while opening through VF page/normal button. I tried both firefox and chrome. we would like to get it working for both methods. Thank you.

A: You need to override styles in VF page as component help text does not render properly in vf container. Try below:
<apex:page sidebar="true" showHeader="true">

        <apex:includeLightning />

    </apex:page>


Q: How to pass pendingInent in Intent.putExtra; to start pendingIntent from anotherActivty I'm trying a start a UI activity from the NotificationListiner service,Then In UI
when user clicks on yes: perform pendingIntent();else: finish()
I tried to achieve the above with Dialog,AlertDialog but since NotificationListiner was a background service it didn't work.
Then made a new Activity;
Tried with Gson
SbnContainer.kt
class SbnContainer {
    lateinit var notification: Notification
    lateinit var title: String
    lateinit var desc: String
    constructor(){
        Log.d("TAG", "Salaam")
    }
    constructor(notification: Notification, title:String, desc:String){
        this.notification = notification
        this.title= title
        this.desc = desc
    }
}

Calling From NotificationService
    var i = Intent(this,CAlertWindow::class.java)
    i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    val gson = Gson()
    var a = SbnContainer(sbn.notification, title, desc)
    val myJson = gson.toJson(a)
    i.putExtra("PACKAGE", myJson)
    startActivity(i)

Receiving from CAlertWindow(AppCompatActivity)
        val gson = Gson()
        val ob: SbnContainer = gson.fromJson(intent.getStringExtra("PACKAGE"), SbnContainer::class.java)
        pendingIntent = ob.notification.contentIntent
        alertWindowLayoutBinding.alrTitle.text = ob.title
        alertWindowLayoutBinding.alrDesc.text = ob.desc
        Log.d("Abdx79/AlertWindow", "In Alert Window")
        alertWindowLayoutBinding.alrOpnB.setOnClickListener {
            pendingIntent.send()
        }
        alertWindowLayoutBinding.alrDntB.setOnClickListener {
            finish()
        }

Error on calling startActivity(i)
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abdx79.notifications_manager/com.abdx79.notifications_manager.CAlertWindow}: java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.CharSequence. Registering an InstanceCreator with Gson for this type may fix this problem.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
     Caused by: java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.CharSequence. Registering an InstanceCreator with Gson for this type may fix this problem.

So how can I solve this.?

A: You can use Serializable for passing a object like ->
 class Shop(
            val name: String,
            val details: String?,
            val id: Int,
            ):Serializable

now pass this Shop class like
 var shop = Shop("name","details",1)
    val intent = Intent(this, AnotherActivity::class.java).putExtra(
                "SHOP",
                shop
            )
    startActivity(intent)

now receive this shop class from another activity
 val shope = intent.getSerializableExtra("SHOP") as Shop

you can also use Parcelable instead of Serializable


Q: How do zipkin do to merge span for search trace request? In the zipkin web ui, when the request url is http://10.19.138.169:9411/zipkin/api/v1/trace/ae60bd175a61e820
I find the return response is
[
    {
        "traceId": "ae60bd175a61e820",
        "id": "ae60bd175a61e820",
        "name": "client",
        "timestamp": 1511858133224433,
        "duration": 508444,
        "binaryAnnotations": [
            {
                "key": "lc",
                "value": "",
                "endpoint": {
                    "serviceName": "monitor-gw-http-c",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "19d69c3e93bc9040",
        "name": "post",
        "parentId": "ae60bd175a61e820",
        "timestamp": 1511858133239803,
        "duration": 490921,
        "annotations": [
            {
                "timestamp": 1511858133239803,
                "value": "cs",
                "endpoint": {
                    "serviceName": "monitor-gw-http-c",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133383290,
                "value": "sr",
                "endpoint": {
                    "serviceName": "monitor-gw-web",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133609368,
                "value": "ss",
                "endpoint": {
                    "serviceName": "monitor-gw-web",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133730724,
                "value": "cr",
                "endpoint": {
                    "serviceName": "monitor-gw-http-c",
                    "ipv4": "10.19.138.169"
                }
            }
        ],
        "binaryAnnotations": [
            {
                "key": "ca",
                "value": true,
                "endpoint": {
                    "serviceName": "",
                    "ipv4": "127.0.0.1",
                    "port": 43928
                }
            },
            {
                "key": "http.path",
                "value": "/security/gateway",
                "endpoint": {
                    "serviceName": "monitor-gw-web",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "key": "http.path",
                "value": "/security/gateway",
                "endpoint": {
                    "serviceName": "monitor-gw-http-c",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "key": "sa",
                "value": true,
                "endpoint": {
                    "serviceName": "",
                    "ipv4": "127.0.0.1",
                    "port": 8090
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "16eefe087852af41",
        "name": "ennmonitorsecuritygatewayserver/put",
        "parentId": "19d69c3e93bc9040",
        "timestamp": 1511858133393425,
        "duration": 212916,
        "annotations": [
            {
                "timestamp": 1511858133393425,
                "value": "cs",
                "endpoint": {
                    "serviceName": "monitor-gw-web",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133588237,
                "value": "sr",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133593907,
                "value": "ss",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133606341,
                "value": "cr",
                "endpoint": {
                    "serviceName": "monitor-gw-web",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "8ef78f0edefe3a4b",
        "name": "data enqueue",
        "parentId": "16eefe087852af41",
        "timestamp": 1511858133592958,
        "duration": 129,
        "binaryAnnotations": [
            {
                "key": "lc",
                "value": "",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "97c637bcc891b86a",
        "name": "data dequeue, send to kafka",
        "parentId": "16eefe087852af41",
        "timestamp": 1511858133593147,
        "duration": 2416,
        "binaryAnnotations": [
            {
                "key": "lc",
                "value": "",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "f193c7f4193f2879",
        "name": "",
        "parentId": "16eefe087852af41",
        "timestamp": 1511858133594113,
        "duration": 7575,
        "annotations": [
            {
                "timestamp": 1511858133594113,
                "value": "ms",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133601688,
                "value": "ws",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            }
        ],
        "binaryAnnotations": [
            {
                "key": "kafka.topic",
                "value": "rdkafka",
                "endpoint": {
                    "serviceName": "monitor-gw-s",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    },
    {
        "traceId": "ae60bd175a61e820",
        "id": "54a3f6268df0aaee",
        "name": "",
        "parentId": "f193c7f4193f2879",
        "timestamp": 1511858133600067,
        "duration": 5,
        "annotations": [
            {
                "timestamp": 1511858133600067,
                "value": "wr",
                "endpoint": {
                    "serviceName": "monitor-kafka-consumer",
                    "ipv4": "10.19.138.169"
                }
            },
            {
                "timestamp": 1511858133600072,
                "value": "mr",
                "endpoint": {
                    "serviceName": "monitor-kafka-consumer",
                    "ipv4": "10.19.138.169"
                }
            }
        ],
        "binaryAnnotations": [
            {
                "key": "kafka.topic",
                "value": "rdkafka",
                "endpoint": {
                    "serviceName": "monitor-kafka-consumer",
                    "ipv4": "10.19.138.169"
                }
            }
        ]
    }
]
It can easy to find that there are 8 spans.
When I use the api to get the trace with the same traceId
        ElasticsearchStorage storage = ElasticsearchStorage.newBuilder()
                .hosts(Arrays.asList("http://10.19.138.169:9200")).build();
    List<Span> trace = null;
    try {
        trace = storage.spanStore().getTrace(traceId).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

I get
[
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "97c637bcc891b86a",
    "name": "data dequeue, send to kafka",
    "timestamp": 1511858133593147,
    "duration": 2416,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "id": "ae60bd175a61e820",
    "name": "client",
    "timestamp": 1511858133224433,
    "duration": 508444,
    "localEndpoint": {
      "serviceName": "monitor-gw-http-c",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "f193c7f4193f2879",
    "id": "54a3f6268df0aaee",
    "kind": "CONSUMER",
    "timestamp": 1511858133600067,
    "duration": 5,
    "localEndpoint": {
      "serviceName": "monitor-kafka-consumer",
      "ipv4": "10.19.138.169"
    },
    "tags": {
      "kafka.topic": "rdkafka"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "ae60bd175a61e820",
    "id": "19d69c3e93bc9040",
    "kind": "SERVER",
    "name": "post",
    "timestamp": 1511858133383290,
    "duration": 226078,
    "localEndpoint": {
      "serviceName": "monitor-gw-web",
      "ipv4": "10.19.138.169"
    },
    "remoteEndpoint": {
      "ipv4": "127.0.0.1",
      "port": 43928
    },
    "tags": {
      "http.path": "/security/gateway"
    },
    "shared": true
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "19d69c3e93bc9040",
    "id": "16eefe087852af41",
    "kind": "CLIENT",
    "name": "ennmonitorsecuritygatewayserver/put",
    "timestamp": 1511858133393425,
    "duration": 212916,
    "localEndpoint": {
      "serviceName": "monitor-gw-web",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "19d69c3e93bc9040",
    "id": "16eefe087852af41",
    "kind": "SERVER",
    "name": "ennmonitorsecuritygatewayserver/put",
    "timestamp": 1511858133588237,
    "duration": 5670,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    },
    "shared": true
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "f193c7f4193f2879",
    "kind": "PRODUCER",
    "timestamp": 1511858133594113,
    "duration": 7575,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    },
    "tags": {
      "kafka.topic": "rdkafka"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "ae60bd175a61e820",
    "id": "19d69c3e93bc9040",
    "kind": "CLIENT",
    "name": "post",
    "timestamp": 1511858133239803,
    "duration": 490921,
    "localEndpoint": {
      "serviceName": "monitor-gw-http-c",
      "ipv4": "10.19.138.169"
    },
    "remoteEndpoint": {
      "ipv4": "127.0.0.1",
      "port": 8090
    },
    "tags": {
      "http.path": "/security/gateway"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "ae60bd175a61e820",
    "id": "19d69c3e93bc9040",
    "kind": "SERVER",
    "name": "post",
    "timestamp": 1511858133383290,
    "duration": 226078,
    "localEndpoint": {
      "serviceName": "monitor-gw-web",
      "ipv4": "10.19.138.169"
    },
    "remoteEndpoint": {
      "ipv4": "127.0.0.1",
      "port": 43928
    },
    "tags": {
      "http.path": "/security/gateway"
    },
    "shared": true
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "19d69c3e93bc9040",
    "id": "16eefe087852af41",
    "kind": "SERVER",
    "name": "ennmonitorsecuritygatewayserver/put",
    "timestamp": 1511858133588237,
    "duration": 5670,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    },
    "shared": true
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "97c637bcc891b86a",
    "name": "data dequeue, send to kafka",
    "timestamp": 1511858133593147,
    "duration": 2416,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "f193c7f4193f2879",
    "kind": "PRODUCER",
    "timestamp": 1511858133594113,
    "duration": 7575,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    },
    "tags": {
      "kafka.topic": "rdkafka"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "19d69c3e93bc9040",
    "id": "16eefe087852af41",
    "kind": "CLIENT",
    "name": "ennmonitorsecuritygatewayserver/put",
    "timestamp": 1511858133393425,
    "duration": 212916,
    "localEndpoint": {
      "serviceName": "monitor-gw-web",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "ae60bd175a61e820",
    "id": "19d69c3e93bc9040",
    "kind": "CLIENT",
    "name": "post",
    "timestamp": 1511858133239803,
    "duration": 490921,
    "localEndpoint": {
      "serviceName": "monitor-gw-http-c",
      "ipv4": "10.19.138.169"
    },
    "remoteEndpoint": {
      "ipv4": "127.0.0.1",
      "port": 8090
    },
    "tags": {
      "http.path": "/security/gateway"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "id": "ae60bd175a61e820",
    "name": "client",
    "timestamp": 1511858133224433,
    "duration": 508444,
    "localEndpoint": {
      "serviceName": "monitor-gw-http-c",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "f193c7f4193f2879",
    "id": "54a3f6268df0aaee",
    "kind": "CONSUMER",
    "timestamp": 1511858133600067,
    "duration": 5,
    "localEndpoint": {
      "serviceName": "monitor-kafka-consumer",
      "ipv4": "10.19.138.169"
    },
    "tags": {
      "kafka.topic": "rdkafka"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "8ef78f0edefe3a4b",
    "name": "data enqueue",
    "timestamp": 1511858133592958,
    "duration": 129,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    }
  },
  {
    "traceId": "ae60bd175a61e820",
    "parentId": "16eefe087852af41",
    "id": "8ef78f0edefe3a4b",
    "name": "data enqueue",
    "timestamp": 1511858133592958,
    "duration": 129,
    "localEndpoint": {
      "serviceName": "monitor-gw-s",
      "ipv4": "10.19.138.169"
    }
  }
]
It is easy to find that there are 18 spans.
It seems that some of spans are merged in the web request, I want to know to where is the cource code deal this.
Thanks!

A: The first request uses v1 of the Zipkin api while the second uses v2 (see https://github.com/openzipkin/zipkin/issues/1499 for the v2 specification). Spans are broken up by kind (SERVER and CLIENT) instead of having client receive, server receive, client send, and server send annotations (hence why there are more spans).


Q: Web-scraping for a specific class of tag I am attempting to draw financial data from the Australian stock exchange (ASX). Specifically, the share registry for a particular company.
The website would be something like this (I say something because the ticker in the URL would change from firm to firm).
The HTML snippet I am looking at is:
COMPUTERSHARE INVESTOR SERVICES PTY LIMITED

Yarra Falls, 452 Johnston Street, ABBOTSFORD, VIC, AUSTRALIA, 3067

My overarching goal is to create a spreadsheet whereby I would have a list of Ticker Symbols and a macro would take that symbol, place it in the url and draw the adjacent Share Registry value into Excel. (In this case, COMPUTERSHARE INVESTOR SERVICES PTY LIMITED)
I tried to figure out how to use a variable url (I believe it involves Concatenation) and draw financial tables from websites.
I've settled on this tutorial that doesn't post the results into Excel, just presents it in a box. If I can results to post in the box that'll be a great first step.
Many tutorials use the IE object and from what I can gather, the use of XMLHttpRequest is far more efficient and nimble and considering I would have a large number of ticker symbols, would probably be best to use with regards to time.
Sub Get_Web_Data()
    ' TeachExcel.com

    Dim request As Object
    Dim response As String
    Dim html As New HTMLDocument
    Dim website As String
    Dim price As Variant

    ' Website to go to.
    website = "https://www.asx.com.au/asx/share-price-research/company/BFG/details"

    ' Create the object that will make the webpage request.
    Set request = CreateObject("MSXML2.XMLHTTP")

    ' Where to go and how to go there - probably don't need to change this.
    request.Open "GET", website, False

    ' Get fresh data.
    request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"

    ' Send the request for the webpage.
    request.send

    ' Get the webpage response data into a variable.
    response = StrConv(request.responseBody, vbUnicode)

    ' Put the webpage into an html object to make data references easier.
    html.body.innerHTML = response

    ' Get the price from the specified element on the page.
    price = html.getElementsByClassName("disclaimer disclaimer-company-info").Item(0).innerText

    ' Output the price into a message box.
    MsgBox price

End Sub

I edited the code to present the only HTML class element that seems to be working for me, which is the disclaimer info at the bottom of the page. I gather that the use of html.getElementsByClassName is wrong in my scenario.
I have read that CSS Selectors might be applicable in this case and the use of 'children' (I think) as the info I am after (ng-binding) occurs numerous times throughout the table, so I gather I would need to direct the macro to select the nth instance.
I do not expect a completely written extract. Any hints and tips to point me in the right direction?

A: How about this?
Sub Web_Table_Option_Two()
    Dim HTMLDoc As New HTMLDocument
    Dim objTable As Object
    Dim lRow As Long
    Dim lngTable As Long
    Dim lngRow As Long
    Dim lngCol As Long
    Dim ActRw As Long
    Dim objIE As InternetExplorer
    Set objIE = New InternetExplorer
    objIE.Navigate "https://www.asx.com.au/asx/share-price-research/company/BFG/details"

    Do Until objIE.ReadyState = 4 And Not objIE.Busy
        DoEvents
    Loop
    Application.Wait (Now + TimeValue("0:00:03")) 'wait for java script to load
    HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
    With HTMLDoc.body
        Set objTable = .getElementsByTagName("table")
        For lngTable = 0 To objTable.Length - 1
            For lngRow = 0 To objTable(lngTable).Rows.Length - 1
                For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                    ThisWorkbook.Sheets("Sheet1").Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
                Next lngCol
            Next lngRow
            ActRw = ActRw + objTable(lngTable).Rows.Length + 1
        Next lngTable
    End With
    objIE.Quit
End Sub

If you want to specify the row, you can do that, and just grab the row number that you want/need.
Finally, if you want to loop through an array of stock tickers, use the code below.
Sub Web_Table_Option_Two()
    Dim HTMLDoc As New HTMLDocument
    Dim objTable As Object
    Dim lRow As Long
    Dim lngTable As Long
    Dim lngRow As Long
    Dim lngCol As Long
    Dim ActRw As Long
    Dim objIE As InternetExplorer
    Set objIE = New InternetExplorer
    Dim c As Range
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim wb As Workbook: Set wb = ThisWorkbook

    Set sht = wb.Sheets("Stocks")

    'find last used row in ColumnA
    LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

    For Each c In Range("A2:A" & LastRow)

    mystock = c.Value

        objIE.Navigate "https://www.asx.com.au/asx/share-price-research/company/" & mystock & "/details"

        Do Until objIE.ReadyState = 4 And Not objIE.Busy
            DoEvents
        Loop

        Sheets.Add After:=ActiveSheet
        ActiveSheet.Name = mystock

        ActRw = 1
        Application.Wait (Now + TimeValue("0:00:01")) 'wait for java script to load
        HTMLDoc.body.innerHTML = objIE.Document.body.innerHTML
        With HTMLDoc.body
            Set objTable = .getElementsByTagName("table")
            For lngTable = 0 To objTable.Length - 1
                For lngRow = 0 To objTable(lngTable).Rows.Length - 1
                    For lngCol = 0 To objTable(lngTable).Rows(lngRow).Cells.Length - 1
                        ThisWorkbook.ActiveSheet.Cells(ActRw + lngRow + 1, lngCol + 1) = objTable(lngTable).Rows(lngRow).Cells(lngCol).innerText
                    Next lngCol
                Next lngRow
                ActRw = ActRw + objTable(lngTable).Rows.Length + 1
            Next lngTable
        End With

    Next c

    objIE.Quit

End Sub

Before:

After:


Q: Cannot send email in perl For some reason I cannot send an email in perl. I checked my env path and sendmail path everything is correct. But I am not receiving the email.I am not entirely sure if I am missing something.
#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;

print header;
print start_html("Results");

$ENV{PATH} = "/usr/sbin" ;

open (MAIL, "|/usr/sbin/sendmail -oi -t") or
    &dienice("Can't fork for sendmail: $!\n");

my $recipient = "myusername\@gmail.com";

print MAIL "To: $recipient\n";

print MAIL "From: nobody\@cgi101.com\n" ;

print MAIL "Subject: Form Data\n\n";

foreach my $p (param()) {
    print MAIL "$p = ", param($p), "\n";
}

close(MAIL);

print <<EndHTML;

Thank You

Thank you for writing!

Return to our home page.

EndHTML

print end_html;

A: It's extremely hard to tell what the issue might be.  I'm assuming mail works normally from the command prompt?
That said, have you tried MIME::Lite?
use MIME::Lite;

my $body = <<EndHTML;

Thank You

Thank you for writing!

Return to our home page.

EndHTML

my $msg = MIME::Lite->new(
  Type    => 'text/html',
  From    => 'nobody@cgi101.com',
  To      => 'myusername@gmail.com',
  Subject => 'Form Data',
  Data    => $body
);

$msg->send;

A: Impossible to give much help without knowing what errors you are getting. But it's 2014 and we can probably do a little better than talking directly to sendmail to send an email.
For email handling, you should probably be looking in the Email::* namespace on CPAN. In particular, Email::Sender is the recommended approach for sending email.


Q: sql server status change time THENUMBER       NUMBER      SYSMODTIME              TYPE
ACTIM2816332    IM0540202   2014-11-18 09:17:53.000 Closed
ACTIM2806050    IM0540202   2014-11-13 15:11:29.000 Update
ACTIM2806051    IM0540202   2014-11-13 15:11:29.000 External Vendor Assignment
ACTIM2806049    IM0540202   2014-11-13 15:11:29.000 Status Change
ACTIM2806046    IM0540202   2014-11-13 15:10:34.000 Assignment
ACTIM2804167    IM0540202   2014-11-13 09:31:12.000 Status Change
ACTIM2804166    IM0540202   2014-11-13 09:31:12.000 Assignment
ACTIM2802130    IM0540202   2014-11-12 17:09:57.000 Open

Could You please help me to create a select to calculate time difference between type change from open to close ?
I need to be a universal for different NUMBER.

A: Minutes
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (mi, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER

Hours
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (hh, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER


Q: How can I set up a battery full notication on Ubuntu? Is there any software which can alert me when battery is 100 % ? I do not want to keep charging further causing battery damage. I use 20.04 LTS.


Q: How to make hover effect only on hamburger button, not on close button? I have a problem with the following code :
.btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

How to make this hover code only work in the state of the hamburger button, not on the close button?

$('.btn-menu').on('click', function() {
  $('body').toggleClass('menu-open');
});
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

/* How to make this only on burger, not on close */
.btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

<button class="btn-menu" type="button" style="background-color: red;">

</button>

A: Because you add .menu-open to the body, you need to apply the hover effect when the body doesn't have the class with :not.
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

$('.btn-menu').on('click', function() {
  $('body').toggleClass('menu-open');
});
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

<button class="btn-menu" type="button" style="background-color: red;">

</button>

Also your script without JQuery :
document.querySelector(".btn-menu").addEventListener("click", () => {
  document.querySelector("body").classList.toggle("menu-open")
})

document.querySelector(".btn-menu").addEventListener("click", () => {
  document.querySelector("body").classList.toggle("menu-open")
})
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}
<button class="btn-menu" type="button" style="background-color: red;">

</button>

Note that if you only have 1 element with a class, you can use an id (and then use getElementById() instead).


Q: Support for ',' in input type="number" in IE 11 using Angular + material I need to accept 10,12 as a valid number in IE 11 because the users only have a German number pad as an input device which only has a comma as a decimal separator.
The current behavior is (userinput -> value used)
10,12 -> 10

The desired behavior is
10,12 -> 10.12
10.12 -> 10.12

As it is currently in Chrome.
My current idea is to implement a ControlValueAccessor for an input type="text" which parses the value into a number, but my attempts for that failed.
The input has to work with reactiveForms and has to be a numeric value

A: I encountered the same problem and was not able to get a comma as the decimal separator with <input type="number"> even when setting the language to a different locale and using a step smaller than 1:
<input type="number" step="0.01" lang="en-US">

So I opted for a custom solution based on <input type="text"> with a custom filtering  mechanism to only allow numbers in.
See this stackblitz for a complete demo.

The most important part is filtering what the user inputs in the field. I suggest you write a directive that listens to input/keydown/paste events and that uses a regex to only allow float/integer numbers.
The following regex (/^-?\d*(,|\.)?\d*$/) allows a number to begin with an optional - followed by digits, then a comma or dot and more digits.
If the new value (current value + key pressed) does not match the regex, simply prevent the event from happening with event.preventDefault(). Otherwise, do nothing and let the value go to the input.
Note that you also have to take care of the copy/cut/paste/undo/redo special keys. And also take into account the cursor position and the selection if any.
Once the filtering is done, you can implement the ControlValueAccessor interface and bind it to your input via its change/input events. Do the string to number conversions in these handlers and do the number to string conversion in a getter or a pipe that you bind to the value attribute.
Here is an example of such a directive, you could generalize it by giving the regex as an input parameter.
import { Directive, Input, HostListener, forwardRef } from '@angular/core';

@Directive({
  selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
  @HostListener('keydown', ['$event'])
  public onKeydown(event: KeyboardEvent): void {
    const { key } = event;
    if (this.isSpecialOperation(event) || !this.isKeyPrintable(event)) {
      return;
    }
    const newValue = this.getNewValue(event.target as HTMLInputElement, key);
    if (!this.valueIsValid(newValue)) {
      event.preventDefault();
    }
  }

  @HostListener('paste', ['$event'])
  public onPaste(event: ClipboardEvent): void {
    const pastedText = event.clipboardData.getData('text');
    const newValue = this.getNewValue(event.target as HTMLInputElement, pastedText);
    if (!this.valueIsValid(newValue)) {
      event.preventDefault();
    }
  }

  private getNewValue(target: HTMLInputElement, str: string): string {
    const { value = '', selectionStart, selectionEnd } = target;
    return [
        ...value.split('').splice(0, selectionStart),
        str,
        ...value.split('').splice(selectionEnd)].join('');
  }

  private valueIsValid(value: string): boolean {
    return /^-?\d*(,|\.)?\d*$/.test(value);
  }

  private isSpecialOperation(event: KeyboardEvent): boolean {
    const { keyCode, ctrlKey, metaKey } = event;
    // allow ctr-A/C/V/X/Y/Z
    const keysACVXYZ = [65, 67, 86, 88, 89, 90];
    if ((ctrlKey || metaKey) && keysACVXYZ.indexOf(keyCode) >= 0) {
      return true;
    }
    return false;
  }

  private isKeyPrintable(event: KeyboardEvent): boolean {
    const { keyCode } = event;
    return (
      (keyCode > 47 && keyCode < 58)      || // number keys
      keyCode === 32 || keyCode === 13    || // spacebar & return key(s)
      (keyCode > 64 && keyCode < 91)      || // letter keys
      (keyCode > 95 && keyCode < 112)     || // numpad keys
      (keyCode > 185 && keyCode < 193)    || // ;=,-./` (in order)
      (keyCode > 218 && keyCode < 223));      // [\]' (in order)
  }
}

And a custom input-number component implementing ControlValueAccessor:
import { Component, ViewChild, forwardRef, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'app-input-number',
  template: `
    <input
      type="text"
      #input
      appNumberOnly
      [placeholder]="placeholder"
      [value]="_stringifiedValue"
      (input)="_onInput($event.target.value)"
      (change)="_onChange($event.target.value)"
      (blur)="input.value = _stringifiedValue">
  `,
  styles: [`
    :host { width: 100%; display: block; }
    input { width: 100%; }
  `],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputNumberComponent),
      multi: true
    }
  ]
})
export class InputNumberComponent implements ControlValueAccessor {
  private onChange = [(_: number) => {}];
  private onTouch = [() => {}];

  @Input() placeholder;

  @ViewChild('input') _input: ElementRef;

  @Input()
  get value(): number {
    return this._value;
  }
  set value(value: number) {
    const safeValue = this.safeValue(value);
    if (safeValue !== this._value) {
      this._value = safeValue;
      this.onChange.forEach(fn => fn(safeValue));
    }
  }
  private _value: number = undefined;

  @Output() valueChange = new EventEmitter<number>();

  get _stringifiedValue(): string {
    const val = (this._input.nativeElement.value || '').replace('.', ',');
    if (val === '-' || val === ',') return val;
    const safeValue = this.safeValue(this.value);
    return this.stringify(safeValue).replace('.', ',');
  }

  _onInput(value: string): void {
    this.value = this.safeValue(value);
  }

  _onChange(value: string): void {
    this.value = this.safeValue(value);
    this.valueChange.emit(this.value);
  }

  private safeValue(val: string | number): number {
    const safeValue = parseFloat(this.stringify(val).replace(',', '.'));
    return isNaN(safeValue) ? undefined : safeValue;
  }

  private stringify(val: string | number): string {
    return val === undefined || val === null ? '' : `${val}`;
  }

  public registerOnChange(fn: any): void {
    this.onChange.push(fn);
  }

  public registerOnTouched(fn: any): void {
    this.onTouch.push(fn);
  }

  public writeValue(inputValue: number): void {
    this.value = this.safeValue(inputValue);
  }
}

The component can then be used with two-way binding with [(ngModel)] or with [(value)]. It will work with reactive-forms too:
<app-input-number [(ngModel)]="value"></app-input-number>
<app-input-number [(value)]="value"></app-input-number>


Q: Remove portion of text using GetElementsByClassName I'm trying to use the following script to remove ".00" from all prices on a page I'm working on. The ".00" is built in automatically by the WP theme I'm working with.
Here's the script I'm using:

The prices are formatted as such:

$24.00

...but it's not working. What am I missing?

A: getElementsByClassName returns a HTMLCollection. You must iterate it:

var elements = document.getElementsByClassName("hungry-menu-item-price");
for(var i=0; i<elements.length; ++i)
  elements[i].textContent = elements[i].textContent.replace(".00", "");

$24.00

A: document.getElementsByClassName() function returns a nodeList, not an element
so it must be :
document.getElementsByClassName('hungry-menu-item-price')[0].innerHTML


Q: Do I need to send the data in $.ajax as json? I have an $.ajax request that's sending the data in a serialize() and gets a json array in return. It works perfectly without any issues on Chrome develop's tools and Firefox's firebug. My question is, do I HAVE to send the data(user inputs) as json? I need json for the response but not for the request.

A: No, you send the data however you like but keep in mind how you send it will affect how you can retrieve it.
Also you aren't sending JSON in your request as .serialize() does not return JSON it returns a text string in standard URL-encoded notation.

A: No, you don't need to send it as JSON.  You can send it in any other format, but your receiver will need to know how to interpret it.  Usually people use JSON or XML since your receiver can easily parse these types of data.
You'll need to set the content-type, then you can tell the receiver how to process this content-type.


Q: Activity crashes when paused I have an activity that keeps crashing onPause. Theres a looped thread that draws on a canvas. And When I paused the application or try to move to another activity it crashes.
I have it so it closes out onPause, because I don't want it to post a force close. But I want to be able to go back to the activity
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
    boolean retry = true;
    _canDraw = false;
    while(retry) {
        try {
            DrawThread.join();
            retry = false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    android.os.Process.killProcess(android.os.Process.myPid());
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    android.os.Process.killProcess(android.os.Process.myPid());
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.face_button:
        _canDraw = false;
        try {
            DrawThread.join();
            whack.this.startActivity(selectFace);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

A: @Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    android.os.Process.killProcess(android.os.Process.myPid());
}

You're wondering why it crashes onPause? You're crashing it.


Q: Histogram computational efficiency I am trying to plot a 2 GB matrix using MATLAB hist on a computer with 4 GB RAM. The operation is taking hours. Are there ways to increase the performance of the computation, by pre-sorting the data, pre-determining bin sizes, breaking the data into smaller groups, deleting the raw data as the data is added to bins, etc?
Also, after the data is plotted, I need to adjust the binning to ensure the curve is smooth. This requires starting over and re-binning the raw data. I assume the strategy involving the least computation would be to first bin the data using very small bins and then manipulate the bin size of the output, rather than re-binning the raw data. What is the best way to adjust bin sizes post-binning (assuming the bin sizes can only grow and not shrink)?

A: I don't like answers to StackOverflow Questions of the form "well even though you asked how to do X, you don't really want to do X, you really want to do Y, so here's a solution to Y"
But that's what i am going to do here. I think such an answer is justified in this rare instance becuase the answer below is in accord with sound practices in statistical analysis and because it avoids the current problem in front of you which is crunching 4 GB of datda.
If you want to represent the distribution of a population using a non-parametric density estimator, and you wwish to avoid  poor computational performance, a kernel density estimator (KDE) will do the job far better than a histogram.
To begin with, there's a clear preference for KDEs versus histograms among the majority of academic and practicing statisticians. Among the numerous texts on this topic, ne that i think is particularly good is An introduction to kernel density estimation )
Reasons why KDE is preferred to histogram

*

*the shape of a histogram is strongly influenced by the choice of
total number of bins; yet there is no authoritative technique for
calculating or even estimating a suitable value. (Any doubts about this, just plot a histogram from some data, then watch the entire shape of the histogram change as you adjust the number of bins.)

*the shape of the histogram is strongly influenced by the choice of
location of the bin edges.

*a histogram gives a density estimate that is not smooth.
KDE eliminates completely histogram properties 2 and 3. Although KDE doesn't produce a density estimate with discrete bins, an analogous parameter, "bandwidth" must still be supplied.
To calculate and plot a KDE, you need to pass in two parameter values along with your data:
kernel function: the most common options (all available in the MATLAB kde function) are: uniform, triangular, biweight, triweight, Epanechnikov, and normal. Among these, gaussian (normal) is probably most often used.
bandwith: the choice of value for bandwith will almost certainly have a huge effect on the quality of your KDE. Therefore, sophisticated computation platforms like MATLAB, R, etc. include utility functions (e.g., rusk function or MISE) to estimate bandwith given oother parameters.

KDE in MATLAB
kde.m is the function in MATLAB that implementes KDE:
[h, fhat, xgrid] = kde(x, 401);

Notice that bandwith and kernel are not supplied when calling kde.m. For bandwitdh: kde.m wraps a function for bandwidth selection; and for the kernel function, gaussian is used.

But will using KDE in place of a histogram solve or substantially eliminate the very slow performance given your 2 GB dataset?
It certainly should.
In your Question, you stated that the lagging performance occurred during plotting. A KDE does not require mapping of thousands (missions?) of data points a symbol, color, and specific location on a canvas--instead it plots a single smooth line. And because the entire data set doesn't need to be rendered one point at a time on the canvas, they don't need to be stored (in memory!) while the plot is created and rendered.


Q: Using the Riemann hypothesis to predict $p_n$, the $n^{th}$ prime number In this video, Terence Tao states that if you assume the Riemann hypothesis to be true, you can predict the $n^{th}$ prime number $p_n$ using
$$\int_2^{p_n} \frac{dt}{\text{log}(t)} = n+O\left(\sqrt{n\cdot\text{log}^3 n}\right)$$
which will have an error of about $\sqrt{n}$. He goes on to say that the error $O\left(\sqrt{n\cdot\text{log}^3 n}\right)$ predicted by the Riemann hypothesis is essentially the same type of error one would have expected if the primes were distributed randomly.
$\bullet$ Does this mean for a given value $n$, $O\left(\sqrt{n\cdot\text{log}^3 n}\right)$ cannot be calculated and acts as a random variable?
$\bullet$ How then could you use the formula
$$\int_2^{p_n} \frac{dt}{\text{log}(t)} = n+O\left(\sqrt{n\text{log}^3 n}\right)$$
to get a prediction for $p_n$? Would you ignore $O(\cdot)$ and numerically find $p_n$ such that
$$\int_2^{p_n} \frac{dt}{\text{log}(t)} = n$$
is satisfied?
$\bullet$ He shows here that the $10^{12}-th$ prime number is $29,996,224,275,833$ and that the Riemann hypothesis predicts it to be $29,996,219,470,277$ which gives an error of about $4,805,556$. However, he says the error will be about $\sqrt{n}=\sqrt{10^{12}}=10^6$ which is nearly $5$ times less than our error. Am I interpreting this statement incorrectly?

A: For your last point, he seems to be showing $\rm{Li}^{-1}(n)$.  At this size we can get even closer using $\rm{R}^{-1}(n)$, though I believe asymptotically it doesn't matter.
We can certainly do this approximation and get good results with or without the RH.  With the RH we can make hard statements about how bounded the error will be.  Also note the error bounds (Shoenfeld 1976) are on li(x), we're doing the inverse function here to approximate the nth prime.
Add: "[...] the error will be about [...]".  Not really.  The bounds for the error are asymptotically that amount (as BananaCats mentions in a comment).  Especially with R(x) they will fluctuate around the actual value, so at any given point it could be quite close.  We have bounds (e.g. Dusart, Axler, etc.) that tell us it won't get terribly far away from Li(x).  If the Riemann Hypothesis is true then we know the bounds are much tighter even for values we haven't checked.  Some researchers such as Büthe and Axler have gone over empirical Riemann zero data and shown we can correctly use the much tighter Schoenfeld bound up to $5.5 \cdot 10^{25}$.


Q: Collapse pandas DataFrame based on daily column value I have a pandas DataFrame with multiple measurements per day (for example hourly measurements, but that is not necessarily the case), but I want to keep only the hour for which a certain column is the daily minimum.
My one day in my data frame looks somewhat like this
    DATE                Value               Distance
17  1979-1-2T00:00:00.0 15.5669870447436    34.87
18  1979-1-2T01:00:00.0 81.6306803714536    31.342
19  1979-1-2T02:00:00.0 83.1854759740486    33.264
20  1979-1-2T03:00:00.0 23.8659679630303    32.34
21  1979-1-2T04:00:00.0 63.2755504429306    31.973
22  1979-1-2T05:00:00.0 91.2129044773733    34.091
23  1979-1-2T06:00:00.0 76.493130052689     36.837
24  1979-1-2T07:00:00.0 63.5443183375785    34.383
25  1979-1-2T08:00:00.0 40.9255407683688    35.275
26  1979-1-2T09:00:00.0 54.5583051827551    32.152
27  1979-1-2T10:00:00.0 26.2690011881422    35.104
28  1979-1-2T11:00:00.0 71.3059740399097    37.28
29  1979-1-2T12:00:00.0 54.0111262724049    38.963
30  1979-1-2T13:00:00.0 91.3518048568241    36.696
31  1979-1-2T14:00:00.0 81.7651763485069    34.832
32  1979-1-2T15:00:00.0 90.5695814525067    35.473
33  1979-1-2T16:00:00.0 88.4550315358515    30.998
34  1979-1-2T17:00:00.0 41.6276969038137    32.353
35  1979-1-2T18:00:00.0 79.3818377264749    30.15
36  1979-1-2T19:00:00.0 79.1672568582629    37.07
37  1979-1-2T20:00:00.0 1.48337999844262    28.525
38  1979-1-2T21:00:00.0 87.9110385474789    38.323
39  1979-1-2T22:00:00.0 38.6646421460678    23.251
40  1979-1-2T23:00:00.0 88.4920153764757    31.236

I would like to keep all rows that have the minimum "distance" per day, so for the one day shown above, one would have only one row left (the one with index value 39). I know how to collapse the data frame so that I only have the Distance column left. I can do that - if I first set the DATE as index - with
df_short = df.groupby(df.index.floor('D'))["Distance"].min()

But I also want the Value column in my final result. How do I keep all columns?
It doesn't seem to work if I do
df_short = df.groupby(df.index.floor('D')).min(["Distance"])

This does keep all the columns in the final result, but it seems like the outcome is wrong, so I'm not sure what this does.
Maybe this is already posted somewhere, but I have trouble finding it.

A: You can use aggregate
df_short = df.groupby(df.index.floor('D')).agg({'Distance': min, 'Value': max})

If you want the kept Value column is the same with minimum of Distance column:
df_short = df.loc[df.groupby(df.index.floor('D'))['Distance'].idxmin(), :]

A: Make a datetime Index:
df.DATE = pd.to_datetime(df.DATE) # If not already datetime.
df.set_index('DATE', inplace=True)

Resample and find the min Distance's location:
df.loc[df.resample('D')['Distance'].idxmin()]

Output:
                         Value  Distance
DATE
1979-01-02 22:00:00  38.664642    23.251


Q: flutter web alternates/reduce size of canvaskit.wasm My flutter web initial page load is slow(10-15 secs),
Found that large amount of time is spent in downloading "https://unpkg.com/canvaskit-wasm@0.24.0/bin/canvaskit.wasm" which is around 2.5 MB as per browser logs.
Is there a way to reduce this time/alternate file path/ minification which can be done?
(package is built using flutter build web)

A: Changed web renderer to html renderer
flutter build web --web-renderer html

which resulted in significant reduction in initial load time

A: For the moment there is no solution for this, anyways the Flutter team is working on that and there should be a solution as soon as possible.
You can check the status of this in this link:
Flutter github issue

A: There is a possibility to integrate the canvaskit at build process and host it with your web app for offline support.
Therefore you need to define the url like:
flutter build web --dart-define=FLUTTER_WEB_CANVASKIT_URL=/canvaskit/
This may could also reduce loading time. (direct network connection, no dns lookup...)


Q: Python Script Erroring with argparse.ArgumentError I am running a python selenium script but it's getting an error of
https://i.stack.imgur.com/oQdvx.png
argparse.ArgumentError: argument --screenshot/--save_screenshot/--save-screenshot/--ss: conflicting option string: --screenshot
From reading, there seems to be a pytest-argument being defined in multiple locations.  My install dependency step looks like this:
https://i.stack.imgur.com/XmXoe.png
Any recommendations on how to get rid of this to then execute the test?


Q: Chrome screen keyboard blocking content at bottom of page on mobile Here, I recorded video about problem.
https://www.youtube.com/watch?v=WZbKix3XGTE
Problem is when keyboard on screen. The content is behind of keyboard not reachable. If there is input end of page user can't see what is typing in it.
I have this issue only with chrome, other browsers work normal.
All solutions in my mind about this contains javascript. But I am not sure javascript handle this perfectly. I wanted to ask you knowledge before start. Is there any other option for this only with CSS or something else?
Code in example
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=1" />
    <title></title>

Top

        <input type="text" />

Codepen Link
https://codepen.io/hllktlhndd/pen/yZKzyZ

A: Did you get answer for this ?
This worked before okay, but now the android-chrome comes on top of the page and does not push it up anymore.
I'm using webview, maybe they have some option for it?
Quick fix is to add padding at the bottom of the screen, maybe 200 - 300px


Q: MongoDB StitchClient cannot be accessed inside a js function I have already called stClient.login function inside  "addUser()" and "loginUser()" and they worked pretty well. I am able to add the user to my MongoDB database and find the user when login clicked. (dont bother with delete one) After finding a logged user in DB, i am loading a new HTML page where i pass the name of the logged user and profil photo retrieved from MongoDB. Besides, i also want to display the comments of the logged user along with the name and profil photo. Here the issue comes: in showComments method, i am not able to access the stitch Client. Any help is so much appreciated.
Below is the code:
Html 1:
<!DOCTYPE html>

    <title>myFb</title>
     <link rel="stylesheet" type="text/css" href="style1.css">

Hello My App

    <button name="adding" onclick="addUser()">Add User</button>

    <button name="deleting" onclick="deleteUser()">Delete User</button>

    <button name="logging" onclick="loginUser()">Login</button>

Common JS for 2 HTMLs:
let db;
    let itemsCollection;
    let stClient;
    let globalName;
    let temp;

     let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');

    function onLoadConnectDB(){
        clientPromise.then(stitchClient=>{
            stClient=stitchClient;
            db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
            itemsCollection=db.collection("ClonedFbUsers");
        });

    }

function addUser(){
    var n= prompt("Your username: ")
    const userId = stClient.authedId();
    stClient.login().then(()=>
        itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );
 // });
    alert("added");
}

function deleteUser(){

    var d= prompt("Username to delete: ");
    const userId = stClient.authedId();
    stClient.login().then(()=>
        itemsCollection.deleteOne({ userName: "Messi" })
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );
    alert("User "+d+ " deleted.");

}

function loginUser(){
var n= prompt("Your username: ");
globalName=n;
    const userId = stClient.authedId();
    try{
    stClient.login().then(()=>

         itemsCollection.find({ userName : n }).execute()
        ).then(docs=>

        loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
        );

}catch(err){
    alert("not found a user");
}

 // });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
    document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
    //document.getElementById("name").value=name;
}else{
    //no user in db
    alert(name+ " is not found");
}

}
 function onLoad () {
    //onLoadConnectDB();

    var pic;
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('name').value = data.name;
    document.getElementById('pp').src=decodeURIComponent(data.prof);
    showComments(data.name);

   // document.getElementById('pp').value=data.pp;
}

 function showComments(globalName){

//ISSUE IS HERE!!

        stClient.login().then(()=>

         itemsCollection.find({ userName : globalName }).execute()
        ).then(docs=>

        document.getElementById("comments").innerHTML = docs.map(c => "
" + c.comments + "
").join("")
        );
        };

HTML2
<!DOCTYPE html>

    <title>MyProfile</title>
     <link rel="stylesheet" type="text/css" href="style2.css">

         &nbsp &nbsp Home  &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp &nbsp   &nbsp &nbsp &nbsp &nbsp

 <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly>

<button type="submit" onclick="addPhoto()">Add Photo</button>

<button type="submit">Choose Profile Photo</button>

Show comments

A: The issue is relating to async/sync communication. After separating js for html2, i was calling onLoad2() function inside onLoad() function after assuming the connection is established, but no. Should 'wait' till the connection is established and then call another function. js2:
    let db;
    let itemsCollection;
    let stClient;
    let globalName;
    let temp;

    let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');

function onLoad(){

        clientPromise.then(stitchClient=>{
            stClient=stitchClient;
            db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
            itemsCollection=db.collection("ClonedFbUsers");
            onLoad2(); //if you call outside then, wont work. onLoad2() will be interpreted before establishing connection to db

        });
    }

     function onLoad2 () {
    var pic;
    var url = window.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('name').value = data.name;
    document.getElementById('pp').src=decodeURIComponent(data.prof);
    showComments(data.name);

}

 function showComments(globalName){
    console.log("i am here");
    const userId = stClient.authedId();

        stClient.login().then(()=>

         itemsCollection.find({ userName : globalName }).execute()
        ).then(docs=>

        document.getElementById("comments").innerHTML = docs.map(c => "
" + c.comments.msg + "
").join(" ")
        );
        }

   function addComment(){

    var n=document.getElementById("name").value;

    var com= document.getElementById("comment").value
   stClient.login().then(()=>
        itemsCollection.updateOne({userName : n}, {$push:{comments:{msg:com,time:"22:30",like:4}}})
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );

   }

HTML for the js2:
    <!DOCTYPE html>

    <title>MyProfile</title>
     <link rel="stylesheet" type="text/css" href="style2.css">

         &nbsp &nbsp Home  &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp &nbsp   &nbsp &nbsp &nbsp &nbsp

 <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly>

<button type="submit" onclick="addPhoto()">Add Photo</button>

<button type="submit">Choose Profile Photo</button>

    <input type="text" name="comment" id="comment" placeholder="Type comment">
    <button onclick="addComment()">Send</button>


Q: I cant import the ucf 101 dataset (torchvision), 'list index out of range' error dataset = torchvision.datasets.UCF101(r'my_directory', annotation_path=r'my_directory2', frames_per_clip=16, step_between_clips=1, frame_rate=None, fold=1, train=True, transform=transforms.Compose([transforms.ToTensor()]), _precomputed_metadata=None, num_workers=1, _video_width=64, _video_height=64, _video_min_dimension=0, _audio_samples=0)

This line works, the problem is when I try to do any kind of operation using 'dataset', in particular this one:
data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)

I get the error, so i can't work on the video data because I can't use the dataLoader, the error is:
IndexError: list index out of range

Complete error message:

    ---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-dc3631481cb3> in <module>
----> 1 data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)

~\anaconda3\lib\site-packages\torch\utils\data\dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context)
    211             else:  # map-style
    212                 if shuffle:
--> 213                     sampler = RandomSampler(dataset)
    214                 else:
    215                     sampler = SequentialSampler(dataset)

~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in __init__(self, data_source, replacement, num_samples)
     90                              "since a random permute will be performed.")
     91
---> 92         if not isinstance(self.num_samples, int) or self.num_samples <= 0:
     93             raise ValueError("num_samples should be a positive integer "
     94                              "value, but got num_samples={}".format(self.num_samples))

~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in num_samples(self)
     98         # dataset size might change at runtime
     99         if self._num_samples is None:
--> 100             return len(self.data_source)
    101         return self._num_samples
    102

~\anaconda3\lib\site-packages\torchvision\datasets\ucf101.py in __len__(self)
     96
     97     def __len__(self):
---> 98         return self.video_clips.num_clips()
     99
    100     def __getitem__(self, idx):

~\anaconda3\lib\site-packages\torchvision\datasets\video_utils.py in num_clips(self)
    241         Number of subclips that are available in the video list.
    242         """
--> 243         return self.cumulative_sizes[-1]
    244
    245     def get_clip_location(self, idx):

IndexError: list index out of range

A: Problem:
This problem occurs when you run your code on windows because windows paths use backslash ("\") instead of forward slash ("/").
As you see in the code:
https://github.com/pytorch/vision/blob/7b9d30eb7c4d92490d9ac038a140398e0a690db6/torchvision/datasets/ucf101.py#L94
So, this line of code reads the file path from label file as “action\video_name” and merge it with “root” path using backslash therefore full path becomes like “root\action/video_name”. Such paths doesn’t match with the video lists at line#97 and returns empty list for indices variable.
Solution:
Two of possible solutions can be:

*

*Replace the forwardslashes “/” in the label files with backslashes “\”.

*Override the _select_fold(…) function of class UCF101 and fix the backslashes inside the function


Q: How to get devise custom User columns to save? I am reading that the application controller needs to have a before filter: before_filter :configure_permitted_parameters, if: :devise_controller?
however, I am receiving this error:

undefined method `before_filter' for ApplicationController:Class Did
  you mean? before_action

How can I get the new User fields added with a migration to save with devise?

A: Add new column in to your database
after In your ApplicationController.rb Add
before_action :configure_permitted_parameters, if: :devise_controller?
private
def configure_permitted_parameters
 devise_parameter_sanitizer.permit(:sign_up, keys:[:profile_pic,:fname,:mobile,:gender])
end

Here use keys  => your added fields


Q: Why need to decrease clientHeight from windowHeight while calculating scrollPercent? I am trying to show how much a user has scrolled through the page a with progress bar and I have done it.  But I have a little confusion here.
Here is the code that I found to calculate  scrollPercent which works well

windowHeight = Math.max(
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
body.scrollHeight,
body.offsetHeight
);

const  scrolledPercent =
((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
100;

Initially, I thought, to get the scrollPercent , I need to get the current scrollPosition and divide that number with the total height of the page and multiply by 100% . which is like normally how we get % of something.
const  scrolledPercent =
((html.scrollTop || body.scrollTop) / windowHeight) * 100;

but this line doesnot worked as I expected . If I do this the progress bar wont reach 100% even if I scroll to end of the page. I don't understand why am I wrong here !
So, my question is why do we need to decrease the html.clientHeight  from  windowHeight ?
Thank you.
Demo here:

// --------------------------------------------
// variables
// --------------------------------------------

const html = document.documentElement,
  body = document.body,
  countryList = document.querySelector(".country__list");
scrollNavigated = document.querySelector(".scroll__navigated");
let windowHeight;

// --------------------------------------------
// function
// --------------------------------------------

async function prepareListOfCountries() {
  let list = await fetch("https://restcountries.eu/rest/v2/all");
  list = Array.from(await list.json());
  let markup = list
    .map((country, index) => {
      return `

              ${country.name}${country.capital}

`;
    })
    .slice(0, 30)
    .join(" ");
  countryList.innerHTML = markup;
}

function updateScrolledStatus(e) {
  windowHeight = Math.max(
    html.clientHeight,
    html.scrollHeight,
    html.offsetHeight,
    body.scrollHeight,
    body.offsetHeight
  );

  const scrolledPercent =
    ((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
    100;
  // const scrolledPercent =
  //   ((html.scrollTop || body.scrollTop) / windowHeight) * 100; // this line doesnot work
  scrollNavigated.style.width = scrolledPercent + "%";
}

prepareListOfCountries();

// --------------------------------------------
// event-handler
// --------------------------------------------

window.addEventListener("scroll", updateScrolledStatus);
*::after,
*::before,
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #fff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
 Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.container {
  max-width: 980px;
  margin: 0 auto;
}

.justify-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.items-center {
  display: flex;
  align-items: center;
}

.card {
  background-color: #fff;
  box-shadow: 0 0 12px 12px rgba(0, 0, 0, 0.054);
  border-radius: 4px;
  padding: 16px;
}

.country__flag img {
  height: 100%;
  width: 100%;
}

.header {
  padding: 24px 0;
  background-color: #333;
  color: #f1f1f1;
  position: -webkit-sticky;
  position: sticky;
}

.content {
  padding: 50px 0;
}

.content__form {
  margin: 0 auto;
  margin-bottom: 32px;
}

.content__search {
  width: 50%;
  padding: 12px 16px;
  border-radius: 20px;
  border: 1px solid #ddd;
  transition: 0.2s;
}

.content__search:hover {
  box-shadow: 0 1px 6px 0 rgba(32, 33, 36, 0.28);
}

.content__search:focus {
  outline: none;
}

.country__list {
  margin-top: 50px;
  margin: 10px auto;
}

.country__item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.country__name, .country__capital, .country__flag {
  width: 33.33%;
}

.country__flag {
  width: 32px;
  height: 24px;
}

.scroll__navigator {
  height: 2px;
  margin: 0 auto 32px;
  background-color: #333;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.scroll__navigated {
  display: block;
  height: 100%;
  width: 0;
  background: orangered;
  transition: 0.3s linear;
}

        All countries list

        <form class="content__form">
          <input class="content__search" />
        </form>

              NepalKathmandu

A: As an example, say that the height of your client is 100px and the height of your whole page is 500px.
When the scroll position is 0px, you're able to see the first 100px of your site, so from 0px to 100px.
At scroll position 100px, you can see the range 100px to 200px, because you've moved the page, and therefore the visible range, on by 100px.
At scroll position 400px, you can therefore see the range 400px to 500px – in other words, you've scrolled to the bottom.
This demonstrates that the scrollable height of the page (400px) is less than the actual height of the page (500px), namely by the height of the client.
To get the percentage scrolled, you need to use the scrollable height, so it is necessary to subtract the height of the client from the height of the page to get a correct value, or you'll never be able to scroll to the bottom. It's not possible to scroll by 500px on a site that is only 500px long!


Q: makefile fails - implicit rule compiles one object file but doesn't compile the rest Makefile isn't using implicit rules correctly. I am following this guide here.
Here's my makefile:
objects = main.o hello.o
hello : $(objects)
    cc -o hello $(objects)

hello.o : defs.h
main.o : defs.h hello.h

.PHONY : clean
clean :
    -rm hello $(objects)

I get the following error:
cc: error: main.o: No such file or directory

It creates the object code hello.o, but does not do it for main.c. If I swap lines and main is above, it'll create main.o but not hello.o.
Here's my main.c file:
#include "defs.h"
#include "hello.h"

int main(int argc, char** argv) {
   display_hello();
   return (EXIT_SUCCESS);
}

Here's my hello.c file:
#include "defs.h"

void display_hello()
{
    printf("Hello!\n");
}

My hello.h file:
#ifndef HELLO_H
#define HELLO_H

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

#endif /* HELLO_H */

void display_hello();

Here's my defs.h file:
#ifndef DEFS_H
#define DEFS_H

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

#endif /* DEFS_H */

#include <stdio.h>
#include <stdlib.h>

A: Works fine for me, I created the files as https://gist.github.com/boyvinall/f23420215707fa3e73e21c3f9a5ff22b
$ make
cc    -c -o main.o main.c
cc    -c -o hello.o hello.c
cc -o hello main.o hello.o

Might be the version of make like @Beta said, but even an old version of GNU make should work just fine for this.
Otherwise, ensure you're using tabs to indent in the makefile, not spaces.


Q: GridControl Navigation In VFP9 I have a grid control ,witch  show the records from a database table. And also I have a command button wherewith I want to navigate from a row to another. I tried with thisform.grid1.ActiveRow = thisform.grid1.ActiveRow +1 ,but this doesn't work. Thanks in advance.

A: Per the VFP documentation, the ActiveRow Property "Specifies the row that contains the active cell in a Grid control. Not available at design time; read-only at run time".
I would do something like this.
IF EOF("TableAlias) = .F.
    SKIP 1 IN "TableAlias"
ENDIF


Q: Will JS be aligned with the ECMAScript specs regarding the "typeof null"? In the ECMAScript specs, it is clearly stated that Null is a type whose one and only value is null:
4.3.12 null value
primitive value that represents the intentional absence of any object value

4.3.13 Null type
type whose sole value is the null value

My question is very simple: why on earth we've got the below:
typeof null
>"object"

Is there any intent to correct/amend this? (either the specs or the JS language)

A: JS does align with the ECMAScript spec. null values may have a Null type, but that does not mean that typeof is supposed to return "null". You can see the spec behavior in section 12.5.5.1, which defines the runtime behavior of typeof, that Null-type objects return "object" from typeof.


Q: The existence of a vector arbitrarily separated from a close subspace Lax Contains a proof of the following claim:

Claim: Let $Y$ be a closed, proper subspace of the normed linear space $X$. Then there is a vector $z$ in $X$ of length 1, $$\|z\| = 1$$ satisfying $$\|z-y\|  >1/2$$ for all $y$ in $Y$.
Proof: Since $Y$ is a proper subspace of $X$, some point $x$ of $X$ does not
belong to $Y$. Since $Y$ is closed, $x$ has a positive distance to
$Y$: $$\inf_{y \in Y} \|x-y\| = d > 0$$ There is then a $y_0 \in Y$ such that $$\|x - y_0\| < 2d \quad (*)$$
Denote $z' = x - y_0$; we can then write $(*)$ as $\|z'\| < 2d$. It follows from definition of $d$ above that $$\|z' - y \| \geq d \quad (**)$$ for all $y$ in $Y$. Setting $z = \frac{z'}{\|z'\|}$ gives the vector and combining $(*)$ and $(**)$ gives the condition.

I'm failing to see how to put together $(*)$ and $(**)$ to finish the proof. Thoughts?

A: $\|z'-\|z'\|y\|\geq d$ since $\|z'\|y\in Y$, this implies that $\|{{z'-\|z'\|y}\over {\|z'\|}}\|\|\geq {d\over{\|z'\|}}$ Which implies that $\|{z'\over{\|z'\|}}-y\|\geq 1/2$


Q: What's the result of an integer list plus an integer in C? I should post the complete code.
int f(int x, int *y) {
   static int a =0;
   int b =0;
   while(b<x) {
       a =a +y[b];
       b =b +1;
   }
   return a;
 }
 int main(int argc, char **argv){
     int z[5] ={1,2,3,4,5};
     int r1, r2;
     r1 =f(3, z);
     r2 =f(1, z+1);
 }

The value of r2 is 8. What is z+1 here?

A: The expression z+1 is an example of pointer arithmetic.
The array z decays to a pointer to the first element of the array, i.e. &z[0].  z+1 means "take the address contained at z and add 1 array element to that address".  This is the same as &z[1].
So this function call:
r1 =f(3, z);

Passes in the address of the first element of z, resulting in the array z being visible in the function.
In this function call:
r2 =f(1, z+1);

It passes in the address of the second element of z.  So the function is able to see the array starting from the second element.


Q: How to apply alternating background color to divs which are not siblings I'd like aaaa and bbbb to have red background. How can I do this , the usual answers dont seem to work since the target divs are not siblings
Here is my CSS/HTML:

div.rules-container>div.ng-star-inserted>div.rules-form:nth-of-type(odd) {
  background: red;
}

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

A: Use :nth-child(odd).
Answer 1:
If you want all the odd numbers, then do this:

.rules-container .ng-star-inserted:nth-child(odd) {
  background-color: red;
  }

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

      dddddddddddddd

      eeeeeeeeeeeeee

Answer 2:
If you only want 1 & 3, not 5 , then change the css to:

.rules-container .ng-star-inserted:nth-child(1), .rules-container .ng-star-inserted:nth-child(3) {
  background-color: red;
}

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

      dddddddddddddd

      eeeeeeeeeeeeee


Q: Why does rpart not produce a perfect prediction when forced to? I am trying to understand rpart all the details in rpart package. I am aware of the complexity parameter cp, which prevents a split if the improvement is less than cp
If I set minbucket = 1, minsplit = 1 and cp = -Inf (or cp = 0) the tree should be allowed to grow to perfectly fit the data; provided that all the values of the predictor, or combination of predictors, are different. But it does not.
There must be another parameter which is preventing some splits to be made since, as you can see in this image, data is not fitted perfectly. One can clearly see there are some leaves which have more than one element, as we see them layered in the lower part.

This is a MVE illustrating this issue, and generating the image above:
set.seed(1)
sample_size <- 1000
y <- rgamma(sample_size, shape = 2, rate = 0.75)
x <- rgamma(sample_size, shape = 0.5, rate = 2)

library(rpart)
md <- rpart(formula = y ~ x, data = data.frame(y,x), method = "anova", cp = -Inf, minbucket = 1, minsplit = 1)

# All elements in x are unique:
length(unique(x)) == sample_size

#Number of leaves with more than one element:
sum(md$frame[md$frame$var == "<leaf>", "n"] > 1)

#Scatterplot
plot(y, predict(md, newdata = data.frame(x)), xlab = "Observed", ylab = "Predicted",
     col = scales::alpha("black", 0.2), pch = 16)

Note: For debugging purposes note that using sample_size = 185 already produces a leaf with 2 values.

A: I apologize for posting an erroneous answer in a former attempt to help (now deleted). This post explains how to calculate the depth of a tree:
https://stackoverflow.com/a/40900725/6503141
So if you run the code in the question and after that the following
nodes <- as.numeric(rownames(md$frame))
max(rpart:::tree.depth(nodes))

You will find that you have reached the maxdepth = 30 limit described in help(rpart.control) as

Set the maximum depth of any node of the final tree, with the root node counted as depth 0. Values greater than 30 rpart will give nonsense results on 32-bit machines.

On my 64-bit Windows machine (R version 4.0.2, rpart version 4.1-15) setting maxdepth to anything larger then 30 leads to an error message.
With set.seed(1); sample_size <- 185 you also reach maxdepth == 30 but not with set.seed(1); sample_size <- 184. This makes maxdepth the a likely candidate for the parameter you search. Unfortunately there seems to be no obvious way to increase it.


Q: Give every question in a Google-Form an unique id I want to make a Google Form using Google Apps Scripts. The questions in the form comes from a Google Sheet which includes the id and text of a question. When the form is submitted and I export the questions to a sheet the column names are the questions as text. I would rather replace them using an unique ID based on a column from my own Google Sheet where the questions are also stored as text.
How can I solve this?

A: Build a Question Text to ID hash table
function hashtable() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  let texttoid = {};
  sh.getDataRange().getDisplayValues().forEach(r => texttoid[r[1]]=r[0]);
  Logger.log(JSON.stringify(texttoid));
}

Execution log
11:58:17 AM Notice  Execution started
11:58:18 AM Info    {"text1":"id0","text2":"id1","text3":"id2","text4":"id3","text5":"id4","text6":"id5","text7":"id6","text8":"id7","text9":"id8","text10":"id9","text11":"id10"}
11:58:18 AM Notice  Execution completed

Sheet0:

id0
text1

id1
text2

id2
text3

id3
text4

id4
text5

id5
text6

id6
text7

id7
text8

id8
text9

id9
text10

id10
text11

You can goto to Google Apps Script Reference and using the search box find any function that you don't understand. If it's a pure JavaScript function the go here
You could store the hash table in cache if wish to use it repeatedly to save the time of building it each time from a spreadsheet.


Q: Oracle PL/SQL set column names using other table I'm struggling with naming columns in one table, using a reference table containing these names. I'm sure it should be possible, but I can't seem to find the right solution or think of the correct logic to achieve it...
Situation: I got 2 tables, one with data, columns having descriptive names, and one with a translation of these column names to meaningful names (reference table, or 'codebook').
I'm looking for a way to return the data of the first table, with the names of the columns given in the second column of the second table.
Tables look like:
dataTable:
q1,q2,q3
1,2,3
4,5,6

and
translationTable:
descName, meanName
q1, meaning1
q2, meaning2
q3, meaning3

Result should be:
meaning1,meaning2,meaning3
1,2,3
4,5,6

Help would be highly appreciated!

A: You can not directly do it, because you need a query whose columns are variable, based on some value.
Slightly different, what you can do is build a dynamic SQL to have your query created by Oracle:
SETUP:
SQL> create table dataTable(q1,q2,q3) as
  2  select 1,2,3 from dual union all
  3  select 4,5,6 from dual
  4  ;

Table created.

SQL> create table translationTable(descName, meanName) as
  2  select 'q1', 'meaning1' from dual union all
  3  select 'q2', 'meaning2' from dual union all
  4  select 'q3', 'meaning3' from dual ;

Table created.

This will create and print your query:
SQL> declare
  2      vSQL varchar2(1000);
  3  begin
  4      select listagg (column_name || ' AS "' || meanName || '"', ', ') within group (order by column_name)
  5      into vSQL
  6      from user_tab_columns col
  7        inner join translationTable    tr
  8          on (upper(tr.descName) = col.column_name)
  9      where table_name = upper('dataTable');
 10      --
 11      vSQL := 'select ' || vSQL || ' from dataTable';
 12      dbms_output.put_line(vSQL);
 13  end;
 14  /
select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable

PL/SQL procedure successfully completed.

If you copy the statement and run it:
SQL> select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable;

  meaning1   meaning2   meaning3
---------- ---------- ----------
         1          2          3
         4          5          6

SQL>

This way you have your query, but you can not fetch it, because it still has variable columns.
You can easily edit this code to make it build a query that returns strings, composed by concatenating the felds; this way you will always have a single field, but it's different from what you asked:
SQL> select 'meaning1, meaning2, meaning3' from dual
  2  union all
  3  select Q1 || ',' || Q2 || ',' ||  Q3 from dataTable;

'MEANING1,MEANING2,MEANING3'
--------------------------------------------------------------------------------
meaning1, meaning2, meaning3
1,2,3
4,5,6


Q: How does a CRC check work between a microcontroller and EEPROM? I have communication between an EEPROM and a microprocessor over SPI and I want to take care of data integrity.
Could you please confirm my below understanding?
I have a data which I want to write  in the  EEPROM along with a CRC code.
Before writing in EEPROM I will use a CRC16 polynomial to generate a CRC code and append it to the data and send if over SPI to the EEPROM.
When I read the EEPROM after system reset or tun time again over SPI from the microcontroller the data along with the CRC code are read (data+crc) and it is divided by same CRC16 polynomial to check with remainder zero? If zero data is good else not.
Could you please confirm if my above understanding is correct?
I just have to implement data integrity for one memory block and for that I'm doing dual CRC check for single memory block by implementing redundant block.

A: The remainder will alwas be the same, but if it is always zero or something elsr depends on the exact CRC algorithm, namely the "final xor".
If you have to write for example written 10 bytes of data and have calculated 2 bytes of CRC from that data, you write 12 bytes to the memory.
When you read if back, you read all 12 bytes, calculate the CRC from the first 10 bytes, and check that the calculated CRC matches the 2 bytes of CRC read back from the memory.
There is also another method to calculate the CRC of all 12 bytes read back, it will add up to a constant check value if the CRC is correct, but depending on the CRC algorithm you use the result could be always zero but it can be something else too.


Q: Solving equation of two variables, solution in natural numbers Task: Two items are being sold, small and large types.
The small type costs $98$ cents each, the large type costs $158$ cents.
In the end, the total amount of sold items is $17028$ cents  $(\$170.28)$.
All in all, there have been $100$ small and $100$ large items at the beginning.*
So I wrote down an equation
$98x + 158y = 17028$, where x is the amount of small types and y the amount of large types, solved for y and plotted a function. The only natural solution for that equation is
$x = 48, y = 78$, with $1 \le x,y \le 100$
Any idea how this could be proved? I tried writing $xy = l$ for an $l \in \mathbb{N}$, and used $y = \dfrac{l}{x}$ in the equation above.
I got $98x + 158 \dfrac{l}{x} = 17028 \iff 98x^2 - 17028x + 158l = 0$ and tried solving this through the p-q-formula, but this approach was not quite constructive so far deciding what l has to be, so that x is a natural number.


Q: SQL Server query to Postgres Please help me to convert this SQL Server Query to a Postgres query. I am using Postgresql 9.3.I am not able to get the desired output in postgres
If object_ID(N'tempdb.dbo.#tmp') is not NULL
    Drop table #tmp;

create table #tmp
(
variable_int_col int,
timestamp_int_col int,
value_col int
)

insert into #tmp values
(8,1449486435,25),
(8,1449486436,26),
(9,1449486435,40),
(9,1449486436,44),
(9,1449486440,52)

select * from #tmp

Declare @sql varchar(max);
Declare @sql2 varchar(max);

set @sql= STUFF((select distinct ','+ QUOTENAME(variable_int_col) from #tmp FOR XML PATH('')) ,1,1,'');
set @sql2= STUFF((select distinct ','+ 'ISNULL(' + QUOTENAME(variable_int_col) + ',0)' + ' AS ' + QUOTENAME('variable_' + cast(variable_int_col as varchar) + '_value') from #tmp FOR XML PATH('')) ,1,1,'');

set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
               PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';
-- print @sql

If object_ID(N'dbo.newTable') is not NULL
    Drop table newTable;

set @sql='select * into newTable from (' + @sql + ') s';

exec(@sql);

select * from newTable;

I have tried But failed to convert this line
set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
                   PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';

Please Help


Q: How to get confusion matrix and ROC curve when using flow_from_directory? I've trained a model using:
    train_datagen = ImageDataGenerator(rescale = 1/255,
                                       zoom_range=0.3,
                                       shear_range=0.3,
                                       horizontal_flip=True,
                                       rotation_range=30,
                                       fill_mode="nearest",
                                       validation_split = 0.2)

    test_datagen  = ImageDataGenerator(rescale = 1./255
                                      )

    train_dataset  = train_datagen.flow_from_directory(directory = './train',
                                                       target_size = tsize,
                                                       class_mode = 'categorical',
                                                       subset = 'training',
                                                       batch_size = BS)

    valid_dataset = train_datagen.flow_from_directory(directory = './train',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      subset = 'validation',
                                                      batch_size = BS)

    test_dataset = test_datagen.flow_from_directory(directory = './test',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      batch_size = BS)

and also:
    hist = model.fit(train_dataset,validation_data=valid_dataset,epochs=30,callbacks=[vgg_step_1])

How can i plot confusion matrix?, im confused, i only have the validation vs train plot.

A: To get a confusion matrix you need to make predictions on the test set. Then you need to provide the predicted values and the associated true values to the confusion matrix. Note -- in your code for the test_dataset you MUST set shuffle=False in flow_from_directory!!
Code below should generate an adaptable confusion matrix plot and classification report. model is your trained model.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import seaborn as sns
sns.set_style('darkgrid')
def cm_cr(test_gen, model):
    preds=model.predict(test_gen)
    labels=test_gen.labels
    classes=list(test_gen.class_indices.keys()) # ordered lst of class names
    pred_list=[ ] # will store the predicted classes here
    true_list=[]
    for i, p in enumerate (preds):
        index=np.argmax(p)
        pred_list.append(classes[index])
        true_list.append(classes[labels[i]])
    y_pred=np.array(pred_list)
    y_true=np.array(true_list)
    clr = classification_report(y_true, y_pred, target_names=classes)
    print("Classification Report:\n----------------------\n", clr)
    cm = confusion_matrix(y_true, y_pred )
    length=len(classes)
    if length<8:
        fig_width=8
        fig_height=8
    else:
        fig_width= int(length * .5)
        fig_height= int(length * .5)
    plt.figure(figsize=(fig_width, fig_height))
    sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False)
    plt.xticks(np.arange(length)+.5, classes, rotation= 90, fontsize=16)
    plt.yticks(np.arange(length)+.5, classes, rotation=0, fontsize=16)
    plt.xlabel("Predicted")
    plt.ylabel("Actual")
    plt.title("Confusion Matrix")
    plt.show()

cm_cr(test_dataset, model)

I did not do the ROC curve but there is a good tutorial here for that activity.


Q: How to make the calendar using the TimeGridWeek view show me only the name of the day I am making a generic weekly calendar so i want to only show the name of the day no the number but a i didn't find how to do it.
I am using fullcalendar v6
https://fullcalendar.io/
How it look

How it should be


Q: element onChange javascript not working <select name='cmg_select'  onChange="javascript:window.location.href='index.php?'+this.value">
    <option value='pening'> pening </option>
    <option value='complete'> complete </option>
    <option value='pening'> pening </option>
</select>

The concatenation is not working.

A: *

*Remove the javascript: portion

*Remove the href portion

The result :

     < select name='cmg_select' onchange="window.location='index.php?'+this.value" >

A: Try this instead
<select name='cmg_select' onChange="window.location.href='index.php?'+this.options[this.selectedIndex].value">
<option value='pening' > pening </option>
<option value='complete' > complete </option>
<option value='pening' > pening </option>
</select>

A: Remove the javascript: from the onchange attribute.


Q: How do I click on a drop down menu that is hidden using Selenium? I'm trying to click on a drop down menu, but since it is hidden, I'm getting the error:
could not be scrolled into view

I've done some digging and I see that using some JavaScript could help, but I'm not sure how to implement that into my Python script.

<input name="idTeam1Desktop" type="hidden" id="idTeam1Desktop" value="">

This is what I have so far:
driver = webdriver.Firefox(profile, options=options)
driver.get("https://tradenba.com/trade-machine")
element = driver.find_element_by_xpath("//*[@id='idTeam1Desktop']")
element.click()

A: To click on the drop down menu and select the menu item with text as MIL you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following xpath based Locator Strategies:

*

*Using XPATH:
driver.get('https://tradenba.com/trade-machine')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='select-idTeam1Desktop']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='MuiListItemText-root MuiListItemText-inset']/span/div/p[text()='MIL']"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

*Browser Snapshot:


Q: Display a Popup Goal:
When you rightclick one of the row in the table, a popup with links should display, close to the row and cursor. A similiar concept is gmail's functionality.
Problem:
I cannot find a demo version in order to use it.
Information:
I'm using Bootstrap and jQuery..