text:
Q: How do I force VB6 to POST using TSL encryption? The company where I work has an old VB6 application that they want to force to use TSL, rather than SSL. I looked at the code, and told them they should be fine. The code does a post to the client website using HTTPS. It doesn't specify what encryption to use.
This is the relevant code:
Sub PostXML()

Dim XMLHttpRequest  As MSXML2.XMLHTTP
Dim TempString      As String
Dim strURL          As String
Dim strArgs         As String

strURL = gPostWebServer & "/" & gPostFile

'ARB 1/8/2004 This is to trap if send fails and allow it to continue.
On Error GoTo errorHandler:

If Not XMLHttpRequest Is Nothing Then Set XMLHttpRequest = Nothing

Set XMLHttpRequest = New MSXML2.XMLHTTP

strArgs = "?Username=" & gPostUserName & "&Password=" & gPostPassword

XMLHttpRequest.Open "POST", strURL & strArgs, False

XMLHttpRequest.send dom_GlobalXMLObject

If XMLHttpRequest.Status >= 400 And XMLHttpRequest.Status <= 599 Then
    TempString = "Client Website is not available. Order was not posted successfully ..."
    flgOrderPostSuccess = False
    strOrderPostError = TempString
Else
    TempString = XMLHttpRequest.responseText

    'Parse the response
    Dim sValid          As String
    Dim sComments       As String
    Dim sTimeStamp      As String

    Dim oRoot           As MSXML2.IXMLDOMElement
    Dim lNodes          As MSXML2.IXMLDOMNodeList
    Dim oNodes          As MSXML2.IXMLDOMElement
    Dim lNodes1         As MSXML2.IXMLDOMNodeList
    Dim oNodes1         As MSXML2.IXMLDOMElement
    Dim lNodes2         As MSXML2.IXMLDOMNodeList
    Dim oNodes2         As MSXML2.IXMLDOMElement

    Call Set_Global_XML_Object
    dom_GlobalXMLObject.loadXML (TempString)

    dom_GlobalXMLObject.Save (Report_Folder & "\Response.xml")

    'Get the root of the XML tree.
    Set oRoot = dom_GlobalXMLObject.documentElement
    If Not oRoot Is Nothing Then
        Set lNodes = oRoot.childNodes

        For Each oNodes In lNodes
            Select Case oNodes.nodeName
                Case "Acknowledgement"
                    Set lNodes1 = oNodes.childNodes
                    For Each oNodes1 In lNodes1
                        Select Case oNodes1.nodeName
                            Case "Received"
                                sTimeStamp = Trim(oNodes1.nodeTypedValue)
                            Case "Validated"
                                sValid = Trim(oNodes1.nodeTypedValue)
                            Case "Errors"
                                Set lNodes2 = oNodes1.childNodes
                                For Each oNodes2 In lNodes2
                                    Select Case oNodes2.nodeName
                                        Case "Description"
                                            sComments = sComments & vbCrLf & Trim(oNodes2.nodeTypedValue)
                                    End Select
                                    Set oNodes2 = Nothing
                                Next
                                Set lNodes2 = Nothing
                        End Select
                        Set oNodes1 = Nothing
                    Next
                    Set lNodes1 = Nothing
            End Select
        Next
        If UCase(sValid) = "YES" Then
            TempString = sTimeStamp & " " & "Order uploaded successfully"
            flgOrderPostSuccess = True
            strOrderPostError = ""
        Else
            TempString = "Order had following problems:" & vbCrLf
            TempString = TempString & sComments
            strOrderPostError = TempString
        End If
    Else    'Non XML response
        TempString = Replace(TempString, vbCr, vbCrLf)
        TempString = "Order had following problems:" & vbCrLf & TempString
        strOrderPostError = TempString
    End If
End If

Call FillLogTextBox("-----------------------------------------------" & vbCr)
Call FillLogTextBox(TempString)
Call FillLogTextBox("-----------------------------------------------" & vbCr)

Set oRoot = Nothing
Set lNodes = Nothing
Set oNodes = Nothing
Set lNodes1 = Nothing
Set oNodes1 = Nothing
Set lNodes2 = Nothing
Set oNodes2 = Nothing

Set XMLHttpRequest = Nothing

Exit Sub

errorHandler:
TempString = Err.DESCRIPTION
If InStr(1, TempString, "Method") > 0 Or InStr(1, Err.DESCRIPTION, "failed") > 0 Then
    TempString = "Client Website was not found. Order was not posted successfully..."
    Call FillLogTextBox(TempString)
    Call FillLogTextBox("-----------------------------------------------" & vbCr)
    Exit Sub
End If

End Sub

When the client switched from SSL to TSL last weekend, everything worked, except the posts from this one old VB6 app. (So I'm told, anyways. This isn't an application I've supported before.)
We have other VB6 apps that I maintain, but none do a POST out of VB6. All of them use BizTalk for posting.
The client has given us until next Wednesday to fix our app. So, the powers that be want me to force the app to use TSL.
Normally, I don't have problems with VB6, but I've never tried forcing the encryption used to POST. Generally, when we did POST out of the other VB6 apps, they negotiated with Windows on their own, and took care of things. While I've seen successful attempts to force VB6 to use TSL when sending an email, I've never seen anyone do it for POSTing.
All that being said, does anyone know how to force VB6 to use TSL when POSTing?
Thanks

A: With SChannel you cannot control available/used protocols and ciphers at an application level, you have to configure SChannel protocols/ciphers on the Win2003 box at system level. Here is KB on the subject: http://support.microsoft.com/kb/245030
To disable SSLv3 for both inbound and outbound connections merge something like this in registry (and reboot):
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"DisabledByDefault"=dword:00000001
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000000
"DisabledByDefault"=dword:00000001

While there make sure SSLv2 is nuked too.
You might prefer to use IISCrypto -- a nice utility that makes SSL/TLS protocols/ciphers registry config trivial.


text:
Q: What is the standard common mode voltage of Media Dependent Interface MDI[0:3]± signals? I am working on the selection RJ45 connector for MDI interface between PHY and the link-partner.
I am planning to use this PHY for my SGMII interface application. From various online readings, I understood some RJ45 connectors can have CT (Center tap) pin connection to a power supply to bias MDI signals. I just want to clarify if I have to select RJ45 connector with CT power supply to bias the MDI signals?
For the RJ45 connector selection, I would like to know what is the common-mode voltage of MDI signals (which I could not find in the datasheet). Is MDI signal common-mode voltage a standard value or it will change based on the selected PHY?

redpajama_set_name: RedPajamaStackExchange


text:
Q: stop click.trigger() from firing on a particular nested element I am trying to use click.tigger() to change the mode of the template to editable. Problem is I have a image gallery inside this template that I don't want click.trigger to fire on.
app.js:
<div click.trigger="enableEdit()">
    <response containerless></response>
</div>

response.html:
<template>
    <div>
       ...
       <gallery></gallery> <-- I want this to still be able to fire
       <button click.trigger="save()">save</button> <-- I want this to work as well but they wont with "enableEdit()" above attached.
    </div>
</template>

Gallery.js:
attached() {
    const carousel = new Flickity(this.gallery, {
      cellAlign: 'left',
      contain: true,
      lazyLoad: true,
    });
  }

Once I click the trigger it does work and enable edit. The gallery is using a Plugin called Flickity. Above I show how I instantiated it.

A: Consider putting the click binding on a sibling element.  Avoid stopping events from bubbling because it can make your code brittle/not-portable.
A quick fix would be to inspect the click event's target. Find out if the click originated from your gallery element or one of it's children.
<div click.trigger="enableEdit($event.target)">
  <response containerless></response>
</div>

enableEdit(target) {
  if (target.nodeName === 'gallery' || target.closest('gallery') !== null) {
    // it's the gallery element or one of it's children... get out of here...
    return;
  }
  ...
}

note:  Element.closest(selector) isn't supported in Internet Explorer yet. Use a simple polyfill to be safe.


text:
Q: echo in jquery doens't output as expected I found on stackoverflow how to use a php variable in jquery, but on my test page, it simply isn't working:
$('#q').keyup(function(e) {
  var test = "<?php echo 'test123'; ?>";
  alert(test);
});

The code above outputs "" literally in the box where I want it to say "test123". I tried using single quotes instead of double, other small changes ... Didn't get it to work. Am I missing something?
The code above sits in a .js file which is linked in a .php page, which is (again) linked in my index.php file via require_once.

A: You should not use PHP in javascript files (.js). Javascript and PHP are different languages. PHP works on the server-side and Javascript on the client-side.
You have to put this code in your <head> under the jquery.js file, like this:
<script type="text/javascript" src="link-to-jquery-file.js"></script>
<script type="text/javascript">
$('#q').keyup(function(e) {
    var test = "<?php echo 'test123'; ?>";
    alert(test);
});
</script>

Also make sure your file extension ends with .php
There is also an advanced solution for this, and that would be using the header() function. Save as javascript.php or someting Example:
<?php
header("Content-Type: text/javascript");
?>
$('#q').keyup(function(e) {
    var test = "<?php echo 'test123'; ?>";
    alert(test);
});

Then attach the file in your <head> like this:
<script type="text/javascript" src="javascript.php"></script>

Goodluck!


text:
Q: Swift 2 TableView Sorting I have an iOS project I'm working on in Xcode 7 using Swift 2.  I have an array called details with a dictionary which includes a String and an Int value.  The Int is called cellOrder in the Class and the idea is to sort the details array in a TableView with a sort based on the cellOrder Int value.
The array shows the String values which are names.  I looked here to try and implement this into my project with no success.
Here is my array:
// Array of data for the TableView
var details = [ProjectDetails]()

Here is my TableView Code:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return details.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel!.text = details[indexPath.row]

    return cell

}

How do I do the sort and where would I put the code, ViewDidLoad() or maybe cellForRowAtIndexPath?
UPDATE:
My ViewDidLoad():
override func viewDidLoad() {
    super.viewDidLoad()

    // TableView Sorting
    details.sortInPlace({$0.cellOrder < $1.cellOrder})

    tableView.delegate = self

    ...

}

Update 2:
My ProjectDetails class for the array data is:
import UIKit

class ProjectDetails: NSObject, NSCoding {

    // MARK: Properties

    var fileName: String
    var cellOrder: Int

    ...

}

A: To sort the array you would just do
details.sortInPlace({$0.cellOrder < $1.cellOrder})
in viewDidLoad, or you could use
details.sort({$0.cellOrder < $1.cellOrder})[indexPath.row]
in cellForRowAtIndexPath, but that could prove dangerous if you do not keep track of your array.
One will sort the array in place, one will return a sorted immutable array.
If you insist on sorting immutably (has its pros and cons beyond this scope) assign it to another array and use that in your logic.

A: You must sort the itens in this array details[], after that, you can call tableView.reloadData() to reload the info.
In the cellForRowAtIndexPath you must just take the data to fill the cell, so NO SORT THERE!
Sort anywhere else, before call the function to reload.


text:
Q: Java - Change the value in a HashMap I have a HashMap that like this:  HashMap<UUID, CustomClass>.
CustomClass has a lot of properties that make it meaningfully unique.  I need to be able to update the value of a key already in the map with a new instance of CustomClass.  Then I need to call a method called "CustomClass.clearInfo()" that clears/nulls/zeros out the values of all the properties accordingly.
The problem is the "Put" method just changes the reference of the value to refer to the new instance, so when I call clearInfo(), the hashed value is also cleared.
I need to keep the values before the call to clearInfo().

A: You can remove the object using the HashMap.remove(key) method. Then you can put a new object in the key you have just removed.
See the documentation for remove().


text:
Q: Trouble setting up a ctrl + keydown event listener (Not detected) I want to have an event listener that console logs a text string after a ctrl  + left/right arrow key is pressed simultaneously. However, the event isn't being picked up by the function below:
$(document).keydown(function (event) {
    if (event.which === 37 && event.ctrlKey) {
    console.log('ctrl-left');
    }

if (event.which === 39 && event.ctrlKey) {
    console.log('ctrl-right');
    }

else {
    console.log('nothing detected');
    }
});

Any idea what i'm doing wrong?

A: There is a problem in your if branches, making a CTRL+Left keypress to log both ctrl-left and nothing detected at the same time.
Also, the browser's default event handling would need to be stopped to avoid issues.
This worked for me on Firefox 44.0.2:
$(document).keydown(function (event) {
    event.preventDefault();
    if (event.which === 37 && event.ctrlKey) {
      console.log('ctrl-left');
    } else if (event.which === 39 && event.ctrlKey) {
      console.log('ctrl-right');
    } else {
      console.log('nothing detected');
    }
});


text:
Q: Docker - how to use a saved file created in the container Objective: train a machine learning model in a .py (train_model.py) file, save the model to a .joblib file (Inference_xgb.joblib), load the model into another .py (Inference.py) file, use the model to make predictions and save the output.
Issue: Inference.py cannot find the Inference_xgb.joblib file.
Relevant code snippets:
Training (train_model.py):
#!/usr/bin/python3

import pandas as pd
from xgboost import XGBClassifier
from joblib import dump

def train():
    # load in and read training data
    training = './train.csv'
    data_train = pd.read_csv(training)
    label = data_train['2020 Failure'] # what we want to predict
    features = data_train.drop(['2020 Failure', 'FACILITYID'], axis =1, inplace=False) # what we train on the model to learn
    features = features.drop('Unnamed: 0', axis=1)
    x_train = features
    y_train = label

    # XGBoost model training
    xgb_model = XGBClassifier(use_label_encoder=False, eval_metric="logloss")
    xgb_model.fit(x_train, y_train)
    # save model
    dump(xgb_model, 'Inference_xgb.joblib')

if __name__== '__main__':
    train()

Testing (Inference.py):
#!/usr/bin/python3

import pandas as pd
from joblib import load
from sklearn.metrics import confusion_matrix
import os

def inference():
    # load and read in test data
    testing = './test.csv'
    data_test = pd.read_csv(testing)

    label = data_test['2020 Failure'] # what we want to predict
    features = data_test.drop(['2020 Failure', 'FACILITYID'], axis =1 ) # what we train on the model to learn
    features = features.drop('Unnamed: 0', axis=1)
    IDS = data_test['FACILITYID']
    x_test = features
    y_test = label

    # run model
    xgb_model = load('Inference_xgb.joblib')
    y_label = xgb_model.predict(x_test)
    cm = confusion_matrix(y_test,y_label)
    print("Confusion Matrix: ")
    print(cm)

    # write results
    dirpath = os.getcwd()
    print('CURRENT PATH: ', dirpath)
    output_path = os.path.join(dirpath, 'output.csv')
    output_df = pd.DataFrame(y_label, columns=['Prediction'])
    output_df.insert(0, "FACILITYID", IDS.values)
    output_df.to_csv(output_path)
    print('OUTPUT DF')
    print(output_df)

if __name__ == "__main__":
    inference()

Dockerfile:
FROM jupyter/scipy-notebook

RUN pip install joblib
RUN pip install xgboost==1.5.0

USER root

WORKDIR /scaleable-model

COPY train.csv ./train.csv
COPY test.csv ./test.csv

COPY train_model.py ./train_model.py
COPY inference.py ./inference.py

RUN python3 train_model.py

Comments, observations, and what I've tried:
I've noticed that removing WORKDIR /scaleable-model fixes the issue, but I want to keep the WORKDIR to /scaleable-model so I can mount the .csv output to my host machine.
I am running docker build in the scaleable-model directory on my host machine. That is, I cd to /home/user/pathto/scaleable-model and run docker build -t scaleable-model -f Dockerfile .
I then call docker run and specify I want to call Inference.py, this is how the error is generated.
I've tried hardcoded paths as well but this did not help. I also created a Inference_xgb.joblib on my host machine in the same directory where I am building the container, but this did nothing either.
I suspect that either:

*

*the Inference_xgb.joblib file is not being created properly in the container

*I am messing up the directory structure somehow inside the container and thus Inference.py cannot find the file.

To quote Michael Burry, "I guess when someone's wrong, they never know how". I'd like to try to understand the how here.
EDIT:
Checking the contents of the container, the file (Inference_xgb.joblib) IS being created in the directory that I want (/scaleable-model). Therefore, it must be an issue with Inference.py` not detecting the file for some reason.

A: To verify if the model file is being created in the container, you can -

*

*Create a container and start a bash terminal
docker run -it <image_name> bash

*Check the current directory - this should be scalable-model
pwd

*List the contents of the directory - this should show the model file
ls


text:
Q: How can I get a correct publish date in TYPO3? I am using TYPO3 7.6.9 and want to use the publish date and expiration date options for content elements in TYPO3, but currently this is not working correctly for me, because the time part seems to be incorrect.
For example:
If I set the publish date to: 18:00 04-09-2016 and the real time is 19:00 04-09-2016 then the element is not visible in frontend. For this reason I have checked some values and it seems that there is a two hour difference to the real time, because 17:00 04-09-2016 is working.
Furthermore I have set the timezone via install tool to UTC and I think that is the problem:
[SYS][phpTimeZone] = UTC

I have set the timezone to UTC because I got a two hour difference by using the timezone "Europe/Berlin" and different datetime objects in an extension. I could fix this by set the timezone to UTC, but now I got in trouble with the publish and expiration options.
Is there a solution to get both to work?

A: Make sure you also define the time zone in PHP's configuration (date.timezone). You should also, but are not required to, properly set your system time zone.

A: The caveat here is that the dates you enter in the backend are UTC, not your local timezone. This is not sooo well documented, but trust me, I debugged that stuff last week ;-)
The dates are stored in your server's timezone, so be cautious with changing the timezone after the fact—this might break existing dates!
The effect you observed is actually exactly what happens when you are in CEST (UTC+2):

*

*you create a content element and set its publication time to 17:00 (UTC)

*you visit the page at 17:01 CEST (15:01 UTC) -> the content is not visible

*you visit the page at 19:01 CEST (17:01 UTC) -> the content is visible


text:
Q: Total Probability and Bayes Rule
The probability that a person has 0, 1, 2, 3, 4, or 5 or more siblings is 0.15, 0.49, 0.27, 0.06, 0.02, 0.01, respectively.

a) Three friends who are not siblings are gathered. What is the probability that they combined have three siblings?

b) Emma and Jacob are not siblings, but combined they have a total of 3 siblings. What is the probability that Emma has no siblings?

So for a) I have calculated that there are 7 possible ways this can occur: 1 situation where all three friends have 1 sibling, 3 cases where two friends have zero siblings and the other one has 3 siblings, and 3 cases where one person has 1 sibling, one person has 2 siblings and the last person has 0 siblings. So calculating this I obtain:
Using the notation that $P(X = N)$ means the probability that one person has $N$ siblings.
$$P(X = 1)^3 + 3*P(X = 0)^2 * P(X = 3) + 3*P(X = 2)*P(X = 1) * P(X = 0) \approx 0.181$$ Is this correct?
For part b) I used the notation $P(E = N)$ to mean the probability that Emma has N siblings, and similarly $P(J = N)$ to mean the probability that Jacob has $N$ siblings.
I interpreted the problem as asking us to calculate $$P(E = 0 | E + J = 3) = \frac{P (E = 0 \cap E + J = 3)}{P(E + J = 3)} = \frac{P(E+J = 3| E = 0) * P(E = 0)}{P(E+J = 3)} = \frac{P(J = 3)*P(E = 0)}{2*P(E = 0)*P(J = 3) + 2 * P(E = 1)*P(J = 2)} \approx 0.4416$$ where I have used Baye's rule to transform the expression.
Are my calculations correct?

A:
So for a) I have calculated that there are 7 possible ways this can occur

I calculated 10 possible ways thus I did not check your calculations

*

*$0-0-3$

*$0-1-2$

*$0-2-1$

*$0-3-0$

*$1-0-2$

*$1-1-1$

*$1-2-0$

*$2-0-1$

*$2-1-0$

*$3-0-0$
Summing the single probabilities I get $0.240769\approx 24\%$
For (b) I get
$$\frac{0.15\times0.06}{0.15\times0.06+0.49\times0.27+0.27\times0.49+0.06\times0.15}=0.031847\approx 3\%$$

A: In first part of the question, when you are counting cases for $2, 1 $ and $0$ siblings, there are $3! = 6$ ways, instead of $3$. They are $\{0, 1, 2\}, \{0, 2, 1\}, \{1, 0, 2\}, \{1, 2, 0\}, \{2, 0, 1\}, \{2, 1, 0\}$. So the probability should be
$P(X = 1)^3 + 3  \ P(X = 0)^2 \  P(X = 3) + 6 \ P(X = 2) \ P(X = 1) \ P(X = 0) \approx 0.2408$
For the second one, you have written the formula correctly but the answer seems wrong.
It should be $ = \frac{0.06 \times 0.15}{2 \times 0.06 \times 0.15 + 2 \times 0.49 \times 0.27} \approx 0.0318$


text:
Q: mergesort symantic cause, evidenet due to the clock timing the process Merge sort is not sorting, the program asks for a number which is then sent into the merge sort function, to be sorted.
Had this problem for a few days and still cant pinpoint the error
The program runs fine, it is just when the merge sort function is called that it isn't processing correctly - evident due to merge sort being able to sort 100000 numbers in 0ms (apparently)
Why is this not working correctly? can you see why the vector isn't being sorted?
   //merge sort
    void merge(vector<int>& a, int l, int m, int r)
    {
        int i, j, k;
        int n1 = m - l + 1;
        int n2 = r - m;

        /* create temp aays */
        std::vector<int> L(n1), R(n2);

        /* Copy data to temp arrays L[] and R[] */
        for (i = 0; i < n1; i++)
            L[i] = a[l + i];
        for (j = 0; j < n2; j++)
            R[j] = a[m + 1 + j];

        /* Merge the temp aays back into a[l..r]*/
        i = 0; // Initial index of first subaay
        j = 0; // Initial index of second subarray
        k = l; // Initial index of merged subarray
        while (i < n1 && j < n2)
        {
            if (L[i] <= R[j])
            {
                a[k] = L[i];
                i++;
            }
            else
            {
                a[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy the remaining elements of L[], if there
        are any */
        while (i < n1)
        {
            a[k] = L[i];
            i++;
            k++;
        }

        /* Copy the remaining elements of R[], if there
        are any */
        while (j < n2)
        {
            a[k] = R[j];
            j++;
            k++;
        }
    }

    /* l is for left index and r is right index of the
    sub-array of arr to be sorted */
    void mergeSort(vector<int>& a, int l, int r)
    {
        if (l < r)
        {
            // Same as (l+r)/2, but avoids overflow for
            // large l and h
            int m = l + (r - l) / 2;

            // Sort first and second halves
            mergeSort(a, l, m);
            mergeSort(a, m + 1, r);

            merge(a, l, m, r);
        }
    }
int main(int argc, char const *argv[])
{

    int num;
    int upperBound = 5;
    cout << "Enter the size of the vector to be sorted: ";
    cin >> num;

    vector<int> a(num, upperBound);
    if (num <= 20)
    {
        for (int i = 0; i < num; i++)
        {
            cout << "Enter numbers: ";
            cin >> a[i];
        }
    }
    else
    {
        for (int i = 0; i < num; i++)
        {
            a[i] = rand() % upperBound;
        }
    }
    //
    //
    int selection;
    cout << "What sorting algoithm would you like to use. 1. Bubble Sort 2. Quicksort 3.Mergesort: ";
    cin >> selection;
    //quicksort setting start and end of vector
    int p = 0;
    int q = num;

    switch (selection) {
    case 1://Passes Numbers to be 'Bubble' sorted
    {
        //cout << "======Original=======" << endl;;
        //printVector(a);
        //cout << "======Sorted=======" << endl;
        the_clock::time_point start = the_clock::now(); // start clock

        bubbleSort(a);
        the_clock::time_point end = the_clock::now(); //end clock
        auto time_taken = duration_cast<milliseconds>(end - start).count(); //calculating time

        //printVector(a);
        cout << "It took " << time_taken << " ms." << endl; //displaying in ms
    }
    break;       // and exits the switch
    case 2://Passes to quicksort
    {
        cout << "======Original=======" << endl;
        //for (auto e : a)
        //  cout << e << " ";
        //cout << endl;

        the_clock::time_point startTime = the_clock::now(); // start clock

        quickSort(a, p, q);

        the_clock::time_point endTime = the_clock::now(); //end clock
        auto time_taken = duration_cast<milliseconds>(endTime - startTime).count(); //calculating time

        cout << "======Sorted=======" << endl;
        //for (auto e : a)
        //  cout << e << " ";
        //cout << endl;
        cout << "It took " << time_taken << " ms." << endl; //displaying in ms
    }
    break;
    case 3:
    {

        int a_size = sizeof(a) / sizeof(a[0]);
        the_clock::time_point startTime = the_clock::now(); // start clock

        mergeSort(a, 0, a_size - 1);

        the_clock::time_point endTime = the_clock::now(); //end clock
        auto time_taken = duration_cast<milliseconds>(endTime - startTime).count(); //calculating time

        cout << "======Sorted=======" << endl;
        //for (auto e : a)
        //  cout << e << " ";
        //cout << endl;
        cout << "It took " << time_taken << " ms." << endl; //displaying in ms
    }break;

    // and exits the switch
    }

}


text:
Q: Sidebar with Jasny bootstrap I would like to use Jasny bootstrap for a sidebar like the admin template.
But I would like that though, once you open the menu , the page is resized and did not have theoff -canvas off-canvas .
http://jsfiddle.net/jasny/k9K5d/
Does anyone know how to do ??

    Project Name

 Link 1

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Brand

Link

Link

                    Dropdown

Action

Another action

Something else here

Separated link

One more separated link

            <form class="navbar-form navbar-left" role="search">

                    <input type="text" class="form-control" placeholder="Search">

                <button type="submit" class="btn btn-default">Submit</button>
            </form>

Link

                    Dropdown

Action

Another action

Something else here

Separated link


text:
Q: removing tooltip Is there a way to disable the default tooltip that shows up in a browser when hovering over an image? This is without removing the title or alt tags. Another option, can the tooltip be made to show a specific text for certain image types (such as JPG) and another text for a different image type (such as PNG)?

A: The title attribute is used as hover text in most browsers by default.  The only way I could see removing them is to remove the title attribute.  JavaScript would be capable of doing this.  I'm sure there is a pure DOM way to do this, but I'm using a little jQuery:
$(function() { // when the document becomes ready for manipulation
  $("[title]").removeAttr('title'); // removes title from all things that have title
  // your other options:
  // all images who's src ends in .jpg
  $("img[src$=.jpg]").attr('title','JPG Image');
  // all images who's src ends in .png
  $("img[src$=.png]").attr('title','PNG Image');
}

If you need to stick this on your pages, I suggest making a site.js file that has this code in it.  Then you need to tell your HTML pages to load it.  You should have some main site template file (and it may already have jQuery - if so skip the include for jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="/js/site.js"> </script>

Response to comment: how about restricting the characters that can appear in the tooltip to zero or up to let's say 10?
This problem gets slightly more complicated, for this one lets pull out .each() on elements with titles:
 $("[title]").each(function() {
    var $this = $(this); // shortcut for later
    var title = $this.attr('title'); // get the title attribute
    // if the length of our title was 10 characters or more, shorten it and set:
    if (title.length>10) {
      $this.attr('title', title.substring(0,10));
    }
 });


text:
Q: Is preprocessor blindly replace the defines? I have a class that has a member function called SendMessage. No member function named SendMessageA exists in the project.
Project is multibite, so I have a define
#define SendMessage  SendMessageA
If I call SendMessage somewhere in that class, will my project call SendMessage or SendMessageA ?
If the replace is made by preprocessor,the project should not compile. Right ?
But I see in a dump that SendMessageA is called ... end eip register is not in any VAD
EDIT
A more specific question: is preprocessor blindly replace the defines ? or first checks for a match in the class ?

A: The Preprocessor runs through your code before compilation.
So any SendMessage would be converted into a SendMessageA. The compiler will then look for a function called SendMessageA and call it.

A: The preprocessor works as a text macro processor. If a macro is defined, all occurrences of the macro are replaced with it's definition.
#define blabla some_real_stuff

struct blabla /* blabla will be replaced with some_real_stuff */
{
   void method();
};

int main()
{
   some_real_stuff x;
   x.method();
}

A:
How C++ preprocessor works

In case of #define A B preprocessor replaces ALL occurences of A with B. It is pure substitution.

Will my project call SendMessage or SendMessageA ?

Your project will call either SendMessageA or SendMessageW - depending on whether it was compiled with unicode support or not. There's no SendMessage function - it doesn't exist.

f the replace is made the project should not compile.

SendMessageA is declared within <widnows.h> (or in a header that is included from windows.h) - somewhere, and its linking info is within one of base system libraries (User32.lib, I think). If you're on windows, there's a very good chance <windows.h> is #included from somewhere, and corresponding *.lib is already in linker dependencies.
--EDIT--

A more specific question: is preprocessor blindly replace the defines ?

Yes, preprocessor blindly replaces defines. For non-blind replacement you have templates, but they have their own limitations. Some thing that can be done with preprocessor cannot be done with templates and vice versa. Preprocessor have stringize operator, templates have type-checking and metaprogramming.

My problem is why sometimes the member function SendMessage is called because the code works (most of the time)

If you have SendMessage method in your code (BAD idea on windows platform - clashes with system macro, replace with sendMessage() or use different name, because even namespaces won't help you to avoid omnipresent preprocessor) your method (not SendMessageA/SendMessageW) will be called from *.cpp ONLY if <windows.h> was not included in that *.cpp.
Compiler operates at one file at a time, and has no knowledge of thing that go on in other files, so if there's no <windows.h> #included, your method will be called, because preprocessor won't have any knowledge about SendMessage #define (from <windows.h>). If <windows.h> is included, then ALL occurences of SendMessage will be replaced with SendMessageA/SendMessageW, because preprocessor does its job first.
One possible solution in your situation would be to avoid using naming convention similar to the one in Win API. I.e. make sure that function names don't start with capital letter. That'll solve many problems, but you'll still get minor trouble from min/max macros.

A: In the Windows API, there are the two functions SendMessageA and SendMessageW. You will be calling one of these two, depending on what #defines you have in your program.
Are you sure that is not what happens?
Edit: oh wait. Is your #define SendMessage SendMessageA before the definition of the SendMessage member function in your source? If so, the compiler will simply use SendMessageA for the name of the member. Otherwise, your function will be SendMessage, but the rest of your program will call the built in Windows function SendMessageA.
If you have many source files, maybe some of them will know about the #define, while others won't.
My recommendation is to rename the member function to something else and dispense with the #define.


text:
Q: PHP SQL delete from where date < current date? I have a table in my database called expire_datetime_off. It's format is 2014-07-11 00:00:00 and I want to delete the row if this date is before the current date at that moment. I have a variable for the current date in Magento PHP. I couldn't figure it out. Any help is appreciated
public function onclearAction()
{
    $mysqli=mysqli_connect("IP","NAME","PASSWORD","SCHEMA");
    if ($mysqli->connect_errno) {
        return $mysqli->connect_error;
    }
    $currenttime = strtotime(Mage::getModel('core/date')->date('Y-m-d H:i:s'));
    mysqli_query($mysqli,"DELETE FROM belvg_countdown WHERE expire_datetime_off < convert(datetime, '$current_time')");
}

A: You can use the database current time:
DELETE FROM belvg_countdown
    WHERE expire_datetime_off < now();

A: It's format is 2014-07-11 00:00:00
if it's in this format then no need to convert it for the comparison
$currenttime = Mage::getModel('core/date')->date('Y-m-d H:i:s');
mysqli_query($mysqli,"DELETE FROM belvg_countdown WHERE expire_datetime_off <  '$current_time'");


text:
Q: Factory Boy Build JSON String from Another Factory I am trying to use Factory Boy in order to generate test data for my test suite. My data consists of JSON objects with a body field that contains an escaped JSON String (example below). I also included example python dataclasses and Factory Boy factories for this example data.
Note: For this example, I am skipping the setup of fake data using Faker or the built-in fuzzers to simplify the question. In a more realistic use case, fields like eventtime, deviceid, enqueuedTime would contain rondomized values (using a fixed seed for the randomness)
I am struggling to figure out how to generate the inner JSON object and stringify it using Factory Boy.
An example data point:
{
    "body": "{\"eventdata\":{\"count\":\"1\",\"sourceid\":\"0\",\"updatetime\":\"1579797993879\",\"description\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit\"},\"eventtime\":\"2020-01-23T16:46:35.522Z\",\"eventversion\":\"1.0.0\",\"eventtype\":\"FooEventType\",\"deviceid\":\"000000123ABC\"}",
    "partition": "30",
    "enqueuedTime": "2020-01-23T16:46:35.594Z",
    "event_type": "FooEventType",
    "year": 2020,
    "month": 1,
    "day": 23}

My Python dataclasses and Factory Boy factories:
from dataclasses import dataclass
import factory

@dataclass
class Root:
  body: str
  partition: str
  enqueued_time: str
  event_type: str
  year: int
  month: int
  day: int

@dataclass
class Eventdata:
  count: str
  sourceid: str
  updatetime: str
  description: str

@dataclass
class Body:
  eventdata: Eventdata
  eventtime: str
  eventversion: str
  eventtype: str
  deviceid: str

class EventdataFactory(factory.Factory):
  class Meta:
    model = Eventdata
  count = "1"
  sourceid = "0"
  updatetime = "1579797993879"
  description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"

class BodyFactory(factory.Factory):
  class Meta:
    model = Body
  eventdata = factory.SubFactory(Eventdata)
  eventtime = "2020-01-23T16:46:35.522Z"
  eventversion = "1.0.0"
  eventtype = "FooEventType" # Note: It is the same in Root
  deviceid = "000000123ABC"

class RootFactory(factory.Factory):
  class Meta:
    model = Root
  body = "Escaped JSON String" # Need help here
  partition = "30"
  enqueuedTime = "2020-01-23T16:46:35.594Z"
  event_type = "FooEventType" # Note: It is the same in Body
  year = 2020
  month = 1
  day = 23

How do I create the escaped JSON string build from 'BodyFactory' for the body field in 'RootFactory'?

A: You can use Params to declare the "structured" body, and a LazyAttribute to convert it to JSON:
class RootFactory(factory.Factory):
    class Meta:
        model = Root

    class Params:
        body_raw = factory.SubFactory(BodyFactory)

    partition = 30
    enqueuedTime = "2020-01-23T16:46:35.594Z"

    # Copy Body.event_type to Root.event_type
    event_type = factory.SelfAttribute('.body_raw.event_type')

    # Convert `body_raw` to JSON
    body = factory.LazyAttribute(lambda o: json.dumps(o.body_raw))

In this model, the raw "Body" object is built as a SubFactory (in class Params), but only available during the factory evaluation: body_raw won't be passed to the dataclass constructor.
The body field is then built by encoding the contents to JSON - or any other custom method for converting a Body object to JSON.
NB: I've also used a factory.SelfAttribute to copy the event_type from BodyFactory to RootFactory.


text:
Q: Get IAM Role Name Using IAM Role ID All AWS IAM Roles have an associated Role Name and Role ID. The Role ID is not usually seen because the AWS Console displays just the Role Name. Inside the JSON message of an S3 Event there's a PrincipalID value that contains the Role ID of the role that was used to perform the S3 action e.g., "principalId":"AWS:AROAKJDKSDKF93HSA:123456789.
From this document we see,

Each IAM entity (user, group, or role) has a defined aws:userid
  variable. You will need this variable for use within the bucket policy
  to specify the role or user as an exception in a conditional element.
  An assumed-role's aws:userId value is defined as
  UNIQUE-ROLE-ID:ROLE-SESSION-NAME (for example,
  AROAEXAMPLEID:userdefinedsessionname).

So we know that the PrincipalId in the S3 Event message is a Role ID to an IAM Role. How can I use that Role ID to get the Role Name? I've searched through the IAM and STS libraries but I don't see any API that allows me to pass in the Role ID and get the Role Name. STS GetCallerIdentity doesn't help and IAM GetRole only accepts a Role Name as input.
Any help would be greatly appreciated. I am simply consuming S3 Events, reading the PrincipalID value from the S3 Event's message json, extracting the IAM Role ID from the PrincipalID, and I need a way to get the IAM Role Name using the IAM Role ID.

A: Here is a quick way to get it through AWS CLI:
aws iam list-roles --query 'Roles[?RoleId==`AROAEXAMPLEID`]'

A: Using python for example you can use list_roles.
The output will give you the role id of each role. Just loop it and search for RoleId you want.
{
    'Roles': [
        {
            'Path': 'string',
            'RoleName': 'string',
            'RoleId': 'string',
            'Arn': 'string',
            'CreateDate': datetime(2015, 1, 1),
            'AssumeRolePolicyDocument': 'string',
            'Description': 'string',
            'MaxSessionDuration': 123,
            'PermissionsBoundary': {
                'PermissionsBoundaryType': 'PermissionsBoundaryPolicy',
                'PermissionsBoundaryArn': 'string'
            },
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'RoleLastUsed': {
                'LastUsedDate': datetime(2015, 1, 1),
                'Region': 'string'
            }
        },
    ],
    'IsTruncated': True|False,
    'Marker': 'string'
}

RoleId (string)
  The stable and unique string identifying the role. For more information about IDs, see IAM Identifiers in the IAM User Guide.

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.list_roles
Also I recommend you to use Paginator.

Some AWS operations return results that are incomplete and require
  subsequent requests in order to attain the entire result set. The
  process of sending subsequent requests to continue where a previous
  request left off is called pagination

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html


text:
Q: В параграфе не подсвечиваются теги. Редактор Atom. В чём дело? В длинном параграфе необходимо было везде подчеркнуть пунктиром слово HTML, до определённого момента теги подсвечиваются красным, но в конце параграфа подсветка пропадает и они отображаются серым цветом. Что тут не так, ребят?

  HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoticg structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as <img /> and <input /> directly introduce content into the page. Other tags such as <p> surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page.


text:
Q: Simple way to implement a Collection? I am developing a collection class, which should implement IEnumerator and IEnumerable.
In my first approach, I implemented them directly. Now I have discovered the yield keyword, and I have been able to simplify everything a whole lot substituting the IEnumerator/IEnumerable interfaces with a readonly property Values that uses yield to return an IEnumerable in a loop.
My question: is it possible to use yield in such a way that I could iterate over the class itself, without implementing IEnumerable/IEnumerator?
I.e., I want to have a functionality similar to the framework collections:
List<int> myList = new List<int>();
foreach (int i in myList)
{
    ...
}

Is this possible at all?
Update: It seems that my question was badly worded. I don't mind implementing IEnumerator or IEnumerable; I just thought the only way to do it was with the old Current/MoveNext/Reset methods.

A: You won't have to implement IEnumerable<T> or IEnumerable to get foreach to work - but it would be a good idea to do so. It's very easy to do:
public class Foo : IEnumerable<Bar>
{
    public IEnumerator<Bar> GetEnumerator()
    {
        // Use yield return here, or
        // just return Values.GetEnumerator()
    }

    // Explicit interface implementation for non-generic
    // interface; delegates to generic implementation.
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

The alternative which doesn't implement IEnumerable<T> would just call your Values property, but still providing a GetEnumerator() method:
public class Foo
{
    public IEnumerator<Bar> GetEnumerator()
    {
        // Use yield return here, or
        // just return Values.GetEnumerator()
    }
]

While this will work, it means you won't be able to pass your collection to anything expecting an IEnumerable<T>, such as LINQ to Objects.
It's a little-known fact that foreach will work with any type supporting a GetEnumerator() method which returns a type with appropriate MoveNext() and Current members. This was really to allow strongly-typed collections before generics, where iterating over the collection wouldn't box value types etc. There's really no call for it now, IMO.

A: You could do somthing like this, but why? IEnumerator is already simple.
Interface MyEnumerator<T>
{
    public T GetNext();
}

public static class MyEnumeratorExtender
{
    public static void MyForeach<T>(this MyEnumerator<T> enumerator,
        Action<T> action)
    {
        T item = enumerator.GetNext();
        while (item != null)
        {
            action.Invoke(item);
            item = enumerator.GetNext();
        }
    }
}

I'd rather have the in keyword and I wouldn't want to rewrite linq.


text:
Q: Validation : Laravel In ContactsRequest.php
public function rules()
        {
            return [
                      'org_id' => 'required',
                      'name' => 'required',
                      'office' => 'required',
                      'mobile' => 'required_without:home',
                      'home' => 'required_without:mobile'
                   ];
        }

So basically what i want is , i have a form which will be taking the attributes specified in the code. But i want to modify code so that entering either one of 'home' or 'mobile' will allow me to create the new user.
What should be done.Any help would be appreciated


text:
Q: Access Custom Permission on a related User in Flow Let's say I have a Custom Permission Can_Do_the_Thing, which I've assigned to Users with a Permission Set.
Within Flow, I know that I can check if the running user has the Custom Permission using {!$Permission.Can_Do_the_Thing}.
However, is it possible to check if a related User (e.g., the record Owner) has the Custom Permission? Something like {!$Record.Owner.Permission.Can_Do_the_Thing}, or something like that? It really seems like this functionality should exist (and it would be quite useful), but I'm not able to find it.


text:
Q: JavaScript: How to redirect user to a page on the basis of selected item of "Datalist" I have this datalist for example:
    <datalist id ="List_1">
     <option value="Page 1">
     <option value="Page 2">
    </datalist>

    <input type = "search" name = "search" list = "List_1">

How can I redirect the user to Page 1 if he select "Page 1" when he selects it in the list.
  Thanks in advance~ !

A: It sounds like you really want a jump list and not a data list. But in any case , your listener should be something like this.
function(e){
    if (e.target.list.options[0]){
        /* location.href = ''; */
    }
}

A: As mentioned in other comments a jump list might be more appropriate. Where will you redirect a user to when they enter something in the input that is not in the datalist?
If you want to make sure that the value is one of the options from the datalist you'll have to do an exra check:
document.querySelector("input[name='search']").addEventListener('input', function(e){
   var input = e.target,
       val = input.value;
       list = input.getAttribute('list'),
       options = document.querySelectorAll('#'+list + ' option');

    for(var i = 0; i < options.length; i++) {
        var option = options[i];
        if(option.value === val) {
            // we have a match, go to the value url
            window.location.href = "http://example.com/" + val;
        }
    }

    // still here? no match found
    doSomethingElse();
});

A: You can use the following html combined with the javascript to redirect the page to the given link:
<datalist id="List_1">
   <option value="Page 1"></option>
   <option value="Page 2"></option>
</datalist>

<input type="search" name="search" list="List_1">

document.querySelector('input').oninput = function() {
   window.location.href = this.value;
};

Hope this helps


text:
Q: Can the integral of a function be larger than function itself? Are there any non zero(i.e not $f \equiv0  $) and non-negative continuous function $f$ defined on $[0,1]$, which satisfies $\int_0^x{f(t)}dt \geq f(x)~ \forall x$ in $[0,1]$?

A: No. Since $f$ is continuous on a compact set it is bounded and achieves both its minimum and maximum, $m=f(x_0)$ and $M=f(x_1)$. Since $f$ is non-constant these are distinct. Pick any $c\in(m,M)$. Without loss of generality assume $x_0<x_1$ By continuity there is some interval $(a,b)\in[0,1]$ containing $x_0$ on which $f<c$. Thus
$$\int_a^b f(t)dt \le \int_a^b cdt = c(b-a) < M(b-a)$$
Note the strict inequality.  Then
$$\int_0^{x_1} f(t)dt$$
$$=\int_0^a f(t)dt + \int_a^b f(t)dt + \int_b^{x_1} f(t)dt$$
$$\le M(a-0) + \int_a^b f(t)dt + M(x_1-b)$$
$$< M(a-0) + M(b-a) + M(x_1-b)$$
$$= Mx_1\le M=f(x_1)$$
Thus
$$\int_0^{x_1} f(t)dt < f(x_1)$$

A: Use the integrating factor $e^{-x}$ to find
$$
\frac{d}{dx}\left(e^{-x}\int_0^xf(s)ds\right)\le 0
$$
so that after integration
$$
e^{-x}\int_0^xf(s)ds-e^0·0\le 0
$$
and thus
$$
f(x)\le\int_0^xf(s)ds\le 0
$$
As $f$ is supposed to be non-negative, the only solution is the zero function.

See also Grönwall lemma.


text:
Q: C++ mysql LNK2019 errors only while building solution Error   LNK1120 6 unresolved externals
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall sql::SQLString::~SQLString(void)" (__imp_??1SQLString@sql@@QAE@XZ) referenced in function _main
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall sql::SQLString::SQLString(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??0SQLString@sql@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall sql::SQLString::SQLString(char const * const)" (__imp_??0SQLString@sql@@QAE@QBD@Z) referenced in function _main
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: __thiscall sql::SQLString::operator class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &(void)const " (__imp_??BSQLString@sql@@QBEABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function _main
Error   LNK2019 unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const & __thiscall sql::SQLString::asStdString(void)const " (__imp_?asStdString@SQLString@sql@@QBEABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function "bool __cdecl sql::operator!=(class sql::SQLString const &,class sql::SQLString const &)" (??9sql@@YA_NABVSQLString@0@0@Z)
Error   LNK2019 unresolved external symbol __imp__get_driver_instance referenced in function _main

This only happens while building the project not compiling
I've looked all over for a solution and just can't find one tried different libraries and all come out with this issue
#include "driver/mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
int main()
{
string Username;
string Pass;

try {
    sql::ResultSet *res;
    sql::ResultSet *res2;
    sql::Driver *driver;
    sql::Connection *con;
    sql::Statement *stmt;

    bool loggingin = true;
    driver = get_driver_instance();
//place holder text not actualy there
con = driver->connect("[host]", "[username]", "[password]");

    con->setSchema("Information");
    stmt = con->createStatement();
    res = stmt->executeQuery("Get Password where Username = '" + Username + "'");
    res2 = stmt->executeQuery("Get HWID where Username = '" + Username + "'");
    while (loggingin) {
        printf("Please Type Your Username: \n >>");
        cin >> Username;
        printf("Please Type Your Password: \n >>");
        cin >> Pass;

        res = stmt->executeQuery("Get Password where Username = '" + Username + "'");

        string password = res->getString(1);
        ;

        while (res->next()) {
            if (res->getRow() == 0 || password != Pass) {
                printf("Username or Password Wrong");

            }
            else {

                if (res2->getString(1) != getHWID()) {
                    exit(1);

                }
                else {
                    loggingin = false;

                }

            }

            break;
        }

    }
    delete con;
    delete res;
    delete res2;

    delete stmt;
}
catch (sql::SQLException &e) {

    system("cls");
    printf("please reload");
    while (true) {
        Sleep(1);

    }
}

I just want it to build there are no other issues just it cant build

A: Fixed by adding mysqlcppconn.lib and mysqlcppconn-static.lib to Linker>Input>Additional Dependancy


text:
Q: Eclipse: The project was not built since its build path is incomplete. Cannot find guava Predicate I am using new Eclipse Oxygen. My project setup includes Maven. One of the Maven dependencies is Guava:
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>20.0</version>
    </dependency>

There are 2 problems I am facing that do not allow me to build the project:
1.
The project was not built since its build path is incomplete. Cannot find the class file for com.google.common.base.Predicate. Fix the build path then try building this project
2.
The type com.google.common.base.Predicate cannot be resolved. It is indirectly referenced from required .class files [...] Java Problem

Here is what I tried to solve it:
I have made clean & build of my project; I have closed and then reopened it; I have removed it from Eclipse and then re-imported and made clean & build.
Nothing seems to help.
Anyone has any ideas? This is super annoying.

A: The problem was not related to Eclipse, but it was a maven issue.
In order to fix it I had to clear ~/.m2/repository folder and run Maven->Update Project in Eclipse.

A: Eclipse by default uses embedded Maven. It is possible, that the guava dependency got corrupted in the embedded Maven's .m2 folder. Try to delete it from there.
Also try to change the Maven in Eclipse to use the same Maven as you use in the command line in:
  Preferences->Maven->Installations


text:
Q: Show hidden files IN SELECT folders only How do I show hidden files in one directory only? I have a development folder that I'd like to see hidden files in, but I don't want to see hidden files anywhere else on my computer.
Here is the code I tried in the terminal to show all hidden files but it's not what I want. Thanks!
    defaults write com.apple.finder AppleShowAllFiles TRUE
    killall Finder


text:
Q: Multiple listviws and rows - Flutter So Apperently I am doing this wrong (according to flutter)
 body:
          ListView.builder(itemBuilder: (context, index){
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: <Widget>[
                    Text(
                      'Text me'
                    )]
                    )
                )
              ),
            ),
          }),
      Row(
        children: <Widget>[
          Expanded(
            child: new RaisedButton(
              padding: const EdgeInsets.all(8.0),
              textColor: Colors.white,
              color: Colors.blue,
              onPressed: () async { await changestation('http://stream.radiomedia.com.au:8015/stream'); },

              child: new Text("Change Station"),
            ),
          ),
          Expanded(
            child: Text('Craft beautiful UIs', textAlign: TextAlign.center),
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.contain, // otherwise the logo will be tiny
              child: const FlutterLogo(),
            ),
          ),
        ],
      ),

The error I am getting is:
Too many positional arguments: 0 expected, but 1 found.  Try removing the extra positional arguments, or specifying the name for named arguments.

A: you have to wrap everything in Column then wrap your ListView.builder with expanded.Like this
Column(
         children: [ Expanded(
           child: ListView.builder(itemBuilder: (context, index){
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: <Widget>[
                    Text(
                      'Text me'
                    )]
                    )
                )
            );
          })),
      Row(
        children: <Widget>[
          Expanded(
            child: new RaisedButton(
              padding: const EdgeInsets.all(8.0),
              textColor: Colors.white,
              color: Colors.blue,
              onPressed: () async {  await changestation('http://stream.radiomedia.com.au:8015/stream');
                                   },

              child: new Text("Change Station"),
            ),
          ),
          Expanded(
            child: Text('Craft beautiful UIs', textAlign: TextAlign.center),
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.contain, // otherwise the logo will be tiny
              child: const FlutterLogo(),
            ),
          ),
        ],
      ),
                      ])

let me know if this work.


text:
Q: MySQL Query, get a column value by a list of rowid's, including duplicate results in result //List of id's I want displayname for
$IDListSQL = '10,10,10,11,10,10';
//My query statement
$q = "SELECT displayname FROM accounts WHERE id IN($IDListSQL)";
//Executes query
$Res = $DB->Query($q);
//Gets all results
$Rows = $Res->fetch_all();
echo var_dump($Rows);
//Output
#->array(2)
{
   [0]=> array(1)
   {
       [0]=> string(14) "Apple"
   }
   [1]=> array(1)
   {
       [0]=> string(10) "Orange"
   }
}

The behaviour I want is an array with all the displayname's in the $IDListSQL, even if its the same ID. I also want them in the order I specified. Trying to figure this out in 1 query rather than doing up to 16 separate select queries for the purpose this is for. Any help would be appreciated kindly.

A: I ended up getting this done with PHP since I already had an array of ID's in the specified order. Used my same query to only get one of each ID, then joined the data into my array with the help of a couple for loops. Appreciate the help, Ctznkane525 I think what you posted would work. It sounds like it is doing the same thing I done up in PHP, trying not to use complex queries unless absolutely necessary. Speed and high ccu is critical for this app.


text:
Q: Python: CalledProcessError, command returned non-zero exit status 1 I am getting this error
Command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned non-zero exit status 1.

here is what I want to achieve.
def get_queries(filename, num_queries=3):
    scored_chunks = []
    absolute_file_path = os.path.join(settings.MEDIA_ROOT, filename)
    # pdf_to_text_output = subprocess.check_output([settings.PDF_TO_TEXT, "-layout", absolute_file_path, "-"], shell=true)
    pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True)
    try:
        text = pdf_to_text_output.decode('utf-8')
    except UnicodeDecodeError:
        text = pdf_to_text_output.decode('ISO-8859-1')
    [..]

I am new to Django and python, I have tried many solutions but nothing is working for me. because I don't know how it works.
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/index/

Django Version: 3.1.2
Python Version: 3.7.4

here is the full traceback.
Traceback (most recent call last):
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47,
    in inner response = get_response(request)
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179,
    in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 70,
    in view return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 98,
    in dispatch return handler(request, *args, **kwargs)
  File "C:\Users\Farhana Noureen\plagtrap\main\views.py", line 302,
    in post results = process_homepage_trial(request)
  File "C:\Users\Farhana Noureen\plagtrap\main\services.py", line 435,
    in process_homepage_trial queries = pdf.get_queries(filename)
  File "C:\Users\Farhana Noureen\plagtrap\util\getqueriespertype\pdf.py", line 18,
    in get_queries pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True)
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 395,
    in check_output **kwargs).stdout
  File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 487,
    in run output=stdout, stderr=stderr)

  Exception Type: CalledProcessError at /index-trial/
  Exception Value: Command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned non-zero exit status 1.

the problem is with the check_output function of the subprocess. I don't know how to rectify this issue.

A: I can't comment, so I can't ask for clarification, but I believe you are trying to run a subprocess that runs a shell command, the name of which is contained within Django's settings.PDF_TO_TEXT variable, and run it on the file absolute_file_path. If so, those two variables shouldn't be in quotes in the subprocess.call arguments:
def get_queries(filename, num_queries=3):
    scored_chunks = []
    absolute_file_path = os.path.join(settings.MEDIA_ROOT, filename)
    pdf_to_text_output = subprocess.check_output([
        settings.PDF_TO_TEXT,
        "-layout",
        absolute_file_path,
        "-",
    ], shell=True)
    try:
        text = pdf_to_text_output.decode('utf-8')
    except UnicodeDecodeError:
        text = pdf_to_text_output.decode('ISO-8859-1')
    ...

The reason here is that subprocess.check_output (and its underlying subprocess.run) do not take strings and parse them into Python variables. The Python parser will first convert the variables settings.PDF_TO_TEXT and absolute_file_path into strings (I assume that's what the variables hold), and then that list of strings will be passed to subprocess.check_output, which just carries them to the shell.


text:
Q: If $T$ is diagonalizable and $c_1,…,c_k$ are distinct eigenvalues of $T$, then minimal polynomial of $T$ is $(x-c_1)\dotsb (x-c_k)$
Let $V$ be $n$-dimensional vector space over $F$ and $T\in L(V,V)$. If $T$ is diagonalizable and $c_1,…,c_k$ are distinct eigenvalues of $T$, then $m_T=p=(x-c_1)\dotsb (x-c_k)$.

My attempt: We need to show $p$ is monic, $p(T)=0$ and if $f\in F[x]$ such that $f(T)=0$, then $\deg (p)\leq \deg (f)$. Clearly $p$ is monic. By theorem 3 section 6.3, $c_1,…,c_k$ are roots of $m_T$. By this post, $k\leq \deg (m_T)$. It's easy to check, $\deg (p)=k$. So $\deg (p)\leq \deg (m_T)\leq \deg (f)$. We claim $p(T)=0$. Since $T$ is diagonalizable, $\exists B=\{\alpha_1,…,\alpha_n\}$ basis of $V$ such that $\alpha_i$ is eigenvector of $T$, $\forall i\in J_n$. Let $\alpha_i\in B$. Then $\exists c_j\in F$ such that $T(\alpha_i)=c_j\cdot \alpha_i$. Since $F[x]$ is commutative linear algebra over $F$, we have $p=(x-c_1)\dotsb (x-c_k)=(x-c_1)\dotsb (x-c_{j-1})(x-c_{j+1})\dotsb (x-c_k)(x-c_{j})$. So $p(T)=(T-c_1I)\dotsb (T-c_jI)$. Since $(T-c_jI)(\alpha_i)=0$, we have $[p(T)](\alpha_i)=0$. Since $\alpha_i$ was arbitrary, $[p(T)](\alpha_i)=0$, $\forall i\in J_n$. Thus $p(T)=0$. By uniqueness, $m_T=p$. Is my proof correct?

A: While I can see no errors in your argument, I would say it achieves this easy result in a rather roundabout way. Note for instance that you introduce an arbitrary annihilating polynomial $f$ but never really use it in the argument; you go straight for the minimal polynomial $m_T$ instead. Which is valid if you know that the minimal polynomial exists: any monic annihilating polynomial whose degree does not exceed that of the minimal polynomial is the minimal polynomial, though there is an smell of circularity when using that in an argument.
I would use the main fact about polynomials in $T$ and eigenvectors instead, namely that $P[T](v)=P[\lambda](v)$ for any polynomial $T$, whenever $T(v)=\lambda v$. For a polynomial $P(T)$ in a diagonalisable $T$ to be $0$, it suffices that it kills all eigenvectors (for it will then be zero on the sum of eigenspaces, which is the whole space), and for this one must have $P[\lambda]=0$ whenever $\lambda$ is an eigenvalue of $T$. Clearly the minimal degree monic polynomial with this property is the product of factors $X-\lambda$ for $\lambda$ running over all distinct eigenvalues.


text:
Q: Getting date/time of creation of a file This seems like a pretty straightforward question but I haven't been able to find a definitive answer anywhere online. How can I get the date/time a file was created through Java's file manager? Aside from just the name of a file, what else can I get about the file's "properties"?

A: I'm not sure how you'd get it using Java 6 and below. With Java 7's new file system APIs, it'd look like this:
Path path = ... // the path to the file
BasicFileAttributes attributes =
    Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();

As CoolBeans said, not all file systems store the creation time. The BasicFileAttributes Javadoc states:

If the file system implementation does not support a time stamp to indicate the time when the file was created then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z).


text:
Q: mac npm install mysql-libmysqlclient error OS:Mac OS X Lion 10.7.3(64bit)
Xcode:4.3.2
Command Line Tools:installed
gcc:4.2
g++:4.2
node:0.6.16
npm:1.1.20
mysql:5.5.21
I try install npm-modules of mysql-libmysqlclient, I installed success on CentOS 6.2, but the OS has problem, this talk about its https://github.com/Sannis/node-mysql-libmysqlclient/issues/107#issuecomment-5485498
localhost:nodejs yangzhaojie$ npm -d install mysql-libmysqlclient
npm info it worked if it ends with ok
npm info using npm@1.1.20
npm info using node@v0.6.16
npm http GET https://registry.npmjs.org/mysql-libmysqlclient
npm http 200 https://registry.npmjs.org/mysql-libmysqlclient
npm http GET https://registry.npmjs.org/mysql-libmysqlclient/-/mysql-libmysqlclient-1.3.2.tgz
npm http 200 https://registry.npmjs.org/mysql-libmysqlclient/-/mysql-libmysqlclient-1.3.2.tgz
npm info shasum 8ae08483d5e37fcb5a37e6e459c7eda073ff486b
npm info shasum /var/folders/bc/gxqr_gj55lg1x77dgcym3mmc0000gn/T/npm-1336054761009/1336054761009-0.6183159125503153/tmp.tgz
npm info shasum 2e0901d4c28613050078931d2930b7f98a9353d0
npm info shasum /Users/yangzhaojie/.npm/mysql-libmysqlclient/1.3.2/package.tgz
npm info into /Users/yangzhaojie/tech/nodejs mysql-libmysqlclient@1.3.2
npm info installOne mysql-libmysqlclient@1.3.2
npm info unbuild /Users/yangzhaojie/tech/nodejs/node_modules/mysql-libmysqlclient
npm info preinstall mysql-libmysqlclient@1.3.2
npm info build /Users/yangzhaojie/tech/nodejs/node_modules/mysql-libmysqlclient
npm info linkStuff mysql-libmysqlclient@1.3.2
npm info install mysql-libmysqlclient@1.3.2

> mysql-libmysqlclient@1.3.2 install /Users/yangzhaojie/tech/nodejs/node_modules/mysql-libmysqlclient
> node-gyp rebuild

info it worked if it ends with ok
spawn python [ '/Users/yangzhaojie/.node-gyp/0.6.16/tools/gyp_addon',
  'binding.gyp',
  '-I/Users/yangzhaojie/tech/nodejs/node_modules/mysql-libmysqlclient/build/config.gypi',
  '-f',
  'make' ]
spawn make [ 'BUILDTYPE=Release', '-C', 'build' ]
  CXX(target) Release/obj.target/mysql_bindings/src/mysql_bindings.o
  CXX(target) Release/obj.target/mysql_bindings/src/mysql_bindings_connection.o
../src/mysql_bindings_connection.cc:1322:22: error: variable length array of non-POD element type 'Local<v8::Value>'
    Local<Value> argv[argc];
                     ^
../src/mysql_bindings_connection.cc:1627:22: error: variable length array of non-POD element type 'Local<v8::Value>'
    Local<Value> argv[argc];
                     ^
../src/mysql_bindings_connection.cc:1691:22: error: variable length array of non-POD element type 'Local<v8::Value>'
    Local<Value> argv[argc];
                     ^
3 errors generated.
make: *** [Release/obj.target/mysql_bindings/src/mysql_bindings_connection.o] Error 1
ERR! Error: `make` failed with exit code: 2
    at ChildProcess.onExit (/Users/yangzhaojie/app/node-0.6.16/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:209:23)
    at ChildProcess.emit (events.js:70:17)
    at maybeExit (child_process.js:362:16)
    at Process.onexit (child_process.js:398:5)
ERR! not ok
npm info mysql-libmysqlclient@1.3.2 Failed to exec install script
npm info unbuild /Users/yangzhaojie/tech/nodejs/node_modules/mysql-libmysqlclient
npm info preuninstall mysql-libmysqlclient@1.3.2
npm info uninstall mysql-libmysqlclient@1.3.2
npm info postuninstall mysql-libmysqlclient@1.3.2

npm ERR! mysql-libmysqlclient@1.3.2 install: `node-gyp rebuild`
npm ERR! `sh "-c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the mysql-libmysqlclient@1.3.2 install script.
npm ERR! This is most likely a problem with the mysql-libmysqlclient package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls mysql-libmysqlclient
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Darwin 11.3.0
npm ERR! command "node" "/Users/yangzhaojie/app/node-0.6.16/bin/npm" "-d" "install" "mysql-libmysqlclient"
npm ERR! cwd /Users/yangzhaojie/tech/nodejs
npm ERR! node -v v0.6.16
npm ERR! npm -v 1.1.20
npm ERR! code ELIFECYCLE
npm ERR! message mysql-libmysqlclient@1.3.2 install: `node-gyp rebuild`
npm ERR! message `sh "-c" "node-gyp rebuild"` failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/yangzhaojie/tech/nodejs/npm-debug.log
npm not ok
localhost:nodejs yangzhaojie$

A: Did you execute the
npm -d install mysql-libmysqlclient

as superuser?
Try
sudo npm -d install mysql-libmysqlclient

A: wangmingle@wangmingle01 //
$ npm -d install mysql
npm info it worked if it ends with ok
npm info using npm@1.0.106
npm info using node@v0.4.7
npm info addNamed [ 'mysql', '' ]
npm info fetch http:/registry.npmjs.org/mysql/-/mysql-0.9.6.tgz
npm info shasum 95a3a9f41f94353c6460664b5867997e88b625bc
npm info shasum /tmp/npm-1337774338269/1337774338269-0.257753849029541/tmp.tgz
npm info shasum 7f9fab740989daba691215768ada0d8c36dd477f
npm info shasum /home/wangmingle/.npm/mysql/0.9.6/package.tgz
npm info into / mysql@0.9.6
npm info installOne mysql@0.9.6
npm info unbuild /node_modules/mysql
npm info preinstall mysql@0.9.6
npm info addNamed [ 'hashish', '0.0.4' ]
npm info fetch http:/registry.npmjs.org/hashish/-/hashish-0.0.4.tgz
npm info shasum 6d60bc6ffaf711b6afd60e426d077988014e6554
npm info shasum /tmp/npm-1337774338269/1337774360833-0.05971289472654462/tmp.tgz
npm info shasum 08ecd695975ee21ddb4b6f3e76e288dec99b2617
npm info shasum /home/wangmingle/.npm/hashish/0.0.4/package.tgz
npm info into /node_modules/mysql hashish@0.0.4
npm info installOne hashish@0.0.4
npm info unbuild /node_modules/mysql/node_modules/hashish
npm info preinstall hashish@0.0.4
npm info addNamed [ 'traverse', '>=0.2.4' ]
npm info fetch http:/registry.npmjs.org/traverse/-/traverse-0.6.1.tgz
npm info shasum abba3297d8cd608796189e9bbcda6c7fc6b7a4f9
npm info shasum /tmp/npm-1337774338269/1337774387669-0.5074084696825594/tmp.tgz
npm info shasum 636da24fb8f438ec6b1ca39a6a4f07e130e9aea0
npm info shasum /home/wangmingle/.npm/traverse/0.6.1/package.tgz
npm info into /node_modules/mysql/node_modules/hashish traverse@0.6.1
npm info installOne traverse@0.6.1
npm info unbuild /node_modules/mysql/node_modules/hashish/node_modules/traverse
npm info preinstall traverse@0.6.1
npm info build /node_modules/mysql/node_modules/hashish/node_modules/traverse
npm info linkStuff traverse@0.6.1
npm info install traverse@0.6.1
npm info postinstall traverse@0.6.1
npm info build /node_modules/mysql/node_modules/hashish
npm info linkStuff hashish@0.0.4
npm info install hashish@0.0.4
npm info postinstall hashish@0.0.4
npm info build /node_modules/mysql
npm info linkStuff mysql@0.9.6
npm info install mysql@0.9.6
npm info postinstall mysql@0.9.6
mysql@0.9.6 /node_modules/mysql
└── hashish@0.0.4
npm info ok


text:
Q: convert nested dict values in pyspark/pandas dataframe to column and rows I have a pyspark dataframe with only one record.  it contains an id field and a "value" field.  the value field contains nested dicts like the example record shown in the inputdf below.  I would like to create a new dataframe like the outputdf below, where the type column is the keys from the nested dict in the value field in inputdf, and the value and active columns contain corresponding values from the nested dicts.  if it's easier, the dataframe could be converted to a pandas dataframe using .toPandas().  does anyone have a slick way to do this?
inputdf:
id value
1  {"soda":{"value":2,"active":1},"jet":{"value":0,"active":1}}

outputdf:
type  value active
soda  2     1
jet   0     1

A: Let us try , notice here I also include the id column
yourdf = pd.DataFrame(df.value.tolist(),index=df.id).stack().apply(pd.Series).reset_index()
Out[13]:
   id level_1  value  active
0   1    soda      2       1
1   1     jet      0       1


text:
Q: How to center right-aligned numbers in table column using CSS? The picture below illustrates what I'm trying to accomplish:

UPD. As you see, I need the longest number to be centered in its cell, and all other numbers to be right aligned to the longest number's right border.
UPD 2. The numbers are dynamic (unknown initially).

A: Seems to me that you need to have a second table inside your main table to determine the width of the numbered content to be centered but right aligned.  Checkout out this fiddle: Fiddle Example
Example Code:
HTML:

Some Title for Numbers in a Table

5 000 000

5 000

5

5 000 000

CSS:
.container {
    width: 400px;
    border: 1px solid #999;
}

.title {
    font-weight: bold;
    text-align: center;
}

.container table {
    margin: 0px auto;
}

.container table td {
    text-align: right;
}

A: Ok I encountered this problem yesterday , went through all the solutions and came up with my own solution that does not modify the DOM in a significant manner but uses JS but I will list the drawbacks of some of the solutions above

*

*Padding extra characters works if your font is monospace

*Creating a fixed padding or fixed width may affect responsive behavior

*Adding a second table inside column is serious DOM manipulation, if you have a 1000 rows and 30 columns, you will start seeing the effects of performance with such a heavy tree

HTML (Using Bootstrap 4.1.1)

      #
      Symbol
      Price
      Volume
      Market Cap
      Circulating Supply
      Total Supply

CSS
.numeric{
  text-align: right;
}

#datatable th, #datatable td{
  text-align: center;
}

.centerspan{
  display: inline-block;
  text-align: right;
  background: yellow;
}

.root-rank, .root-price, .root-market_cap, .root-max_supply{
  background: #efefef;
}

JavaScript
var overview_data = [
    { "rank": 1, "symbol": "BTC", "price": 8004.8, "volume_24h": 5864600000000.0, "market_cap": 137422500058.0, "circulating_supply": 17167512.0, "max_supply": 21000000.0},
    { "rank": 2, "symbol": "ETH", "price": 471.305, "volume_24h": 1930260000.0, "market_cap": 47547607782.0, "circulating_supply": 100885006.0, "max_supply": null},
    { "rank": 3, "symbol": "XRP", "price": 0.454852, "volume_24h": 234947000.0, "market_cap": 17882817260.0, "circulating_supply": 39315683476.0, "max_supply": 100000000000.0},
    { "rank": 4, "symbol": "Bitcoin Cash", "price": 845.04, "volume_24h": 730498000.0, "market_cap": 14580563109.0, "circulating_supply": 17254288.0, "max_supply": 21000000.0},
    { "rank": 5, "symbol": "EOS", "price": 8.14097, "volume_24h": 691908000.0, "market_cap": 7295526131.0, "circulating_supply": 896149492.0, "max_supply": 1000000000.0}
]

var table = document.getElementById("datatable")
var thead = table.tHead
var tbody = table.tBodies[0]
var colClasses = []

for(var i = 0, len= overview_data.length; i < len; i++){
  var tr = document.createElement("tr")
  for(var j in overview_data[i]){
    var td = document.createElement("td")
    td.classList.add("root-" + j)
    var span = document.createElement("span")
    span.classList.add("centerspan")
    span.classList.add('col-' + j)

    //Add this column classes to keep track of one class per column
    if (!colClasses.includes("col-" + j)){
       colClasses.push('col-' + j)
    }
    var text = document.createTextNode(overview_data[i][j] || -1)
    if(!isNaN(overview_data[i][j])){
      td.classList.add("numeric")
    }
    span.appendChild(text)

    td.appendChild(span)
    tr.appendChild(td)
  }
  tbody.appendChild(tr)
}

//This is the main part
for(var i = 0; i < colClasses.length; i++){
  var items = document.querySelectorAll("." + colClasses[i])
  var max = 0

  //Loop through all the items in the col class
  for(var j = 0; j < items.length; j++){
    //Calculate max width of span containing text inside column
    if(items[j].offsetWidth > max){
       max = items[j].offsetWidth
    }
  }

  //Set width of each span to the max width
  for(var j = 0; j < items.length; j++){
    console.log(max)
    items[j].style.width = max + "px"
  }
}

Snapshot

A: There doesn't seem to be any direct CSS method. But you could consider the approach suggested by @CMKanode in a comment. You would need to preprocess the numbers in the column and compute the largest of them (this requires locale-sensitive parsing since you are using a thousands separator), and then you would left-pad the numbers to the same number of characters, using U+2007 FIGURE SPACE as a space that has the same width as digits. And, of course, the column would be declared as centered.
So in the example, "5" would be padded to         5 (assuming you use a normal space as thousands separator; U+2009 THIN SPACE might be better, but it has font issues.
The approach would mean that you need to use a font where digits have the same width (most fonts in computers do) and that contains U+2007.
If the thousands separator were a comma or a period, for example, you would need to use U+2008 PUNCTUATION SPACE in its stead.
In the end, I think this would be excessively complicated. It is probably better to make the column right-aligned but with a suitable left and right padding, selected as a good guess based on the width of the column header and the expected widths of the numbers.

A: Below is not an ideal solution, since the size of the numbers are initially unknown, but it's a little closer without too much additional tags.
CSS:
.numSpan {
    display: inline-block;
    width: 100px;
    text-align: right;
}
td { text-align: center; }

HTML:

    5

A: Add a div to td:

Text Aligned Right

Then add padding / margins to fine tune the placement of the div.

A: You can approximate this with CSS. Create a class:
td.rt-ctr {
  text-align:right;
  padding-right:33%;
}

Then call the class in your chart:

    Item 1
    100.25

    Item 2
    99.75

Depending upon the width of the column, chart and longest data entry, you may need to adjust the percentage in the CSS. This approach isn't perfect, but it is responsive and is a pure CSS method.

A: If I understood correctly, you want something like:
 .right-td { align:right; }

going with
5000000

A: I believe the actual td in that table (if it is indeed a table) will have a fixed width, and lots of padding to give the illusion that it's centre-right-aligned.
You could try a crude style such as this:
/* For demonstration purposes, a fixed width `th`. */
th.headrowrnum {
    width: 200px;
}

td.rightalignnum {
    width: 100px;
    padding: 0 50px;
    text-align: right;
}

HTML:

        Col 1
        Col 2

        X
        5

>

        Y
        500

A: To achieve that alignment, you should do something like this:
HTML:

        12345

CSS:
.my_td
{
    width: 200px;
    align: center;
}

.content
{
    width: 100px;
    margin-left: auto;
    margin-right: auto;
    text-align: right;
}

You just need to adapt the widths to meet your requirements, for instance, max digits in the number.

A: Another possible solution is to use media queries.  In our case, we have roughly the same number of columns in every table.  So, just change the right padding based on screen size to give the desired right/center alignment:
@media (min-width: 769px)
{
   td
   {
      &.financial
      {
         padding-right: 5px;
      }
   }
}

@media (min-width: 1100px)
{
   td
   {
      &.financial
      {
         padding-right: 20px;
      }
   }
}

@media (min-width: 1400px)
{
   td
   {
      &.financial
      {
         padding-right: 30px;
      }
   }
}

A: In CSS, do this to center-align td
td {text-align:center;}


text:
Q: How to bulk insert data using SQLAlchemy ORM where some fields not exists? I have some tables
node = Table(
    "node",
    metadata_obj,
    Column("node_id", Integer, primary_key=True),
    Column("primary_element", Integer, ForeignKey("element.element_id")),
)

element = Table(
    "element",
    metadata_obj,
    Column("element_id", Integer, primary_key=True),
    Column("parent_node_id", Integer),
    ForeignKeyConstraint(
        ["parent_node_id"], ["node.node_id"], name="fk_element_parent_node_id"
    ),
)

How i can bulk insert into node table if primary_element fields not exists in inserting
And then buld insert into element if some row haven't element_id and node_id from node table?
from app import session
from models import User

objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()

I thought the best solution would be to use add.all(). But I don't know how to add not exists


text:
Q: Google app script : call another function after reached last row on google sheet May I don't know how to call another function when reached last row of register code column on google sheet, users click the submit on google form will auto email out another sendMail function
to said that eg 'registration had been closed, thank you.'

my code :
function sendmail() {

  var ss = SpreadsheetApp.getActive();
  var sh1 = ss.getSheetByName("Sheet1");
  var EMAIL_SENT = "EMAIL_SENT";

  var lastRow = sh1.getLastRow();

  var email = sh1.getRange(lastRow, 2).getValue();
  var name = sh1.getRange(lastRow, 1).getValue();
  var registercode = sh1.getRange(lastRow, 3).getValue();

  subjecttxt = "Thank you for registered with us"
  email_Body = "Dear " + name + "," + "
" +
              "your registeration is successfully, your registered code is " + registercode +
              "Thank you for your registeration"

              MailApp.sendEmail({
                to:email,
                subject: subjecttxt,
                htmlBody: email_Body,
              }) ;
  sh1.getRange(lastRow, 4).setValue(EMAIL_SENT);
}

A: I believe your goal is as follows.

*

*In your situation, the values are put to the columns "A" and "B". At that time, your function sendmail is run. At this time, when the values are put to the columns "A" and "B", when the row is over the last row of the column "C", you want to send an email body of registration had been closed, thank you..

If my understanding is correct, how about the following modification?
Modified script:
function sendmail() {
  // This is from https://stackoverflow.com/a/44563639
  Object.prototype.get1stEmptyRowFromTop = function (columnNumber, offsetRow = 1) {
    const range = this.getRange(offsetRow, columnNumber, 2);
    const values = range.getDisplayValues();
    if (values[0][0] && values[1][0]) {
      return range.getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow() + 1;
    } else if (values[0][0] && !values[1][0]) {
      return offsetRow + 1;
    }
    return offsetRow;
  };

  var ss = SpreadsheetApp.getActive();
  var sh1 = ss.getSheetByName("Sheet1");
  var EMAIL_SENT = "EMAIL_SENT";
  var lastRow = sh1.get1stEmptyRowFromTop(1) - 1;
  var email = sh1.getRange(lastRow, 2).getValue();
  var name = sh1.getRange(lastRow, 1).getValue();
  var registercode = sh1.getRange(lastRow, 3).getValue();
  var subjecttxt = "Thank you for registered with us";
  var email_Body;
  if (lastRow < sh1.get1stEmptyRowFromTop(3)) {
    email_Body = "Dear " + name + "," + "
" + "your registeration is successfully, your registered code is " + registercode + "Thank you for your registeration";
  } else {
    email_Body = "registration had been closed, thank you.";
  }
  MailApp.sendEmail({
    to: email,
    subject: subjecttxt,
    htmlBody: email_Body,
  });
  sh1.getRange(lastRow, 4).setValue(EMAIL_SENT);
}

*

*About if (lastRow < sh1.get1stEmptyRowFromTop(3)) {,,,}, in this script, when the values of columns "A" and "B" are put to the next row of the last row of the column "C", email_Body = "registration had been closed, thank you." is used. When you want to use this email_Body at the last row of the column "C", please modify (lastRow < sh1.get1stEmptyRowFromTop(3)) to (lastRow < sh1.get1stEmptyRowFromTop(3) - 1).

*When you want to add "registration had been closed, thank you." to email_Body, when the values are put to the same row of the last row of the column "C", please modify the above if statement as follows.
  if (lastRow < sh1.get1stEmptyRowFromTop(3) - 1) {
    email_Body = "Dear " + name + "," + "
" + "your registeration is successfully, your registered code is " + registercode + "Thank you for your registeration";
  } else {
    email_Body += "registration had been closed, thank you.";
  }


text:
Q: I am having a problem in the game I coded in JS/DOM (problem described in the body) I have coded this "sort of chess game" where the goal is to place 8 queens without them being able to hit each other, so far I have made the whole program and it is working wonderful! I just have one problem, you are able to place a queen on top of another queen. If you do this the game automatically stops. If anyone have any idea on how I can fix this problem, it would mean a lot!!!! (There are also some norwegian variable names in the code, if you need any translation or things like that I will gladly help with that)
Thanks in advance!!!

let knappEl = document.querySelector("button")
knappEl.addEventListener("click", restart)

let tableEl = document.querySelector("table")
let liste = []
let turTeller = 0
let slatt = false
let meldingEl = document.querySelector("#melding")

for (let i = 1; i < 9; i++) {
  let trEl = document.createElement('tr');
  for (let j = 1; j < 9; j++) {
    let tdEl = document.createElement('td');
    tdEl.setAttribute("id", "rute" + i + j)
    tdEl.addEventListener("click", plasserTårn)
    trEl.appendChild(tdEl);
    // Bare på grunn av css
    tdEl.className = (i % 2 === j % 2) ? "hvit firkant" : "svart firkant";
  }
  tableEl.appendChild(trEl);
}

function plasserTårn(e) {
  if (slatt == false) {
    let trykketFirkant = e.target
    let plassertBrikke = {
      rad: trykketFirkant.id.substring(5, 4),
      kolonne: trykketFirkant.id.substring(6, 5)
    }
    console.log(liste)
    console.log(plassertBrikke)
    if (turTeller == 0) {
      if (firkantTrykket = e.target) {
        firkantTrykket.innerHTML = "";
      }
      turTeller = 1
    } else if (turTeller == 1) {
      if (firkantTrykket = e.target) {
        firkantTrykket.innerHTML = "";
      }
      turTeller = 0
    }
    for (let i = 0; i < liste.length; i++) {
      let r = Math.abs(liste[i].rad - plassertBrikke.rad)
      let k = Math.abs(liste[i].kolonne - plassertBrikke.kolonne)
      if (liste[i].rad == plassertBrikke.rad || liste[i].kolonne == plassertBrikke.kolonne || r == k) {
        meldingEl.innerHTML = "En dronning har blir slått"
        window.scrollTo(0, document.body.scrollHeight);
        slatt = true
      } else if (liste.length == 7) {
        meldingEl.innerHTML = "Du har vunnet!"
        window.scrollTo(0, document.body.scrollHeight);
        slatt = true
      }
    }
    liste.push(plassertBrikke)
  } else {
    meldingEl.innerHTML = "Spillet er over!"
  }
}

function restart() {
  location.reload()
  window.scrollTo(500, 0);
}
body {
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  height: 100%;
  text-align: center;
  font-size: 18px;
  background-color: blueviolet;
  color: white
}

h1,
h2,
h3 {
  font-family: 'Roboto', sans-serif;
  font-weight: 100;
  text-transform: uppercase;
  margin: 5px 0;
}

h1 {
  font-size: 2.6em;
}

h2 {
  font-size: 1.6em;
}

h3 {
  font-size: 2.6rem;
  color: white;
  text-align: center;
  text-shadow: 5px 2px purple;
}

p {
  font-size: 1.6em;
  color: white;
  text-align: center;
  text-shadow: 5px 2px purple;
}

.board {
  table-layout: fixed;
  margin-left: auto;
  margin-right: auto;
  width: 440px;
  height: 440px;
  border: 32px solid;
  border-color: darkslategray;
  border-radius: 5px;
}

.firkant {
  resize: none;
  height: 55px;
  width: 55px;
  text-align: center;
  border: -1px black solid;
}

.hvit {
  background: white;
}

.svart {
  background: grey;
}

td:hover {
  background: lightgreen;
  cursor: pointer
}

button {
  color: rgb(150, 12, 177);
  border: solid 1px white;
  text-decoration: none;
  cursor: pointer;
  font-size: 1.2em;
  padding: 18px 10px;
  width: 180px;
  margin: 10px;
  outline: none;
}

Dronningspillet

<button>Prøv igjen!</button>

A: You got a lot of typos in there... You created a variable in the if statement (firkantTrykket= e.target), which you shouldn't, and you didn't check whether the target is an img tag or not.
This code should work just fine:

let knappEl = document.querySelector("button")
knappEl.addEventListener("click", restart)

let tableEl = document.querySelector("table")
let liste = []
let turTeller = 0
let slatt = false
let meldingEl = document.querySelector("#melding")

for (let i = 1; i < 9; i++) {
  let trEl = document.createElement('tr');
  for (let j = 1; j < 9; j++) {
    let tdEl = document.createElement('td');
    tdEl.setAttribute("id", "rute" + i + j)
    tdEl.addEventListener("click", plasserTårn)
    trEl.appendChild(tdEl);
    // Bare på grunn av css
    tdEl.className = (i % 2 === j % 2) ? "hvit firkant" : "svart firkant";
  }
  tableEl.appendChild(trEl);
}

function plasserTårn(e) {
  if (slatt == false) {
    let trykketFirkant = e.target
    let plassertBrikke = { rad: trykketFirkant.id.substring(5, 4), kolonne: trykketFirkant.id.substring(6, 5) }
    console.log(liste)
    console.log(trykketFirkant.tagName)
    if (trykketFirkant.tagName == 'IMG') return; // stops the function if the target is the img tag
    if (turTeller == 0) {
      trykketFirkant.innerHTML = "";
      turTeller = 1
    }
    else if (turTeller == 1) {
      trykketFirkant.innerHTML = "";
      turTeller = 0
    }

    for (let i = 0; i < liste.length; i++) {
      let r = Math.abs(liste[i].rad - plassertBrikke.rad)
      let k = Math.abs(liste[i].kolonne - plassertBrikke.kolonne)
      if (liste[i].rad == plassertBrikke.rad || liste[i].kolonne == plassertBrikke.kolonne || r == k) {
        meldingEl.innerHTML = "En dronning har blir slått"
        window.scrollTo(0, document.body.scrollHeight);
        slatt = true
      }
      else if (liste.length == 7) {
        meldingEl.innerHTML = "Du har vunnet!"
        window.scrollTo(0, document.body.scrollHeight);
        slatt = true
      }
    }
    liste.push(plassertBrikke)
  }
  else {
    meldingEl.innerHTML = "Spillet er over!"
  }
}

function restart() {
  location.reload()
  window.scrollTo(500, 0);
}


text:
Q: Parallel Hints in "Select Into" statement in PL/SQL Parallel hints in normal DML SQL queries in oracle can be used in following fashion
 select /*+ PARALLEL (A,2) */  * from table A ;

In similar fashion can we use parallel hints in PL/SQL for select into statements in oracle?
  select /*+ PARALLEL(A,2) */ A.* BULK COLLECT INTO g_table_a from Table A ;

If i use the above syntax is there any way to verify whether the above select statement is executed in parallel?
Edit : Assuming g_table_a is a table data structure of ROWTYPE table

A: If the statement takes short elapsed time, you don't want to run it in parallel. Note, that e.g. query taking say 0.5 seconds in serial execution could take 2,5 second in parallel, as the most overhead is to set up the parallel execution.
So, if the query takes long time, you have enough time to check V$SESSION (use gv$sessionin RAC) and see all session with the user running the query.
select * from gv$session where username = 'your_user'

For serial execution you see only one session, for parallel execution you see one coordinator and additional session up to twice of the chosen parallel degree.
Alternative use the v$px_session which connects the parallel worker sessions with the query coordinator.
 select SID, SERIAL#, DEGREE, REQ_DEGREE
 from v$px_session
 where  qcsid = <SID of the session running teh parallel statement>;

Here you see also the required degree of parallelism and the real used DOP

A: YOu can easily check this from Explain Plan of the query. In case of Plsql you can also have trace of the procedure and check in the TKprof file.


text:
Q: Azure Function Cosmos DB input binding document count limit I'm building a durable function that periodically processes every record in my Cosmos DB (nights and weekends).  Right now I only have a few hundred records, but once I get into production, I'm anticipating >50k documents to come in with ~1k per week being added.
I am getting the documents via an activityTrigger with the following bindings:
{
  "bindings": [
    {
      "name": "name",
      "type": "activityTrigger",
      "direction": "in"
    },
    {
      "type": "cosmosDB",
      "direction": "in",
      "name": "articles",
      "databaseName": "Arts",
      "collectionName": "ArtData",
      "connectionStringSetting": "CosmosTrigger_ConnectionString",
      "sqlQuery": "SELECT * FROM c WHERE c.type='article'"
    }
  ],
  "scriptFile": "../dist/GetAllArticleData/index.js"
}

Is there a limit to the total number of documents that are returned to an Azure Function via an SQL Query binding?  Or does Azure Functions automatically handle the pagination and there is no upper limit?
If there is no pagination built in, what about chaining durable functions together, where the first activity gets the total row count, then a fan out/in query function is called with the OFFSET and LIMIT clauses being parameters passed in from the orchestrator?  Is that a reliable pattern?

A: The Cosmos DB input binding drains the entire query results and passes them to your Function, no continuation is needed.
If the query has 10 results or 1000, it will drain the query and pass them as input.
Here is the code reference.


text:
Q: jQuery javascript way of checking if some html exist on page Before appending more code, I want to make sure:
Hello

isn't already on the html page inside the div where id='faqs'

Hello

What is the best way of doing this with jquery or javascript?
Thanks

A: The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
    // element isn't on the page
}

A: If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('')
  .attr('href', 'index.php?option=com_content&view=article&id=36')
  .html('hello')
  .appendTo($('#faqs'));

However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;

UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';

// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');

var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
  // do something
} else {
  // do something else
}

Here's a working example -> http://jsfiddle.net/Uzef8/2/

A: You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("Hello") == -1) {
    $('#faqs').append ("Hello");
}

A: if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
    //does'nt exist
}


text:
Q: Is there any reward (apart from monetary winnings) for playing dice poker I've just started playing The Witcher 2, and I've noticed that since the first game the "dice poker" game has been changed from three rounds to one, which pretty much reduces it to pure luck. As such, it isn't much fun.
Is there any reason for persevering with it, apart from potential monetary winnings? Any other reward, or any quest or dialogue options opened up?

A: There is one quest per major area in the game related to dice poker. They usually require you to beat 4 or 5 opponents to finish the quest. So, there is a bit of XP to be had in addition to the Orens you win.
EDIT
In addition, the last opponent you beat in any Poker Face quest line gives you an opportunity to collect a price, usually a diagram for good gear, rather than taking the Orens.