text:
Q: Where did all the time related information go from Revision history? Revision history no more shows the time related information for revisions. The issue seems to be everywhere - Ask Ubuntu, SO, Meta SO - everywhere.

A: This was fixed in the latest deploy.
My fault, introduced this when fixing another bug where the action verb in those blocks would be incorrect or duplicated.


text:
Q: Pygame display on monitor's center When I change resolution of my game, it's window doesn't move so some part of it is out of monitor's scope.
Can I somehow force pygame to display its surface ALWAYS on the middle of the monitor?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Core data fetch is crashing with error "Fatal error: NSArray element failed to match the Swift Array Element type" We have a coredata User entity with the schema as below -
name String
aliases Transformable

Note: aliases is an String array.
The fetch code is like this -
var userDetails:[User]?

let request = NSFetchRequest<NSFetchRequestResult>.init(entityName:"User")
userDetails = try self.viewContext.fetch(request) as? [User]

The fetch request is intermittently crashing with the below errors -

Fatal error: NSArray element failed to match the Swift Array Element
type
Expected User but found _NSCoreTypesetterLayoutCache
Fatal error: NSArrav element failed to match the Swift Arrav Element
type
Expected NSFetchRequestResult but found NSAsynchronousFetchResult
Please let me know if anyone has any suggestions.

A: Initialise your fetch request like this:
let request: NSFetchRequest<User> = User.fetchRequest()

The fetchRequest method is auto-generated (unless you have opted out).
The key is putting your entity class in the angle brackets.


text:
Q: Difference between two timestamps with different weekdays? I've the following dates:
Tue 19:00-20:00
Wed 04:25-15:14

How can i get the difference between Tue 20:00 and Wed 04:25?
I've tried to transform it in datetime objects but since i don't have the day of the month or a year both objects will get the same date:
d1 = datetime.strptime("Tue 20:00", "%a %H:%M")
d2 = datetime.strptime("Wed 04:25", "%a %H:%M")

*

*d1 is: datetime.datetime(1900, 1, 1, 20, 0)

*d2 is: datetime.datetime(1900, 1, 1, 4, 25)
The difference in minutes should be 505 but in this case will be -935.0 because they have the same date, and so they differ by almost 16 hours and not about 8 and a half:
diff = (d2 - d1).total_seconds() / 60  # -935.0

A: datetime.strptime() can't do anything else, because the day of the week is not enough to form a date. You'd need a week number and a year for a week-day to make any sense. If you need to get the relative difference between two dates that are assumed to be in the same week, then any week number and year would do, e.g.:
arbitrary_iso_week = "2020-25 "

d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")

This makes use of the %G and %V formatters for ISO 8601 week numbers.
This produces datetime objects with a more meaningful date releationship:
>>> arbitrary_iso_week = "2020-25 "
>>> d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
>>> d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
>>> d1
datetime.datetime(2020, 6, 16, 20, 0)
>>> d2
datetime.datetime(2020, 6, 17, 4, 25)
>>> (d2 - d1).total_seconds() / 60
505.0

The actual dates don't matter here, just their difference in days. d1 is now earlier, not later, than d2.
You may have to take into account that week days are circular, in that you could have an earlier date on, say, Friday, and a later date on Monday. If you can assume that the first value must be earlier than the second, then the solution is simple. Just subtract 7 days from d1 if it is later than d2:
# if the first date must come before the second, then it must be one week earlier.
if d1 > d2:
    d1 -= timedelta(days=7)


text:
Q: Downloading Tweets via JSON feed code not working I'm building my first android app - something that will display my tweets in a list.
I managed to get the app working earlier, but the tweets would sometimes take a long time to download, and the app would become unresponsive or crash.
I decided to add a thread to the app so the it wouldn't become unresponsive, but now it doesn't work at all :/
Does anyone know what's wrong? It's only my third day of learning java, and I can't seem to figure out what the problem is here.
Here's the code:
package com.app.first;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

public class Twitter extends ListActivity {

public ProgressDialog pd = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    // Show the ProgressDialog on this thread
    pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
            true, false);

    new LoadTwitterFeed().execute();

}

public class LoadTwitterFeed extends AsyncTask<String, Integer, String> {

    String tweets[] = new String[9];

    public String readTwitterFeed() {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(
                "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jjmpsp&include_rts=false&count=10");
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e(ParseJSON.class.toString(), "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        String readTwitterFeed = readTwitterFeed();

        try {
            JSONArray jsonArray = new JSONArray(readTwitterFeed);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                tweets[i] = jsonObject.getString("text").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        setListAdapter(new ArrayAdapter<String>(Twitter.this,
                android.R.layout.simple_list_item_1, tweets));

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // what to do when the task ends.
        pd.hide();

    }

}

}

A: set this code in onPostExecute
setListAdapter(new ArrayAdapter<String>(Twitter.this,
            android.R.layout.simple_list_item_1, tweets));


text:
Q: How to loop through table and add form data to table dynamically? I'm currently working on a sort of hour tracker website, and I am using a form and a table.
Right now I have it working where it adds the form content to the table the first time you submit, but I need it to allow you put in new information into the form and once submitted, it automatically adds a new row with the data.
So far I have this function:
function enterText() {
  var i = 1;
  var table = document.getElementById("myTable");
  var row = table.insertRow(i);

  if (document.getElementById("td1").innerHTML == "") {
    var x = document.getElementById("dt").value;
    document.getElementById("td1").innerHTML = x;
  } else {
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    i++;
  }

  var y = document.getElementById("hrs").value;
  document.getElementById("td2").innerHTML = y;
  var z = document.getElementById("dsc").value;
  document.getElementById("td3").innerHTML = z;
}

So the end goal is to eventually not have to use a table either, but I am using it as a place holder.
edit*
to reply to Freek Bes:
It does make sense to put i as a global. I tested it out a bit and just moving i doesn't make a difference from before, it just inputs the form into the first cell and then when submit is clicked again it adds a blank row. The second example just adds blanks cells. The problem is that I can't seem to get it to add the new content inside of the new cells.
For better context of what I'm doing, here is my html:
<!DOCTYPE html>

<link rel="stylesheet" href="stylesheet.css">

Hour Tracker

Created by:

<form onsubmit="return false" id="first" class="hours">
    Date:

    <input type="date" name="date" id="dt">

    Hours:

    <input type="number" name="hours" id="hrs">

    Description:

    <input type="text" name="description" id="dsc">

    <input type="submit" value="submit" onclick="enterText();">
</form>

        Date
        Hours
        Description

A: You tried to increment the variable i, but i is set to 1 again when you run the function a second time. You need the variable i to be global, by defining it outside of the function. Try this:
var i = 1;

function enterText() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(i);

  if (document.getElementById("td1").innerHTML == "") {
    var x = document.getElementById("dt").value;
    document.getElementById("td1").innerHTML = x;
  } else {
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    i++;
  }

  var y = document.getElementById("hrs").value;
  document.getElementById("td2").innerHTML = y;
  var z = document.getElementById("dsc").value;
  document.getElementById("td3").innerHTML = z;
}

This won't however set the data in the new row. In order for that to work, you'll have to get rid of the ids you're using for the cells alltogether (I don't know what you were trying to do in the if statement, so I got rid of it too for simplicity. You can add it back if you want and check the results yourself):
var i = 1;

function enterText() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(i);

  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  cell1.innerHTML = x;
  cell2.innerHTML = y;
  cell3.innerHTML = z;
  i++;
}


text:
Q: an unknown text show in every page header codeigniter An unknown text ed shown in every pages of codeigniter website.I try a lot to find the mistake but unable to fix the issue,Kindly tell me the issue,I also search the text in models and views files
Screenshot Image below ..


text:
Q: web2py SQLFORM.factory no_table I would like to know why my variables in web2py SQLFORM.factory have a no_table_[name] instead of the actual table name? Is there anything missing code.
e.g
form = SQLFORM.factory(db.event, db.event_permissions, record=record, fields=fields, submit_button='Edit Event Master')

A: SQLFORM.factory works by creating a dummy DAL instance along with a dummy DAL table. By default, the dummy table name is "no_table", but you can change that via the table_name argument.
When you pass entire tables to SQLFORM.factory, it simply extracts the fields from those tables, but it does not retain the table names when constructing the HTML widget id's (instead, it just uses the dummy table name to construct the id's). In the book section on One form for multiple tables, this is why it says:

This only works when the tables don't have field names in common.

If you have fields with the same names in both tables, they will end up with the same id's.


text:
Q: Regex for matching a string that can end with a character or not I have this regex
^([^>]+)/([^>]+)/([^>]+)/([^>]+)/([^>]+)/$

It matches a generic url, like
www.site.com/complete/path/for/this/page/

The problem is that if i go to
www.site.com/complete/path/for/this/page

I get a 404 error, because my regex matches that string only if it ends with a slash.
How can i tell the regex to match the string whether it ends with a slash or not?
I thought about duplicating my rules to match the two cases but i think it is a very ugly way to do it, i'm sure that there is a better way to do it.

A: Make the slash optional
^([^>]+)/([^>]+)/([^>]+)/([^>]+)/([^>]+)/?$

by putting a ? after it.
? is a quantifier that repeats the preceding element 0 or 1 time, so it makes it optional.

A: ^([^>]+)/([^>]+)/([^>]+)/([^>]+)/([^>]+)/([^>]+)/?$

So its 5 expected slashes and 1 optional one in the end? Try this.


text:
Q: Show that if $S$ is a local ring, so is $R$ given that $R \subset S$ is an integral ring extension, I am working on the following exercise:

Let $R \subset S$ be an integral ring extension. Prove that if $S$ is a local ring, so is $R$.

I do not see how I should do this. I know the definitions of local rings and integral extension, but I do not see how these two definitions are related. Could you give me a hint?

A: A standard result about integral ring extensions is that if $\mathfrak{p}$
is a prime ideal of $R$ then $\mathfrak{p}=\mathfrak{P}\cap R$ for some
prime ideal $\mathfrak P$ of $S$.
If $R$ isn't local, it has at least two maximal ideals $\mathfrak m_i$
($i\in\{1,2\}$), and so $S$ has two prime ideals $\mathfrak P_i$
with $\mathfrak P_i\cap R=\mathfrak m_i$. Each $\mathfrak P_i$
is contained in the maximal ideal $\mathfrak M$ of $S$. This implies that
$\mathfrak M\cap R=\mathfrak m_1$ and $\mathfrak M\cap R=\mathfrak m_2$ which is
impossible.


text:
Q: PHP inject into database with PDO & Json similar question I have asked before... But this time with PDO. Trying to understand PDO better, as I know it is better than doing a mysql Query in PHP.
So, I have JSON Data:
{
   "serial_number": "70-b3-d5-1a-00-be",
   "dateTime": "2020-08-14 20:58",
   "passReport": [
      {
         "id": 1,
         "passList": [
            {
               "passType": 1,
               "time": "20:58:38"
            }
         ]
      }
   ]
}

I am trying to get it into my sql database with the following code:
foreach ($decoded as $item) {
    if ($item->serial_number !== '70-b3-d5-1a-00-be') continue;

$statement = $pdo->prepare("INSERT INTO mytable SET serial_number = :serial_number, date_time = :date_time , id = :id, passType = :passType,  time_created = :time_created");
        $statement->execute([
            'serial_number' => $item->serial_number,
            'date_time' => $item->dateTime,
            'id' => $item->passReport->id,
            'passType' => $item->passReport->passList->passType,
            'time_created' => $item->passReport->passList->time
        ]);
}

But the problem is, I don't know what the correct syntax is to execute into mysql with PDO.
I am having a hard time figuring out how to reach each array.

A: A quick restructuring of this should make it work and be more efficient:
$statement = $pdo->prepare("INSERT INTO mytable (serial_number, date_time, id, passType, time_created) VALUES (:serial_number, :date_time, :id, :passType, :time_created");

foreach ($decoded as $item) {
    if ($item->serial_number !== '70-b3-d5-1a-00-be') continue;

    $statement->execute([
        'serial_number' => $item->serial_number,
        'date_time' => $item->dateTime,
        'id' => $item->passReport->id,
        'passType' => $item->passReport->passList->passType,
        'time_created' => $item->passReport->passList->time
    ]);
}

It's worth noting having columns with styles like passType (camel-case) and time_created (underscored) is a real mess. Pick a style and stick to it consistently.


text:
Q: Spring Integration JSON to JSON transformation I am building an application with Spring Integration and I'm trying to figure out if there is an example out there of how a JSON can be transformed to another JSON.
The steps would be
   1.) extract fields of interest from current JSON
   2.) perform logic if required (split values, concatenate, etc..)
   3.) set the value in the new JSON format

I would also like to make this available to the Business Analysts, so that they can make the mapping changes, once the framework is setup.
Cheers
Kris

A: Well, any JSON can simply be deserialized to Map:
new JsonToObjectTransformer(Map.class)

after that you can apply any filters to map keys, build a new Map with new desired keys and serialize it into JSON back:
new ObjectToJsonTransformer()


text:
Q: How do you make a subdomain on a different port? This is my vhosts.conf
<VirtualHost *:80>
DocumentRoot "C:/wamp/www"
ServerName localhost
</VirtualHost>

<VirtualHost *:80>
DocumentRoot "C:/wamp/www/images"
ServerName images.localhost
</VirtualHost>

<VirtualHost *:80>
DocumentRoot "C:/wamp/www/project"
ServerName project.localhost
</VirtualHost>

Listen 8080
<VirtualHost *:8080>
DocumentRoot "C:/wamp/www/trunk"
ServerName localhost
</VirtualHost>

<VirtualHost *:8080>
DocumentRoot "C:/wamp/www/images2"
ServerName images2.localhost
</VirtualHost>

and this is my windows host file
127.0.0.1 project.localhost

127.0.0.1 images.localhost

127.0.0.1 images2.localhost

So the first three are fine. The localhost on port 8080 works, I just go to localhost:8080 and it loads what's inside trunk.
The images2.localhost:8080 shows what's inside C:/wamp/www/trunk and images2.localhost just goes to the wampserver main page. Tried changing to this but it's still the same.

A: Just to add a bit of clarity, the first of these entries "owns" the :8080 port, and so the second one is ignored.
<VirtualHost *:8080>
DocumentRoot "C:/wamp/www/trunk"
ServerName localhost
</VirtualHost>

<VirtualHost *:8080>
DocumentRoot "C:/wamp/www/images2"
ServerName images2.localhost
</VirtualHost>

What you want is name based virtual servers, so you can make the first and second entries unique.  This is what makes the ServerName directive actually do something.  As stated by @quanta, add NameVirtualHost *:8080 to the configuration, and then Apache will pay attention to the url you type in the browser and serve the pages based on the ServerName directive that matches the URL.

A: Insert a NameVirtualHost *:8080 directive and try again.


text:
Q: Will enabling ufw through ssh disrupt current session? I have an ubuntu server that I access through SSH. I've changed standart port (22) to something else. I want to enable ufw on this machine. However, I'm afraid of the possibility of the following scenario occuring: as soon as I enable ufw, it'll start with default settings blocking connections and kicks me from server, especially since I'm connecting through non-standart port. Will that happen? Should I prepare some configuration first or start ufw right away? SSH is the only way of accessing my server, so loosig this due to firewall would be a disaster.
I also have some applications using some ports for UDP and TCP connections. Will these ports be automatically blocked after I enable ufw? Will I need to add exceptions for them after enabling it?

I've probably found what I wanted, but I need a confirmation from somebody.
I haven't enabled ufw yet, but I've ran some configuration commands.
First I did sudo ufw ssh
Second sudo ufw  my_new_ssh_port_here
Then I had a look at /lib/ufw/user.rules
This is part of the file:
### RULES ###

### tuple ### allow any 22 0.0.0.0/0 any 0.0.0.0/0 in
-A ufw-user-input -p tcp --dport 22 -j ACCEPT
-A ufw-user-input -p udp --dport 22 -j ACCEPT

### tuple ### allow any 1111 0.0.0.0/0 any 0.0.0.0/0 in
-A ufw-user-input -p tcp --dport 1111 -j ACCEPT
-A ufw-user-input -p udp --dport 1111 -j ACCEPT

### END RULES ###

Have I set it up to allow ssh connection through my new port successfully? Is it safe to start now or do I need to configure anything else?
I'm still not sure, because sudo ufw show raw doesn't seem to show anything helpful and sudo ufw status verbose still shows Status: inactive only

A: Ya. It may. Based on the default configurations. You can check the present configuration by using the following command sudo ufw show raw. The command will show the configuration of all policy's rules in iptable.


text:
Q: React P tag update but not live I do not want the p tag to be updated live.
When i write in the input p tag automatically update.
i want update when i click ok button and not live mode.
What I write in the input directly updates the p tag. I do not want that
This is code --->
import React, {Component} from 'react'

class Test extends Component{
    constructor(props){
        super(props);
        this.state={
            text:"hello",

        }
        this.alpha=this.alpha.bind(this)
        this.show=this.show.bind(this)

    }
    alpha(event){
        this.setState({text:event.target.value})
    }
    show(){
        alert(this.state.text)
    }
    render(){
        return(

                <input type="text"  onChange={this.alpha} />
                <button onClick={this.show} >ok</button>

{this.state.text}

        )
    }
}
export default Test

A: Do you mean something like this?
import React, {Component} from 'react'

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

        this.state={
            text: '',
            value: 'hello',
        }

        this.handleChange=this.handleChange.bind(this)
        this.apply=this.apply.bind(this)
    }

    handleChange(event) {
        this.setState({ value: event.target.value });
    }

    apply(){
      this.setState(({ value }) => ({ text: value }));
    }

    render(){
        return (

                <input type="text" onChange={this.handleChange} />
                <button onClick={this.apply}>ok</button>

{this.state.text}

        );
    }
}

export default Test


text:
Q: Is it possible to perform a POST API call in PHP with authorization first? I just started CS at University and wanted to create a little webdev project in my vacation. I created a simple contact form which asks the user for some data (text, dropdown choices). After pressing the submit button I would like to perform a POST api call to the UiPath Orchestrator to trigger a robot...
Since this is the very first time I'm dealing with PHP I'm not quite sure how to approach this problem.
I'm able to grab the data from the submitted form. But now I'm struggling with the API call. I've tested it in Swagger UI and Postman and it works.
Problem:
I have to authenticate via a batcher id which is also retrievable through an API call.
Question:

*

*Does it make sense to create a new function which is responsible for the API call, since I might want to add other forms which trigger other bot processes?

*From my research I'm quite sure that I have to use a cURL call (or is this wrong?).. If i need to authenticat every time the submit button is pressed, how can retrieve the token and pass it as a header (or handle idk) argument for the actual POST call?
If you cant understand my problem, I'm very sorry! I will try my best and reformulate it, but since I'm not experienced with this at all I hope you can forgive me.
Already looking forward for your help!
This is my code so far:
add_action('wpcf7_mail_sent','cf7_api_sender');
function cf7_api_sender($contact_form){
$title = $contact_form ->title;
if ($title === 'MA_Demo'){
    $submission = WPCF7_Submission::get_instance();

    if ($submission){
        $posted_data = $submission->get_posted_data();

        $firstname = $posted_data['Firstname'];
        $lastname = $posted_data['Lastname'];
        $department = $posted_data['Departement'][0];
        $workload = $posted_data['Workload'][0];

        /*

        this is what I found so far but ofc it does not work at all.. do I have to put the body (itemData) into the args?
        and where can i pull the beacon token and add it?

        $url = '"https://cloud.uipath.com/..../..../orchestrator_/odata/Queues/UiPathODataSvc.AddQueueItem"
        $args =[
            accept: application/json
            X-UIPATH-OrganizationUnitId: .....
            {  \"itemData\": {    \"Name\": \"...\",    \"Priority\": \"...\",    \"Reference\": \"...\",    \"SpecificContent\": {\"key1\": \"Rick \", \"key2\": \"Roll\"}  }}
        ]

        */

        /* this was to test if it works to pull data

        $myfile = fopen("data.txt", "w") or die("Unable to open file!");
        $txt = $firstname.$lastname.$department.$workload;
        fwrite($myfile, $txt);
        fclose($myfile);

        */
    }
}

}

A: First you'll need to make a call to /api/Account/Authenticate with your tenant, username, and password. It will return something like
{
  "result": "HzptFsZpGMS64j5DTb4TqX-cHVv2AtC4noVCQrkHKr54r...",
  "targetUrl": null,
  "success": true,
  "error": null,
  "unAuthorizedRequest": false,
  "__abp": true
}

Then you use that result in your Add Queue Item call by adding a header item
"Authorization":"Bearer " & result  ("Bearer HzptFsZpGMS64...")

This is for Orchestrator on-prem 2019.10 so cloud may be a little different.


text:
Q: Jquery - Loading Animation Issue I'm trying to display a loading image after an AJAX call has been made.
Currently I have the following Javascript code:
window.onload = function(){

var img = document.createElement("IMG");
img.src = "http://i.stack.imgur.com/FhHRx.gif";

function getCategories(){
    $.ajax({
        url: //url here,
        dataType:'jsonp',
        success: function(data){

            //code here

        },
        statusCode: {
            404: function() {
                alert:('There was a problem with the server');
            }
        }

    });
}

$(document).ajaxStart(function(){
    alert('here');
    var div = document.createElement("div");
    div.id = "id1";
    document.getElementById('id1').appendChild(img);
    document.body.appendChild(div);

}).ajaxStop(function(){
    var element = document.getElementById('id1');
    element.parentNode.removeChild(element);

});

However, I am finding that the code is not even getting to the ajaxStart function as the alert is not appearing... I have tried other methods (eg: How to show loading spinner in jQuery?) to try and get this working but have not been successful as of yet...
Would anyone be able to help with this please?
Thank you.

A: You are more than likely getting an error for Unexpected Token, since you are declaring a function incorrectly.
Uncaught SyntaxError: Unexpected token {

You need to declare a function with either:
function getCategories () { }

Or:
var getCategories = function () { };

A: I think I found the solution here ($(document).ajaxstart not firing)
It seems that ajaxStart only works when XMLHttpRequest is used. If you use JSONP, XMLHttpRequest isn't used. Rather, it inserts a <script> tag to achieve this goal.
I simply used the workaround suggested in the above link.


text:
Q: Flask application to be visible in local network I have a Flask application running under VMware workstation.

*

*VMware uses NAT and virtual machine has IP 192.168.52.132

*I use app.run(host='0.0.0.0') to run my application

*I can see it running in browser if I type http://localhost:5000

*I can also see it running from my host machine if I type http://192.168.52.132:5000 or http://localhost:5000

*netstat -tupln | grep ':5000' gives me:
tcp || 0 ||  0 0.0.0.0:5000 || 0.0.0.0:* || LISTEN || 44937/python

*As suggested in similar topics here, I did:
iptables -I INPUT -p tcp --dport 5000 -j ACCEPT
Unfortunately, if I try to open http://192.168.52.132:5000 from different machine inside the same WiFi network, I only get "Cannot connect to destination (192.168.52.132).
What else should I do to make my app visible from other devices?
Thank you.
p.s.
Running application with debug=True didn't help me too.


text:
Q: How to show less than a specific percentage in an Excel pivot table? I have a pivot table made in Excel and I already have all the % collected data there.
Now, what I need to do is show only the critical ones which are less than 85%, as I don't need anything above that being shown.
Is there a way I can show less than 85% or any other amount in the future?

A: Add another column to your raw data. Set formula to [assuming the % is in column A]:
=A1<85%

Add this column to your pivot table as a filter. Filter for where your new column = TRUE.
Edit for new info
Per your comments below, the %'s are not actually calculated "within" the pivot table, they are next to the pivot table on the same tab. So, simply add an "if" statement to that formula, like so:
= if(('Total Paid'+'Total Contr. Adj.')/('Total Billed Amount'-'Other Adj.'-'Write-Off')<85%,('Total Paid'+'Total Contr. Adj.')/('Total Billed Amount'-'Other Adj.'-'Write-Off'),"")

This will check to see if your formula is <85%. If it is, the formula will appear there.


text:
Q: Delete Files from directory based on file name version I would like to delete old ZIP files from directory based on file name where date created cant be taken into account
E.g.
PyhtonReport_20180404_03.zip
PyhtonReport_20180404_02.zip
PyhtonReport_20180404_01.zip
PyhtonReport_20181221_02.zip
PyhtonReport_20181221_01.zip
PyhtonReport_20180816_01.zip

End Result:
PyhtonReport_20180404_03.zip
PyhtonReport_20181221_02.zip
PyhtonReport_20180816_01.zip

I am tryign to read first 23 characters and if it match with second then compare file1 to file2. If the value is false then append to list and eventually delete it.
import os
source = r'C:\Users\Pyhton'
for filename in os.listdir(source):
    GroupFile = filename[0:22]

Lost how to keep the value of first file and keep on checking.

A: The following should give you the desired end result.
import os

source = r"C:\Users\Pyhton"
file_names = os.listdir(source)

latest_files = {}
for file_name in file_names:
    name_parts = file_name.split("_")
    date_stamp = name_parts[1]

    if date_stamp not in latest_files or file_name > latest_files[date_stamp]:
        latest_files[date_stamp] = file_name

keep_files = latest_files.values()
for file_name in file_names:
    if file_name in keep_files:
        continue

    os.remove(os.path.join(source, file_name))

Create a mapping (latest_files) of date: latest_version_file_name and then remove all files but those in the mapping.

A: EDIT: Sorry, i missed the part about keeping some of them!
import glob
import os
files = glob.glob('path/to/old/files/common_part_of_files_names*.zip')
groups = set([f[:21] for f in files])
for group in groups:
  versions = [f for f in files if f.starts_with(group)]
  versions.remove(max(versions)) # pop latest
  for v in versions:
    os.remove(v)

A: Sorry, I couldn't ressist.
def distinct_dates(files):
    "Remove duplicates of same date files, preserving the first ocurrence"
    o = {}  # Saves first occurrence as {date: file}
    for i, date in enumerate(map(lambda f: f[13:21], files)):
        if date not in o:
            o[date] = files[i]
    return list(o.values())

and its usage
files = [
    "PyhtonReport_20180404_03.zip",
    "PyhtonReport_20180404_02.zip",
    "PyhtonReport_20180404_01.zip",
    "PyhtonReport_20181221_02.zip",
    "PyhtonReport_20181221_01.zip",
    "PyhtonReport_20180816_01.zip",
]

print(distinct_dates(files))


text:
Q: Showing by Hand that $H^1(0)=0 , H^1(-p)=0$ in $\mathbb{C}$ , Mittag-Leffer Problems in $\mathbb{C}$ and $\mathbb{C}/L$ I am trying to show by hand, without using the Riemann-Roch Theorem, that in $\Bbb C_{\infty}$ we will have that $H^1(0)=0$ and $H^1(-p)=0$, but I am having some trouble constructing the functions that are related to the Laurent series, so I guess this is more a complex analysis question that if I have a Laurent series that is like $a_n\frac{1}{z^n}+\ldots+a_0\frac{1}{z}$ at point $p$ and $b_k\frac{1}{z^k}+\ldots+b_m\frac{1}{z^m}$ at point $q$ how can i construct a meromorphic function that will have these laurent series at these points and be holomorphic elesewhere and so on ? I am bit confused on how to make things work.
Also I am trying do another exercise that it's kind of the same idea that I cant find the desired functions, it goes like this

Let $X$ be the complex torus, fix a finite number of points $p_i \in X$ with local coordinate $z_i$ at $p_i$, consider the laurent divisor $Z=\sum\limits_{i}c_iz_i^{-1}.p_i$, show that $Z=\alpha_0(f)$ for some global meromorphic function $f$ iff $\sum\limits_i c_i=0$.

I was able to do the first implication using the residue theorem applied to $fdz$, now for the second one I am trying to construct the function by taking other points $q_j$ such that $\sum\limits_j q_j - \sum\limits_i p_i \in \Bbb Z$ and then using the ratio of theta-translated functions $\frac{\prod_j \vartheta^{q_j}(z)}{\prod_i \vartheta^{p_i}(z)}$ but I dont know how I am going to make the functions get the residue $c_i$ at the point $p_i$, I have to change something from that function but I dont know what.
So any tips or help would be aprecciated. Thanks in advance.


text:
Q: Why 'cpuutilization' data in 'podman info' output showing different value with the output of top or mpstat command. How podman calculating the cpu? The 'CPU utilization' data in 'podman info' output showing different value and not matching with the output of top or mpstat command. How podman calculating the cpu utilization?
Is it showing only podman related cpu usage or the complete system/VM Cpu details.?


text:
Q: How are std::array's compared in C++? For the below code, why is the output coming as 1?
#include<iostream>
#include<array>

int main() {
    std::array<int, 5> a { 10, 11, 12, 15, 14 };
    std::array<int, 5> b { 11, 12, 13, 14, 15 };
    std::cout << (a < b);
}

A: They use the standard algorithm std::lexicographical_compare
From the description of the algorithm in the C++ Standard

3 Remarks: If two sequences have the same number of elements and their
  corresponding elements (if any) are equivalent, then neither sequence
  is lexicographically less than the other. If one sequence is a prefix
  of the other, then the shorter sequence is lexicographically less than
  the longer sequence. Otherwise, the lexicographical comparison of the
  sequences yields the same result as the comparison of the first
  corresponding pair of elements that are not equivalent.

The output of your example is boolean true that is "...the same result as the comparison of the first corresponding pair of elements that are not equivalent."
For your example the result of the comparison (a < b) is the result of the comparison ( a[0] < b[0] )
Below there is a demonstrative program For example you can write such an operator for the class template std::vector.
#include <iostream>
#include <iomanip>
#include <array>
#include <vector>
#include <iterator>
#include <algorithm>

template <typename T>
bool operator <( const std::vector<T> &a, const std::vector<T> &b )
{
    return std::lexicographical_compare( std::begin( a ), std::end( a ),
                                         std::begin( b ), std::end( b ) );
}

int main()
{
    std::array<int, 5> a { 10, 11, 12, 15, 14 };
    std::array<int, 5> b { 11, 12, 13, 14, 15 };

    std::cout << std::boolalpha
              << std::lexicographical_compare( a.begin(), a.end(),
                                               b.begin(), b.end() )
              << '\n';

    std::vector<int> a1 { 10, 11, 12, 15, 14 };
    std::vector<int> b1 { 11, 12, 13, 14, 15 };

    std::cout << std::boolalpha << ( a1 < b1 ) << '\n';

    return 0;
}


text:
Q: Declaring an object with templates and arguments at the same time I don't know how to declare an object using templates and arguments at the same time
Basically, I have:
FileLog.h
#include<algorithm>
#include<fstream>

#include "FileOutput.h"
using namespace std;

template<class T, class R>
class FileLog : public FileOutput
{
    public:
        FileLog(const string file_name) : FileOutput(file_name)
          {
        };
...

And when I create an object :
** Main.cpp**
FileLog<int, int> object;

I get the error
no matching function for call to 'FileLog<int, int>::FileLog()'
And i don't know how to give the string "Filename" in input to it

A: Just as you'd instantiate a non template object :
FileLog<int, int> object("foo.txt");


text:
Q: Flutter make a sound on button press I want to make a sound when the button is pressed in Flutter. The codes don't give an error but make no sound. I would be glad if you help.

A: Use the AudioCache() class like this
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

void playSound(int soundNumber) {
  final player = AudioCache();
  player.play('note$soundNumber.wav');
}

// ignore: must_be_immutable
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Xylophone'),
        backgroundColor: Colors.black,
      ),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: TextButton(
                style: TextButton.styleFrom(
                  backgroundColor: Colors.red,
                ),
                onPressed: () {
                  playSound(1);
                },
                child: Text(''),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: Copy, Paste, Find keyboard shortcuts not working in Windows 10 after a bluescreen and restart. What do I do? Today I had the first ever bluescreen on my laptop since I bought it 2 years ago. The system warned me of some unexpected error and then restarted.
Upon restart, I found everything to be okay, except that the CTRL+C, CTRL+V, CTRL+F shortcuts were no longer working. Strangely, the CTRL+Z and CTRL+X shortcuts are working allright.
I tried the shortcuts in different applications: MS Office 2007, SDL Trados 2013, Google Chrome Browser. The same result, no reaction.
Is there a way to fix this quickly on Windows 10, or is it better to just use a system backup from a week ago? I tried the troubleshooter in the Start-Parameters-Troubleshooting-Keyboard menu but it found no problems.

A: Could it have something to do with stuck keys? If a key is physically stuck (could even be shift or alt, so you might not see any letters being typed), or if there is a software error that causes the system to think you're pressing some other key, shortcuts might not function.

A: If it's not your keyboard problem then you must try this methods given below:-

*

*Open your command prompt as admin and type in the sfc/scannow if it is a registry issue then this scan will fix your issue.

*Use chkdsk C: /f /r /x  command in command prompt and wait for the process until its completion, if any problem in your disk this will it cause windows install on your disk.

*Disable/Uninstall your third-party antivirus software, you may have installed a cracked software or pirated one which is causing your this issue. remove it and check the issue is if resolved.


text:
Q: Is it possible to add kernel symbol dynamically in kernel module? I know there's EXPORT_SYMBOL for kernel modules to expose it's global variables statically.
My question is:
Is it possible to EXPORT_SYMBOL at runtime?
I'm developing a kernel driver for multiple IC modules.
There's a global struct list "A" for each IC modules(ko) to add their own IC detection function. And there will be an action to trigger the scanning of "A".
The design is, there is ko(s) for each IC and a main ko for main functions.
For example, there's m1.ko, m2.ko and mm.ko.
I'll insmod m1.ko (create "A" and add it's own detect function),
insmod m2.ko (check "A" existence, if exist, add it's own, if not create "A" and add) and insmod mm.ko (check "A" existence, if exist, trigger the scanning of "A", else do nothing).
I can check kernel symbol "A" by kallsym_lookup_name, but when I came to create "A" if not exist, I can't find a function to add kernel symbol dynamically.
Is there a method to add kernel symbol at runtime correctly? Or there's an alternative way to achieve the goal?


text:
Q: Having issues searching through file and replacing I'm having a bit of trouble searching through a file and editing certain parameters of the file. The code is below
file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
 text = File.read(file_name)
 replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
 replacedcontent += text.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

so right now what it does is that it print the contents of the file twice and I can only assume its because its inside the do loop. My end goal here is that the file has textToReplace and textToReplace2 and I need it to read through the file, replaced both with whatever the user inputs and save/write changes to the file.

A:
it print the contents of the file twice and I can only assume its because its inside the do loop

Nope, it's because you append it twice:
text = first_replacement_result
text += second_replacement_result

There's two ways to do this: one with mutation:
text.gsub!(...) # first replacement that changes `text`
text.gsub!(...) # second replacement that changes `text` again

or chained replacement:
replacedcontent = text.gsub(...).gsub(...) # two replacements one after another

A: You will need to re-use replacedcontent instead of concatenating it to avoid printing it twice.
file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
text = File.read(file_name)
replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
replacedcontent = replacedcontent.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

OR
replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}").gsub(/textToReplace2/, "#{ReplaceWithThis2}")


text:
Q: How to return null without 204 response? The controller returns 204 when i don't find any data.
[Route("api/[controller]")]
[ApiController]
public class SeasonsController : Controller
{
    private readonly IMediator _mediator;
    private readonly IMapper _mapper;

    public SeasonsController(IMediator mediator, IMapper mapper)
    {
        _mediator = mediator;
        _mapper = mapper;
    }

    [HttpGet, Route("by-betContextId/{betContextId:int}")]
    [SwaggerResponse(HttpStatusCode.OK, typeof(SeasonEntity))]
    public async Task<IActionResult> TryGetByBetContextId(int betContextId)
    {
        SeasonEntity entity = await _mediator.Send(new TryGetSeasonByBetContextId(betContextId));
        //the entity above can be null
        return Ok(entity);
    }
}

This is the client which is autogenerated by nswag
 /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
    /// <exception cref="SportradarFaultException">A server side error occurred.</exception>
    public async System.Threading.Tasks.Task<SeasonEntity> TryGetByBetContextIdAsync(int betContextId, System.Threading.CancellationToken cancellationToken)
    {
        if (betContextId == null)
            throw new System.ArgumentNullException("betContextId");

        var urlBuilder_ = new System.Text.StringBuilder();
        urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Seasons/by-betContextId/{betContextId}");
        urlBuilder_.Replace("{betContextId}", System.Uri.EscapeDataString(ConvertToString(betContextId, System.Globalization.CultureInfo.InvariantCulture)));

        var client_ = _httpClient;
        try
        {
            using (var request_ = await CreateHttpRequestMessageAsync(cancellationToken).ConfigureAwait(false))
            {
                request_.Method = new System.Net.Http.HttpMethod("GET");
                request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                PrepareRequest(client_, request_, urlBuilder_);
                var url_ = urlBuilder_.ToString();
                request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                PrepareRequest(client_, request_, url_);

                var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
                try
                {
                    var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                    if (response_.Content != null && response_.Content.Headers != null)
                    {
                        foreach (var item_ in response_.Content.Headers)
                            headers_[item_.Key] = item_.Value;
                    }

                    ProcessResponse(client_, response_);

                    var status_ = (int)response_.StatusCode;
                    if (status_ == 200)
                    {
                        var objectResponse_ = await ReadObjectResponseAsync<SeasonEntity>(response_, headers_).ConfigureAwait(false);
                        if (objectResponse_.Object == null)
                        {
                            throw new SportradarFaultException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
                        }
                        return objectResponse_.Object;
                    }
                    else
                    {
                        var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
                        throw new SportradarFaultException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                    }
                }
                finally
                {
                    if (response_ != null)
                        response_.Dispose();
                }
            }
        }
        finally
        {
        }
    }

When i return Ok() instead of Ok(entity) i take "Response was null which was not expected."
When i make the call from a REST API client i take 204 error.
How do I get it to return a 200 when the data is null?

A: This issue is related to how NSwag generates the REST client API.
Option 1: Don't use the auto-generated NSwag client code that obviously requires a parsable SeasonEntity:
var objectResponse_ = await ReadObjectResponseAsync<SeasonEntity>(response_, headers_)
    .ConfigureAwait(false);
if (objectResponse_.Object == null)
{
    throw new SportradarFaultException("Response was null which was not expected.", status_,
        objectResponse_.Text, headers_, null);
}

Option 2: Make sure that you always pass a SeasonEntity to the Ok method in your controller action to pass the check in the auto-generated client code.
Option 3: Return a 404 response when entity == null:
[HttpGet, Route("by-betContextId/{betContextId:int}")]
[SwaggerResponse(HttpStatusCode.OK, typeof(SeasonEntity))]
public async Task<IActionResult> TryGetByBetContextId(int betContextId)
{
    SeasonEntity entity = await _mediator.Send(new TryGetSeasonByBetContextId(betContextId));

    if (entity == null)
        return NotFound();

    return Ok(entity);
}

Option 3 makes more sense than option 2. Why would you want to return a 200 response when no matching item was found?

A: I changed the nswag.json configuration from
"defaultResponseReferenceTypeNullHandling": "NotNull",

to
"defaultResponseReferenceTypeNullHandling": "Null",

and changed the controller to
[Route("api/[controller]")]
[ApiController]
public class SeasonsController : Controller
{
    private readonly IMediator _mediator;
    private readonly IMapper _mapper;

    public SeasonsController(IMediator mediator, IMapper mapper)
    {
        _mediator = mediator;
        _mapper = mapper;
    }

    [HttpGet, Route("TryGetByBetContextId")]
    [ProducesResponseType(typeof(SeasonEntity), StatusCodes.Status200OK)]
    public async Task<IActionResult> TryGetByBetContextId(int betContextId)
    {
        SeasonEntity entity = await _mediator.Send(new TryGetSeasonByBetContextId(betContextId));

        if (entity == null)
            return Ok();

        return Ok(entity);
    }
}

A: try to decorate the method of the controller with the attribute
[return: CanBeNull]


text:
Q: Windows 7 64 Bit/Save mode: Rename msi.dll not possible Due to problems with the windows installer 5 I must rename msi.dll for reinstallation. That's not possible in save mode/as administrator (access denied). Of course the service is stopped. Any hints?
Edit: My problem is that I can't install msi files anymore. Everytime after some dialogs I get an error message that the corresponding msi file can't be read. I have tried any infos I found in the www universe and lost a lot of time already. E. g. I replaced the registry settings, used sfc /scannow without success.
In Windows 7 there is no dllcache, so I really don't know what is preventing renaming.

A:
My problem is that I can't install msi files anymore. Everytime after some dialogs
  I get an error message that the corresponding msi file can't be read

This sounds a little bit strange. If you see MSI dialogs and the install fails when you kick it off there must be something else wrong. I assume you have, but have you verified that the problem exists with multiple MSI files? Try with a fresh MSI file, preferably one that you downloaded fresh from the Internet. Try to run from the local disk and from a network disk.
Have you enabled logging for the install? Try to do so with flush to log enabled (the ! character enables continuous flushing to log so that an msiexec.exe crash doesn't leave an empty log file):
msiexec.exe /i C:\Path\Your.msi /L*vx! C:\Your.log

See msifaq.com for more details (logging faq entry). Search for "value 3" in the log file to find errors as explained by Rob Mensching (Wix & Orca author).
Also try to disable any anti virus software and / or desktop security that may be interferring with the file extraction from the MSI's cab file. Is there plenty of disk space? Are there any errors found during a disk scan?

A: Are you trying to revert to a previous version of Windows Installer? Here is some information: http://support.microsoft.com/?kbid=315346.
I suppose you could use system restore as well, but that would have other side effects.
What is the overall problem? Windows Installer 5 does not seem to introduce anything very controversial: http://msdn.microsoft.com/en-us/library/windows/desktop/dd408114(v=vs.85).aspx


text:
Q: URLError in Python I am trying to understand if I can handle the following error in python.
So I have a program which repeatedly calls the following line:
candidate = urllib2.urlopen(absolute_path)

After running my program for some seconds, I turned off my wifi connection, and got the following error:
File "crawler.py", line 28, in urlQuery
  candidate = urllib2.urlopen(absolute_path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
  return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
  response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
  result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open
  return self.do_open(httplib.HTTPConnection, req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open
  raise URLError(err)
urllib2.URLError: <urlopen error [Errno 65] No route to host>

Is there any way I can handle this error?

A: Depends what you want to do when you get this Exception. You can use try-except, standard Python's exception handling technique.
try:
    candidate = urllib2.urlopen(absolute_path)
#except Exception as e: # catches any exception
except urllib2.URLError as e: # catches urllib2.URLError in e
    print ('WiFi connection perhaps lost !! Trying one more time...')
    try:
        candidate = urllib2.urlopen(absolute_path)
    except:
        print ('WiFi connection really lost !! Bailing out..')
        print (e) # print outs the exception message


text:
Q: Filter exact date/time in postgresql I'd like to filter out a record based on update time in Postgresql. My table, under update_timestamp field is storing the following dates:
update_timestamp
April 19, 2022, 7:03 PM
April 19, 2022, 7:01 PM

The timestamp for the second row is 2022-04-19 19:01:11:
SELECT to_char(update_timestamp,'YYYY-MM-DD HH24:MI:SS')
from my_table

to_char
2022-04-19 19:03:44
2022-04-19 19:01:11

Then, if I want to query the second date and time, I am converting string to timestamp:
select update_timestamp
from my_table
where update_timestamp = to_timestamp('2022-04-19 19:01:11','YYYY-MM-DD HH24:MI:SS')

As alternative, I can try another syntax:
select update_timestamp
from my_table
where update_timestamp = '2022-04-19 19:01:11'::timestamp

What is the proper way to query date/time when passing a string? Am I doing something wrong?
Why a query such as this one is giving me the row I need (2022-04-19 19:01:11):
select update_timestamp
from my_table
where update_timestamp < '2022-04-19 19:03:00'

However, a query including the specific value as the following does not return any value:
select update_timestamp
from my_table
where update_timestamp = '2022-04-19 19:01:11'

Is the postgresql engine just able to query date ranges? This is working fine to get 2022-04-19 19:01:11:
select update_timestamp
from my_table
where update_timestamp > '2022-04-19 19:01:10' and update_timestamp < '2022-04-19 19:01:12'

Thanks

A: For a specific value of timestamp you should use date_trunc function, since timestamp has precision of microseconds
so for your example should be:
select update_timestamp
from my_table
where date_trunc('second',update_timestamp) = '2022-04-19 19:01:11';


text:
Q: Filter WooCommerce products by custom attribute I import a huge amount of goods. Each already has custom attributes. How can I use them to filter products in a storefront? I cannot manually create such a huge number of attributes and assign them to each of the goods. Perhaps there is some kind of plugin?
P.S. I know that such a question already exists here, but it was asked back in 2013 and since then much has changed.
Waiting for help!
Thanks.


text:
Q: What's the phrase/idiom for 'being very disappointed in someone'? I'm writing this piece of text, and sometimes it can be tricky, because English is not my first language, so obviously most of the time I think in my mother tongue.
We have this phrase in my language, a word-for-word translation of which is 'to fall in someone's eyes' - it is used when you do something that makes the other person greatly disappointed in you to the point where they don't want anything to do with you.
I browsed the Internet, and this phrase does not seem to be used in English. But I also failed to find anything similar. All the other options I was considering just don't convey the seriousness and importance I'm looking for.

A: Let down
'Let down' by someone means that you feel disappointed in their behaviour, being less than you'd expected.
Example:
I feel very let down that he didn't show up when he promised.
I feel let down by him.
He let me down.
https://www.macmillandictionary.com/dictionary/british/let-down

A: To fall from grace, &  Good books/bad books
Fall from grace is very close to what you ask, it is very close to 'fall, in someone's eyes' though often used in the context of 'a society' or 'a community' or 'authority' rather than individually.
Examples:
He fell from grace, in the dean's eyes, when he was caught cheating in the exam.
He fell from grace, in her eyes, when he was unfaithful to her.
He fell from grace, in the eyes of the team, when he missed the catch.
Note: Grace means 'blessed by God'. If you are outside of that, then you may find yourself outside of society's approval also.
It also implies that before, 'he was in her grace' or was 'in her good graces' (expression) - meaning, admired, revered, possibly even worshipped, by her.
https://www.yourdictionary.com/fall-from-grace
Similar to this, is 'In her good books' or 'in her bad books', meaning, respectively, receiving, or not having, her favour. Such 'books'  being, presumably, a list of names of individuals who are favoured, or disfavoured, by her.
https://dictionary.cambridge.org/dictionary/learner-english/be-in-sb-s-good-bad-books
A poem about such things is popping into my mind, it's lovely, so I'll share it here:
https://www.poetryfoundation.org/poems/44433/abou-ben-adhem


text:
Q: How to config yii2 db connection with a mysql ndb cluster? I have a mysql cluster with 2 sql nodes, I want to use yii2 to connect this cluster without more coding. It's perfect with Elastich search cluster with a thirth party doing like the bellow:
  'elasticsearch' => [
       'class' => 'yii\elasticsearch\Connection',
       'nodes' => [
            ['http_address' => '127.0.0.1:9200'],
            // configure more hosts if you have a cluster
        ],
        'dslVersion' => 7,
   ],

How can we do this with a mysql cluster?

A: after a range time for testing, I have an easy solution want to share for everyone needed.
We just use Yii db replication config, the master's array config is the nodes of mysql ndb cluster, that't it!
[
    'class' => 'yii\db\Connection',

    // common configuration for masters
    'masterConfig' => [
        'username' => 'sqlnodeuser',
        'password' => 'sqlnodepass',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    // list of master configurations
    'masters' => [
        ['dsn' => 'dsn for ndb sql node 1'],
        ['dsn' => 'dsn for ndb sql node 2'],
    ],
]

from yii2 official document: https://www.yiiframework.com/doc/guide/2.0/en/db-dao


text:
Q: Get the query which ran on a mysql connection I am using show processlist in mysql to list all the connections held by my tomcat server.
One of the connection is long running and I want to know which was the query that last ran on this connection, to be able to find a component which hasn't released the connection. Is there any way to find this out? The codebase is huge, and this could help me find the bug faster.
The INFO column in show process list currently shows NULL


text:
Q: Calculated member expression in SSAS 2008 I need to create a calculated member to a cube to show me the total amount due invoices for each customer less than or equal to 60 days.
I understand that I can find the current date minus the date of the invoice and, if the result in days, is less than or equal to 60, then make the sum of all invoices for each customer.
I don't khow how implement this into the expression for a calculated member. I have done this, but I get error in the SELECT and I don't know why:
CREATE MEMBER CURRENTCUBE.[Measures].[Importe60]
AS Sum([Measures].[Importe de la factura])

SELECT [Measures].[Importe60] ON COLUMNS,
[Clientes].[Nombre].Members ON ROWS
FROM CuboVentas
WHERE DateDiff(dd,[Facturas].[Fecha Factura],getDate())<=60,

VISIBLE = 1, ASSOCIATED_MEASURE_GROUP = 'Facturas clientes';

Does anyone know what I'm doing wrong?

A: The problem is with your WHERE-clause.  In MDX, the WHERE-clause should be used as a means for filtering the cube-space.  Then everything in the SELECT-clause is based upon the remaining "sub-cube".
Also, there's no need for the calculated member...the SUM() function is redundant in this case (assuming the aggregation function specified for the [Measures].[Importe de la factura] is SUM).
Here's one way to write the query that is close to the format you have above...
SELECT
    {
        [Measures].[<<measure>>]
    } ON 0,
    {
        [Business Unit].[Division].[Division].Members
    } ON 1
FROM
    [<<cube>>]
WHERE
    {StrToMember("[Order Date].[Date Key].[" + Format(now(), "yyyyMMdd") + "]").Lag(59)
    :
    StrToMember("[Order Date].[Date Key].[" + Format(now(), "yyyyMMdd") + "]")}

Notice how the WHERE-clause specifies a set along the [Order Date] dimension. This basically says give me the entire cube space across all the dimensions...except for the order date dimension for which I just want the set specified".
Also, if you write the query like the following, it may be a bit easier to understand what's going on...
WITH
SET [Past 60 days] AS
    StrToMember("[Order Date].[Date Key].[" + Format(now(), "yyyyMMdd") + "]").Lag(59)
    :
    StrToMember("[Order Date].[Date Key].[" + Format(now(), "yyyyMMdd") + "]")
MEMBER [Measures].[Total Sales Past 60 days] AS
    SUM(
         [Past 60 days]
        ,[Measures].[<<measure>>]
    )
SELECT
    {
        [Measures].[Total Sales Past 60 days]
    } ON 0,
    {
        [Business Unit].[Division].[Division].Members
    } ON 1
FROM
    [<<cube>>]

Note: The "StrToMember()" formula works in my cube because the datekey is in YYYYMMDD format.  yours may be in a different format so you may have to tweak it.


text:
Q: Change UITableViewCell's properties from the presented view In a UITableViewCell on a button click, I do
EditPostViewController.type = "post"
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "editPost") as! EditPostViewController
top?.present(nextViewController, animated: true, completion: nil)

To go to EditPostViewController.
Now in this EditPostViewController, I have a textbox, the user edits and the clicks the back button.
How can I edit the variables of that particular UITableViewCell from  EditPostViewController after some button click event?
So I tried taking the variable of self in the UITableViewCell and then editing it in the EditPostViewController like
EditPostViewController.instance = self

And in EditPostViewController
EditPostViewController.instance.label.text = "something"

This doesn't work. This says that UITableViewCell has no property named instance. Any idea how can I edit the value of this label in the UITableViewCell from EditPostViewController?

A: You can take a look at unwind segues to solve your problem (there are other ways as well).
The iOS developer jump right in page found here can show you detailed instructions on how to get it going:
https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementEditAndDeleteBehavior.html
Basically what you need to do is obtain the target view controller from the EditPostViewController during the unwind segue and update it's datsource. The unwind segue is an @IBAction defined on the "Back" button of the EditPostViewController (or any other button for that matter).


text:
Q: How to change the background color on a view from different activity I need to change the background color on the navigation's header, when i findViewById() in MainActivity I get null.
This is the navigation header,
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_second_header_bg"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#00aeef"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="12dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/school"
        android:layout_width="wrap_content"
        android:layout_height="88dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/schatkamer" />

    <TextView
        android:id="@+id/nav_second_header_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/school"
        android:layout_marginEnd="15dp"
        android:layout_toStartOf="@+id/school"
        android:text="account name"
        android:layout_marginRight="15dp"
        android:layout_toLeftOf="@+id/school" />

</RelativeLayout>

And this is The code in onCreate MainActivity
        second_bar_header = findViewById(R.id.nav_second_header_bg); //this id returns null
        second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));

        TextView tv = findViewById(R.id.nav_second_header_text); // this is null
        tv.setText("hi");

A: YOu should try something like this
    NavigationView navigationView =  findViewById(R.id.you_nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    View header = navigationView.getHeaderView(0);

    TextView username =  header.findViewById(R.id.nav_second_header_text);
    username.setText("Hi");

    second_bar_header = header.findViewById(R.id.nav_second_header_bg);
    second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));


text:
Q: 'ADD_MONTHS' is not recognized as a function or procedure in Derby Database I created table using Derby database
CREATE TABLE PROJECT
(PID  INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY,
PSDATE DATE,
PDURATION INTEGER,
PEDATE DATE,
PRIMARY KEY (PID)
);

I attempted to update end date in this project table, adding duration to start date
UPDATE PROJECT
SET PEDATE = ADD_MONTHS (PROJECT.PSDATE, PROJECT.PDURATION)
WHERE PID = PROJECT.PID;

But I am getting  below error
"[Exception, Error code 30,000, SQLState 42Y03] 'ADD_MONTHS' is not recognized as a function or
 procedure.
 Line 1, column 1"

Thanks in advance to help me to solve this problem

A: you need to tag your database , in mysql you can do:
UPDATE PROJECT
SET PEDATE = DATEADD (PROJECT.PSDATE, interval PROJECT.PDURATION month)
WHERE PID = PROJECT.PID;

in postgresql :
UPDATE PROJECT
SET PEDATE = PROJECT.PSDATE + interval '1 month' * PROJECT.PDURATION
WHERE PID = PROJECT.PID;

A: As a update Query this works in Derby.
  UPDATE PROJECT
  SET PEDATE = DATE( {fn TIMESTAMPADD(SQL_TSI_MONTH, PDURATION, PSDATE)} );


text:
Q: Border Style-Tigger doesn't accept background setter I've got a small problem, which can be solved for now differently, but I would like to do it via the Style.Trigger of the Border.
My current style for the border looks like this:
    <Style x:Key="style_BorderStatus" TargetType="{x:Type Border}">
        <Setter Property="Height" Value="75"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Background" Value="#ccc"/>
        <Setter Property="IsEnabled" Value="False"/>
        <Style.Triggers>
            <Trigger Property="IsEnabled" Value="true">
                <Setter Property="Background" Value="#9f9"/>
                <Setter Property="Cursor" Value="Hand"/>
            </Trigger>
        </Style.Triggers>
    </Style>

My Border looks like this:
<Border Grid.Column="0" Margin="2 2 1 2" Style="{StaticResource style_BorderStatus}">
    <TextBlock x:Name="txtStatusKind" Foreground="#999" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24"/>
</Border>

This works fine so far, even the cursor changes after I set the border to IsEnabled=true.
This means that the trigger style basically works already.
But why is the background setter not affected?

A: I found my mistake, thanks to @Clemens' hint. I've an initialization method in which I set the color values initially, this also has a higher priority than the styles.
It works now, thanks @all


text:
Q: Installing and running VMWare Workstation 10 on Ubuntu 14.04 I'm having trouble installing and running VMWare Workstation 10 on Ubuntu 14.04.
I've tried the vast majority of posts I have found on this topic and none of them have resolved my issue. I have uninstalled VMWare and reinstalled it to get back to a known point and will happily cover old ground again to try and resolve the issue. My thinking is that it's better to start from a known point and post everything that goes wrong individually so that it helps others with the same problem rather than starting halfway through the fix.
The only thing that I ask is that people explain how to do certain steps, for instance instead of saying "just untar the tarball edit the "*.config" file, would you please explain how to do that?
When I try to run the application it produces an alert which tells me to check a log file. Upon checking the log file, the last couple of entries are (can get more if required):
2016-02-16T15:04:23.286Z| vthread-3| I120: Setting destination path for vmnet to "/lib/modules/3.19.0-25-generic/misc/vmnet.ko".
2016-02-16T15:04:23.286Z| vthread-3| I120: Extracting the vmnet source from "/usr/lib/vmware/modules/source/vmnet.tar".
2016-02-16T15:04:23.290Z| vthread-3| I120: Successfully extracted the vmnet source.
2016-02-16T15:04:23.290Z| vthread-3| I120: Building module with command "/usr/bin/make -j8 -C /tmp/modconfig-TT9hWO/vmnet-only auto-build HEADER_DIR=/lib/modules/3.19.0-25-generic/build/include CC=/usr/bin/gcc IS_GCC_3=no"
2016-02-16T15:04:24.202Z| vthread-3| W110: Failed to build vmnet.  Failed to execute the build command.

Any help would be much appreciated.
--------------------------------- Update -------------------------------------
So I decided to carry on trying to fix this myself. This is what I've tried so far, but growing increasingly desperate:
Workstation 10.0.6 downloaded and installed without any issues. On first run, VMWare produces an error stating:
"Unable to start services.
See log file /tmp/vmware-root/vmware-modconfig-9432.log for details."
Upon investigation of that log I discovered it was failing here:
2016-02-18T11:27:59.249Z| vthread-3| I120: Building module with command "/usr/bin/make -j8 -C /tmp/modconfig-07fLDu/vmnet-only auto-build HEADER_DIR=/lib/modules/3.19.0-49-generic/build/include CC=/usr/bin/gcc IS_GCC_3=no"
2016-02-18T11:28:00.176Z| vthread-3| W110: Failed to build vmnet.  Failed to execute the build command.

I have looked online and there seems to be a lot of trouble with this. I tried to apply the fix mentioned here: Error Installing Vmware Workstation On Ubuntu however, this creates an error
Hunk #3 FAILED at 259.
1 out of 3 hunks FAILED -- saving rejects to file vmnet-only/filter.c.rej

I looked into what this error was and it produces this:
*** /dev/null
--- /dev/null
***************
*** 259
- transmit = (hooknum == VMW_NF_INET_POST_ROUTING);
--- 263,267 -----
+ #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 13, 0)
+ transmit = (hooknum == VMW_NF_INET_POST_ROUTING);
+ #else
+ transmit = (ops->hooknum == VMW_NF_INET_POST_ROUTING);
+ #endif

Any assistance is much appreciated.

A: I raised a service ticket with VMWare who in turn informed me that VMWare 10 was not compatible with this Kernel version due to the age of the product. VMWare upgraded my product to VMWare Workstation 12 which I downloaded, installed, and ran without issue.

A: You need to install build-essential
sudo apt-get install build-essential

To execute:
 chmod +x VMwarexxxxxxx.bundle

and
./VMwarexxxxxxx.bundle


text:
Q: Angular 6 watcher does not compile imported less files in main.less Am working on Angular version 6.
And I am using Less for styling.
In Angular previous Versions, I had to include less main file in angular_cli.json file and that worked perfectly for me.
In latest Angular 6 version we have a file called angular.json and I did the same thing. I have added the main.less file inside styles: [].
But the issue that I am facing is that for some reason when my watcher is running it compiles main.less file alone. Imported LESS files are compiling only when I restart the watcher.

A: I found the solution for this.
Run this command
npm install --save-dev less-loader@3.0.0

and
I add this in angular.json
"schematics": {
    "@schematics/angular:component": {
      "styleext": "less"
    }
  },

This allowed Angular to generate less files by default.
Thank you :-)


text:
Q: ds4drv problem with steam Any one using ds4drv to emulate a 360 controller with a dualshock 4 ?
I have installed it and can take input from the controller, change the led colour, use the trackpad as a mouse and emulator recognize an xbox 360 controller, so this all seems good, right ?
The problem comes when I try Steam games, there is just no input from the controller, none at all while ds4drv is running.
The driver says it is running, and I gave my user the permissions but nothing.
This is the command I use to start it via USB
ds4drv --hidraw --emulate-xpad

Out put of this is
[info][controller 1] Created devices /dev/input/js0 (joystick) /dev/input/event17 (evdev)
[info][controller 1] Connected to USB Controller (1C:66:6D:44:A5:39 hidraw5)
[info][hidraw] Scanning for devices
[info][controller 1] Battery: Fully charged

Looks all good to me, all I can think is the kernel driver and ds4drv are conflicting, how can I disable the kernel driver for the ds4 ?

A: I got my hands on ds4drv this weekend, got some problems with it too(though my problem is a bit harder as I'm trying to use DS4 with Dark Souls in Wine through Steam).
First, native driver can interfere with your config (it works perfectly with DS4 though, native Steam detects controller as DS4 and all seems good), so you may wants to just delete /dev/input/jsX of native driver (do not unload hid_sony module as ds4drv --hidraw seem to use it).
Second, ds4drv by default starts in some sort of limited profile (just led and trackpad probably), so you may want to play with ds4drv config file to enable profile switching button (PS button by default) and configure your other profiles.


text:
Q: BackboneJS How to add -method to model I have made a Model which I made to display the whole discography of a band which I get delivered by an API as JSON. So far so good, but I need to sort the albums by its releasedate, so I intent to use the comparator-method, which is not possible to use on Models. So I want to "transform" the Model into a Collection, or is there maybe a better way?
Here is my model I define on my discography.js:
ArtistDiscography.ArtistDiscographyModel = Backbone.Model.extend({
    url: function() {
        return App.APIO + '/i/artist/' + this.get('slug') + '/releases';
    },
    parse: function(response){
        return response.data;
    },
});

the slug value is the JSON value, which returns for example rihanna. The JSON file also contains a value called releaseDate.
In my maincontroller.js, I have this:
define(function (require, exports, module) {
    var ArtistDiscographyModule = require('modules/discography');
)};

ArtistController.prototype.initDiscography = function(name) {
    this.artistdiscographyModel = new ArtistDiscographyModule.ArtistDiscographyModel({slug: name});
    this.artistdiscographyModel.fetch();
    this.artistdiscographyModel.on('sync', function() {
        this.artistDiscographyView = new ArtistDiscographyModule.View({model: this.artistdiscographyModel});
        App.useLayout('artistDiscography', 'artistDiscography').setViews({
            '.releasesDiv' : this.artistDiscographyView,
        }).render();
    }, this);
};

The JSON response is:
data: [{
  "slug" : "rihanna",
  "releases": {
        "title" : "Music Of The Sun",
        "releaseDate": "2005-08-29",
        "tracks": [{ //array of tracks}]
  }, {
       "title" : "Pon de Replay",
       "releaseDate": "2005-08-22"
       "tracks" : [{ //array of tracks}]
  }
}]

Can someone help me out? I would really appreciate it!

A: You can set collection as an attribute of model:
ArtistDiscography.ArtistDiscographyModel = Backbone.Model.extend({
    defaults: {
        slug: '',
        releases: new Releases()
    }
});

Releases = Backbone.Collection.extend({
    model: Release
});

Release = Backbone.Model.extend({
    defaults: {
        title: '',
        releaseDate: '',
        tracks: []
    }
});

Then you can add comparator into Releases collection.
Or you can go dirty and use the underscore's sort function for array:
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

A: Have you tried something along these lines?....
ArtistDiscographyCollection = Backbone.Collection.extend({
    model: ArtistDiscography.ArtistDiscographyModel,
    comparator: function (model) {
        return (model.get('releases').releaseDate);
    }
});


text:
Q: Nested herodoc order of operations I have the following code -
ssh host sh -s << EOF
cd /backup/

ls

psql -U user -d db << SQL
$(sed 's/${previous_quarter}/${current_quarter}/' table_quarters.sql);
$(sed 's/${previous_quarter}/${current_quarter}/' plans.sql);
SQL

EOF

This is the order of execution it is following when I execute it -

*

*table_quarters script

*plans script

*ls command.

Why is it not following this order of execution -

*

*ls command

*table_quarters script

*plans script

A: You are sending a string to the standard input of ssh. This string can only be constructed if the stuff in $(...) is run first, because these parts will be replaced by the output of the enclosed commands.
Once the string is expanded, it's send by ssh to the remote machine which runs the resulting commands in order.
If you want to run the expansions on the remote end, you need to properly escape the dollar signs.


text:
Q: Active directory VBS to VB Hi I need to rewrite VBS script to VB file but I have trouble with following.
In VBS there is this:
Set OU = GetObject(LDAP_Path)
OU.Filter = Array("OrganizationalUnit")
For Each Item In OU
Description_OU = CStr(Item.Get("Description")) //Here is problem
...

In VB (2010) im using "System.DirectoryServices." because I need to work with Active Directory
My question:
How it is that sometimes the Description_OU is empty and how can I test that in VB where Item is:
Dim Item = System.DirectoryServices.DirectoryEntry

In another words: I cannot find anthing like "Description" in .DirectoryEntry
thanks

A: Item.Property("Description")(0).tostring

"Description" = key


text:
Q: PHP - Extracting text from HTML I have a long string of HTML that contains

and a bunch of other tags.
Is there anyway of extracting ONLY the text within the tags from this string?

A: If you want to extract all text within any tags, the simple way is to strip the tags: strip_tags()
If you want to remove specific tags, maybe this SO questions helps.

A: I know I'll be getting a lot of bashing for this, but for a simple task like this I'd use regular expressions.
preg_match_all('~((.*?))~', $html, $matches);

$matches[0] will contain all the span tags and their contents, $matches[1] contains only the contents.
For more complicated stuff you might want to take a look at PHP Simple HTML DOM Parser or similar:
// Create DOM from URL or file
$html = str_get_html($html);

// Find all images
foreach($html->find('img') as $element) {
   echo $element->src . '
';
}

Etc.


text:
Q: Is the number 20 magic? I have references that advised to consider a sample size of minimum 20 for data fitting distribution.
Is there any sense in this?
thanks

A: I thought the sample size magic number is 1,000. That's what most US national polls have, to produce the margin of error of about 3%:
$$
z_{0.975}\sqrt{0.5\cdot0.5/1000} = 1.96 \cdot 0.158 = 0.031
$$
In reality, the effective sample sizes are lower than 1,000, more like 700 or so, due to unequal probability of selection and non-response adjustments, leading to the margin of error of 3.7%.
With just 20 observations, you technically cannot get very high values of skewness and kurtosis (normalized by the sample standard deviations, of course):
$$
|\mbox{skewness}| \le \frac{n-2}{\sqrt{n-1}} = 4.58, |\mbox{kurtosis}| \le \frac{n^2 - 3n + 3}{n-1} = 18.05.
$$
If you are fitting a distribution by the method of moments, you obviously cannot fit say a lognormal distribution with a reasonably typical variance of logs equal to 1 (income distributions in moderate-to-high income inequality countries; US, Brazil, South Africa, Russia all have higher variance of log-incomes), as it has a surprisingly large kurtosis of 111. Of course it would be silly to fit a lognormal distribution by the method of moments, but I just wanted to show that some real world distributions will likely be more complicated than what can be described with 20 observations.
Another view on distribution fitting can be taken through kernel density estimation: for the sample of size $n=20$, the most popular rule gives the bandwidth of
$$
h=1.06 \hat\sigma n^{-1/5}=0.58\hat\sigma
$$
which effectively spans the whole distribution using the Gaussian kernel. In other words, most samples of size 20 will look normal if you run kernel density estimation across them, unless they clearly have a notable kurtosis (which would then mean that there are some outlying observations that will show up as separate bumps on the kernel density plot).

A: Nope.  Not remotely.
Think about it like this: if you had a billion-dimensional space (humanity) and you pulled 20 samples out using whatever method (20 people) could you use information gained them to understand reasonably well every person on the planet?  Not remotely.  There are 100 billion stars in the Milky Way galaxy.  By picking (randomly) 20 of them can you understand all of galactic astronomy?  No way.
In a 1-d space there are some heuristics, mostly valid rules of thumb that can help, that describe how many measurements you want to take.  They include varying degrees of utility and justification but are in some sense more well defended than "20".  They include "5 measurements per variable in your fit equation", "at least 35 samples of a Gaussian density function", and "at least 300 samples of a binomial function".  Real statisticians and not a nerd-bomber like me will be able to associate particular confidence intervals and uncertainties from first principles and without a calculator.
If you use the rule of "5 measurements per parameter in your fit equation" and you want to fit the cumulative density of a 2 dimensionally curved bi-cubic surface in terms of distribution of heights you are going to have an underlying system that is $ \int {\int {\frac {a_3{r^3}+a_2{r^2}+a_1r+a_0}{a_1r+a_0}}} dr $, a ratio of a 5th order polynomial to a cubic.  It will have 6+4=10 coefficients.  If you are trying to fit your 10 parameter values using 2 measurements per parameter, or by using 20 measurements, then you will be violating this heuristic.  This heuristic recommends a minimum of 10*5=50 measurements.
Please remember "best" is a meaningless idea without having a "measure of goodness".  What is the best path?  If you are going to your doom, maybe an extremely long and pleasant one.  If you are going to your own coronation, maybe a short and magnificent one.  If you are walking through the desert, a cool shady one.  What is the "best" number of samples?  It is so stunningly dependent on your problem that it cannot begin to be answered with authority before that.  All of them?  As many as you can?  Those only make a little sense.  Yes it is like being partially dead or pregnant.  Being partially nonsensical is a consequence of a very under-defined problem.
If you are trying to accurately forecast airflow over a plane?  You might need several million measurements to get into the ball-park.  If you want to know how tall you are, one or two might do the job.
This does not bring up the important points of "spanning the space" and "sampling at locations that minimize variance in parameter estimates" but the the question suggested a more freshman-level answer would be relevant.  These things require knowing more about the nature of the problem before they can be implemented.
Note: edited to improve per suggestions.

A: So much of this depends on the expected distribution and what your research question is.  As a rule of thumb, you should be wary of rules of thumb. If you know the expected distribution, run some simulations of different sizes and determine how often the sample simulations reflect the actual distribution.  This should give you some guidance as the final required sample size.

A: Perhaps for the context where you're carrying out t-tests or ANOVAR - a pretty common context in basic statistical applications - it's around the sample size you need for each group in order to be able to have much confidence in each group's mean's being approximately normally distributed (according to the central limit theorem) when the distribution can be assumed to be more or less unimodal & not extremely peaky.  Twenty & not nineteen or twenty-one because it's a round number.

A: Check Russ Lenth's Power and Sample Size Page for some articles on the subject (in the Advice section in the middle of the page).
The minimum number of individuals in your sample varies wildly according to population size, the number of dimensions (if you are dividing the data in categories) and measures (if you are taking continuous measures about the sample indivifuals) you are taking, the size of your universe, the technique of analysis you intend to use (this is a very important point - technique is defined during the planning of the study or during experimental design, never after), and complexity shown by previous studies.
And 20 is not enough for any serious research outside the subjects of "rare diseases" and "experimental psychology" (psych as Popper defined in his work).
Refining the answer based on comments below:
And 20 is not enough for any serious research outside the subjects of "rare diseases" and "experimental psychology" (psych as Popper defined in his work) that involves fitting a probability distribution.
And no, you should not keep poisoning people to get to a large sample size. Common Sense and Sequential Tests order you to stop.


text:
Q: Vue.js firebase instance - Users UID as database ref Is it possible to get the following example working? I have pushed some objects into the firebase realtime-database and the reference is the UID of the signed in user. But even if I want to query  the object at the reference which we can get from firebase.auth.currentUser.uid, I'm getting an error uid of NULL. Is there a way to get this functionality working?
The Vue.js Code:
import firebase from '.././firebase';
import { db } from '.././firebase';

export default {
    name: 'addMatch',
    data() {
        return{
            tableTennisData: [],
            player1Name: '',
            player2Name: '',
            //Game 1
            firstMatchPlayer1Game1: '',
            firstMatchPlayer1Game2: '',
            firstMatchPlayer1Game3: '',
            firstMatchPlayer1Game4: '',
            firstMatchPlayer1Game5: '',
      }
    },

    firebase: {
        tableTennisData: db.ref(firebase.auth().currentUser.uid).child('tableTennis'), // UID Of Null error!
    },
        addMatch: function (e){
            e.preventDefault();
            const obj = {
            //Game 1
            player1Name: this.player1Name,
            player2Name: this.player2Name,
            firstMatchPlayer1Game1: this.firstMatchPlayer1Game1,
            firstMatchPlayer1Game2: this.firstMatchPlayer1Game2,
            firstMatchPlayer1Game3: this.firstMatchPlayer1Game3,
            firstMatchPlayer1Game4: this.firstMatchPlayer1Game4,
            firstMatchPlayer1Game5: this.firstMatchPlayer1Game5,
            }
            firebase.auth().onAuthStateChanged(function (){
                db.ref(firebase.auth().currentUser.uid).child('tableTennis').push(obj);
            });

            console.log(obj);
        },

    },

A: It sounds like the user isn't signed in yet.
Keep in mind that it takes a moment for Firebase to restore the user's authentication state when you load a page. If you call auth.currentUser before that, you will get back null.
tableTennisData: db.ref(firebase.auth().currentUser.uid).child('tableTennis'),

I don't see where you call this code, but you'll want to wrap it in an onAuthStateChanged handler as you already do in addMatch.


text:
Q: Merge columns with the same name - Python Hi I'm having a quick problem where I want to merge the two columns into just one. The two columns are actually the same but with different names

A: If you're using Pandas and Assuming the Type of the values in the columns are not strings, You can try this:
df.fillna(0, inplace=True) #this will fill the NaN values with 0. This is required for the next step
df['column1'] = df['column1'] + df['column1_A'] #Add the 2 columns

If there is a value in the 1st column and the value in the 2nd column is NaN, the resulting value is the value of the column that has the value.
If however, both columns have values, then their values will be added.

A: Assuming you are using a dataframe, you can use combine_first or fillna:
column1 = df['column1'].combine_first(df['column1_A'])
0    1
1    2
2    3
3    4
4    5

Documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html
or
column1 = df['column1'].fillna(df['column1_A'])
0    1
1    2
2    3
3    4
4    5

Documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html


text:
Q: What's the equivalent of PHP's "$my_array[]" in Python? What's the equivalent of PHP's "append to array" ($my_array[] = "abc";) in Python, which I have recently started learning?
Let's say that I've a dictionary like this:
my_dict = {'fruits':['orange', 'pear']}

And now I want to add another fruit to my_dict['fruits']: apple

A: .append() adds new elements:
my_dict = {'fruits':['orange', 'pear']}
my_dict['fruits'].append('apple')

A: Python is great for experimenting and helping you find things like this, and as you already know roughly what you're looking for (just named/termed differently), then here's a tip that should make it a bit easier for you...
>>> my_dict = {'fruits':['orange', 'pear']}
>>> type(my_dict['fruits'])
<type 'list'>

So we know that it's list (in this case the built-in list type)... We know we want to "add" something to it... So let's look at what it offers...
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

insert, extend and append look useful... Let's see what it says...
>>> help(list.extend)
Help on method_descriptor:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable

Doesn't sound quite right...
>>> help(list.insert)
Help on method_descriptor:

insert(...)
    L.insert(index, object) -- insert object before index

Seems a little specific about positioning...
>>> help(list.append)
Help on method_descriptor:

append(...)
    L.append(object) -- append object to end

Hey, looking good :)
It just so happens that in this instance, you could just do help(my_dict['fruits'])...


text:
Q: Conditional modifying of rows in a dataframe in R In my Data, I'm trying to change y to qlogis(y) when dv=="B".
But I wonder why I get a warning message saying NaNs produced?
Note that .5 and .6 are between 0 and 1 and shouldn't return any NaNs.
library(dplyr)

Data = read.table(text=
"
id dv y
1  A  2
1  B  .5
1  C  11
2  A  4
2  B  .6
2  C  19
", h=TRUE)

mutate(Data, y = ifelse(dv=="B", qlogis(y), y))

A: We may use replace to apply only qlogis to subset of data and not on the full data
library(dplyr)
Data %>%
   mutate(y = replace(y, dv == "B", qlogis(y[dv == "B"])))

-output
 id dv          y
1  1  A  2.0000000
2  1  B  0.0000000
3  1  C 11.0000000
4  2  A  4.0000000
5  2  B  0.4054651
6  2  C 19.0000000

i.e.
> qlogis(2)
[1] NaN
Warning message:
In qlogis(2) : NaNs produced
> qlogis(0.5)
[1] 0

The warning is related to how the ifelse process the output i..e all the arguments should have the same length.  Thus, qlogis(y) gets applied to the whole column and inside the function, it is processed so that only a subset is returned.  But, the warning already comes from the qlogis function resulting from NaN on values greater than 1. i.e. in the source code
...
p = log(lower_tail ? (p / (1. - p)) : ((1. - p) / p));
...

Thus a value greater than 1 with default case of lower.tail argument TRUE
> log((2/(1-2)))
[1] NaN
> log((1/(1-1)))
[1] Inf

> qlogis(1)
[1] Inf
> qlogis(0.9)
[1] 2.197225
> qlogis(1.2)
[1] NaN
Warning message:
In qlogis(1.2) : NaNs produced

ifelse
function (test, yes, no)
{
...

 ans <- test
    len <- length(ans)
    ypos <- which(test)
    npos <- which(!test)
    if (length(ypos) > 0L)
        ans[ypos] <- rep(yes, length.out = len)[ypos]
    if (length(npos) > 0L)
        ans[npos] <- rep(no, length.out = len)[npos]
    ans
...

Now, we do the same steps as in the ifelse code
> test <- Data$dv == "B"
> ans <- test
>  len <- length(ans)
>     ypos <- which(test)
>     npos <- which(!test)
> ypos
[1] 2 5
> npos
[1] 1 3 4 6
> yes <- qlogis(Data$y)### it is the input on the whole column
Warning message:
In qlogis(Data$y) : NaNs produced


text:
Q: Delete all the Hangfire jobs At startup, I try to delete all the existing hangfire jobs, but none of the methods I use seem to work.
Notice that I use a MongoDB database, but not sure it is related to the issue.
Here is how I add my job:
RecurringJob.AddOrUpdate<IPostIndexerJob>(j => j.Execute(), configuration.GetValue<string>("Job:Interval"));

Here is my code, if anyone has an idea that help?
static private void ScheduleJobs(IConfiguration configuration)
        {
            PurgeJobs1();
            PurgeJobs2();
            PurgeJobs3();
        }

        static private void PurgeJobs1()
        {
            var mon = JobStorage.Current.GetMonitoringApi();
            mon.EnqueuedJobs("socloze-elasticsearch-post-indexer", 0, 99999999).ForEach(x =>
            {
                BackgroundJob.Delete(x.Key);
            });
        }

        static private void PurgeJobs2()
        {
            var monitor = JobStorage.Current.GetMonitoringApi();
            foreach (var queue in monitor.Queues())
            {
                PurgeQueue(queue.Name);
            }
        }

        static private void PurgeJobs3()
        {
            // Clean
            foreach (var item in Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs())
                RecurringJob.RemoveIfExists(item.Id);
        }

        static private void PurgeQueue(string queueName)
        {
            var toDelete = new List<string>();
            var monitor = JobStorage.Current.GetMonitoringApi();

            var queue = monitor.Queues().First(x => x.Name == queueName);
            for (var i = 0; i < System.Math.Ceiling(queue.Length / 1000d); i++)
            {
                monitor.EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x => toDelete.Add(x.Key));
            }
            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }

A: To delete recurring job (what i think you meant) you should firstly ask your storage to provide you all recurring jobs you have set:
jobStorage.GetConnection().GetRecurringJobs(); // where jobStorage is your storage instance, you can access it via JobStorage.Current in static context.

then delete a desired entry:
recurringJobManager.RemoveIfExists("someId"); // where recurringJobManager is instance of IRecurringJobManager

then PurgeJobs3() should work as expected (as it uses IRecurringJobManager under the hood). Perhaps the job identifier does not match your target?


text:
Q: The largest size of a subgroup of a general linear group with the property that all elements have the first $k \times k$ block invertible I wanted to see if there is any connection between the invertibility of a matrix and the invertibility of a particular block of the matrix.

Particularly I want to find out the largest size of a subgroup of $GL_n(\mathbb{F}_q)$ with the property that the first $k \times k$ block of all the matrices in that subgroup is invertible.

I have formalized the problem (trying to do away with matrices) in the following manner.

Let $V$  be a vector space over $\mathbb{F_q}$ of dimension $n$. Let $W$ be a subspace of $V$ so that $V = W \oplus W'$ and dim($W$) $= k$. Let $P$ denote the projection along $W'$ onto $W$ and $G$ be a subgroup of $GL(V)$.
  Then define $\tilde{G} =  \{ T \in G |$  $P\circ T: W  \to W$ is invertible $\}$.
1) Under what conditions is $G = \tilde{G}$?
2) What is the largest size of $G$ such that $G=\tilde{G}$?

A few observations:
1) If $G  = GL(V)$, then $G \neq \tilde{G}$.
2) I have a group of size $|M_{k \times (n-k)}(\mathbb{F}_q)|$ ($M_{k \times (n-k)}(\mathbb{F}_q)$ is the additive group of $k \times (n-k)$ matrices over $\mathbb{F}_q$) for which $G = \tilde{G}$ holds.
P.S: There was a power cut in the campus suddenly. I will complete the details, if required, at a later moment. Sorry for the inconvenience.
Thank you,
Isomorphism