text:
Q: 2016 CCC S4 Combining riceball code?? C++ the quesiton is like this :
Alphonse has N rice balls of various sizes in a row. He wants to form the largest rice ball possible for his friend to eat. Alphonse can perform the following operations:
If two adjacent rice balls have the same size, Alphonse can combine them to make a new rice ball. The new rice ball's size is the sum of the two old rice balls' sizes. It occupies the position in the row previously occupied by the two old rice balls.
If two rice balls have the same size, and there is exactly one rice ball between them, Alphonse can combine all three rice balls to make a new rice ball. (The middle rice ball does not need to have the same size as the other two.) The new rice ball's size is the sum of the three old rice balls' sizes. It occupies the position in the row previously occupied by the three old rice balls.
Alphonse can perform each operation as many times as he wants.
Determine the size of the largest rice ball in the row after performing 0 or more operations.
Input Specification
The first line will contain the integer, N (1≤N≤400).
The next line will contain N space separated integers representing the sizes of the riceballs, in order from left to right. Each integer is at least 1 and at most 1000000.
For 1 of the 15 available marks, N=4.
For an additional 2 of the 15 available marks, N≤10.
For an additional 2 of the 15 available marks, N≤50.
Output Specification
Output the size of the largest riceball Alphonse can form.
Sample Input 1
Copy
7
47 12 12 3 9 9 3
Output for Sample Input 1
Copy
48
Explanation for Sample Input 1
One possible set of moves to create a riceball of size 48 is to combine 12 and 12, forming a riceball of size 24. Then, combine 9 and 9 to form a riceball of size 18. Then, combine 3, 18 and 3 to form a riceball of size 24. Finally, combine the two riceballs of size 24 to form a riceball of size 48.
My code is this:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int num;
    cin >> num;
    vector<int> rice;
    int temp;
    for(int i = 0; i< num; i++)
    {
        cin >> temp;
        rice.emplace_back(temp);
    }
    int change = 0;
    int chain = 0;
    for(int i = 0; i > -1; i++)
    {
        for(int j = 0; j < num; j++)
        {
            for(int k = 1; k < num-j; k++)
            {
                if(rice[j] == rice [j+k])
                {
                    chain++;
                }
                else
                {
                    k = num-j;
                }
            }
            if(chain != 0)
            {
                for(int m = 1; m <= chain; m++)
                {
                    rice[j] = rice[j] + rice[j+1];
                    rice.erase(rice.begin()+j+1, rice.begin()+j+2);
                    change = 1;
                    if(m == chain)
                    {
                        num -= chain;
                        change = 1;
                        chain = 0;
                        j=-1;
                        continue;
                    }
                }
            }
            if(j < num-2)
            {
                if (rice[j] == rice[j+2])
                {
                    rice[j] = rice[j] + rice[j+1] + rice[j+2];
                    rice.erase(rice.begin()+j+1, rice.begin()+j+3);
                    change = 1;
                    j=-1;
                    num-=2;
                    continue;
                }
            }
        }
        if(change == 0)
            {break;}
        change = 0;
    }
    sort(rice.begin(),rice.end());
    cout << rice.back() << endl;
    return 0;
}

the test case that doesn't work right now is input: 10 1 2 1 2 1 2 1 2 1 2 and the output should be 14, but the only way to get that is to ignore the 1 at the beginning which i got no idea how to do / thks a lot


text:
Q: Qt QML - margins at ChartView Why does the ChartView object have margins other than the Rectangle object? How to make them the same? For example, if the ChartView object is replaced with a Rectangle, the margins become the same.
import QtQuick 2.7
import QtQuick.Controls 2.2
import QtCharts 2.2

Rectangle {
    anchors.fill: parent
    color: "#eeeeee"

    Rectangle {
        id: idRectConsole1
        width: 200
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.bottom: parent.bottom
        anchors.margins: 20
        color: "#ffffff"

    }

    ChartView {
        anchors.top: parent.top
        anchors.left: idRectConsole1.right
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 20
        legend.visible: false

        LineSeries {
            name: "1"
            XYPoint { x: 2; y: 0.73278}
            XYPoint { x: 4; y: 1.2213}
            XYPoint { x: 6; y: -0.73278}

        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Querying on mysql docker container via python, throwing timeout error after few hours Inserting via debezium connector to mysql database brought up via docker container.
Trying to query and it is working fine until some number of hours. But, after that, same query is throwing below exception.
export JAVA_HOME=/tmp/tests/artifacts/java-17/jdk-17; export PATH=$PATH:/tmp/tests/artifacts/java-17/jdk-17/bin; docker exec -i mysql_be1e6a mysql --user=demo --password=demo -D demo -e "select count(k) from test_cdc_f0bf84 where uuid = 'd1e5cd6d-8f7a-457c-b2ea-880c2be52f69'"

2023-01-02 16:27:43,812:ERROR: failed to execute query MySQL rows count by uuid:
Traceback (most recent call last):
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/channel.py", line 699, in recv
    out = self.in_buffer.read(nbytes, self.timeout)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/buffered_pipe.py", line 164, in read
    raise PipeTimeout()
paramiko.buffered_pipe.PipeTimeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/suites/cdc/abstract.py", line 667, in try_query
    res = query_function()
          ^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/suites/cdc/test_cdc.py", line 635, in <lambda>
    query = lambda: self.mysql_query(
                    ^^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/suites/cdc/abstract.py", line 544, in mysql_query
    result = self.ssh.exec_on_host(host, [
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/main/connection.py", line 335, in exec_on_host
    return self._exec_on_host(host, commands, fetch, timeout=timeout, limit_output=limit_output)[host]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/main/connection.py", line 321, in _exec_on_host
    res = list(out)
          ^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/file.py", line 125, in __next__
    line = self.readline()
           ^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/file.py", line 291, in readline
    new_data = self._read(n)
               ^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/channel.py", line 1361, in _read
    return self.channel.recv(size)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubuntu/workspace/stress_tests/run_test_with_universe/src/env/lib/python3.11/site-packages/paramiko/channel.py", line 701, in recv
    raise socket.timeout()
TimeoutError

After some time, logged manually to machine and tried to read, it still reads fine. Not sure, what does this issue mean.
As explained, tried querying from database via python. Expected it will return count of rows, which it was happening until certain time, but after that, it threw timeout error and socket error.

A:
Trying to query and it is working fine until some number of hours. But, after that, same query is throwing below exception.

The default value for interactive_timeout and wait_timeout is 28880 seconds (8 hours). you can disable this behavior by setting this system variable to zero in your MySQL config.
source: Configuring session timeouts


text:
Q: Some answers need to be random in the form. Is there just a way to click a variable with the Target as the variable I'm just curious if I can get IDE to click a target that's a variable. So far I believe that the variable is right,but...
 <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="selenium.base" href="https://docs.google.com/" />
    <title>yolt</title>

yolt

        label
        yolo

        open
        /a/students.d125.org/forms/d/1if5ewBKPn39pphsm92i5gX2Lv8iEx5cOfmnDhTiHmi4/viewform

        click
        id=group_241280888_2

        click
        id=group_267410756_2

        click
        id=group_1306947924_2

        click
        //form[@id='ss-form']/ol/div[3]/div/div/ul/li[2]/label

        click
        id=group_1960845646_1

        click
        //form[@id='ss-form']/ol/div[4]/div/div/ul/li/label/span[2]

        click
        //form[@id='ss-form']/ol/div[5]/div/div/ul/li[3]/label/span

        click
        id=group_1065210562_3

        click
        id=group_990809070_10

        click
        id=group_990809070_10

        click
        id=group_990809070_9

        click
        id=group_990809070_3

        click
        //form[@id='ss-form']/ol/div[6]/div/div/ul/li[8]/label/span[2]

        click
        id=group_990809070_8

        click
        //form[@id='ss-form']/ol/div[6]/div/div/ul/li[7]/label/span[2]

        click
        id=group_990809070_7

        click
        id=group_1745483943_1

        click
        //form[@id='ss-form']/ol/div[7]/div/div/ul/li/label/span[2]

        click
        id=group_1030193806_6

        click
        id=group_241280888_2

        click
        id=group_267410756_2

        click
        id=group_1306947924_2

        click
        id=group_1306947924_2

        click
        id=group_1960845646_1

        click
        id=group_1065210562_3

        store
        javascript{Math.floor(Math.random()*11)}
        x

        store
        "id=group_990809070_"+x
        y

        click
        ${y}

Basically, it loads a form, answers some questions. But, I was wondering if I can get randomized answers by appending a random int string to the target string. Then just click on that button

A: Selenium IDE is rather non-functional, but there are some opportunities to do it.
Look at http://docs.seleniumhq.org/docs/08_user_extensions.jsp#using-user-extensions-with-selenium-ide
You can define helper functions in user-extensions.js
For example if you have two xpath like //div[1] and //div[2] You will define something like
type rndAnswer javascript{Math.floor(Math.random() * 2) + 1}

and then use a variable {rndAnswer} for clicking //div/[{answer}]


text:
Q: how can i open the file explorer to open again when the user exist out? the problem i am trying to solve is when the user starts the program , a file explorer opens. if the user exist the window i want to ask the user if they want to quit the program y or n.
from tkinter.filedialog import askdirectory
import pyinputplus as py

def get_location_path():
    while True:
        path = askdirectory(title='Select Folder') # shows dialog box and return the path to the folder the user picks
        if path == '':
            y = py.inputYesNo("would you like to quit the program? ")
            if y == 'yes':
              break
            if y == 'no':
              continue
        else:
            return path

y = get_location_path()
print(y)

when i run the program and i exist the window without picking a folder, it will ask me if i want to quit the program, if i type y it quits the program but if i type n it does nothing and i cant even exist the program by pressing CTRL + C
enter n:
would you like to quit the program? n
empyty space

A: I've had to add some code to get your code to work as a tkinter app - it seems like you want this to run as a command line app which isn't what tkinter is for; however, I've tried to come up with a solution that uses tkinter since that's how this question is tagged.
import tkinter as tk
# import pyinputplus as py  # (you don't need this if using tkinter)
from tkinter import messagebox as tkm  # use native tkinter dialogs instead
from tkinter.filedialog import askdirectory

class App(tk.Tk):
    def __init__(self):
        super().__init__(). # initialize tk
        self.title('My App')
        self.geometry('640x480')

        self.path = ''  # create a variable to store the path
        self.get_location_path()  # prompt the user for a path

    def get_location_path(self):
        self.path = askdirectory(title='Select Folder')  # show file dailog

        if self.path:  # if a path is selected...
            self.use_location_path()  # do whatever needs to be done with the path
        elif (  # no path selected; ask the user if they want to quit
            tkm.askyesno(
                title='Exit Program?',
                message='Would you like to quit the program?'
            )
        ):
            self.destroy()  # yes, quit
        else:
            self.get_location_path()  # no, ask for path again

    def use_location_path(self):
        print(self.path)  # do some work...
        self.destroy()  # quit once the work is done

if __name__ == '__main__':
    App().mainloop()  # run the app


text:
Q: Fitting a Custom Scipy Distribution I have redefined the lognormal distribution using custom scipy class. I have simulated this distribution and I am trying to recover the original parameters I have specified, however, the fit method is returning different parameters.
import numpy as np
import pandas as pd
from scipy.stats import rv_continuous
from scipy.special import erf
from scipy.special import erfinv

class lognorm_v2(rv_continuous):

    def _pdf(self, x, mu, sigma):
        return 1 / (x * sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 * ((np.log(x) - mu)/sigma)**2)

    def _cdf(self, x, mu, sigma):
        return 0.5 + 0.5 * erf((np.log(x) - mu)/ (np.sqrt(2)*sigma))

    def _sf(self, x, mu, sigma):
        u = (x)**b/(1+x**b)
        return 1 - 0.5 + 0.5 * erf((np.log(x) - mu)/ (np.sqrt(2)*sigma))

    def _ppf(self,x, mu, sigma):
        return np.exp(sigma * erfinv(2*x - 1) - mu)

    def _argcheck(self, mu, sigma):
        s = sigma > 0
        return s

np.random.seed(seed=111)
logn = lognorm_v2(name='lognorm_v2',a=0,b=np.inf)
test = logn.rvs(mu=2,sigma=1,loc=0,scale=1,size=100000)

logn.fit(test)
logn.fit(test,floc=0,fscale=1)

When loc and scale are not fixed I obtain the parameters:
(0.9216388162274325,
0.7061876689651909,
-0.0003659266464081178,
0.05399544825451739)
When they are fixed the result is:
(-2.0007136838780917, 0.7086144279779958, 0, 1)
Why am I not able to extract the mu 2 and sigma 1 specified in the original simulation? I understand I will not get the exact values, but they should be very close for 100K simulations.
My numpy is version 1.19.2 and scipy is 1.5.2.
Thank you!

A: I've corrected code with proper _ppf, and it seems to produce proper fits for mu and sigma
Code, Python 3.9 Windows 10 x64
import numpy as np
from scipy.stats import rv_continuous
from scipy.special import erf
from scipy.special import erfinv

SQRT2 = np.float64(1.4142135623730951)

class lognorm_v2(rv_continuous):

    def _pdf(self, x, μ, σ):
        return 1 / (x * σ * SQRT2 * np.sqrt(np.pi)) * np.exp(-0.5 * ((np.log(x) - μ)/σ)**2)

    def _cdf(self, x, μ, σ):
        return 0.5 + 0.5 * erf((np.log(x) - μ)/ (SQRT2*σ))

    def _ppf(self, x, μ, σ):
        return np.exp(μ + σ * SQRT2 * erfinv(2.0*x - 1.0))

    def _argcheck(self, μ, σ):
        s = σ > 0.0
        return s

np.random.seed(seed=111)
logn = lognorm_v2(name='lognorm_v2', a=0.0, b=np.inf)
test = logn.rvs(μ=2.0,σ=1.0,loc=0.0,scale=1.0, size=100000)

logn.fit(test,floc=0,fscale=1)

prints out
(1.9990788106319746, 1.0021523463000124, 0, 1)


text:
Q: How to rename a PostgreSQL cluster? I googled and found this old web page, which said just to change the name of the directory.  I tried it but it didn't work:
$ pg_lsclusters
Version Cluster   Port Status Owner    Data directory                     Log file
8.4     main      5432 down   postgres /var/lib/postgresql/8.4/main       /var/log/postgresql/postgresql-8.4-main.log
9.1     main      50420 online postgres /var/lib/postgresql/9.1/main       /var/log/postgresql/postgresql-9.1-main.log$ pg_ctlcluster 9.1 main stop

$ pwd
/var/lib/postgresql/9.1

$ ls
main

$ mv main oldmain

$ pg_ctlcluster 9.1 oldmain start
Error: specified cluster does not exist

PostgreSQL 9.1.4, Ubuntu 11.10

A: Debian/Ubuntu has a pg_renamecluster command (available in "postgresql-common" package) which does just what you need:

*

*renames config and data directory,

*renames existing log files,

*changes a number of settings in the postgresql.conf.

Man page.
Note for Systemd users: generators are used to create unit file (i.e. service) for each PostgreSQL cluster. So after the pg_renamecluster you should reload Systemd config, enable and start new service:

sudo systemctl daemon-reload
sudo systemctl enable postgresql@<version>-<new cluster name>.service
sudo systemctl start postgresql

A: Update: version 166 of the postgresl-common package added pg_renamecluster. See Ilya's new answer about that.

In older versions (including Postgres 9.1.4 on Ubuntu 11.10) the name of a cluster is bound to the name of the data directory in the "Multi-Version/Multi-Cluster PostgreSQL architecture" introduced by Martin Pitt. This is shipped with Debian packages (Debian, Ubuntu and related distributions). For a detailed description of the architecture, see:
/usr/share/doc/postgresql-common/README.Debian.gz

Or browse the file online here.
Other installations do not have all of these features, so some people may be confused when you talk about cluster names.
Just renaming the data directory does not work, because you have to change the directory in/etc/postgresql/<version>/<cluster> accordingly.
And there are a couple of settings in your postgresql.conf, that have to be adjusted, too. Run a grep in the directory to see:
postgres@db:/etc/postgresql/9.1/main$ grep 'main' ./*


text:
Q: Stop Jquery to automatic fire onclick event while rendering html table using innerHtml How to stop Jquery from firing onclick event while the html is rendering html table with buttons.
These buttons need to be present which inturns calls backend API for refresh reasons.
And refreshUser() need to be triggered manually when refresh button is clicked.
jqueryfile.js
 $(document).ready(function () {
    refreshUser = function (userId) {
        $.ajax({
            url: "/services/svcCall/refreshUserDetails",
            type: 'POST',
            data: {format: 'json', userId: userId},
            success: function (response) {
                $('#userDetails-result').html("Refreshed completed.");
            },
            error: function () {
                $('#userDetails-result').html("
There was an error processing your request. Please try again.
");
            }
        });
    };
    $('#userDetails-search').click(function () {
        $('#userDetails-search').html("Fetching ...");
        $.ajax({
            url: "/services/svcCall/allUserDetails",
            type: 'POST',
            data: {format: 'json'},
            success: function (response) {
                var length = response.length;
                var outerString = '

';
                outerString += "
 UserDetails size present: " + length + "
";
                var innerString = '

';
                for (var i = 0; i < length; i++) {
                    innerString += "
"
                        + " JSON:" + JSON.stringify(response[i]) + "	"
                        + " <input type=\"button\" onclick=\"" + refreshUser(response[i].userId) + "\" value=\" Refresh \">
";
                }
                innerString += "

";
                outerString = outerString + innerString + "
";
                $('#userDetails-search').html(outerString);
            },
            error: function () {
                $('#userDetails-search').html("
There was an error processing your request. Please try again.
");
            }

        });
    });
});

HTML file

<button id="userDetails-search">Find me all User Details</button>

A: your onclick should put refreshUser in string instead
 onclick=\"refreshUser(" +response[i].userId + ")\"


text:
Q: Usage of QueryResult inside reactive neo4j Spring repository I have the following repository:
public interface MessageRepository extends ReactiveNeo4jRepository<Message, Long>, ExtendedMessageRepository
{
    @Query("MATCH(m:Message) WHERE id(m)=$start MATCH(m)-[:PREDECESSOR*1..11]->(message:Message)<-[:SENT]-(user:User) MATCH(m)-[:PREDECESSOR]->(predecessor:Message) RETURN message, user AS sender, predecessor AS predecessor ORDER BY message.timestamp")
    Flux<Message> findPredecessors(long start);
}

Basically this repository works and I get the correct amount of message objects. The only problem is that sender and predecessor inside the message objects are null. Am I missing something or is this feature currently not supported for the neo4j-rx repositories?
public class Message extends AbstractEntity
{
    private String content;

    private LocalDateTime timestamp;

    @Relationship(type = "SENT", direction = Relationship.Direction.INCOMING)
    private User sender;

    @Relationship(type = "PREDECESSOR", direction = Relationship.Direction.OUTGOING)
    private Message predecessor;

    // getter, setter
}


text:
Q: Do kernel *.S files use x64 assembly or for 32 bits? In this question: GCC-Assemby Error: Relocation R_X86_64_32S against '.data', is a example of 'hello world` in x64. I came on this, because I was finding a good GAS asm book with for x64 architecture (why to learn old 32bit asm), but most tutors and books are for 32 only. (such as profesional asm language, which is a lot recommended). My purpose, or why I even want to learn asm (GAS not nasm), is so I can understand kernel *.S files. But in the example above (first url) there is shown COMPLETELY different hello world in x64, then is in 32.
So my question is: How different is x64 from 32-bit x86 and how much does kernel use each other (that is the reason I want to learn x64)?


text:
Q: Tkinter Canvas bind '' event to item Am I missing something ? I thought I've done something like the example below.
But neither I found a script of mine that act like I hoped, nor I have found something online.
Basically I want to bind the Configure event to an item. Isnt it possible like the error suggest?
Resources : Canvas and tag_bind
import tkinter as tk

def do_something(event=None):
    print('something')
def stupid_workaround():
    if cnvs.coords(lbl) != lbl_coords:
        do_something()
        cnvs.coords(lbl, *lbl_coords)

    cnvs.after(200,stupid_workaround)

root = tk.Tk()
cnvs = tk. Canvas(root,highlightthickness=0)
lbl = cnvs.create_text(0,0, text='this is an exampel', anchor='nw')
lbl_coords = cnvs.coords(lbl)
btn = tk.Button(root, text='change coords', command=lambda:cnvs.coords(lbl,10,10))
btn.pack()
stupid_workaround()
#cnvs.bind(lbl, '<Configure>', do_something) #throws no error
#cnvs.tag_bind(lbl, '<Configure>', do_something) #throws error

cnvs.pack()
root.mainloop()

_tkinter.TclError: requested illegal events; only key, button, motion, enter, leave, and virtual events may be used

A: Like the error says, you can't bind to the <Configure> event, it's simply not an option. That event is only valid for widgets, not items drawn on a canvas.


text:
Q: how does django get_next_by_FOO() query work? i want to know how get_next_by_FOO()/get_previous_by_FOO() fetch data from database. anyone know the SQL code for that?. can anyone tell me how it works behind the scene?

A: The method is implemented in the django/db/models/base.py [GitHub] file:
    def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
        if not self.pk:
            raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
        op = 'gt' if is_next else 'lt'
        order = '' if is_next else '-'
        param = getattr(self, field.attname)
        q = Q(**{'%s__%s' % (field.name, op): param})
        q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk})
        qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by(
            '%s%s' % (order, field.name), '%spk' % order
        )
        try:
            return qs[0]
        except IndexError:
            raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
The is_next will be True if you query for get_next_by_FOO, and False if you query for get_previous_by_FOO.
For the get_next_by_FOO this thus will create a query that looks like:
Model.objects.filter(
    Q(FOO__gt=current_foo)
    Q(FOO=current_foo, pk__gt=current_pk)
).order_by('FOO', 'pk')[0]
It thus will search for the first Model objects where the FOO field is the same, but the primary key is greater, or where the FOO field is (strictly) larger.
This thus will result in query that looks like:
SELECT *
FROM model
WHERE FOO > current_FOO
   OR (FOO = current_FOO AND id > current_pk)
ORDER BY FOO ASC, id ASC
LIMIT 1
It will thus aim to find that element by ordering the records, and fetching the first one.
For get_previous_by_FOO, the query is similar, except that > is replaced with < and we order in the opposite way:
SELECT *
FROM model
WHERE FOO < current_FOO
   OR (FOO = current_FOO AND id < current_pk)
ORDER BY FOO DESC, id DESC
LIMIT 1


text:
Q: Ambari YARN container settings I'm interested in CPU settings on Ambari, concretely, I see CPU options such as:

Percentage of physical CPU allocated for all containers on a node
Number of virtual cores

And per container:

Minimum Container Size (VCores)
Maximum Container Size (VCores)

I saw similar settings regarding the RAM and I was able to find some recommendations about it, but I found none for the case of CPU.
Concretely, I'm interested whether I should keep a number of VCores for the system (as in the case of memory), or should I use it all for containers? That is, should the Number of virtual cores be set to maximal value or not? And what to use as Percentage?

A: I would suggest that you keep a minimum of 2 cores per node for the operating system and a minimum of 2 gigs of memory for the same. The remaining you could safely utilise for your applications being launched on yarn. That being said, you can use it all but it might choke your system in case you run extremely cpu intensive jobs.


text:
Q: Unix AWK field seperator finding sum of one field group by other I am using below awk command which is returning me unique value of parameter $11 and occurrence of it in the file as output separated by commas. But along with that I am looking for sum of parameter $14(last value) in the output. Please help me on it.
sample string in file
EXSTAT|BNK|2014|11|05|15|29|46|23169|E582754245|QABD|S|000|351

$14 is last value 351
bash-3.2$ grep 'EXSTAT|' abc.log|grep '|S|' |
  awk -F"|" '{ a[$11]++ } END { for (b in a) { print b"," a[b] ; } }'

QDER,3
QCOL,1
QASM,36
QBEND,23
QAST,3
QGLBE,30
QCD,30
TBENO,1
QABD,9
QABE,5
QDCD,5
TESUB,1
QFDE,12
QCPA,3
QADT,80
QLSMR,6

bash-3.2$ grep 'EXSTAT|' abc.log
EXSTAT|BNK|2014|11|05|15|29|03|23146|E582754222|QGLBE|S|000|424
EXSTAT|BNK|2014|11|05|15|29|05|23147|E582754223|QCD|S|000|373
EXSTAT|BNK|2014|11|05|15|29|12|23148|E582754224|QASM|S|000|1592
EXSTAT|BNK|2014|11|05|15|29|13|23149|E582754225|QADT|S|000|660
EXSTAT|BNK|2014|11|05|15|29|14|23150|E582754226|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|14|23151|E582754227|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|15|23152|E582754228|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|15|23153|E582754229|QADT|S|000|258
EXSTAT|BNK|2014|11|05|15|29|17|23154|E582754230|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|18|23155|E582754231|QADT|S|000|263
EXSTAT|BNK|2014|11|05|15|29|18|23156|E582754232|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|19|23157|E582754233|QADT|S|000|270
EXSTAT|BNK|2014|11|05|15|29|19|23158|E582754234|QADT|S|000|264
EXSTAT|BNK|2014|11|05|15|29|20|23159|E582754235|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|20|23160|E582754236|QADT|S|000|241
EXSTAT|BNK|2014|11|05|15|29|21|23161|E582754237|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|21|23162|E582754238|QADT|S|000|229
EXSTAT|BNK|2014|11|05|15|29|22|23163|E582754239|QADT|S|000|234
EXSTAT|BNK|2014|11|05|15|29|22|23164|E582754240|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|23|23165|E582754241|QADT|S|000|254
EXSTAT|BNK|2014|11|05|15|29|23|23166|E582754242|QADT|S|000|402
EXSTAT|BNK|2014|11|05|15|29|24|23167|E582754243|QADT|S|000|223
EXSTAT|BNK|2014|11|05|15|29|24|23168|E582754244|QADT|S|000|226

A: You can use a second array.
awk -F"|" '/EXSTAT\|/&&/\|S\|/{a[$11]++}/EXSTAT\|/{s[$11]+=$14}\
           END{for(b in a)print b","a[b]","s[b];}' abc.log

Explanation
/EXSTAT\|/&&/\|S\|/{a[$11]++} on lines that contain both EXSTAT| and |S|, increment a[$11].
/EXSTAT\|/ on lines containing EXSTAT| add $14 to s[$11]
END{for(b in a)print b","a[b]","s[b];} print out all keys in array a, values of array a, and values of array s, separated by commas.

A: You need not use grep for searching the file if it contains EXSTAT the awk can do that for you as well.
For example:
awk 'BEGIN{FS="|"; OFS=","} $1~EXSTAT && $12~S {sum[$11]+=$14; count[$11]++}END{for (i in sum) print i,count[i],sum[i]}' abc.log

for the input file abc.log with contents
EXSTAT|BNK|2014|11|05|15|29|03|23146|E582754222|QGLBE|S|000|424
EXSTAT|BNK|2014|11|05|15|29|05|23147|E582754223|QCD|S|000|373
EXSTAT|BNK|2014|11|05|15|29|12|23148|E582754224|QASM|S|000|1592
EXSTAT|BNK|2014|11|05|15|29|13|23149|E582754225|QADT|S|000|660
EXSTAT|BNK|2014|11|05|15|29|14|23150|E582754226|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|14|23151|E582754227|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|15|23152|E582754228|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|15|23153|E582754229|QADT|S|000|258
EXSTAT|BNK|2014|11|05|15|29|17|23154|E582754230|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|18|23155|E582754231|QADT|S|000|263
EXSTAT|BNK|2014|11|05|15|29|18|23156|E582754232|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|19|23157|E582754233|QADT|S|000|270
EXSTAT|BNK|2014|11|05|15|29|19|23158|E582754234|QADT|S|000|264
EXSTAT|BNK|2014|11|05|15|29|20|23159|E582754235|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|20|23160|E582754236|QADT|S|000|241
EXSTAT|BNK|2014|11|05|15|29|21|23161|E582754237|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|21|23162|E582754238|QADT|S|000|229
EXSTAT|BNK|2014|11|05|15|29|22|23163|E582754239|QADT|S|000|234
EXSTAT|BNK|2014|11|05|15|29|22|23164|E582754240|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|23|23165|E582754241|QADT|S|000|254
EXSTAT|BNK|2014|11|05|15|29|23|23166|E582754242|QADT|S|000|402
EXSTAT|BNK|2014|11|05|15|29|24|23167|E582754243|QADT|S|000|223
EXSTAT|BNK|2014|11|05|15|29|24|23168|E582754244|QADT|S|000|226

it will give an output as
QASM,1,1592
QGLBE,1,424
QADT,20,5510
QCD,1,373

What it does?

*

*'BEGIN{FS="|"; OFS=","} excecuted before the input file is processed. It sets FS, input field seperator as | and OFS output field seperator as ,

*$1~EXSTAT && $12~S{sum[$11]+=$14; count[$11]++} action is for each line

*

*$1~EXSTAT && $12~S checks if first field is EXSTAT  and 12th field is S

*sum[$11]+=$14  array sum of field $14 indexed by $11

*count[$11]++ array count indexed by $11

*END{for (i in sum) print i,count[i],sum[i]}' excecuted at end of file, prints the content of the arrays

A: #!awk -f
BEGIN {
  FS = "|"
}
$1 == "EXSTAT" && $12 == "S" {
  foo[$11] += $14
}
END {
  for (bar in foo)
    printf "%s,%s\n", bar, foo[bar]
}

A: Just add another associative array:
awk -F"|" '{a[$11]++;c[$11]+=$14}END{for(b in a){print b"," a[b]","c[b]}}'

tested below:
> cat temp
EXSTAT|BNK|2014|11|05|15|29|03|23146|E582754222|QGLBE|S|000|424
EXSTAT|BNK|2014|11|05|15|29|05|23147|E582754223|QCD|S|000|373
EXSTAT|BNK|2014|11|05|15|29|12|23148|E582754224|QASM|S|000|1592
EXSTAT|BNK|2014|11|05|15|29|13|23149|E582754225|QADT|S|000|660
EXSTAT|BNK|2014|11|05|15|29|14|23150|E582754226|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|14|23151|E582754227|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|15|23152|E582754228|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|15|23153|E582754229|QADT|S|000|258
EXSTAT|BNK|2014|11|05|15|29|17|23154|E582754230|QADT|S|000|261
EXSTAT|BNK|2014|11|05|15|29|18|23155|E582754231|QADT|S|000|263
EXSTAT|BNK|2014|11|05|15|29|18|23156|E582754232|QADT|S|000|250
EXSTAT|BNK|2014|11|05|15|29|19|23157|E582754233|QADT|S|000|270
EXSTAT|BNK|2014|11|05|15|29|19|23158|E582754234|QADT|S|000|264
EXSTAT|BNK|2014|11|05|15|29|20|23159|E582754235|QADT|S|000|245
EXSTAT|BNK|2014|11|05|15|29|20|23160|E582754236|QADT|S|000|241
EXSTAT|BNK|2014|11|05|15|29|21|23161|E582754237|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|21|23162|E582754238|QADT|S|000|229
EXSTAT|BNK|2014|11|05|15|29|22|23163|E582754239|QADT|S|000|234
EXSTAT|BNK|2014|11|05|15|29|22|23164|E582754240|QADT|S|000|237
EXSTAT|BNK|2014|11|05|15|29|23|23165|E582754241|QADT|S|000|254
EXSTAT|BNK|2014|11|05|15|29|23|23166|E582754242|QADT|S|000|402
EXSTAT|BNK|2014|11|05|15|29|24|23167|E582754243|QADT|S|000|223
EXSTAT|BNK|2014|11|05|15|29|24|23168|E582754244|QADT|S|000|226
> awk -F"|" '{a[$11]++;c[$11]+=$14}END{for(b in a){print b"," a[b]","c[b]}}' temp
QGLBE,1,424
QADT,20,5510
QASM,1,1592
QCD,1,373
>

also check the test here


text:
Q: Counting r-combination with generating functions logic I am currentely discussing generating functions in my discrete mathematic class. However the professor showed us how to solve counting problems of the form $x^1 + x^2 + x^3 = n$ with $x_i$ and $n$ positives integers and some restrictions. I understand the procedure, but I cannont find why we redefine the problem this way. If someone could maybe give me a link (because I've been looking forever) or a proof of why it works (other than the intuitive "the exponents adds up so it works") I would be eternally grateful :D.
Heres what I (think) I understand:
A generating function would be a way to "encode" information about any real number sequence, finite or inifinite $a_n = a_1, a_2, ... a_k, ... $   into a power serie
$$\sum_{k\geq 0}{}{a_kx^k}$$ where $x$ is an "inderterminate" variable, which in some way we dont really care about It's value (maybe?) and see it more as a position indicator.
Therefore, we kind of take for granted that for some appropriate x, the function is analytical and we can manipulate it.
Alright so from there I get it, it's kind of a way to represent a sequence and by finding it's generating function we can find the $k^{th}$ term desired.
But here's the example we did with no explanation of why it worked.
"Find the number of solution of $$e_1 + e_2 + e_3 = 17$$ such that $$2\leq e_1\leq5$$  $$3\leq e_2\leq 6$$     $$4\leq e_3\leq7$$  and $n$, $e_1$, $e_2$, $e_3$ $\in \mathbb{Z}_\geq0$
And the way they do it is just saying "well all u have to do is find the coefficient of $x^{17}$ in $(x^2+x^3+x^4+x^5)(x^3+x^4+x^5+x^6)(x^4+x^5+x^6+x^7)$
But from what I've been told so far it's kind of multiplying the 3 generating functions of the sequences $(0,0,1,1,1,1,0...)(0,0,0,1,1,1,1,0,...)(0,0,0,0,1,1,1,1,0,0...)$
Is there something I am missing, or maybe are there no real "logic" behind it and we just define it this way cause it works..??
Anyways, thank you everyone. I tried to make my question as clear as possible but still I'm sorry of the question is unclear but ultimately I'm trying to understand why do we define it this way other than "because it works".
Thank you!!!!

A: I'll try to explain the example you gave, the problem of finding the number of integer solutions to $e_1+e_2+e_3=17$ given $2\leq e_1\leq 5$, $3\leq e_2\leq 6$, and $4\leq e_3\leq 7$.
Suppose we thought about the problem backwards, i.e., what if someone asked you what is the coefficient of $x^{17}$ in the polynomial $$(x^2+x^3+x^4+x^5)(x^3+x^4+x^5+x^6)(x^4+x^5+x^6+x^7).$$
We can note that the product polynomial is formed by taking the sum over every possible product of three terms where the each term is chosen from each of the three factor polynomials (this polynomial product rule can be proved by induction). We then would group the terms of the same exponent in the result to find the coefficient of $x^{17}$. We get one more term of $x^{17}$ for every combination of three terms that give a product of $x^{17}$, which happens precisely when we chose some $e_1\in\{2,3,4,5\}$, $e_2\in\{3,4,5,6\}$, and $e_3\in\{4,5,6,7\}$ so that $x^{e_1}x^{e_2}x^{e_3} = x^{e_1+e_2+e_3} = x^{17}$, so the coefficient on $x^{17}$ is exactly the number of ways to choose terms in the polynomials $x^{e_1}$, $x^{e_2}$, and $x^{e_3}$ from $(x^2+x^3+x^4+x^5)$, $(x^3+x^4+x^5+x^6)$, and $(x^4+x^5+x^6+x^7)$, respectively. So, this is exactly the same as counting the number of ways that $e_1+e_2+e_3=17$.
Now, the reason why we prefer to do it in terms of these polynomials/series instead of just the raw combinatorial problem is because putting it in terms of polynomials/series gives us a much richer set of tools we can manipulate and analyze the representation in. As long as the polynomials are equal, we will always have the information encoded in the coefficients once we write our expression in polynomial form.
I hope that clears things up!


text:
Q: Código de comparação de datas Tenho um código que compara a data atual com uma data específica e verifica se essa "entrega" esta atrasada em dia ou vence hoje por exemplo mas mesmo que seja a mesma data que a atual o else não aparece "em dia" não acontece que puder me ajudar agradeço
$hoje = new DateTime();

echo $hoje->format("d/m/Y");

$entrega = new DateTime('2018-07-10');

echo "

";

if ($hoje > $entrega) {
    echo "Atrasado";
    echo "

";
    $interval = $hoje->diff($entrega);
    echo "$interval->days dias";

} else if ($hoje == $entrega) {
    echo "Vence hoje";
} else {
    echo "Em dia";
}


text:
Q: What are the differences between these terms in kernel compilations How does the terms
make, make bzImage, make modules, make install, make modules_install relate to each other.
One kernel tutorial I saw used all make bzImage, make modules, make install, make modules_install commands to compile and install a new kernel. While another one used only make, make install and make modules_install commanads. So what are the differences?

A: Over time, the Linux kernel compilation process has itself been developed further. It has become more complex, but also more streamlined. Run make help in the kernel source directory to see a list of all make targets and brief explanations of each.
With the current 5.x kernel series, the commands make and make all are equivalent: both of them will run an architecture-specific list of default targets.
On the x86 hardware architecture, the default list contains:

*

*make vmlinux to build the bare kernel (this is also automatically executed if you run make bzImage, as before you can make a compressed bootable kernel image file, you'll first need to make the thing you'll want to compress; the uncompressed version is also useful for certain kernel debugging tools.)

*make modules to build the kernel modules

*make bzImage to create the bootable compressed kernel image file.

All of the above can be executed as a regular user, without extra privileges.
On the other hand, make install will use either ~/bin/installkernel or /sbin/installkernel if they exist. Your own ~/bin/installkernel might include the use of sudo or similar where applicable, but the system /sbin/installkernel is typically written to expect that you already have root access.
Likewise, make modules_install will copy the modules of the new kernel version to /lib/modules/<kernel_version>/ directory tree, so it will require root access to run successfully.
As the best practice is to avoid running any long and complicated processes (such as kernel compilation!) as root if there is no specific need, the current minimal kernel compilation process would be something like:

*

*configure kernel as a regular user

*run make or make all as a regular user

*run sudo make modules_install to install the kernel modules

*run sudo make install to install the actual kernel. I would recommend doing this last, since /sbin/installkernel may trigger other operations like automatic building of an initramfs file, and those other operations would be more successful if the new kernel modules are already in place.

But if you are doing kernel development and not just building a customized kernel for your own needs, you might want to use a more fine-grained process; for example, if you are developing a kernel module, you might want to run make modules as a separate step so you can more easily see if it fails because of an error you've made, and can get to fixing the error more quickly. After fixing the error, you will then be able to just skip to running make modules again, as the previous steps are already successfully done.
Likewise, a developer working with the early kernel start-up process might just want the bzImage for testing in another system (one with a tricky set of ACPI tables or whatever), and not care about the modules at all.


text:
Q: XMPP receive history without rejoining the MUC Suppose A has already joined into the MUC. At the time of join A will receive complete history. But after that is there any way for A to receive the complete history any number of times by doing some query to MUC.
Leaving and Rejoining the MUC is not acceptable. :(
I have seen How to re-request room roster and history from a muc in ejabberd
But the last comment with  is not working for me.
Please help me, if this is even possible or not. If yes can you give me the stanza that needs to be sent to muc. BTW I am using smack API and openfire
Thanks,
Nitiraj


text:
Q: Python translate def into lambda? How can I translate def functions into lambda python?
def a(x):
if x % 7 == 0:
    x += x // 7
    return x
else:
    return x

i tried like this but it didnt work
a= lambda x: x += x//7 if x%7 else x

and how can I translate this too. I don't understand this one
def b(x):
if x == True:
    r = 32
elif x == False:
    r = 38

A: you cannot do assignment inside a lambda
a= lambda x: x + (x//7 if x%7 else x)

x = a(15)

as pointed out in the comments I think your lambda would actually be
a= lambda x: (x + x//7) if x % 7==0 else x


text:
Q: How to get selected item QlistWidget pyqt I want to get selected element when the user selects an item in QlistWidget then clicked button to get this element

A: Try this one:
from PyQt5.QtWidgets import (QWidget, QListWidget, QVBoxLayout, QApplication)
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.l = QListWidget()
        for n in range(10):
            self.l.addItem(str(n))

        self.l.itemSelectionChanged.connect(self.selectionChanged)

        vbox = QVBoxLayout()
        vbox.addWidget(self.l)

        self.setLayout(vbox)
        self.setGeometry(300, 300, 300, 300)
        self.show()

    def selectionChanged(self):
        print("Selected items: ", self.l.selectedItems())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

With this approach you will have all items, selected by clicking, using keyboard arrows or dragging the mouse on them, printed.

A: You can use itemActivated signal from QListWidget class and bind it to some of your method.
yourQListWidget.itemActivated.connect(itemActivated_event)

def itemActivated_event(item)
    print(item.text())

Now everytime user click on some item in your QListWidget the text inside of this item is printed.

A: Binding a method to the itemClicked signal from QListWidget also seems to work:
yourQListWidget.itemClicked.connect(itemClicked_event)

def itemClicked_event(item):
    print(item.text())

For me, the itemClicked signal works with single-clicking the item and itemActivated works with double clicking.


text:
Q: PIL install error: SyntaxError: Missing parentheses in call to 'print' I am trying to install PIL (the Python Imaging Library) using the command:
pip install PIL  --allow-unverified PIL --allow-all-external

seeing the following errors:
gkhan@Gkan ~ $ pip install PIL  --allow-unverified PIL --allow-all-external
Collecting PIL
  PIL is potentially insecure and unverifiable.
  Downloading http://effbot.org/media/downloads/PIL-1.1.7.tar.gz (506kB)
    100% |████████████████████████████████| 507kB 1.5MB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-egu_a9q6/PIL/setup.py", line 182
        print "--- using Tcl/Tk libraries at", TCL_ROOT
                                            ^
    SyntaxError: Missing parentheses in call to 'print'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-egu_a9q6/PIL

A: The python command on your system runs Python 3, but the setup script for PIL is written for Python 2. Python 2 and Python 3 are two different languages; they look a lot like each other but they aren't compatible, and one of the differences is that print requires parentheses in Python 3 but not in Python 2.
Run pip2 or pip2.7 instead of pip3 if these commands are available. Otherwise something like python2.7 /usr/bin/pip install … should work.
Note that so far, it is recommended for python to be Python 2 but a minority of distributions (Arch Linux at least) install Python 3 as /usr/bin/python.


text:
Q: A name for the lag time of memory when catching up to new developments Is there a name for the lag time of memory for when something in your environment or life changes, and you need to get accustomed to it? It's kind of a catch-up of memory for updated knowledge to stick.
Ex. Recently we had our kitchen cabinets redone, and for this most food items and even the microwave were moved to temporary places on the other side of the kitchen for 3 weeks while we waited for the re-installation. A week after they were installed, I still find myself turning the wrong direction when I am looking to use the microwave oven in its original place.
Another comedic trope example often employed by Hollywood screenwriters …An American (North or South)  transfers to Honkers or London and still finds themselves trying to get in the wrong driver-side of the car even after 3 or 4 days until finally it sticks, but then when they go back home after 6 months the same but opposite happens.
My research comes up with the 21-day rule
, but that does not describe the memory issue, and it is mostly discounted.

Maxwell Maltz was a plastic surgeon in the 1950s when he began noticing a strange pattern among his patients.
When Dr. Maltz would perform an operation — like a nose job, for example — he found that it would take the patient about 21 days to get used to seeing their new face. Similarly, when a patient had an arm or a leg amputated, Maxwell Maltz noticed that the patient would sense a phantom limb for about 21 days before adjusting to the new situation.

These experiences prompted Maltz to think about his own adjustment period to changes and new behaviors, and he noticed that it also took himself about 21 days to form a new habit. Maltz wrote about these experiences and said, "These, and many other commonly observed phenomena tend to show that it requires a minimum of about 21 days for an old mental image to dissolve and a new one to jell (sic)."

-JamesClear.com
What is that phenomena of catch-up time for memory lag called?

A: Acclimatisation

the process or result of becoming accustomed to a new climate or to new conditions.

Lexico
This is a phenomenon studied in biological sciences, and covers a broad scope.  You could narrow it down with mnemonic acclimatisation to specify that it is memory-related.


text:
Q: Rails 4: ActiveRecord::RecordNotFound in PostsController#edit This is a basic error and lots of people have ask similar questions, such as:

*

*ActiveRecord::RecordNotFound in PostsController#show

*ActiveRecord::RecordNotFound in PostsController#show clicking a link
However, none of them actually helped me solve the issue I am facing now.
In my Rails 4 app, I have four models:
class User < ActiveRecord::Base
  has_many :administrations
  has_many :calendars, through: :administrations
end

class Calendar < ActiveRecord::Base
  has_many :administrations
  has_many :users, through: :administrations
  has_many: :posts
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Post < ActiveRecord::Base
  belongs_to :calendar
end

Here are my routes:
Rails.application.routes.draw do

  root to: 'pages#home'

  devise_for :users, :path => 'account'

  resources :calendars do
    resources :posts, shallow: true
  end

end

Here is the problem: when I am on a calendar, for instance http://localhost:3000/calendars/11, I have all the posts that belong to this calendar displayed, with Show, Edit and Destroy links alongside each post.
When I click the Edit link, I am taken to http://localhost:3000/posts/11/edit.5* and I get the following error:
ActiveRecord::RecordNotFound in PostsController#edit
Couldn't find Post with 'id'=11

# Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.

Note: I don't know why I keep getting this weird url, with .5 at the end.
Here is the content of my PostsController:
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
    @calendar = Calendar.find(params[:calendar_id])
  end

  # POST /posts
  # POST /posts.json
  def create
    @calendar = Calendar.find(params[:calendar_id])
    @post = @calendar.posts.create(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to calendar_path(@calendar), notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    @calendar = Calendar.find(params[:calendar_id])
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to calendar_path(@calendar), notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @calendar = Calendar.find(params[:calendar_id])
    @post.destroy
    respond_to do |format|
      format.html { redirect_to calendar_path(@calendar), notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:date, :time, :subject, :format, :copy, :media)
    end
end

UPDATE: as per @Nathan's comment, here is the edit.html.erb view:

Editing Post

<%= render 'form' %>

<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>

and here is the _form.html.erb partial used in it:
<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>

<%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:

      <% @post.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

      <%= f.label :date %>

      <%= f.date_select :date %>

      <%= f.label :time %>

      <%= f.time_select :time %>

      <%= f.label :subject %>

      <%= f.text_field :subject %>

      <%= f.label :format %>

      <%= f.text_field :format %>

      <%= f.label :copy %>

      <%= f.text_area :copy %>

      <%= f.label :media %>

      <%= f.text_field :media %>

    <%= f.submit %>

<% end %>

UPDATE 2: as per @danielricecodes' answer, here is the result of running rake routes in Terminal:
Prefix Verb   URI Pattern                                 Controller#Action
                   posts GET    /posts(.:format)                            posts#index
                         POST   /posts(.:format)                            posts#create
                new_post GET    /posts/new(.:format)                        posts#new
               edit_post GET    /posts/:id/edit(.:format)                   posts#edit
                    post GET    /posts/:id(.:format)                        posts#show
                         PATCH  /posts/:id(.:format)                        posts#update
                         PUT    /posts/:id(.:format)                        posts#update
                         DELETE /posts/:id(.:format)                        posts#destroy
                    root GET    /                                           pages#home
        new_user_session GET    /account/sign_in(.:format)                  devise/sessions#new
            user_session POST   /account/sign_in(.:format)                  devise/sessions#create
    destroy_user_session DELETE /account/sign_out(.:format)                 devise/sessions#destroy
           user_password POST   /account/password(.:format)                 devise/passwords#create
       new_user_password GET    /account/password/new(.:format)             devise/passwords#new
      edit_user_password GET    /account/password/edit(.:format)            devise/passwords#edit
                         PATCH  /account/password(.:format)                 devise/passwords#update
                         PUT    /account/password(.:format)                 devise/passwords#update
cancel_user_registration GET    /account/cancel(.:format)                   devise/registrations#cancel
       user_registration POST   /account(.:format)                          devise/registrations#create
   new_user_registration GET    /account/sign_up(.:format)                  devise/registrations#new
  edit_user_registration GET    /account/edit(.:format)                     devise/registrations#edit
                         PATCH  /account(.:format)                          devise/registrations#update
                         PUT    /account(.:format)                          devise/registrations#update
                         DELETE /account(.:format)                          devise/registrations#destroy
       user_confirmation POST   /account/confirmation(.:format)             devise/confirmations#create
   new_user_confirmation GET    /account/confirmation/new(.:format)         devise/confirmations#new
                         GET    /account/confirmation(.:format)             devise/confirmations#show
             user_unlock POST   /account/unlock(.:format)                   devise/unlocks#create
         new_user_unlock GET    /account/unlock/new(.:format)               devise/unlocks#new
                         GET    /account/unlock(.:format)                   devise/unlocks#show
          calendar_posts GET    /calendars/:calendar_id/posts(.:format)     posts#index
                         POST   /calendars/:calendar_id/posts(.:format)     posts#create
       new_calendar_post GET    /calendars/:calendar_id/posts/new(.:format) posts#new
                         GET    /posts/:id/edit(.:format)                   posts#edit
                         GET    /posts/:id(.:format)                        posts#show
                         PATCH  /posts/:id(.:format)                        posts#update
                         PUT    /posts/:id(.:format)                        posts#update
                         DELETE /posts/:id(.:format)                        posts#destroy
               calendars GET    /calendars(.:format)                        calendars#index
                         POST   /calendars(.:format)                        calendars#create
            new_calendar GET    /calendars/new(.:format)                    calendars#new
           edit_calendar GET    /calendars/:id/edit(.:format)               calendars#edit
                calendar GET    /calendars/:id(.:format)                    calendars#show
                         PATCH  /calendars/:id(.:format)                    calendars#update
                         PUT    /calendars/:id(.:format)                    calendars#update
                         DELETE /calendars/:id(.:format)                    calendars#destroy

UPDATE 3: as per @Nathan's second comment, here is the content of my show.html.erb calendar view:

<%= @calendar.name %> Calendar

Posts

<% if @calendar.posts.any? %>

            Date
            Time
            Subject
            Format
            Copy
            Media

  <% @calendar.posts.each do |post| %>

        <%= post.date %>
            <%= post.time %>
            <%= post.subject %>
            <%= post.format %>
            <%= post.copy %>
            <%= post.media %>
        <%= link_to 'View', post %>
        <%= link_to 'Update', edit_post_path(@calendar, post) %>
        <%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>

  <% end %>
<% else %>

This calendar does not contain any post yet: just create one with the form below.

<% end %>

Add a post to <%= @calendar.name %> Calendar:

<%= form_for([@calendar, @calendar.posts.build]) do |f| %>

    <%= f.label :date %>

    <%= f.date_select :date %>

    <%= f.label :time %>

    <%= f.time_select :time %>

    <%= f.label :subject %>

    <%= f.text_field :subject %>

    <%= f.label :format %>

    <%= f.text_field :format %>

    <%= f.label :copy %>

    <%= f.text_area :copy %>

    <%= f.label :media %>

    <%= f.text_field :media %>

    <%= f.submit %>

<% end %>

<%= link_to 'Edit', edit_calendar_path %> |
<%= link_to 'Back', calendars_path %>

UPDATE 4: here are the routes when I remove the shallow option from the post resource:
Prefix Verb   URI Pattern                                 Controller#Action
                   posts GET    /posts(.:format)                            posts#index
                         POST   /posts(.:format)                            posts#create
                new_post GET    /posts/new(.:format)                        posts#new
               edit_post GET    /posts/:id/edit(.:format)                   posts#edit
                    post GET    /posts/:id(.:format)                        posts#show
                         PATCH  /posts/:id(.:format)                        posts#update
                         PUT    /posts/:id(.:format)                        posts#update
                         DELETE /posts/:id(.:format)                        posts#destroy
                    root GET    /                                           pages#home
        new_user_session GET    /account/sign_in(.:format)                  devise/sessions#new
            user_session POST   /account/sign_in(.:format)                  devise/sessions#create
    destroy_user_session DELETE /account/sign_out(.:format)                 devise/sessions#destroy
           user_password POST   /account/password(.:format)                 devise/passwords#create
       new_user_password GET    /account/password/new(.:format)             devise/passwords#new
      edit_user_password GET    /account/password/edit(.:format)            devise/passwords#edit
                         PATCH  /account/password(.:format)                 devise/passwords#update
                         PUT    /account/password(.:format)                 devise/passwords#update
cancel_user_registration GET    /account/cancel(.:format)                   devise/registrations#cancel
       user_registration POST   /account(.:format)                          devise/registrations#create
   new_user_registration GET    /account/sign_up(.:format)                  devise/registrations#new
  edit_user_registration GET    /account/edit(.:format)                     devise/registrations#edit
                         PATCH  /account(.:format)                          devise/registrations#update
                         PUT    /account(.:format)                          devise/registrations#update
                         DELETE /account(.:format)                          devise/registrations#destroy
       user_confirmation POST   /account/confirmation(.:format)             devise/confirmations#create
   new_user_confirmation GET    /account/confirmation/new(.:format)         devise/confirmations#new
                         GET    /account/confirmation(.:format)             devise/confirmations#show
             user_unlock POST   /account/unlock(.:format)                   devise/unlocks#create
         new_user_unlock GET    /account/unlock/new(.:format)               devise/unlocks#new
                         GET    /account/unlock(.:format)                   devise/unlocks#show
          calendar_posts GET    /calendars/:calendar_id/posts(.:format)     posts#index
                         POST   /calendars/:calendar_id/posts(.:format)     posts#create
       new_calendar_post GET    /calendars/:calendar_id/posts/new(.:format) posts#new
                         GET    /posts/:id/edit(.:format)                   posts#edit
                         GET    /posts/:id(.:format)                        posts#show
                         PATCH  /posts/:id(.:format)                        posts#update
                         PUT    /posts/:id(.:format)                        posts#update
                         DELETE /posts/:id(.:format)                        posts#destroy
               calendars GET    /calendars(.:format)                        calendars#index
                         POST   /calendars(.:format)                        calendars#create
            new_calendar GET    /calendars/new(.:format)                    calendars#new
           edit_calendar GET    /calendars/:id/edit(.:format)               calendars#edit
                calendar GET    /calendars/:id(.:format)                    calendars#show
                         PATCH  /calendars/:id(.:format)                    calendars#update
                         PUT    /calendars/:id(.:format)                    calendars#update
                         DELETE /calendars/:id(.:format)                    calendars#destroy
MacBook-Pro-de-Thibaud:calendy TXC$ rake routes
                  Prefix Verb   URI Pattern                                      Controller#Action
                    root GET    /                                                pages#home
        new_user_session GET    /account/sign_in(.:format)                       devise/sessions#new
            user_session POST   /account/sign_in(.:format)                       devise/sessions#create
    destroy_user_session DELETE /account/sign_out(.:format)                      devise/sessions#destroy
           user_password POST   /account/password(.:format)                      devise/passwords#create
       new_user_password GET    /account/password/new(.:format)                  devise/passwords#new
      edit_user_password GET    /account/password/edit(.:format)                 devise/passwords#edit
                         PATCH  /account/password(.:format)                      devise/passwords#update
                         PUT    /account/password(.:format)                      devise/passwords#update
cancel_user_registration GET    /account/cancel(.:format)                        devise/registrations#cancel
       user_registration POST   /account(.:format)                               devise/registrations#create
   new_user_registration GET    /account/sign_up(.:format)                       devise/registrations#new
  edit_user_registration GET    /account/edit(.:format)                          devise/registrations#edit
                         PATCH  /account(.:format)                               devise/registrations#update
                         PUT    /account(.:format)                               devise/registrations#update
                         DELETE /account(.:format)                               devise/registrations#destroy
       user_confirmation POST   /account/confirmation(.:format)                  devise/confirmations#create
   new_user_confirmation GET    /account/confirmation/new(.:format)              devise/confirmations#new
                         GET    /account/confirmation(.:format)                  devise/confirmations#show
             user_unlock POST   /account/unlock(.:format)                        devise/unlocks#create
         new_user_unlock GET    /account/unlock/new(.:format)                    devise/unlocks#new
                         GET    /account/unlock(.:format)                        devise/unlocks#show
          calendar_posts GET    /calendars/:calendar_id/posts(.:format)          posts#index
                         POST   /calendars/:calendar_id/posts(.:format)          posts#create
       new_calendar_post GET    /calendars/:calendar_id/posts/new(.:format)      posts#new
      edit_calendar_post GET    /calendars/:calendar_id/posts/:id/edit(.:format) posts#edit
           calendar_post GET    /calendars/:calendar_id/posts/:id(.:format)      posts#show
                         PATCH  /calendars/:calendar_id/posts/:id(.:format)      posts#update
                         PUT    /calendars/:calendar_id/posts/:id(.:format)      posts#update
                         DELETE /calendars/:calendar_id/posts/:id(.:format)      posts#destroy
               calendars GET    /calendars(.:format)                             calendars#index
                         POST   /calendars(.:format)                             calendars#create
            new_calendar GET    /calendars/new(.:format)                         calendars#new
           edit_calendar GET    /calendars/:id/edit(.:format)                    calendars#edit
                calendar GET    /calendars/:id(.:format)                         calendars#show
                         PATCH  /calendars/:id(.:format)                         calendars#update
                         PUT    /calendars/:id(.:format)                         calendars#update
                         DELETE /calendars/:id(.:format)                         calendars#destroy

Any idea how I can fix this?

A: Two arguments are being passed in for a named path (edit_post) which expects one argument.  This is causing problems when the controller action set_post tries to determine which :id to use when looking up the record to set as @post.
It's also why you have that .5 mysteriously appended to the end of your URL — I believe 5 is the :id of post (in that context), and 11 is the :id of @calendar.
edit_post_path only needs to know the :id of the post you want to edit, so you can fix this by changing <%= link_to 'Update', edit_post_path(@calendar, post) %> to <%= link_to 'Update', edit_post_path(post) %> (note the removal of @calendar).
If you really do want to edit this post as a resource nested under calendar (at the path /calendars/<calendar_id>/posts/<post_id>/edit), take a look at your config/routes.rb.  The shallow: true option (which you used when nesting :posts under :calendars) is what's keeping the nested :edit path from being created.
You'll need to have that nested :edit path available, and then you can pass two arguments just as you are now (something like edit_calendar_post_path(@calendar, post)).

A: The error makes me think there's a problem with the link you're building in your view template.  I'd help more but I do not see the View file or the output from rake routes.  Without those two things, its hard for me to tell you why your app is generating a funny url - but it usually means the view template is not calling the correct url_helper.

A: The problem his related to the edit_post_path. With shallow nesting, the edit route is outside of the parent scope. The .5 is the Post ID being added to the url, but not as a valid url param because there's already an ID param from the calendar. Based on the way your routes are setup, it looks like you would need to set the id as a param in the link, like this:
link_to "edit post", edit_post_path(post)


text:
Q: How to handle actions after a PayPal transaction succeded using paypal-checkout-server-sdk I want to make a Donation page for my website, so people can donate and receive gifts for donation and i discovered the PayPal API and then on client there appear buttons and if you click them you can pay with PayPal or credit card, but my problem is that I didn't yet figure out how to handle the succeeded Payment on the Server.

On the Client I was able to handle the succeeded payment by adding .then(details) after return actions.order.capture(), but it was too unsecure for me to handle the stuff on the client.
Client code:
paypal.Buttons({
    createOrder: function () {
        return fetch('/create-order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                items: [{
                    id: 2,
                    quantity: 1
                }],
            })
        }).then((res) => {
            if (res.ok) return res.json()
            return res.json().then(json => Promise.reject(json))
        }).then(({ id }) => {
            return id
        }).catch((err) => {
            console.error(err)
        })
    },
    onApprove: function (data, actions) {
        return actions.order.capture().then((details) => {
            alert('Transaction completed by ' + details.payer.name.given_name)
            console.log(details)
        })
    },
}).render("#paypal")

Server Code:
// Add a little percentage for the USD to EUR conversition rate
const storeItems = new Map([
    [1, { price: Math.round(50 * 1.1), name: '50€ Donation', }],
    [2, { price: Math.round(25 * 1.1), name: '25€ Donation' }],
    [3, { price: Math.round(10 * 1.1), name: '10€ Donation' }],
    [4, { price: Math.round(5 * 1.1),  name: '5€ Donation' }],
])

app.get('/', (req, res) => {
    res.render('index', { clientId: process.env.PAYPAL_CLIENT_ID })
})

app.post('/create-order', async (req, res) => {
    const request = new paypal.orders.OrdersCreateRequest()
    const total = req.body.items.reduce((sum, item) => {
        return sum + storeItems.get(item.id).price * item.quantity
    }, 0)
    request.prefer('return=representation')
    request.requestBody({
        intent: "CAPTURE",
        purchase_units: [
            {
                amount: {
                    currency_code: "USD",
                    value: total,
                    breakdown: {
                        item_total: {
                            currency_code: "USD",
                            value: total,
                        },
                    },
                },
                items: req.body.items.map(item => {
                    const storeItem = storeItems.get(item.id)
                    return {
                        name: storeItem.name,
                        unit_amount: {
                            currency_code: "USD",
                            value: storeItem.price,
                        },
                        quantity: item.quantity,
                    }
                }),
            },
        ],
    })

    try {
        const order = await paypalClient.execute(request)
        res.json({ id: order.result.id })
    } catch (err) {
        res.status(500).json({ error: err.message })
        console.error(err.message)
    }
})

A: actions.order.capture() and actions.order.create() are both client-side code.
Do not use either function for a server integration. Both creation and capture should be done from the same place.
Your onApprove function needs to call a route on your server to do to the capture. There are links with details and sample code within Set up standard payments, in the part of 'Add and modify the code' that explains a server integration. Particularly a link to this demo pattern that shows proper client-side error handling when capturing on a server.


text:
Q: How to send an array to a store to initialize in store with Vuex? I am building a front-end application and I started to use vuex framework with vue front-end library. I have a state and I want to fill it by initial values, sending values with an array. My question is, How can I initialize state ? Do I need to follow action-mutation path for that ? Or just directly manipulate state as a start up only

A: A typical store is like this:
const store = new Vuex.Store({
    state: {
        foo: [],
        bar: 1
    }
});

Just initialize the values there inside the state property.
However, if you want to initialize your state repeatedly, you can do it with a mutation:
const store = new Vuex.Store({
    state: {
        foo: [],
        bar: 1
    },
    mutations: {
        initialization(state) {
            state.foo = [];
            state.bar = 1;
         }
    }
});


text:
Q: Counterexample Sobolev inequality? Below is the Gagliardo-Nirenberg-Sobolev inequality I am using:
Let $u\in C_c^\infty(\mathbb R^n\to\mathbb R$) for $n>1$ and $1\leq p <n$ then there exists $C>0$ independent of $u$ such that $$\|u\|_{L^q(\mathbb R^n)}\leq C\|Du\|_{L^p(\mathbb R^n)},$$
where $q=\frac{np}{n-p}$.

Could somebody please explain the flaw in my thinking that this is a counterexample!
Define the sequence of functions $f_m\in C_c^\infty(\mathbb R^n)$ by $$f_m(x)=1, |x|\leq m\\
f_m(x)=0, |x|\geq m+1$$
and $f_m$ smooth for $|x|\in(m,m+1)$ with the uniform bound $\|Df_m\|_\infty\leq k$.
 Then $\|f_m\|_q\to\infty$ as $m\to\infty$ yet $\|Df_m\|_p$ remains bounded.

A: The issue is that $||Df_m||_p$ does not remain bounded.
$Df_m$ is non-zero on the domain $\{x|m\leq |x|\leq m+1\}$, the size of which tends to infinity as $m$ tends to infinity.


text:
Q: Random Variables Transformation A point P is randomly chosen on the triangle with sides' length 1. The triangle is spun randomly (uniformly) about its vertex (0,0). Let (X, Y) denote P's coordinate. Find the joint density of (X, Y).

A: In polar coordinates $(R,\Theta)$, obviously $\Theta$ is uniformly distributed on $[0,2\pi)$, and $R$ is independent of $\Theta$.  We only need to know the distribution of $R$.  Two of the sides of the triangle give uniform distributions on $[0,1]$.  I'll let you do the other one.


text:
Q: Custom post type category not displaying category ID I'm trying to get the category ID so I can call a loop query on only that category ID. However the following code returns null. Any ideas why? In the admin bar it shows edit category with an ID of 3, however I need this ID to be generated dynamically.
$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
var_dump($category_id);

This category is generated from a custom post type.
I used this to get the category ID:
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

EDIT: I registered the custom post type like this:
// Register Custom Post Type
function custom_post_type() {

$labels = array(
    'name'                  => _x( 'Works', 'Post Type General Name', 'text_domain' ),
    'singular_name'         => _x( 'Work', 'Post Type Singular Name', 'text_domain' ),
    'menu_name'             => __( 'Works', 'text_domain' ),
    'name_admin_bar'        => __( 'Works', 'text_domain' ),
    'archives'              => __( 'Item Archives', 'text_domain' ),
    'attributes'            => __( 'Item Attributes', 'text_domain' ),
    'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
    'all_items'             => __( 'All Items', 'text_domain' ),
    'add_new_item'          => __( 'Add New Item', 'text_domain' ),
    'add_new'               => __( 'Add New', 'text_domain' ),
    'new_item'              => __( 'New Item', 'text_domain' ),
    'edit_item'             => __( 'Edit Item', 'text_domain' ),
    'update_item'           => __( 'Update Item', 'text_domain' ),
    'view_item'             => __( 'View Item', 'text_domain' ),
    'view_items'            => __( 'View Items', 'text_domain' ),
    'search_items'          => __( 'Search Item', 'text_domain' ),
    'not_found'             => __( 'Not found', 'text_domain' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
    'featured_image'        => __( 'Featured Image', 'text_domain' ),
    'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
    'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
    'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
    'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
    'items_list'            => __( 'Items list', 'text_domain' ),
    'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
    'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
);
$args = array(
    'label'                 => __( 'Work', 'text_domain' ),
    'description'           => __( 'Work Description', 'text_domain' ),
    'labels'                => $labels,
    'supports'              => array( 'title', 'editor' ),
    'taxonomies'            => array( 'category', 'post_tag' ),
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => true,
    'menu_position'         => 5,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'page',
    'show_in_rest' => true,
);
register_post_type( 'works', $args );

}
add_action( 'init', 'custom_post_type', 0 );

A: get_the_category retrieve array of post categories.
This tag may be used outside the loop by passing a post id as the parameter.
The syntax is
$categories = get_the_category(  $post_id  ); // Outside the loop

// OR

$categories = get_the_category( ); // Inside the loop

Note: This function only returns results from the default "category" taxonomy. For custom taxonomies use get_the_terms() .
$categories = get_the_terms( $post_id, 'taxonomy' );

I hope this may help.

A: I used this to get the category ID.
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;


text:
Q: Python: Saving dictionary to .py file I have got a dictionary this_dict produced in a python script that I would like to write to a separate python module dict_file.py. This would allow me to load the dictionary in another script by importing dict_file.
I thought a possible way of doing this was using JSON, so I used the following code:
import json

this_dict = {"Key1": "Value1",
             "Key2": "Value2",
             "Key3": {"Subkey1": "Subvalue1",
                      "Subkey2": "Subvalue2"
                     }
            }

with open("dict_file.py", "w") as dict_file:
    json.dump(this_dict, dict_file, indent=4)

When I opened the resulting file in my editor, I got a nicely printed dictionary. However, the name of the dictionary in the script (this_dict) was not included in the generated dict_file.py (so only the braces and the body of the dictionary were written). How can I include the name of the dictionary too?
I want it to generate dict_file.py as follows:
this_dict = {"Key1": Value1,
             "Key2": Value2,
             "Key3": {"Subkey1": Subvalue1,
                      "Subkey2": Subvalue2
                     }
            }

A: 1) use file.write:
file.write('this_dict = ')
json.dump(this_dict, dict_file)

2) use write + json.dumps, which returns a string with json:
file.write('this_dict = ' + json.dumps(this_dict)

3) just print it, or use repr
file.write('this_dict = ')
file.write(repr(this_dict))
# or:
# print(this_dict, file=file)

A: If you don't want to use pickle as @roganjosh proposed in the comments, a hacky workaround would be the following:
this_dict = {"Key1": "Value1",
             "Key2": "Value2",
             "Key3": {"Subkey1": "Subvalue1",
                      "Subkey2": "Subvalue2"
                     }
            }

# print the dictionary instead
print 'this_dict = '.format(this_dict)

And execute the script as:
python myscript.py > dict_file.py

Note: Of course this assumes that you will not have any other print statements on myscript.py.


text:
Q: Web Part "Recent Checkins" in sharepoint not showing changes I have connected a project to my TFS. When creating a team project I have also created a SharePoint site. Everything is working well except for the "Recent Checkins" web part which are not being displayed.
I am given the following error:

TF10127: The path does not include a source control item. Type or select a different path.

I tried selecting the source from the change button available as mentioned in this post but I am constantly being given the same error message.
Note: I am using a GIT repository, and the version of TFS is 2013.

A: The SharePoint integration with TFS does not support git. That webpart will not work with git.


text:
Q: Selecting specific class and add title to it with Jquery I'm currently working on a project where I retrieve large amounts of data from a csv which I have converted into an array containing over a hundred objects. Each object contains 15 data points as you can see below.

What I'm doing below is select a specific class (.centrale-vak__key) and append a span with a class that matches item["Items in CHILDoc"] in the datafile. After that it adds the text in that same item["Items in CHILDoc"] to the span.

$.each(data1, function (index, item) {
      if (item["Kwadrant in CHILDoc"] == "Centrale vak") {
            $(".centrale-vak__key").append("" + item["Items in CHILDoc"] + "" + "
");
      }
})

What I would like to do is add a title to each created span (there are several "Centrale vak" items in the data file). For this I would like to use another data variable (data2). I have this snippet so far.

        $.each(data2, function(index, item){
            if (item["Kwadrant in CHILDoc"] == "CHILDoc") {
                $(".item-childoc_ " + item["Items in CHILDoc"].replace(/[^a-zA-Z0-9]/g,''))
                    .attr("title", item["Items in CHILDoc"]);
            }
        })

For some reason the class selector is not working. Adding extra "" around it doesn't work either. Is there an easier way to solve this?

A: Try this code:
  $.each(data2, function(index, item){
        if (item["Kwadrant in CHILDoc"] == "CHILDoc") {
            $(".centrale-vak__key").find(".item-childoc_ " + item["Items in CHILDoc"].replace(/[^a-zA-Z0-
            9]/g,'')).first().prop("title", item["Items in CHILDoc"]);
        }
    })


text:
Q: Amp page rel=canonical pointing to non-amp auto Wordpress I am stuck with this thing.
I have the original page (article) in Wordpress that has rel="amphtml" in it inserted auto.
Now, I need to have from amp page a rel="canonical" pointing to the original one, and do this auto.
I have written this code to amp html:
  <link rel="canonical" href="https://www.example.com<?php echo $_SERVER['REQUEST_URI'];?>">

But this code makes AMP page to point to itself, and not to the original version.
Any thoughts? I am a bit new in this

A: I found the solution.
I will post it here, maybe another user will need it
I have added in amp html-start.php this (after head)

<link rel="canonical" href="<?php echo get_permalink( $post->ID ); ?>">


text:
Q: Metric variation of a four-vector I am trying to calculate the metric variation $\frac{\delta T^{\alpha\beta}}{\delta g^{\mu\nu}}$. Here, $T^{\alpha\beta}$ is the stress-energy tensor of a perfect fluid, given by $T^{\alpha\beta} = (\rho+p)u^\alpha u^\beta + g^{\alpha \beta} p$.
What I would get is therefore $$\frac{\delta T^{\alpha\beta}}{\delta g^{\mu\nu}} = \frac{\delta[(\rho+p)u^\alpha u^\beta]}{\delta g^{\mu\nu}} +\frac{\delta g^{\alpha\beta}}{\delta g^{\mu\nu}} p.$$
What I do not understand is how to compute the term $\frac{\delta[(\rho+p)u^\alpha u^\beta]}{\delta g^{\mu\nu}}$. Is it null?


text:
Q: How to set a maximum number of days to select using v-calendar range in vue.js? Using vuejs vcalendar range , I want to limit the number of days the user can select. Do you know it there is some kind of a "maxDays" option?
I have also tried to create a method where when the range is bigger than a certain number of days, the end date is modified to fit the maximum range. The issue here that I found was that the calendar wasnt updating, even if the date object was.
So lets say I have in my template the following calendar:
<v-date-picker v-model="range" is-range />
Where "range" is:
data() {
    return {
      range: {
        start: new Date(),
        end: new Date(),
      },
    };
  }

I have a method that checks if the range is valid. And if it is not valid (i.e. when it is too big), the end date is modified:
if (!this.validRange) {
        let startDate = this.range.start;
        let endDate = new Date();
        endDate.setDate(startDate.getDate() + 6);
        this.$set(this.range, "end", endDate);
      }

And as I said, the value range.end changes properly, but the calendar still shows the same range without updating the range.end value.
Is there a way I can fix this?
And I know other libraries can do those kind of thigs, I just want to know if it is possible with v-calendar.
Thanks a lot for your help!
Julien

A: Here is a fiddle: https://jsfiddle.net/Lhd9eov4/
HTML:
<div id='app'>
  <v-date-picker
          v-model="range"
          is-range
          @input="handleInput()"
        />
</div>

JS:
new Vue({
  el: '#app',
  data() {
    return {
      range: {
        start: new Date(),
        end: new Date().setDate(new Date().getDate() + 1),
      }
  }},

  methods:{
        handleInput(){
        this.$nextTick(() => {
        this.range = {
          start: this.range.start,
          end: new Date().setDate(this.range.start.getDate() + 6),
          };
        });
      }
    }
})

The range seems reactive when you create a new object. Listening to the input event and then updating the range (in another DOM update cycle) seems to do the job.


text:
Q: Sandcastle Help File Builder not showing documentation for xml comments for html/asp.net elements in .ascx.designer.vb file I am using Sandcastle Help File Builder to build the documentation for a VB.net project but the documentation for the asp.net/html elements are not appearing.
The xml comments for these are defined in the .ascx.designer.vb file for the respective Web Form or Web Forms User Control. An example of this code is as follows:
Partial Public Class WebUserControl
    '''
    '''TblsDiv control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents TblsDiv As Global.System.Web.UI.HtmlControls.HtmlGenericControl
End Class

In the help file created by Sandcastle Help File Builder, the documentation for these elements appear blank as if there were no xml comments.
Is this an issue with Sandcastle Help File Builder or is there another way to add xml comments to the respective html/asp.net elements?

A: After doing some research the only thing I have found was a very old answer Protected Withevents not documenting properly of the developer of SHFB from the year 2007.

The VB.NET compiler performs some stuff behind the scenes that causes this problem.  In the XML comments file, the "bw" member is documented as a field (F:AbstractApp.bw) which on the surface appears to be correct.  However, the compiler converts it to a private field (_bw), decorates it with an AccessedThroughProperty attribute, and creates a protected property called "bw" (P:AbstractApp.bw).  As such, the XML comments get ignored because they now refer to a field that doesn't exist and there are no comments for the compiler generated property.  What's also interesting is that the property won't show up until you include internal or private members in the documentation build because _bw is private so it doesn't see the property if they are omitted.
It's a pain to have to do it, but what you could do is create a "Comments Only" XML file and add the XML comments to it for the properties that the compiler creates.  The other option, if they aren't that relevant is to turn off the document privates and internals options or use the API filter to get rid of them so that they don't show up in the documentation at all.

But it seems to me this is a problem remaining today.
Please note I'm not a ASP.net developer and I can test this using Visual Studio Community 2015 and Sandcastle Help File Builder (SHFB) Version 2019.15.9.0 at this stage only.
My code snippet for testing in a WebUserControl1.ascx.vb:
'''
''' TEST Sandcastle Help File Builder (SHFB)
'''
Partial Public Class WebUserControl
  '''
  '''TblsDiv control.
  '''
  '''<remarks>
  '''This is for test case only.
  '''Sandcastle Help File Builder (SHFB) not showing documentation for xml comments for html.
  '''</remarks>
  Protected WithEvents TblsDiv As Global.System.Web.UI.HtmlControls.HtmlGenericControl

End Class

Building the solution is resulting in a file WebForms_Basic.xml I added as a documentation source in SHFB's project explorer.
<member name="T:WebApplication2.WebUserControl">

 TEST Sandcastle Help File Builder (SHFB)

</member>
<member name="F:WebApplication2.WebUserControl._TblsDiv">

TblsDiv control.

<remarks>
This is for test case only.
Sandcastle Help File Builder (SHFB) not showing documentation for xml comments for html.
</remarks>
</member>

Building help file - you know - is resulting in:

Editing the following line in WebForms_Basic.xmland building the help files without building the solution
<member name="P:WebApplication2.WebUserControl.TblsDiv">

is resulting in what you expected. You need to adapt this for your needs.


text:
Q: two returns in one function for laravel api Is it true that in laravel api the first return will break the function and won't let it continue executing the rest of the function?
I have this function
public function get(Request $request)
{
    $users = User::doesntHave('reservations')->get();
    if ($users) {
       return Response::json($users);
 }
     // do something here if no users attached with reservation and do
    // return Response::json($users);
}

when I do this I get no data! What is my mistake ?

A: I guess what you want is to check if result is empty or not:
if (!$users->isEmpty()) {
    return Response::json($users);
}

return Response::json('There is no result');

And yes, you can return response only once.

A: This is not exclusive to Laravel, but yes. A return statement per definition will return to the caller of the function immediately, so nothing else after it will be executed.

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.


text:
Q: Fitting a big grid (wxGrid) in a dialog (wxDialog) Here is my layout:

*

*I have a sizer that contains a grid (with a proportion of 1) and a ok/cancel button bar

*The all thing is in a wxDialog
Here it is:
|||||||||||||||
|             |
|    GRID     |
|             |
|             |
|             |
|||||||||||||||
| OK  CANCEL  |
|||||||||||||||

The issue is that the grid contains too many row, and over flow the screen, so in the end I don't see the top part of the dialog. Is there a way, when calling Fit() on the dialog, to limit its height ?
I have tried stuff like this: SetSizeHints(-1,-1,-1,500); and SetMaxSize(500,500) but it did not worked.
Also I have tried to do that: this->SetSize(this->GetSize().GetX(), 500);, but since the vertical scroll bar appears on the grid, it is not wide enough and a horizontal scroll bar shows up.
EDIT
In the constructor I call wxGrid(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize)

A: The easiest way to handle this is to use a grid of fixed size.  If there are more rows than will fit, then a scroll bar will appear.  You set the size you want in the constructor.
new wxGrid( this, IDC_grid, wxPoint(-1,-1),wxSize(igridxsize,igridysize));

If you want the size of the grid to adjust, e.g. when the user resizes the application window, things are a bit more complex.  You need handle the window size event and change the grid size as appropriate.
Something along these lines:
myDialog::OnSize(wxSizeEvent& event);
{
wxSize dialogSize = event.GetSize();
myGrid->OnSize( wxSizeEvent(
     dialogSize.GetWidth() * 0.9, dialogSize.GetHeight() * 0.7 ));
}


text:
Q: IIS related System.ExecutionEngineException After too many hours of research I have come up with nothing to solve this problem.
I am running a WPF program in an .xbap page file being hosted on internet explorer. Running the project in Visual Studio 2010 works just fine and generates no errors.
I want to be able to host the webpage on IIS 7.0 and to browse to it with a windows forms application. To test this I created a new website on port 80 in IIS manager. I then published the project to the local website folder and added the autogenerated project certificate file (projectName_TemporaryKey.pfx) to my Trusted Publishers and Trusted Root Certification Authorities.
My problem is this: whenever I try to browse to the file with internet explorer or with my windows forms program, the wpf program stops working. When pulling up the just-in-time debugger, I am informed that there is a System.ExecutionEngineException but am given no source code, no stack trace, and no data outside of an empty Dictionary enumerable. My guess is that this might have something to do with the database call made in the program to another machine, but I can't prove that.
I've tried several things to solve this including repairing my .NET 4.0 framework and altering permissions but nothing seems to be affect the error.
Does anyone know of a way to get more information on this error, or perhaps a step I may have missed when publishing this project?
Thanks very much.

A: Some things to check:

*

*Windows event log often includes additional exception information (although usually in an awful format)

*Output some trace information from your application so you can follow what's happening

*Try attaching a debugger to the WPFHost and then stepping through the code


text:
Q: Deal on Fed removes obstacle Does "Fed" refer to "Federal Reserve"? Or refer to "Federal Government"?

Deal on Fed removes obstacle to agreement on COVID relief

WASHINGTON (AP) — Top congressional lawmakers struck a late-night agreement on the last major obstacle to a COVID-19 economic relief package costing nearly $1 trillion, clearing the way for votes as early as Sunday.
.......
The breakthrough involved a fight over Federal Reserve emergency powers that was defused by an odd couple: the Senate's top Democrat and a senior conservative Republican.

Source:  Associated Press

A: From your paragraph you quoted, it is evident that the title refers to the "Federal Reserve".
I did a quick search and found another article that corroborates this. From The New York Times:

Senators broke through an impasse late Saturday night over a Republican effort to curtail the powers of the Federal Reserve, clearing away what had been seen as the final hurdle to a deal on a $900 billion stimulus package as lawmakers raced against a Sunday-night deadline to avoid a government shutdown.

(emphasis mine)

Additionally, the "Federal Reserve" can be referred to as "the Fed". From Wikipedia:

The Federal Reserve System (also known as the Federal Reserve or simply the Fed) ...

It is rare to use "Fed" to refer to the Federal Government. (Personally, I do not recall such usage.)


text:
Q: Get active gtk window in python How would I get a handle to the active gtk.Window in python? (not a window I created, but the currently focused window).

A: The answer is actually not OS-specific -- you can do it within GTK. You can get a list of all the toplevel windows from the application using gtk.window_list_toplevels(), then iterate through it until you find one where window.is_active() returns True.
If you want to consider other windows than the ones from your application, then you could try gtk.gdk.screen_get_default().get_toplevel_windows() but this will only get you GDK windows and not GTK windows, because you have no way of knowing whether those GDK windows are actually associated with GTK windows.

A: [Note: This answers the question as the OP originally phrased it, which other readers will probably be searching for - not the very different question that they changed it to in comments on the other answer.]
If you have a GtkApplication and have added your GtkWindows to it - which you should probably do, because GtkApplication can do lots of really cool stuff! - then you can use GtkApplication's much simpler API dedicated to this purpose:
Gtk.Application.get_active_window():

Gets the "active" window for the application.
The active window is the one that was most recently focused (within the application). This window may not have the focus at the moment if another application has it — this is just the most recently-focused window within this application.