text:
Q: pandas: Get an average value of sales for a day of week based on 4 past weeks I'm stacked, and I need the wisdom of the stackoverflow.
I want to create a simple averaging model for sales based on the day of the week from past using pandas.
I mean, the model predicts value of Sales for next Monday based on the last 4 Mondays. Also, if there are no enough weeks in the past, just make an average of existing weeks.
Sample of my time-series df:
     weekDay weekNum Sales
Date
2013-01-01  2   1   22
2013-01-02  3   1   33
2013-01-03  4   1   44
2013-01-04  5   1   55
2013-01-05  6   1   66
2013-01-06  7   2   76
2013-01-07  1   2   23
2013-01-08  2   2   55
2013-01-09  3   2   34
2013-01-10  4   2   43
2013-01-11  5   2   34
2013-01-12  6   2   53
2013-01-13  7   3   52
2013-01-14  1   3   41
2013-01-15  2   3   31
2013-01-16  3   3   31
2013-01-17  4   3   42
2013-01-18  5   3   23
2013-01-19  6   3   41
2013-01-20  7   4   31
2013-01-21  1   4   31
2013-01-22  2   4   31
2013-01-23  3   4   43
2013-01-24  4   4   53
2013-01-25  5   4   32
2013-01-26  6   4   12
2013-01-27  7   5   41
2013-01-28  1   5   41
2013-01-29  2   5   12
2013-01-30  3   5   76
2013-01-31  4   5   43
2013-02-01  5   5   32
2013-02-02  6   5   54
2013-02-03  7   6   43
2013-02-04  1   6   43
2013-02-05  2   6   12
2013-02-06  3   6   12
2013-02-07  4   6   43
2013-02-08  5   6   22
2013-02-09  6   6   12

What I've tried:
ts.resample('D').rolling(28).mean()["Sales"]
ts.resample('W-MON').rolling(1).mean()["Sales"]

but it didn't help.

A: Ok, Sorry, I think I understand now what you are looking for:
res = df.join(df.groupby('weekDay').rolling('28d').mean(), rsuffix='_avg')

so now res contains:

                   weekDay weekNum  Sales  weekDay_avg  weekNum_avg  Sales_avg
weekDay date
1       2013-01-07       1       2     23          1.0          2.0  23.000000
        2013-01-14       1       3     41          1.0          2.5  32.000000
        2013-01-21       1       4     31          1.0          3.0  31.666667
        2013-01-28       1       5     41          1.0          3.5  34.000000
        2013-02-04       1       6     43          1.0          4.5  39.000000
2       2013-01-01       2       1     22          2.0          1.0  22.000000
        2013-01-08       2       2     55          2.0          1.5  38.500000
        2013-01-15       2       3     31          2.0          2.0  36.000000
        2013-01-22       2       4     31          2.0          2.5  34.750000
        2013-01-29       2       5     12          2.0          3.5  32.250000
        2013-02-05       2       6     12          2.0          4.5  21.500000
3       2013-01-02       3       1     33          3.0          1.0  33.000000
        2013-01-09       3       2     34          3.0          1.5  33.500000
        2013-01-16       3       3     31          3.0          2.0  32.666667
        2013-01-23       3       4     43          3.0          2.5  35.250000
        2013-01-30       3       5     76          3.0          3.5  46.000000
        2013-02-06       3       6     12          3.0          4.5  40.500000
4       2013-01-03       4       1     44          4.0          1.0  44.000000
        2013-01-10       4       2     43          4.0          1.5  43.500000
        2013-01-17       4       3     42          4.0          2.0  43.000000
        2013-01-24       4       4     53          4.0          2.5  45.500000
        2013-01-31       4       5     43          4.0          3.5  45.250000
        2013-02-07       4       6     43          4.0          4.5  45.250000
5       2013-01-04       5       1     55          5.0          1.0  55.000000
        2013-01-11       5       2     34          5.0          1.5  44.500000
        2013-01-18       5       3     23          5.0          2.0  37.333333
        2013-01-25       5       4     32          5.0          2.5  36.000000
        2013-02-01       5       5     32          5.0          3.5  30.250000
        2013-02-08       5       6     22          5.0          4.5  27.250000
6       2013-01-05       6       1     66          6.0          1.0  66.000000
        2013-01-12       6       2     53          6.0          1.5  59.500000
        2013-01-19       6       3     41          6.0          2.0  53.333333
        2013-01-26       6       4     12          6.0          2.5  43.000000
        2013-02-02       6       5     54          6.0          3.5  40.000000
        2013-02-09       6       6     12          6.0          4.5  29.750000
7       2013-01-06       7       2     76          7.0          2.0  76.000000
        2013-01-13       7       3     52          7.0          2.5  64.000000
        2013-01-20       7       4     31          7.0          3.0  53.000000
        2013-01-27       7       5     41          7.0          3.5  50.000000
        2013-02-03       7       6     43          7.0          4.5  41.750000

and in order to make it similar to your good ol' DataFrame that we began with:
res.drop(['weekDay', 'weekDay_avg', 'weekNum_avg'], axis=1, inplace=True)
res.reset_index(inplace=True)
res.set_index('date', inplace=True)
res.sort_index(inplace=True)

so now it looks like this:

           weekDay weekNum  Sales  Sales_avg
date
2013-01-01       2       1     22  22.000000
2013-01-02       3       1     33  33.000000
2013-01-03       4       1     44  44.000000
2013-01-04       5       1     55  55.000000
2013-01-05       6       1     66  66.000000
2013-01-06       7       2     76  76.000000
2013-01-07       1       2     23  23.000000
2013-01-08       2       2     55  38.500000
2013-01-09       3       2     34  33.500000
2013-01-10       4       2     43  43.500000
2013-01-11       5       2     34  44.500000
2013-01-12       6       2     53  59.500000
2013-01-13       7       3     52  64.000000
2013-01-14       1       3     41  32.000000
2013-01-15       2       3     31  36.000000
2013-01-16       3       3     31  32.666667
2013-01-17       4       3     42  43.000000
2013-01-18       5       3     23  37.333333
2013-01-19       6       3     41  53.333333
2013-01-20       7       4     31  53.000000
2013-01-21       1       4     31  31.666667
2013-01-22       2       4     31  34.750000
2013-01-23       3       4     43  35.250000
2013-01-24       4       4     53  45.500000
2013-01-25       5       4     32  36.000000
2013-01-26       6       4     12  43.000000
2013-01-27       7       5     41  50.000000
2013-01-28       1       5     41  34.000000
2013-01-29       2       5     12  32.250000
2013-01-30       3       5     76  46.000000
2013-01-31       4       5     43  45.250000
2013-02-01       5       5     32  30.250000
2013-02-02       6       5     54  40.000000
2013-02-03       7       6     43  41.750000
2013-02-04       1       6     43  39.000000
2013-02-05       2       6     12  21.500000
2013-02-06       3       6     12  40.500000
2013-02-07       4       6     43  45.250000
2013-02-08       5       6     22  27.250000
2013-02-09       6       6     12  29.750000

Hope this time this really helps (:


text:
Q: Can't remove Google Cloud project I was playing around with terraform to create an infrastructure for a couple of services on GCP. GCP organises all the infra in so called projects. I specified a project_id incrorrectly in terraform files(actually I set project_id to already existing in my GCP, but ptoject name was different). Terraform in plan phase was successful, but after apply it failed. Then I executed terraform destroy, set correct project_id(and name), executed terraform apply again, this time successfully. But when I opened the GCP console I saw that actually 2 projects were created in project list(one with correct name and id and another with some random name: smth like My Project 1234 as name and beaming-light-546562 as id). And now gcloud projects list command shows 3 projects(this random one, correct one and previously existing one).
The problem is that I can't remove that "random" project, neither from gcloud utility nor from gcp console. I get an error
<myuser_mail_address> does not have permission to access projects instance or poject doesn't exist

Also that random project is not linked to my billing account.
How can I remove that "random" project
EDIT
It seems strange that the project with id beaming-light-546562 can't be removed by me(the owner of an account) with reasons that I do not have permissions to do that. Also the name of an id: it is similar to technic docker is using for generating names of running containers. I do not recall that terraform has such a feature. Could it be gcp itself who generates such random names?

A: I tried to recreate the error i.e, I created a sample project(via console) and deleted the same sample project in cloud shell using this command
gcloud projects delete <project ID> and again tried to delete the same sample project in cloud shell and got this error message:

You can cross verify if the reason listed in the image i.e PROJECT_DELETE_INACTIVE is present in the output of your gcloud projects delete <project ID> command.This means that the project is inactive and the project becomes inactive when it's deleted.
From this document :
The project takes approximately 30-days for complete deletion, At the end of the 30-day period, the project and all its resources are deleted and cannot be recovered.
Edit:
It seems to be a known issue with GCP. Leaving "Google Groups" related to GCP is a fix to this issue. You can track this Public Issue for more information.
You might have been added into a project through a group, so it appears in the project list. However, you have not been granted permission to modify the IAM of that project, so you can't remove the group from the permission list.
As a workaround, you can leave "Google Groups" related to GCP and reload the GCP console webpage so that all your unknown/inaccessible projects will disappear from the projects list. You can find what groups you're a member of, using this Google Groups link.
NOTE : You can leave the groups in order to lose the access, but there could be a situation where your email is added to a single role/permission and you would not be able to remove yourself from the IAM list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Write /etc/hosts via ansible using variables inside magical variables I'm trying to write file /etc/hosts via ansible for cluster purposes. I want to use group_vars variable inside of magical variables. Here is working  example, where I use ansibe_default_ipv4 without group_vars variable:
    - name: Add hosts to /etc/hosts
      lineinfile:
      args:
         dest: "/etc/hosts"
         regexp: "{{ hostvars[item]['ansible_default_ipv4']['address'] }}"
         line: "{{ hostvars[item]['ansible_default_ipv4']['address'] }} {{ hostvars[item]['ansible_fqdn'] }}   {{ hostvars[item]['ansible_fqdn'].split('.')[0] }}"
      with_items: "{{ play_hosts }}"
      tags: ha-cluster

But I want to use something like ansible_{{ cluster_interface }} instead of ansible_default_ipv4, where cluster_interface is the variable in group_vars, like eth0 or eth1. To make role more flexible with using certain interfaces for different clusters.
Here is not working example:
    - name: Add hosts to /etc/hosts
      lineinfile:
      args:
         dest: "/etc/hosts"
         regexp: "{{ hostvars[item]['ansible_default_ipv4']['address'] }}"
         line: "{{ hostvars[item]['ansible_{{ cluster_ineterface }}']['ipv4']['address'] }} {{ hostvars[item]['ansible_fqdn'] }}   {{ hostvars[item]['ansible_fqdn'].split('.')[0] }}"
      with_items: "{{ play_hosts }}"
      tags: ha-cluster

The error:
fatal: [node1.linux.cluster.test]: FAILED! => {
"failed": true,
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined.
The error was: 'dict object' has no attribute 'ansible_{{ cluster_interface }}'\n
\nThe error appears to have been in '/home/name/.ansible/roles/ha-cluster/tasks/main.yml':
line 36, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n
\nThe offending line appears to be:\n\n\n- name: Add hosts to /etc/hosts\n  ^ here\n"
}

Ansible Version: 2.2.1.0-2
Host: Debian 9.4
Is it even possible to use group_vars inside of magical vars?
Thank you!


text:
Q: unable to run command ~$ vue add unit-mocha in vue cli 3 I want to add mocha as a unit testing plugin to my already created vue project, which was built using CLI 3 i.e. vue create myProj
this is for vue CLI 3.0.0+, in which my current project is running
BELOW IS THE ERROR when i run command
~$ vue add unit-mocha
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/vue-cli-plugin-unit-mocha - Not found
npm ERR! 404
npm ERR! 404  'vue-cli-plugin-unit-mocha@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Piktorlabs\AppData\Roaming\npm-cache\_logs\2019-11-04T10_03_45_315Z-debug.log
 ERROR  command failed: npm install --loglevel error -D vue-cli-plugin-unit-mocha

hence as per the NPM documentation at https://www.npmjs.com/package/@vue/cli-plugin-unit-mocha
it says to run command ~$ vue add unit-mocha
to add mocha unit testing plugin in an already created project, but i get a 404 error in the CLI saying that the npm directory does not exist

A: The issue was I did not update the Vue cli to the latest version, the cli version was 2.6.0...once I updated it to 4.0 0, the issue was resolved


text:
Q: Adding Point Graphic to ArcGIS API for JavaScript Map? Can you please take a look at this JSFiddle and let me know why I am not able to add the Marker into the Map? I am getting this error

Uncaught TypeError: Cannot read property 'add' of null

Here is the code I have
var map;
var graphicsArray = [];
require(["esri/map",
    "esri/geometry/Geometry",
    "esri/geometry/Point",
    "esri/geometry/Polyline",
    "esri/geometry/Polygon",
    "esri/graphic",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/Color",
    "esri/InfoTemplate",
    "dojo/domReady!",
    "esri/geometry"], function (Map,

Geometry,
Point,
Polyline,
Polygon,
Graphic,
SimpleMarkerSymbol,
SimpleLineSymbol,
SimpleFillSymbol,
Color,
InfoTemplate) {
    map = new Map("map", {
        basemap: "topo",
        center: [-106.61, 35.1107],
        zoom: 13
    });

    var point = new Point(-106.61, 35.1107);
    var pointSymbol = new SimpleMarkerSymbol();
    var pointAttributes = { city: "Albuquerque", state: "New Mexico" };
    var pointInfoTemplate = new InfoTemplate("Albuquerque");
    var pointGraphic = new Graphic(point, pointSymbol, pointAttributes).setInfoTemplate(pointInfoTemplate);

    graphicsArray.push(pointGraphic);
    for (i = 0; i < graphicsArray.length; ++i) {
        map.graphics.add(graphicsArray[i]);

    }

});

      html, body, #map {
          height: 100%;
          width: 100%;
          margin: 0;
          padding: 0;
      }
      body {
          background-color: #FFF;
          overflow: hidden;
          font-family:"Trebuchet MS";
      }

<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">

A: You have to wait for the map to load before you can interact with it.
See http://developers.arcgis.com/javascript/3/sandbox/sandbox.html?sample=graphics_add, or for an updated version of your sample: http://jsfiddle.net/ady51wrn/7/.


text:
Q: Azure WebJob File Storage activity trigger alternative I read this question and answer but it doesn't solve my problem.
What would be the best way of solving the following scenario.

*

*I have a file storage which receives files from an external app.

*I need to process those files as soon as they arrive.

*This is currently achieved through an Azure Web Job

This is a change request  to a solution (Web Job) which is already working based on a TimerTrigger. Basically it's executed every N minutes.
Since I can't change the external program which puts files into storage, my options are limited to the following:

*

*Decrease the time in TimerTrigger so it checks for files every 1 minute (which is sufficient enough in terms of the business requirements)

*Mount a share in my main (is this even possible.?) and use FileTrigger
Any suggestions are greatly appreciated.

A: As you said, you could decrease the time in TimerTrigger to let WebJob execute more frequent and detect whether any files are uploaded (or created) to file storage.
Besides, you can run the net use command to mount the file share.

example:
net use z: \\samples.file.core.windows.net\logs /u:samples <storage-account-key>

and then you could try to use FileTrigger to detect whether new files arrive in the specified directory.


text:
Q: Reference Request - Functional Derivatives I am looking for some good references that introduce functional derivatives in a quick but rigorous way. Any suggestions?
In addition, I saw somewhere that functional derivatives are related to Frechét derivatives. Is this accurate? How are they related?

A: Meanwhile someone could add something about the references, let me tell you how the Frechét technique is used to get the famous Euler-Lagrange condition with a classical example.
Let us suppose the you have a integral functional like
$$A=\int_I{\cal L}(x,y,y')dx$$
where $y=y(x)$.
Now to mimic Frechét procedure we take
$$A_{\varepsilon}=\int_I{\cal L}(x,y+\varepsilon h,y'+\varepsilon h')dx.$$
Employ expansions to get
$${\cal L}(x,y+\varepsilon h,y'+\varepsilon h')={\cal L}(x,y,y')+\varepsilon h\frac{\partial{\cal L}}{\partial y}+\varepsilon h'\frac{\partial{\cal L}}{\partial y'}+R(\varepsilon^2,x).
$$
Upon some basic manipulation you will get
$$\frac{A_{\varepsilon}-A}{\varepsilon}=
\int_I h\left(\frac{\partial{\cal L}}{\partial y}-\frac{d}{dx}\frac{\partial{\cal L}}{\partial y'}\right)dx+\frac{1}{\varepsilon}\int_IR(\varepsilon^2,x)dx,$$
So, under some mild conditions, in the limit we arrive at
$$\lim_{\varepsilon\to0}\frac{A_{\varepsilon}-A}{\varepsilon}=
\int_I h\left(\frac{\partial{\cal L}}{\partial y}-\frac{d}{dx}\frac{\partial{\cal L}}{\partial y'}\right)dx,$$
for all function $h=h(x)$, which if they obey $h|_{\partial I}=0$ then, asking for
$\lim_{\varepsilon\to0}\frac{A_{\varepsilon}-A}{\varepsilon}=0$ in order to be a detector of extreme data $(x,y,y')$, one is led to the fact that
$$\int_I h\left(\frac{\partial{\cal L}}{\partial y}-\frac{d}{dx}\frac{\partial{\cal L}}{\partial y'}\right)dx=0,$$
for all suitable $h$, then is needed that
$$\frac{\partial{\cal L}}{\partial y}-\frac{d}{dx}\frac{\partial{\cal L}}{\partial y'}=0,$$ to manipulate and find $y$ the extremizing function.


text:
Q: Error WordPress test Phpunit calling function in functions.php I'm testing with PhpUnit, calling functions of the functions.php
I have a function in which it verifies if it is a page and the SLUG template is equal to a page
function my_scripts() {

    var_dump (get_page_template_slug());

    if (is_page() && get_page_template_slug() == 'page-script.php') {

    ........
    }
}

In my test, I have this code
public function test_my_scripts(){

    $page_id = $this->factory->post->create(
        array(
            'post_type' => 'page',
        )
    );
    add_post_meta( $page_id , '_wp_page_template', 'page-script.php' );
    add_filter( 'page_template', 'custom_page_template' );

    var_dump(get_page_template_slug($page_id));

    my_scripts();

}

The result of the var_dump of my test is
string(15) "page-script.php"
and that of the function of the functions.php
bool(false)
And do not enter the condition IF.
How can I establish that the call to the function that is from a page and the slug is indicated to enter the condition if?
Thanks

A: I have found the solution and it is to put this before the call to the function my_scripts();
$this->go_to(get_permalink($page_id));


text:
Q: U-substitution for integral of 1/(1+e^x)dx. What am I doing wrong? Here is my work, with the right answer. I feel like every step is right, but somehow I am getting the wrong answer. How?
$$ \int \frac{1}{1+e^z}dz = \int\frac{1}{e^z(\frac{1}{e^z} + 1)}dz
=\int\frac{1}{\frac{1}{e^z} + 1}\frac{1}{e^z}dz $$
subbing $u = \frac{1}{e^z} + 1$, $\frac{du}{dz} = -e^{-z}dz \implies -du = \frac{1}{e^z}dz$ so
$$\int \frac{1}{1+e^z}dz = -\int\frac{1}{u}du = -\ln(u) + C = -\ln(e^{-z}+1) + C$$
But the right answer is $z - \ln(1+e^z)+C$

A: The "right answer" is merely the simplification of the answer you found.
$$
z+\text{ln}\left(1+e^{-z}\right)==\text{ln}\left(1+e^z\right)\\
e^{z+\text{ln}\left(1+e^{-z}\right)}==e^{\text{ln}\left(1+e^z\right)}\\
e^z\left(1+e^{-z}\right)==1+e^z\\
e^z+1==1+e^z
$$

A: Your answer is correct.
$$
-\ln \left( e^{-z}+1\right) + C = -\ln \left[ e^{-z} \left( 1 + e^z\right)\right] + C = \dots
$$


text:
Q: How to calculate specific cell values in python pandas? There is a pandas dataframe as follow:
import pandas as pd
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
'age': [20, 19, 22, 21],
'favorite_color': ['blue', 'blue', 'yellow', "green"],
'grade': [88, 92, 95, 70]}

df = pd.DataFrame(raw_data)

I want to divide age and grade numeric cell values equal blue in favorite_color column to 125.0 value and yellow values divide to 130.0 and green to 135.0. Results mus be inserted in new columns age_new, grade_new.
By below code I receive error.
df['age_new'] =(df.loc[df['favorite_color']=='blue']/125.0)
df['age_new'] =(df.loc[df['favorite_color']=='yellow']/130.0)
df['age_new'] =(df.loc[df['favorite_color']=='green']/135.0)
df['grade_new'] =(df.loc[df['favorite_color']=='blue']/125.0)
df['grade_new'] =(df.loc[df['favorite_color']=='yellow']/130.0)
df['grade_new'] =(df.loc[df['favorite_color']=='green']/135.0)

Error:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

A: map
mods = {'blue': 125, 'yellow': 130, 'green': 135}

df.assign(
    mods=df.favorite_color.map(mods),
    age_new=lambda d: d.age / d.mods,
    grade_new=lambda d: d.grade / d.mods
)

               name  age favorite_color  grade  mods   age_new  grade_new
0    Willard Morris   20           blue     88   125  0.160000   0.704000
1       Al Jennings   19           blue     92   125  0.152000   0.736000
2      Omar Mullins   22         yellow     95   130  0.169231   0.730769
3  Spencer McDaniel   21          green     70   135  0.155556   0.518519

Similar
mods = {'blue': 125, 'yellow': 130, 'green': 135}

df.join(df[['age', 'grade']].div(df.favorite_color.map(mods), axis=0).add_suffix('_new'))

               name  age favorite_color  grade   age_new  grade_new
0    Willard Morris   20           blue     88  0.160000   0.704000
1       Al Jennings   19           blue     92  0.152000   0.736000
2      Omar Mullins   22         yellow     95  0.169231   0.730769
3  Spencer McDaniel   21          green     70  0.155556   0.518519

A: You can use .replace instead of .loc, so that you only perform the operation once.
import pandas as pd

raw_data = {
    'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
    'age': [20, 19, 22, 21],
    'favorite_color': ['blue', 'blue', 'yellow', "green"],
    'grade': [88, 92, 95, 70]}

df = pd.DataFrame(raw_data)

color_d = {
    "blue": 125,
    "yellow": 130,
    "green": 135
}

df[["age_new", "grade_new"]] = df[["age", "grade"]].div(
    df['favorite_color'].replace(color_d),
    axis=0)

df.head()

Which gives
    name                age favorite_color  grade   age_new     grade_new
0   Willard Morris      20  blue            88      0.160000    0.704000
1   Al Jennings         19  blue            92      0.152000    0.736000
2   Omar Mullins        22  yellow          95      0.169231    0.730769
3   Spencer McDaniel    21  green           70      0.155556    0.518519


text:
Q: Convert Object type to List I have an object which can be of any collection type like IEnumerable or IQueryable or List.
Now i want this object to be converted into type List.
Can anyone tell me how can i achieve this??
Thanks

A: If you have .net 3.5 and System.Linq:
List<NewType> converted =
    myUnknownEnumeration.OfType<NewType>().ToList();

You need OfType to do the conversion (you can use Cast<>() instead if you want to throw an exception for any of the the wrong type) and ToList converts anything enumerable into a list.

A: You could cast your object to IEnumerable(T), then call ToList on it (.NET 3.5 required).


text:
Q: reading json with big numbers in spark causing rounding I am currently trying to read into spark a JSON file with large numbers. unsigned 64bit longs.
When I read it in, no matter the pyspark.sql.types I use in my schema LongType, DecimalType, DoubleType, etc...
Issue :
My numbers get rounded off. Even if I read them in as a StringType in my schema.
Is there a way to read these numbers in without rounding?

A: Turns out it wasn't spark at all.  It was from a dump of the data with elasticdump that produced the JSON with rounded numbers.  So going to just reindex it to a string and then dump it back out again like filbranden suggested


text:
Q: Check if parameter in URL is specific id I want to create functions for editing tables.
But I have more form which go to the same PHP page so when submit is sent I send a parameter in the URL like this php/edit.php?id=website and in the PHP code I want to check the ID in the URL so the function executes.
Here is the PHP code where I try to confirm the ID and then execute the function
<?php
    if(isset($_POST["submit"]) && isset($_GET['id']) == "website" {
    include('config.php');
    $sql2 = "UPDATE tblWebsite SET websiteNaam='".$_POST["websitenaam"]."' WHERE websiteId=".$_POST["websiteid"]."";

    if($db->query($sql2) === TRUE) {
        header('Location: /bvdo/pages.php');
        } else {
        echo "";
        }
    }
?>

Good to note the function is working because if I remove the && isset($_GET['id']) == "website" the database is updating with new values.

A: You can't combine isset and a compare. Also, you are missing a closing bracket in your if statement. What you probably want is this:
if(isset($_POST["submit"]) && isset($_GET['id']) && $_GET['id'] == "website") {
    // Do something
}

Explanation:
With isset($var) you check if the variable $var was initialized anywhere (if it was set). If the variable was set, isset returns true, otherwise it returns false. So what you are effectively comparing is if true == "website", and that is obviously never the case.
With $var2 == "a string" you check if your $var equals a string.
You can't mix them up, but check them one by one.

A: Instead of adding complication to code, why don't you split save the id to hidden input and get it along with the $_POST['id'].
if(isset($_POST["submit"]) && isset($_POST['id']) == "website" {
include('config.php');
$sql2 = "UPDATE tblWebsite SET websiteNaam='".$_POST["websitenaam"]."' WHERE websiteId=".$_POST["websiteid"]."";

if($db->query($sql2) === TRUE) {
    header('Location: /bvdo/pages.php');
    } else {
    echo "";
    }
}

Now no need to worry about URL parameter.

A: One other way to clean up the code would be using a function that checks if the value is set. You can do it separately by checking If function == your value.
function getValue($id) {
  if (!isset($_GET[$id])) {
    return false;
  }
    return $_GET[$id];
  }

  if (getValue('id') == 'website') {
    include('config.php');
    $sql2 = "UPDATE tblWebsite SET websiteNaam='".$_POST["websitenaam"]."'
    WHERE websiteId=".$_POST["websiteid"]."";

    if($db->query($sql2) === TRUE) {
      header('Location: /bvdo/pages.php');
    } else {
      echo "";
    }
  }
}

OR
If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:
if ((isset($variable) ? $variable : null) === $value) { }

The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.


text:
Q: Expand array once it reaches limit I have a program in which I need to print out several Movie objects (represented just by a single String) in an array. I start with a text file that already has five movies inside of it, but in the console, I am to allow the user to expand the array if he/she wants. (I cannot use an arraylist in this problem). I've attempted to design a program that does this, but I get an out of bounds exception each time I try to add a new movie. I also need to check the array to see if there is a duplicate movie object inside it? How can I do that?
Question: How can I allow the user to expand the array and add more movies to the list? How can I check the array to see if there is already a certain movie title inside of it?
public class MovieDriver {

    //variable declaration
    static Movie[] movies = new Movie[5];
    static Scanner scan = new Scanner(System.in);
    static int input = 0;
    static String title = "";

    public static void main(String[] args) throws FileNotFoundException {

        //retrieves movie data
        getData();

        System.out.println("Welcome to the favorite movie program.");

    do{
        System.out.println("Press 1 to print the list, 2 to add another movie, 3 to end the program.");

        input = scan.nextInt();

        switch(input) {

        case 1:
            for(int i = 0; i < movies.length; i++)
            {
            System.out.println(movies[i].toString());
            }

            break;

        case 2:
            System.out.println("Please enter the movie you would like to add to the list:");
            title = scan.nextLine();
            movies = Arrays.copyOf(movies, movies.length+1);
            movies[movies.length] = new Movie(title);

            break;

        case 3:
            System.out.println("Program terminated.");

            break;

            }
        } while (input != 3);
    }

    // method to retrieve data
    public static void getData() throws FileNotFoundException {
        // reads in movie data
        File MovieData = new File("./src/Movies.txt");
        Scanner fileScanner = new Scanner(MovieData);
        int i = 0;

        // while there is a new line in the data, goes to the next one
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            Scanner lineScanner = new Scanner(line);
            String title = lineScanner.nextLine();

            // creates a movie
            movies[i] = new Movie(title);
            i++;
        }
    }
}

A: first question: IndexOutOfBound
No need to use System.arraycopy().
You use the right method with Arrays.copyOf(). The problem comes from
movies = Arrays.copyOf(movies, movies.length+1);
movies[movies.length] = new Movie(title);  // <--- here

After you call copyOf(), the new length of the array is 6. And when you do movies[movies.length]=... you try to access the 7th element. Just do:
movies = Arrays.copyOf(movies, movies.length+1);
movies[movies.length-1] = new Movie(title);  // it will set the last slot of the array

But you have a second problem with the Scanner. When you scan the input with nextInt(), the end-of-line is not read. It means that if you enter 2 (add a movie), the 2 is read, but not the new-line. Then the new-line is read by title = scan.nextLine() and you have an empty title...
The solution is:
case 2:
   scan.nextLine();  // <-- add this to "eat" the previous new-line
   System.out.println("Please enter the movie you would like to add to the list:");
   title = scan.nextLine();
   movies = Arrays.copyOf(movies, movies.length+1);
   movies[movies.length-1] = new Movie(title);
   break;

Second question: check duplicate
Since you just have a plain/native array and no sorting between the movies, you can implement a simple for loop like:
case 2:
   scan.nextLine();  // <-- add this to "eat" the previous new-line
   System.out.println("Please enter the movie you would like to add to the list:");
   title = scan.nextLine();
   if (!checkDuplicate(title)) {
      movies = Arrays.copyOf(movies, movies.length+1);
      movies[movies.length-1] = new Movie(title);
   }
   break;

and add a function (assuming there is a Movie#getTitle():
    private static boolean checkDuplicate(String title) {
        for (Movie m : movies) {
            if (title.equals(m.getTitle())) {
                return true;
            }
        }
        return false;
    }

A: To expand the array by 1:
Movie[] temp = new Movie[movies.length + 1];
System.arraycopy(movies, 0, temp, 0, movies.length);
movies = temp;

To check if there is a duplicate movie object, implement equals in your Movie class. Then iterate through the existing movies, and check if movies[i].equals(newMovie).

A: To expand the array, you must recreate an array of desired size and copy the content of previous array to new one.
   static Movie[] movies = new Movie[5];

  // expanding
  Movie[] newMovieArray = new Movie[10];
  for(int i = 0; i < 5; i++){
       newMovieArray[i] = movies[i];
  }
  movies = newMovieArray;


text:
Q: Alternative ways to handle cuncurrency in a cinema bookin system My group and i have made a cinema booking system for a school project where the subject was cuncurrency control. It is made with c# and entity framework in an n-tier arcitecture where the presentationtier consisted of an mvc project.
We chose to use pessimistic locking (IsolationLevel.ReadCommited) during the "select seats for reservation" phase so that the database is locked while someone is checking if seats are available and when the seats are added to the reservation. I am currently looking if for example optimistic concurrency could have been an option an if so how it would work.
Here is a picture of the database diagram:

When you click on a specific show it will automatically create an empty reservation for you and then build the screen(cinema hall) with it seats and information wheather they are available or not.
Here is the method for creating a list of the seats linked to a screen(cinema hall):
public static List<SeatReservationInfo> GetSeatInfoForShow(Guid reservationId)
        {
            using (EntityContext db = new EntityContext())
            {
                //Retrieve a reservation on its id
                var reservation = db.Reservations.FirstOrDefault(r => r.Id == reservationId);
                //Retrieve the show linked to the reservation
                var show = db.Shows.First(i => i.Id == reservation.ShowId);
                //Used to check if the reservation is expired
                var expired = DateTime.Now.Subtract(new TimeSpan(0, 0, 15, 0));
                //Henter sæder ud tilhørende en specifik sal og laver Seat modellen om til en SeatReservationInfo model
                //Retrieve all seats linked to a specific screen and turn the Seat model into a SeatReservationModel which containt availablity status of the seat
                return
                    db.Seats.Where(s => s.ScreenId == show.ScreenId)
                        .OrderBy(s => s.RowNumber)
                        .ThenBy(s => s.SeatNumber)
                        .Select(s => new SeatReservationInfo
                        {
                            Id = s.Id,
                            Type = s.Type,
                            RowNumber = s.RowNumber,
                            SeatNumber = s.SeatNumber,
                            Availability = s.ReservationSeats.Any(a => a.ReservationId == reservationId)
                                ? SeatAvailability.ReservedSelf
                                : s.ReservationSeats.Any(
                                    a =>
                                        a.Reservation.ShowId == reservation.ShowId &&
                                        (a.Reservation.Status == ReservationStatus.Completed ||
                                         (a.Reservation.Status == ReservationStatus.Started &&
                                          DateTime.Compare(a.Reservation.Created, expired) >= 0)))
                                    ? SeatAvailability.Reserved
                                    : SeatAvailability.Available
                        }).ToList();
            }
        }

From this method, the screen(Cinema hall) is built with seats as checkboxes where you can select multible seats at once. Your selected seats is then sent with your reservationId via an AJAX call to the TryBookSeats method which will first see if anyone have tried to reserve your seats and if not then reserve them by placing them in the ReservationSeats table.
Here is the TryBookSeats method:
public static bool TryBookSeats(List<Guid> seatIds, Guid reservationId)
        {
            //bool who will become true if seats are available
            bool success;
            //Starts a database connection
            using (var db = new EntityContext())
            //Starts a transaction where the isolationlevel is set to ReadCommitted (pessimistic concurrency)
            using (var scope = db.Database.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                //Used to check if the reservation is expired
                var expired = DateTime.Now.Subtract(new TimeSpan(0, 0, 15, 0));
                //Retrieve a reservation that hasnt expired
                var reservation = db.Reservations.First(x => x.Id == reservationId && DateTime.Compare(x.Created, expired) >= 0);
                //Checks if the selected seats are available. if so set success to true
                success = !db.ReservationSeats.Any(
                    i =>
                        i.ReservationId != reservationId && i.Reservation.ShowId == reservation.ShowId &&
                        seatIds.Contains(i.SeatId) &&
                        (i.Reservation.Status == ReservationStatus.Completed ||
                         (i.Reservation.Status == ReservationStatus.Started &&
                          DateTime.Compare(i.Reservation.Created, expired) >= 0)));

                if (success)
                {
                    //Remove last selected seats connected to the current reservation
                    db.ReservationSeats.RemoveRange(db.ReservationSeats.Where(i => i.ReservationId == reservationId));
                    //Add seats to the database
                    foreach (var id in seatIds)
                    {
                        db.ReservationSeats.Add(new ReservationSeat
                        {
                            Id = Guid.NewGuid(),
                            ReservationId = reservationId,
                            SeatId = id
                        });
                    }
                }
                db.SaveChanges();
                scope.Commit();
            }
            return success;
        }

As you can sse have we used the isolationLevel ReadCommited which we presume is pessimistic locking and will ensure that no conflicts ocure while adding the seats to ReservationSeats.
And i presume that we wouldt encounter any deadlocks since we only lock one table.
i understand that one way optimistic cuncurrency works is before you commit an update to the database you will check if the database has been altered since you retrieved the record. Could we have chosen to, before adding the seats(and reservationId) to the reservationSeats table do a check to see if they have been reserved for the show.


text:
Q: Why break down the denominator in Bayes' Theorem? (I'm a newbie at stats. I'm a mathematician and a programmer and I'm trying to build something like a naive Bayesian spam filter.)
I've noticed in many places that people tend to break down the denominator in the equation from Bayes' Theorem. So instead of this:
$\frac{P(A|B)\cdot P(B)}{P(A)}$
We are presented with this:
$\frac{P(A|B)\cdot P(B)}{P(A|B)\cdot P(B)+P(A|\neg B)\cdot P(\neg B)}$
You can see that this convention is used in this Wikipedia article and in this insightful post by Tim Peters.
I am baffled by this. Why is the denominator broken down like this? How does that help things at all? What's so complicated about calculating $P(A)$, which in the case of spam filters would be The probability that the word "cheese" appears in an email, regardless of whether it's spam or not?

A: One reason for using the total probability rule is that we often deal with the component probabilities in that expression and it's straightforward to find the marginal probability by simply plugging in the values.  For an illustration of this, see the following example on Wikipedia:

*

*Bayes' Theorem > Example 1: Drug Testing
Another reason is recognizing equivalent forms of Bayes' Rule by manipulating that expression.  For example:
$P(B|A) = \frac{P(A|B) P(B)}{P(A|B)P(B) + P(A|\lnot B)P(\lnot B)}$
Divide through the RHS by the numerator:
$P(B|A) = \frac{1} {1 + \frac{P(A|\lnot B)}{P(A|B)} \frac{P(\lnot B)}{P(B)}}$
Which is a nice equivalent form for Bayes' Rule, made even handier by subtracting this from the original expression to obtain:
$\frac{P(\lnot B|A)}{P(B|A)} = \frac{P(A|\lnot B)} {P(A|B)} \frac {P(\lnot B)} {P(B)}$
This is Bayes' Rule stated in terms of Odds, i.e. posterior odds against B = Bayes factor against B times the prior odds against B.  (Or you could invert it to get an expression in terms of odds for B.)  The Bayes factor is the ratio of the likelihoods of your models.  Given that we're uncertain about the underlying data generating mechanism, we observe data and update our beliefs.
I'm not sure if you find this useful, but hopefully it's not baffling; you should obviously work with the expression that works best for your scenario.  Maybe someone else can pipe in with even better reasons.

A: Previous replies are detailed enough, but an intuitive way of looking why $P (A) $ (ie dinominator in the Bayes theorem) is broken into two cases.
It is hard to comment about what is the $P(A)$ without any knowledge whether the email is ham or spam. You are correct that "cheese" appears in spam as well as in ham, but if you look at the probability of appearance of "cheese" given that the email is ham ($P(A | B)$, $B$ is representative for ham), you can definitely say a lot of it. At least in my case, I don't receive a lot of spams which contain cheese, therefore in my case $P(A | B)$ will be high (say 90%). Similarly, $P(A | \neg B)$ will be low in my case, as not a lot of spams contain the word cheese. Basically, we try to look at the occurrence of event of interest (here A) partitioned into two disjoint events, $B$ and $\neg B$. If we partition A into two separate events, we can say better about the conditional probabilities $P(A | B)$ and $P(A | \neg B)$. In order to get the total probability we also need to weight for the conditional probabilities for the occurance of events on which we condition ie $P(B)$ and $P(\neg B)$. Therefore the final expression  $$P(A) = P(A|B)\cdot P(B)+P(A|\neg B)\cdot P(\neg B)$$

A: The short answer to your question is, "most of the time we don't know what P(cheese) is, and it is often (relatively) difficult to calculate."
The longer answer why Bayes' Rule/Theorem is normally stated in the way that you wrote is because in Bayesian problems we have - sitting in our lap - a prior distribution (the P(B) above) and likelihood (the P(A|B), P(A|notB) above) and it is a relatively simple matter of multiplication to compute the posterior (the P(B|A)).  Going to the trouble to reexpress P(A) in its summarized form is effort that could be spent elsewhere.
It might not seem so complicated in the context of an email because, as you rightly noted, it's just P(cheese), right?  The trouble is that with more involved on-the-battlefield Bayesian problems the denominator is an unsightly integral, which may or may not have a closed-form solution.  In fact, sometimes we need sophisticated Monte Carlo methods just to approximate the integral and churning the numbers can be a real pain in the rear.
But more to the point, we usually don't even care what P(cheese) is.  Bear in mind, we are trying to hone our belief regarding whether or not an email is spam, and couldn't care less about the marginal distribution of the data (the P(A), above).  It is just a normalization constant, anyway, which doesn't depend on the parameter;  the act of summation washes out whatever info we had about the parameter.  The constant is a nuisance to calculate and is ultimately irrelevant when it comes to zeroing in on our beliefs about whether or not the email's spam.  Sometimes we are obliged to calculate it, in which case the quickest way to do so is with the info we already have: the prior and likelihood.


text:
Q: Why am I getting [object Object] after accessing JSON data? I am making a simple GET request and filling up a webpage with some data. Every other line works except for 'addresses' which contains two arrays, and on my webpage it prints out '[object Object]', instead of the data. Here is an example of the JSON (apologies for the poor formatting):
data: Array(7)
   0:
   addresses: Array(2)
   0:
     city: "Houghton"
     line1: "800 East Lakeshore Drive"
     line2: ""
     line3: ""
     postalCode: "49931"
     stateCode: "MI"
     type: "Physical"

proto: Object
Here is the code block where I try to access 'addresses':
for (let i = 0; i < parkData.length; i++) {
    $("#results-list").append(`
${parkData[i].fullName}

${parkData[i].addresses[0]}

    Directions

    Website

${parkData[i].description}

Like I said above, all of the other lines work but when I try to get the first index of addresses I just get that weird Object response. Any ideas? Thank you!

A: [object Object] means that it's not a string but an object that (probably) has an address as property of this object, i.e. instead of parkData[i].addresses[0] you need to access some property (which one I cannot tell from your code as you are not showing the whole object that you got from JSON), for example like this:
const {city, line1} = parkData[i].addresses[0].city
const fullAddress = `City: {city}, Address: {line1}`

And only then, after constructing the address, you add it into your page as fullAddress

A: This is because you need to go deeper in some of the properties for sure. Double check every iteration and you will find that you are appending an object. I think you didn't paste all the response. You can use jsonviewer to better see the structure
Edit-> As I can see...address is an object, so you need to iterate over it in order to append strings.
So it would be: ... address[0].map(a => ... a.someAddressProperty


text: Q: Installing new application I got few linux applications from a chip(MAGAZINE) cd I wanted to try (especially vlc and a few others), but didn't know how to install them. I saw a button named install it gives me some info but I can't install things like I used to with windows. I installed a few with software center, but my network connection is slow and it took me more than a hour to download an install a 10mb software. So please tell me how to install such software.


text:
Q: How to draw an an elliptic curve such as Y^2 = X^3 - X with tikz? I need to draw the elliptic curve Y^2 = X^3 - X (as below) with the tikz package. As tikz doesn't support implicit curves I tried to create a pfgplot where I add a plot for the positive square roots and one for the negative square roots but I'm still experiencing problems.

This is my Code so far:
\documentclass[10pt]{article}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            axis x line=center,
            axis y line=center,
            xtick={-1,1},
            xmin=-2,
            xmax=2,
            ymin=-2,
            ymax=2,
            ]
            \addplot[mark=none,samples=200,domain=-2:2] {sqrt(x^3-x)};
            \addplot[mark=none,samples=200,domain=-2:2] {-sqrt(x^3-x)};
        \end{axis}
    \end{tikzpicture}
\end{document}

Which produces this output:

As you see, the curve is not connected near the x-Axis and there are also weird lines between 0 and 1. Is there a way to fix these problems or is there a better way to plot the ellipse all together?

A: You can make a reparametrization of the curve or simpler set your samples to an odd number. Setting your samples to an odd number will in this case sample the curve at the critical points, x=-1, x=0 and x=1. The only thing left is to make sure that the two sides are not connected by a line - this can be done by splitting the domain on two plots or with a filter like this:
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines=center,
xtick={-1,1},
xmin=-2, xmax=2,
ymin=-2, ymax=2,
]
\addplot[red, domain=-2:2, samples=201, y filter/.expression={x>0&&x<1?nan:y}, unbounded coords=jump, smooth] {sqrt(x^3-x)};
\addplot[red, domain=-2:2, samples=201, y filter/.expression={x>0&&x<1?nan:y}, unbounded coords=jump, smooth] {-sqrt(x^3-x)};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: TCPDF: how to pass an image to header (not blurry) Passing a logo-image into the header of a Pdf-Document via "tcpdf" needs millimeter as unit. I dont have millimeters. The image have pixels as width and height.
However, every value i tried out, it was blurry.
    /**
 * Set header data.
 * @param $ln (string) header image logo
 * @param $lw (string) header image logo width in mm
 * @param $ht (string) string to print as title on document header
 * @param $hs (string) string to print on document header
 * @param $tc (array) RGB array color for text.
 * @param $lc (array) RGB array color for line.
 * @public
 */
public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {

I have a logo both as an jpeg-image and as a png-image. Both images has extends as a width and a height-parameter messed in pixel.
However, TCPDF needs a value in Millimeter.
How can i determine the right parameter, so i can pass a jpeg or png image into the header of a TCPDF-created PDF-File?
I opened up these files in GIMP and tried out the scale-image-dialog. I could determine the width and height in millimeters, but passed to TCPDF, the image is still blurry...

A: How are you viewing the 'blurry' image - in Adobe's PDF reader? If so, make sure you have the PDF size set at 100%. My Adobe reader opens docs @167%, so the image(s) used to create the PDF doc in TCPDF appear 'blurry' until I view the doc at 100%.


text:
Q: There's a GROUP_CONCAT, is there a GROUP_SUM? qty is an int. This SQL works, but I want to sum the qty values, not concatenate them. There is no GROUP_SUM: is called something else?
SELECT sku as filterSKU, storenumber as storenumberSKU,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 0 THEN qty ELSE NULL END)) AS Monday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 1 THEN qty ELSE NULL END)) AS Tuesday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 2 THEN qty ELSE NULL END)) AS Wednesday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 3 THEN qty ELSE NULL END)) AS Thursday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 4 THEN qty ELSE NULL END)) AS Friday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 5 THEN qty ELSE NULL END)) AS Saturday,
      GROUP_CONCAT((CASE weekdayoftransaction WHEN 6 THEN qty ELSE NULL END)) AS Sunday
    FROM `reconciled`.sale
    GROUP BY sku, storenumber;

Here's the table:
CREATE TABLE `sale` (
  `saleID` int(11) NOT NULL AUTO_INCREMENT,
  `EmployeeFirstName` varchar(45) DEFAULT NULL,
  `EmployeeLastName` varchar(45) DEFAULT NULL,
  `ProductDescription` varchar(45) DEFAULT NULL,
  `Unit` varchar(45) DEFAULT NULL,
  `SKU` varchar(45) DEFAULT NULL,
  `Qty` int(11) DEFAULT NULL,
  `UnitCost` decimal(10,3) DEFAULT NULL,
  `UnitPrice` decimal(10,3) DEFAULT NULL,
  `Manufacturer` varchar(45) DEFAULT NULL,
  `EmployeeNumber` varchar(45) DEFAULT NULL COMMENT 'The employee who handled the transaction',
  `LoyaltyNumber` varchar(45) DEFAULT NULL,
  `StoreNumber` varchar(45) DEFAULT NULL,
  `DateOfTransaction` date DEFAULT NULL,
  `TimeOfTransaction` time DEFAULT NULL,
  `DateOfTransactionString` varchar(45) DEFAULT NULL,
  `TimeOfTransactionString` varchar(45) DEFAULT NULL,
  `WeekdayOfTransaction` int(11) DEFAULT NULL,
  `MonthOfTransaction` int(11) DEFAULT NULL,
  `YearOfTransaction` int(11) DEFAULT NULL,
  `WeekdayNameOfTransaction` varchar(45) DEFAULT NULL,
  `MonthNameOfTransaction` varchar(45) DEFAULT NULL,
  `TotalPrice` decimal(10,3) DEFAULT NULL,
  PRIMARY KEY (`saleID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

A: It's simply called sum. You can achieve the grouping by the group by clause (which you already have!):
SELECT   sku AS filterSKU, storenumber AS storenumberSKU,
         SUM(CASE weekdayoftransaction WHEN 0 THEN qty ELSE NULL END) AS Monday,
         SUM(CASE weekdayoftransaction WHEN 1 THEN qty ELSE NULL END) AS Tuesday,
         SUM(CASE weekdayoftransaction WHEN 2 THEN qty ELSE NULL END) AS Wednesday,
         SUM(CASE weekdayoftransaction WHEN 3 THEN qty ELSE NULL END) AS Thursday,
         SUM(CASE weekdayoftransaction WHEN 4 THEN qty ELSE NULL END) AS Friday,
         SUM(CASE weekdayoftransaction WHEN 5 THEN qty ELSE NULL END) AS Saturday,
         SUM(CASE weekdayoftransaction WHEN 6 THEN qty ELSE NULL END) AS Sunday
FROM     `reconciled`.sale
GROUP BY sku, storenumber;


text:
Q: Calculate Supremum of the taylor series of an holomorphic function let $t\in [0,1[$ and the function: $f_t(z) = \frac{z-t}{1-zt}$ which is holomorphic in the Open Disc $D(0,1)$.
I am trying to find $\sup_{|z|<1}|\sum_{k=0}^{+\infty} a_n z^n|$ where $\sum_{k=0}^{+\infty} a_n z^n$ is the Taylor series at $0$ of $f_t(z)$
What I did:
I calculated Taylor series at $0$ of $f_t(z)$:
$f_t(z)=-t + \sum_{k \geq 1}^{+\infty}z^k(t^{k-1} - t^{k})$
From here I don't know how to follow-up, Any help, a hint is much appreciated.
Many thanks!

A: It's holomorphic, so it can't have an interior maximum. Since $|t|<1$, the definition of $f_{t}$ extends perfectly well to $|z|=1$, so let $z = e^{i\theta}$ and investigate:
$$|f_{t}|^{2} = \frac{(z-t)(\bar{z}-t)}{(1-zt)(1-\bar{z}t)} = \frac{1-2\cos \theta t + t^{2}}{1-2\cos \theta t + t^{2}} = 1$$
so the supremum is $1$.
Alternatively, note that $f_{t}$ is a Mobius map, and hence sends circles and lines to circles and lines, and is determined by the images of any three distinct points in $\mathbb{C}$. The map sends $1\mapsto 1$, $-1\mapsto -1$ and $i \mapsto \frac{i-t}{1-it}$ (which has modulus $1$). So it sends the unit circle to itself, and by continuity it sends the whole unit disk to itself. In particular, $|z| \le 1 \implies |f(z)| \le 1$ (showing the supremum is attained is straightforward).


text:
Q: How can i line break when exporting to excel Datatable? In the code example below the numbers appear one after the other with the br tag, but it looks side by side in the Excel extension. How can I solve this?

        Numbers

        1
2
3

$(document).ready(function() {
  $('#mytable table').DataTable({
    bFilter: false,
    bLengthChange: false,
    dom: 'Bfrtip',
    buttons: [ 'excel' ],
    order: []
  });
});


text:
Q: How can I escape from this mode inside git bash?
The dollar sign disappears and the arrow sign pops up. Any idea why and how to handle this situation?

A: backslash tells the terminal you want to continue typing our command on a new line.
hit enter to finish the command and execute
ctrl+c to get out of it without executing


text:
Q: radio buttons in a tableview cells swift Currently I am trying to make a store-like view that shows multiple different listing (spaceships) and you can only select one at a time. It would be for a game where you can select your different spaceships. I am sing a UITableView with a UITableViewCell Xib file. I have only one table cell Xib file to format all of the different listings. The style of the Select button is suppose to be like a Radio Button.
The difficulty I am having is that when I click one button, it makes all the buttons say "Selected."
This is the code that I have:
TableViewController:
import UIKit

struct CellData {
    var image: UIImage?
    var message: String?
    var id: Int?

}

var array = [String]()
var buttonArray = [ShopButton]()

class ViewController: UITableViewController {

    var data = [CellData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        data = [CellData.init(image: #imageLiteral(resourceName: "ship_0"), message: "Red Ship", id: 0), CellData.init(image: #imageLiteral(resourceName: "ship_1"), message: "Blue Ship", id: 1), CellData.init(image: #imageLiteral(resourceName: "ship_3"), message: "Yellow Ship", id: 2)]
        array = ["Select", "Select", "Select"]

            }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
        cell.mainImageView.image = data[indexPath.row].image
        cell.mainLabel.text = data[indexPath.row].message
        cell.buttonOutlet.setTitle(array[indexPath.row], for: .normal)
        cell.buttonOutlet.tag = data[indexPath.row].id!
        buttonArray.append(cell.buttonOutlet)
        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

}

TableViewCell
import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var mainImageView: UIImageView!
    @IBOutlet weak var mainLabel: UILabel!
    @IBOutlet weak var buttonOutlet: ShopButton!

    @IBAction func button(_ sender: ShopButton) {
        buttonOutlet.makeSelected()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

    }

My SubClass for the UIButton:
import UIKit

class ShopButton: UIButton {

    var buttonID = Int()

    func makeSelected() {

            switch self.buttonID {
            case 0:
                array = ["Selected", "Select", "Select"]
                buttonTitle()
                print("Ship: Red Ship")
            case 1:
                array = ["Select", "Selected", "Select"]
                buttonTitle()
                print("Ship: Blue Ship")
            case 2:
                array = ["Select", "Select", "Selected"]
                buttonTitle()
                print("Ship: Yellow Ship")
            default:
                print("Error: Default Initiated")
            }

    }
    func buttonTitle() {

        for button:ShopButton in buttonArray {
            button.setTitle(array[button.buttonID], for: .normal)
        }

    }

    override func awakeFromNib() {

    }

}

I realize this might not be the best approach to making this shop setup so if anyone has an answer to how to fix this or a different way that would be much better than what I have currently done, it would be much appreciated. Thanks.

A: You can possibly use this logic in didSelectRowAt in table view like:
You can make the tag of button equivalent to the indexpath.row of tableview
        for (button in buttons)    {
             button.isSelected = false;
        }

        if button.tag == indexpath.row{ //Here sender.tag would be your indexPath.row
            button.isSelected = true;
            button.setImage(#imageLiteral(resourceName: "ic_Radio_filled"), for: .normal)
        }else{
            button.isSelected = false;
            button.setImage(#imageLiteral(resourceName: "ic_Radio_Empty"), for: .normal)
        }

Let me know if it works for you.


text:
Q: Compare columns in two dataframes to set values in one from another I need to take values from a larger database, coor, and add them to an existing column in a smaller one, xshooter, where the entries match. I'm using RA columns in both to find the matching instances. I need a way to rewrite the for loops using pandas functions to reduce runtime.
for j in coor.index:
  for i in xshooter_master_tabl.index:
    if coor['RA_ICRS'][j] == xshooter_master_tabl['ra'][i]:
      xshooter_master_tabl['star_id'][i] = coor['SimbadName'][j]


text:
Q: Overriding/removing inline !important I have a site using htmlcommentbox.com's comment system. It seems to use inline !importants to make a link to the site stay there. This is the code I'm using from them:

Loading comments...

 <link rel="stylesheet" type="text/css" href="htmlcommentbox.css" />

My CSS is:
body {
    background-color: #000;
}
p {
    color: #FFF;
}
a {
    color: #FFF;
}
span,
div a {
    display: none !important;
}

I will include more if necessary. Can I remove the link to their site?

A: You could simply select the element and remove the style attribute:
document.querySelector('.home-desc + a').removeAttribute('style');

..then you can use the following CSS to hide it:
.home-desc + a,
.home-desc {
    display: none;
}

Example Here
Alternatively, since all you are doing is hiding the elements, you could just remove them entirely.
You could also avoid JS completely and set the opacity to 0 and add pointer-events: none. This will essentially hide the element(s).
.home-desc + a,
.home-desc {
    opacity: 0;
    pointer-events: none;
}

Example demonstrating this.

A: I'd suggest to remove the link from the DOM after the script has been executed, then you do not need to remove or override the !important:
document.getElementById('HCB_comment_box').addEventListener('DOMSubtreeModified', function () {
    var desc = document.querySelector('#HCB_comment_box .home-desc');
    var link = document.querySelector('#HCB_comment_box .home-desc').nextSibling;
    var parent = desc.parentNode;
    parent.removeChild(desc);
    parent.removeChild(link);
});

Fiddle


text:
Q: Represent G as a product of two proper subgroups, at least one of which is normal. Find the order of G without listing all itself elements. I don't really know where to start with this question - an instructive answer would be appreciated!
Let $G=\langle (1,2,3,4,5,6,7,8,9), (1,8,9,4,2,3,7,5,6) \rangle $Represent $G$ as a product of two proper subgroups,  at least one of which is normal. Find the order of $G$ without listing all itself elements.
I thought about taking $\langle(1,2,3,4,5,6,7,8,9)\rangle$ as a proper subgroup, but I couldn't work out whether it was proper or not in the context of G. Also, it doesn't help with the rest of the question!

A: Hints.  Take $A = \langle (1,2,3,4,5,6,7,8,9)\rangle$ and $B = \langle (1,8,9,4,2,3,7,5,6)\rangle$.  Then show that $A$ is normal in $G$.  Use that fact to show that $G = AB$. Determine the orders of $A$ and $B$, and then use the formula $\mid G\mid = \mid AB\mid = \frac{\mid A\mid\mid B\mid}{\mid A\cap B\mid}$.   For this, you'll need to compute the intersection $A\cap B$.


text:
Q: Foreign key BIGSERIAL NULL Postgres I can not insert a record in the POSTGRES database, I want the foreign key to be null.
My table:
CREATE TABLE sad_avaliado (
    id                BIGSERIAL NOT NULL,
    tenant_id         INT8 NOT NULL,
    funcionario_id    BIGSERIAL NOT NULL,
    epoca_id          BIGSERIAL NOT NULL,
    cca_id            BIGSERIAL,
    avaliador_id      BIGSERIAL NOT NULL,
    apagado           boolean NOT NULL,
    PRIMARY KEY (id)
 );
alter table sad_avaliado add constraint sad_funcionario_fkey foreign key (funcionario_id) references sad_funcionario;
alter table sad_avaliado add constraint sad_epoca_fkey foreign key (epoca_id) references sad_epoca;
alter table sad_avaliado add constraint sad_cca_fkey foreign key (cca_id) references sad_cca;
alter table sad_avaliado add constraint sad_avaliador_fkey foreign key (avaliador_id) references sad_avaliador;

My SQL Insert:
INSERT INTO public.sad_avaliado(
id, tenant_id, funcionario_id, epoca_id, cca_id, avaliador_id, apagado)
VALUES (1, 1, 1, 1, null, 1, false);

My Error:
ERROR:  null value in column "cca_id" violates not-null constraint

A: The foreign key references for BIGSERIAL should use BIGINT:
CREATE TABLE sad_avaliado (
    id                BIGSERIAL NOT NULL,
    tenant_id         INT8 NOT NULL,
    funcionario_id    BIGINT NOT NULL,
    epoca_id          BIGINT NOT NULL,
    cca_id            BIGINT,
    avaliador_id      BIGINT NOT NULL,
    apagado           boolean NOT NULL,
    PRIMARY KEY (id)
 );

I think this is the one exception to the notion that foreign key references should have the same type as the primary key.  I mean, the underlying type is the same, but BIGSERIAL is used to specify that it is auto-incrementing (other databases use a separate keyword such as auto_increment or identity).

A: bigserial is meant for autoincremented id columns and it has default "not null" and creates one sequence.
And you should not specify your id in insert statements as it is inserted as default with nextval()
see this example
    test=# create table test01 ( id bigserial );
    CREATE TABLE
    test=# \d test01*
                                Table "public.test01"
     Column |  Type  | Collation | Nullable |              Default
    --------+--------+-----------+----------+------------------------------------
     id     | bigint |           | not null | nextval('test01_id_seq'::regclass)

                           Sequence "public.test01_id_seq"
      Type  | Start | Minimum |       Maximum       | Increment | Cycles? | Cache
    --------+-------+---------+---------------------+-----------+---------+-------
     bigint |     1 |       1 | 9223372036854775807 |         1 | no      |     1
    Owned by: public.test01.id

A: Use bigint instead of bigserial.


text:
Q: How to convert hex string to Java string? For logging purpose we are converting the logs to byte array and then to hex string. I want to get it back in a Java String, but I am not able to do so.
The hex string in log file looks something like
fd00000aa8660b5b010006acdc0100000101000100010000

How can I decode this?

A: Using Hex in Apache Commons:
String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));

A: Try the following code:
public static byte[] decode(String hex){

        String[] list=hex.split("(?<=\\G.{2})");
        ByteBuffer buffer= ByteBuffer.allocate(list.length);
        System.out.println(list.length);
        for(String str: list)
            buffer.put(Byte.parseByte(str,16));

        return buffer.array();

}

To convert to String just create a new String with the byte[] returned by the decode method.

A: Just another way to convert hex string to java string:
public static String unHex(String arg) {

    String str = "";
    for(int i=0;i<arg.length();i+=2)
    {
        String s = arg.substring(i, (i + 2));
        int decimal = Integer.parseInt(s, 16);
        str = str + (char) decimal;
    }
    return str;
}

A: byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);

A: There is yet another way to do this if using JDK17 or above, see the new  HexFormat class which has useful methods for converting byte[] <=> hexadecimal String :
String hexStr ="5468697320697320616e206578616d706c6520737472696e67";
byte[] bytes = HexFormat.of().parseHex(hexStr);
String str = new String(bytes, StandardCharsets.UTF_8 /* or Charset.forName("whateverencoding")*/);

You of course need to know the exact character encoding of the hexadecimal representation in order to generate the correct String value.

A: You can go from String (hex) to byte array to String as UTF-8(?). Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                + Character.digit(hex.charAt(i + 1), 16));
    }
    return data;
}

Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);

A: First of all read in the data, then convert it to byte array:
 byte b = Byte.parseByte(str, 16);

and then use String constructor:
new String(byte[] bytes)

or if the charset is not system default then:
new String(byte[] bytes, String charsetName)


text:
Q: How to export logstash data to external database I've setup logstash instance ,and github logs are forwarding to this logstash instance. I am in need of run the query to fetch the information from logstash like database query.
Please let me know how to connect logstash to oracle database and get those logstash info from DB
thanks

A: You can query elasticsearch directly via the API - look at the examples in the API documentation here, http://www.elastic.co/guide/en/elasticsearch/reference/1.4/search.html
If you have the logs being captured with a specific 'type', you could do something like:
curl -XGET 'http://localhost:9200/logstash-*/_search?q=type:github&size=50'

which would search the logstash indices for anything with type 'github' and return the first 50 entries.


text:
Q: File handling in getline function I have a text file that looks like this:
 A          4     6
 B          5     7
 c          4     8

I want to store it in three different arrays:
char pro[];     // contains values A B C
int arrival[];  // contains values of 4 5 5
int Burst[];    // contains values of 6 7 8

I don't know how to do that. Any help (tutorials, pseudo code etc.) is appreciated.

A: That's my proposal. Hope that helps.
Basically what it does, it creates three containers (see std::vector from STL). They can have infinite size (you don't have to declare it afront). The create three auxilliary variables which you then use to read from stream.
The condition in while loop checks if data is still in the file stream.
I did not use .eof() method because it always reads the last line in a file twice.

using namespaces std;

int main() {

vector<char> pro;
vector<int> arrival;
vector<int> Burst;

/* your code here */

char temp;
int number1, number2;

ifstream file;
file.open("text.txt");

if( !(file.is_open()))
  exit(EXIT_FAILURE);

while (file >> temp >> number1 >> number2)
{
  pro.push_back(temp);
  arrival.push_back(number1);
  Burst.push_back(number2);
}

file.close();

}


text:
Q: how to copy a pointer's value to an simple variable inside a constexpr constructor i try to make this code work. I want make the constructor  accept a pointer to function, then copy the value of the pointer to f and then xor with 1234. This  normally should run on compile time. Then when i want to get the function pointer it will call the un_xor() so i can get the original pointer.
typedef void (*func)();

class xorfunc
{
public:
    __int64 f;
    inline constexpr xorfunc(func function)
        : f(0)
    {
        f = (__int64)function;
        f ^= 1234;
    }

    const func un_xor() const {
        return (func)(f ^ 1234);
    }

};

#define OCB(my_func) []{ constexpr xorfunc expr(my_func); return expr; }().decrypt()

//and then i call it like this
void fun1()
{
}

func ptr = OCB(fun1);

with this code i get these errors:
'expression did not evaluate to a constant' and 'expression must have a constant value'
what is the problem with this?
can anyone help me make it work?

A: You can't do it. The reason is that the numerical value of a pointer (as obtained through a reinterpret_cast) is not a compile-time constant. The code may be running on a system without virtual memory (in which case loading it at any particular address is not guaranteed; it will be loaded somewhere that has enough space) or a system that is using address space randomization and so on. Even if the system can guarantee that a variable or function in your program will always have the same address, the compiler cannot; the linker has to concatenate the static sections from the various translation units that the program is made up from in order to determine the final layout. Any value that is only known at link time cannot participate in arbitrary compile-time computations.


text:
Q: shutil copy issue So I have the following script
# Import system modules
import arcpy, os
import fnmatch
import shutil
import zipfile

zipf = zipfile.ZipFile('MXD_DC.zip', 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(r"Y:\Data\MXD_DC"):
       for file in files:
            zipf.write(os.path.join(root, file))

 shutil.copy(r'MXD_DC.zip', 'D:/')

After copying the file over to d drive when I try to unzip it, the error is "Before you can extract files, you must copy files to this compressed zipped folder". I can take the original zip file from the other drive and unzip it just fine. I can manually copy it over to d drive and unzip it just fine. It happens only when I use shutil to copy to the d drive.

A: You need to close the zipfile before you go to copy it. Either zipf.close() before the shutil.copy or
with zipfile.ZipFile('MXD_DC.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, dirs, files in os.walk(r"Y:\Data\MXD_DC"):
        for file in files:
            zipf.write(os.path.join(root, file))

shutil.copy2('MXD_DC.zip','D:/')

You could also use shutil.copy2 again.


text:
Q: Electromagnetic waves in vacuum If there is no source then also there is electromagnetic waves described by Maxwell equation. how if there is no source then existence of EM waves. What gives energy to this EM  waves. Is it vacuum fluctuation or something else?

A: The fact that you can solve Maxwell's equations in vacuo means that the vacuum can propagate electromagnetic waves. It cannot generate them, since as you point out there are no sources (charges and currents). The waves were generated somewhere else, where there was a current or a charge moving around, and you are just looking at a region where there's "nothing"*.
The energy of those waves is the energy stored in the oscillating electric and magnetic fields, and it comes from the source. E.g. for dipole radiation (see link later) an accelerating charge slows down and the lost kinetic energy goes into creating EM waves.
Remember that the Maxwell's equations are differential equations, i.e. they require boundary conditions. One of the things to have to fix is the amplitude of a wave $E_0$. You can set it to $0$ and have no electromagnetic waves whatsoever. But if you indeed have a wave propagating, then it means that $E_0 \neq 0$ and its value must be computed with information about how this wave was generated. For example, in the case of dipole radiation, you can compute the pre-factor.
*: Let me just stress that this is in the context of classical electrodyanmics. If you were to venture into the quantum world, then you would have particle-antiparticle pairs and their respective electric fields popping out of nowhere.


text:
Q: Build a basic Altimeter with SwiftUi for Apple Watch I am trying to build a MVP with SwiftUI that simply shows me the changes in altitude on my Apple Watch. From there I will figure out where to go next (I want to use it for paragliding and other aviation things).
I have previous experience in python, but nothing in Swift, so even after a ton of tutorials I am very unsure about how and where to declare and then use functionalities.
Here is my code so far:
//
//  ContentView.swift
//  Altimeter WatchKit Extension
//
//  Created by Luke Crouch on 29.09.20.
//

import SwiftUI
import CoreMotion

//class func isRelativeAltitudeAvailable() -> Bool

struct ContentView: View {
    let motionManager = CMMotionManager()
    let queue = OperationQueue()
    let altimeter = CMAltimeter()
    let altitude = 0
    var relativeAltitude: NSNumber = 0

    var body: some View {

        if motionManager.isRelativeAltitudeAvailable() {
         switch CMAltimeter.authorizationStatus() {
         case .notDetermined: // Handle state before user prompt
             fatalError("Awaiting user prompt...")
         case .restricted: // Handle system-wide restriction
            fatalError("Authorization restricted!")
         case .denied: // Handle user denied state
            fatalError("Auhtorization denied!")
         case .authorized: // Ready to go!
             print("Authorized!")
         @unknown default:
            fatalError("Unknown Authorization Status")
         }
            altimeter.startRelativeAltitudeUpdates(to: queue, withHandler: CMAltitudeHandler)
        }

// something like relative Altitude = queue[..]

        Text("\(relativeAltitude)")
            .font(.largeTitle)
            .fontWeight(.bold)
            .foregroundColor(Color.green)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I am getting multiple errors that I dont know how to deal with:

*

*Type 'Void' cannot conform to 'View', only struct/enum/class types can conform to protocols.

*Value of type CMMotionManager has no member 'isRelativeAltitudeAvailable'

*Type '()' cannot conform to View...

*Cannot convert value of type 'CMAltitudeHandler.Type' (aka '((Optional, Optional) -> ()).Type') to expected argument type 'CMAltitudeHandler' (aka '(Optional, Optional) -> ()')

Could you please give me some hints?
Thank you so much!
Luke

A: I figured it out after trying around a lot:
//
//  ContentView.swift
//  Altimeter WatchKit Extension
//
//  Created by Lukas Wheldon on 29.09.20.
//

import SwiftUI
import CoreMotion

struct ContentView: View {
    @State var relativeAltitude: NSNumber = 0
    @State var altitude = 0
    let altimeter = CMAltimeter()

    func update(d: CMAltitudeData?, e: Error?){
        print("altitude \(altitude)")
        print("CMAltimeter \(altimeter)")
        print("relative Altitude \(relativeAltitude))")

    }

    var body: some View {
        VStack {
            Text("\(altimeter)")
                .fontWeight(.bold)
                .foregroundColor(Color.green)
            Button(action: {
                print("START")
                self.startAltimeter()
            }, label: {
                Text("Start Altimeter")
                    .bold()
                    .foregroundColor(.green)
            })
        }
    }

    func startAltimeter() {
        if CMAltimeter.isRelativeAltitudeAvailable() {
            switch CMAltimeter.authorizationStatus() {
             case .notDetermined: // Handle state before user prompt
             print("bb")
             //fatalError("Awaiting user prompt...")
             case .restricted: // Handle system-wide restriction
             fatalError("Authorization restricted!")
             case .denied: // Handle user denied state
             fatalError("Authorization denied!")
             case .authorized: // Ready to go!
             let _ = print("Authorized!")
             @unknown default:
             fatalError("Unknown Authorization Status")
             }
            self.altimeter.startRelativeAltitudeUpdates(to: OperationQueue.main) {(data,error) in DispatchQueue.main.async {
                print("\(altitude)")
                print("\(relativeAltitude)")
            }

            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }

}

Next steps will be to check if I can access the barometer raw data and calculate altitudes on that.


text:
Q: Code to redirect to another page if answer is correct I am making an online test. There are 10 levels. The question is picked from database and if the answer is correct then it update the level cleared of that particular user  and show next question on the same page.
But I want to direct the page to another page if the answer is correct whose url is in the database and update the level number of the user as above.
I know how to display question in same page but don't know how to redirect if correct.
Here is the code of simple test where questions are displayed n the same page.
<?php
 session_start();
 if(!isset($_SESSION['myusername'])){
 header("location:index.php?unreg=1");
  }
 else {
 $myuser = $_SESSION["myusername"];
  $mypass = $_SESSION["mypassword"];

 $host="localhost"; // Host name
  $username=""; // Mysql username
   $password=""; // Mysql password
  $db_name=""; // Database name
  $tbl_name="members"; // Table name
    $tbl_name2="quiz"; // Table name 2

     // Connect to server and select databse.
     mysql_connect("$host", "$username", "$password")or die("cannot connect");
   mysql_select_db("$db_name")or die("cannot select DB");

     if(isset($_POST['qno']))
    {
       $sql3="SELECT * FROM $tbl_name2 WHERE id='".$_POST['qno']."'";
    $result3=mysql_query($sql3);

       $disp3=mysql_fetch_assoc($result3);

      $sql4="SELECT * FROM $tbl_name WHERE username='$myuser' and password='$mypass'";
        $result4=mysql_query($sql4);

      $disp4=mysql_fetch_assoc($result4);

     if($disp3['Answer']==$_POST['Answer'])
     {

     $sql5 ="UPDATE $tbl_name SET level_crossed='".($disp4

   ['level_crossed']   +1)."', Score='    $disp4['Score']+1)."' WHERE
      username='$myuser' and password='$mypass'";
     $result5=mysql_query($sql5);
         }
         else {
          $sql5="UPDATE $tbl_name SET level_crossed='".($disp4['level_crossed']+1).
         "' WHERE username='$myuser' and password='$mypass'";
         $result5=mysql_query($sql5);

        }

         }

        $sql="SELECT * FROM $tbl_name WHERE username='$myuser' and password='$mypass'";
        $result=mysql_query($sql);

     $disp=mysql_fetch_assoc($result);
            echo "    ".$disp['level_crossed']."    ";

          $sql7="SELECT * FROM $tbl_name2 WHERE id='".($disp['level_crossed']+1)."'";
           $result7=mysql_query($sql7);

            $disp2=mysql_fetch_assoc($result7);
               ?>

     <?php

      echo "Q.)".$disp2['Question']."    ";
        ?>

           <form name="quizq" action="quiz1.php" method="post" >
         <input name="qno" type="hidden" value="<?php echo $disp['level_crossed']+1; ?>" />
          <input type="radio" name="Answer" value="<?php echo $disp2['Option1'];>" /><?
                                                                                php echo $disp2['Option1']; ?>

      <input type="radio" name="Answer" value="<?php echo $disp2['Option2']; ?>" />
          <?php  echo $disp2['Option2']; ?>

      <input type="radio" name="Answer" value="<?php echo $disp2['Option3']; ?>" />
     <?php echo $disp2['Option3']; ?>

      <input type="radio" name="Answer" value="<?php echo $disp2['Option4']; ?>" />
       <?php echo $disp2['Option4']; ?>

       <input type="submit" value="Submit Answer" />
        </form>

         Logout
   <?php

     }
    ?>

A: To redirect to another url:
header('Location: /path/of/next/page');

Just like any other header, you cannot have any output rendered before calling header. This includes echo, print, and any text outside of php tags.

A: You can redirect the page using headers
header( 'Location: http://www.url.com/' );

A: try to use header
For example:
header( 'Location: test.php' );


text:
Q: FFT frequency of sound On microphone at some time, starts flowing sound defined frequency(500hz). How do I know when the signal began to come to the microphone? To solve this problem, I know that I need to use FFT(Fast Fourier transform). But I dont understand, how should I take after FFT frequency? I'm use NAudio on C#. And my buffer from microphone is byte array.

A: Using an FFT for this is overkill and not particularly appropriate. A much simpler solution for this kind of problem (tone detection/onset detection) is the Goertzel filter.

A: Determining WHEN a signal is sampled into a buffer is a programatical problem.
That has nothing to do with determining WHAT the frequency content of the sampled signal is (using the FFT). See my reply for your other question...

A: A narrow IIR bandpass filter followed by an envelope detector might be one possible method to try.  Another thing to try might be cross-correlation against a matched filter, if you know the rise time of your tone burst.  You will have to calibrate out the latency of your audio input signal path as well.


text:
Q: Assembly Version Captured Before "BeforeBuild" Target I am using MSBuild.Community.Tasks to help with two things, namely adjusting the version and zipping up a file.  I am not married to this, so an alternate approach is welcome provided it produces what I'm looking for.  The goal is to increment the build number before the build, then ZIP up a new DLL (with a couple of other files) after the build.  The ZIP file should be named according to the build.
I am almost there, however, my version number in my DLL is always one step behind my version.txt file (auto-gen'd from the Version task). Here is what I have in the BeforeBuild target:
  <Target Name="BeforeBuild" BeforeTargets="PrepareForBuild">
    <Message Text=" --=== Before Build ===--"></Message>
    <ItemGroup>
      <PreviousFiles Include="$(MSBuildProjectDirectory)\BuildPackage\$(AssemblyName).*.zip">
        <InProject>false</InProject>
      </PreviousFiles>
    </ItemGroup>
    <Delete Files="@(PreviousFiles)"></Delete>
    <Delete Files="$(MSBuildProjectDirectory)\BuildPackage\$(AssemblyName).dll"></Delete>
    <Version VersionFile="version.txt" RevisionType="Increment">
      <Output TaskParameter="Major" PropertyName="Major" />
      <Output TaskParameter="Minor" PropertyName="Minor" />
      <Output TaskParameter="Build" PropertyName="Build" />
      <Output TaskParameter="Revision" PropertyName="Revision" />
    </Version>
  </Target>

This deletes any files from the previous build, then increments the version.txt file correctly.
Next, in my AfterBuild target I have put this together:
  <Target Name="AfterBuild" AfterTargets="Build">
    <Message Text=" --=== After Build ==--"></Message>
    <AssemblyInfo CodeLanguage="CS" OutputFile="AssemblyVersion.cs" AssemblyVersion="$(Major).$(Minor).$(Build).$(Revision)" AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)" />
    <ItemGroup>
      <ProjectOutputFiles Include="bin\$(AssemblyName).dll">
        <InProject>false</InProject>
      </ProjectOutputFiles>
      <ZipFiles Include="$(MSBuildProjectDirectory)\BuildPackage\*.*" Exclude="$(MSBuildProjectDirectory)\BuildPackage\*.zip">
        <InProject>false</InProject>
      </ZipFiles>
    </ItemGroup>
    <Copy SourceFiles="@(ProjectOutputFiles)" DestinationFolder="$(MSBuildProjectDirectory)\StorePackage" />
    <Zip Files="@(ZipFiles)" WorkingDirectory="$(MSBuildProjectDirectory)\BuildPackage" ZipFileName="$(MSBuildProjectDirectory)\BuildPackage\$(AssemblyName).$(Major)-$(Minor)-$(Build)-$(Revision).zip" ZipLevel="9" />
  </Target>

Basically, I'm updating AssemblyInfo.cs and specifying some file groups. I then copy the project output over and finally ZIP up the required files.
This all works great, except my DLL version is always 1 revision number behind my actual revision number - i.e., what is stored in version.txt and what the name of the .ZIP file is saved out as.
Am I missing something obvious here?  It's like the version is captured before the build process even starts or something.
Thanks in advance.

A: GOSH, yes, I am missing something obvious.  As soon as I re-read the question, right before posting, it became clear what I had done incorrectly.  I even spelled it out.
The fix was to move the AssemblyInfo task up to the BeforeBuild target.  This is the task that outputs the .cs file containing the attributes required to inject the correct versioning information into the DLL.  Leaving the update of this file until after the build has completed meant that my DLL was going to be losing the race in perpetuity.
I'm going to go ahead and post this anyways, in case someone else runs into something similar.
Cheers.

Edit  For what it's worth, the final version of these targets required moving the ZIP operation out into a separate target (I called it ZipProjectOutput) because of a race condition that I couldn't resolve: the DLL was never showing up in the ZIP file, and I think that the timing of the OS releasing a lock on the file or something might have been to blame.
I used the AfterTargets="AfterBuild" to have the ZipProjectOutput target execute when the other was complete. I'm not entirely happy about this as I'm not certain I'm just "winning" the race here, rather than solving the problem, but this is working for me now rather slickly. #WFM


text:
Q: Table in markdown in Jupyter Notebook is stretched, I want to make it proportional I want to create this table proportional, the problem is in Jupyter Notebook' markdown the second column is stretched, making the table looks ugly.
This is my table:
| Lake | $V$ (km$^{3} \times 10^{3}$) | r (km$^{3}$/year) |
| -----: | :------ | :------ |
| Superior | 12.2 | 65.2 |
| Michigan | 4.9 | 158 |
| Erie | 0.46 | 175 |
| Ontario | 1.6 | 209 |

table


text:
Q: need to create a Facebook tab for the mobile app I am having Google Play link(Android) and iTunes App Link(iTunes). I want to create a Facebook tab for my business page and on click of Facebook tab, my Google Play link can be opened.
I have registered myself on developers.facebook.com/apps and created a new App. Now Under Basic Info I get confused on what to enter the value for App Domains so I have entered play.google.com because my Google Play link starts with this.
Now under Page Tab, I have entered all the required information but entered probably the wrong value for Page Tab Edit URL . So I finally save my application but it is not working.
So now I have deleted my Page Tab section and I then switched over to App on Facebook section where under Canvas URL I have placed my Google Play URL with all the required details and then submitted for review.
Before I submit for the review finally it asked me that there should be no external URL used But I have used my Google Play URL in the  Canvas URL section which is external.
I am completely confused now with this Facebook. I have also Googled a lot but with no result for me.
Please Guide me on integrating Android link(play.google.com) as Facebook Business Page tab.
Thanks !

A: I have solved this issue by using static iframe facebook application
What I did is simply created my desire page in HTML and placed it on my server and by static iframe facebook App, I called this page into IFrame.
Problem solved !


text:
Q: Hibernate XML Mapping Unidirectional (No Foreign key) I have been working on a legacy application (Important to state as I can't change the data structure)
I have a lookup table which have ID from two tables, I am trying to get the description from the two tables using unidirectional one to one mapping
Let me also mention that Although the person table has Address_ID and Secondary_Address_id , they are NOT foreign keys to the Address and Secondary_address_table in the database
when I run the query I get the addressDescription and secondaryAddressDescription as null, also when trying to insert into the table Person using getHibernateTemplate.merge(person)
I get the error Hibernate Mismatch Exception for class Address expecting java.lang .long but got integer
Listed below are the Hibernate Mapping Files and the POJO with it
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="com.sample.Person" table="Person">
        <id name="personId" type="java.lang.Integer" column="PERSON_ID">
            <generator class="native" />
        </id>

        <property name="addressId" column="ADDRESS_ID" type="java.lang.Long" />
        <property name="secondaryAddressId" column="SECONDARY_ADDRESS" type="java.lang.Integer" />
        <property name="primary" column="PRIMARY" type="java.lang.String" />

        <one-to-one name="address" class="com.sample.Address" cascade="none" foreign-key="addressId" >

        </one-to-one>

        <one-to-one name="secondaryAddress" class="com.sample.SecondaryAddress" cascade="none" foreign-key="secondaryAddressId">

        </one-to-one>

    </class>

    <query name="Address.getAddressById">
        <![CDATA[
  Select per.personId as personId,per.addressId as addressId,
                       per.secondaryAddressId as secondaryAddressId,, ad.description as addressDescription, sad.description as secondaryAddressDescription
                        from Person per left join per.address ad left join per.secondaryAddress sad  where
                         per.personId=:personId
   ]]>
    </query>

</hibernate-mapping>

Hibernate Mapping for Address
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="com.Address" table="ADDRESS">
        <id name="addressId" type="java.lang.Long" column="ADDRESS_ID">
            <generator class="native" />
        </id>

        <property name="description" column="DESCRIPTION" type="java.lang.String" not-null="true"/>

    </class>

</hibernate-mapping>

Hibernate Mapping for SecondaryAddress
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="com.SecondaryAddress" table="SECONDARY_ADDRESS">
        <id name="secondaryAddressId" type="java.lang.Integer" column="SECONDARY_ADDRESS_ID">
            <generator class="native" />
        </id>

        <property name="description" column="DESCRIPTION" type="java.lang.String" not-null="true"/>

    </class>

</hibernate-mapping>

POJO for Person (Not pasting the getter/setters to have less code here)
public class Person implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -1186272503323568780L;

    private Integer personId;
    private Long addressId;
    private Integer secondaryAddressId;
    private String addressDescription;
    private String secondaryAddressDescription;
    private Integer address;
    private String secondaryAddress;

  }


text:
Q: Error while getting integer from file(Convert String to Int) I have a file: student.txt
1      Adam     50       50       50

2      Eric     34       28       38

3      Joash    44       48       49

4      Bill     34       30       45

I have 2 classes: 1 is main and another one does all the work.
// Class 1 ******************

public class Main {
    public static void main(String[] args) {
        readfile a = new readfile();
        a.openFile();
        a.readFile();
        a.closeFile();
    }
}

// ********* Class 2

import java.util.*;
import java.io.*;
import java.lang.*;

public class readfile {

    private Scanner x;

    public void openFile(){
        try{
            x = new Scanner(new File("student.txt"));

        }
        catch(Exception e){
            System.out.println("Error");
        }
    }
    public void readFile(){
        int a=0;
        String b;
        int c=0;
        int d = 0;
        int e = 0;
        int total;
        while(x.hasNext()){
             a = x.next();
             b = x.next();
             c = x.next();
             d = x.next();
             e = x.next();
             int total = c+d+e;
             total = x.nextInt();
            System.out.printf("%s %s %s %s %s %s/n",a,b,c,d,e,total);
        }
    }
    public void closeFile(){
        x.close();
    }
}

I have 2 errors:
1) This is at a = x.next(); where it says

Can't convert from String to int.

Can you tell me how to fix that?
2) This is at:

Exception in thread "main"
Error java.lang.NullPointerException

How do I fix this?

A: Try:
a = Integer.parseInt(x.next());

Instead of
a = x.next();

And you may try using
a = x.nextInt();

A: Scanner.next() returns the next token as a String. When java tries to set int a to a String, an error occurs. You can fix this by using Scanner.nextInt(), which will return the next token as an integer, or throw an error if the next token is not an int. If


text:
Q: How can I customize email, password login error with different angle? I am already created signup or register field by using firebase. I am also created firebase login field. Now I am try to handle firebase error -
When someone trying to login the error displayed in two ways :

*

*If he give the right email with wrong password then I want displayed - You password doesn't
match.

*If he want to access by an email which haven't any account and then I want to displayed -
You doesn't have any account with this email.

Except firebase default error message :
{error?.message}


text:
Q: Reversing Alternate Levels of a perfect binary tree The problem statement is:

Given a Perfect Binary Tree, reverse the alternate level nodes of the binary tree.

Given tree:
               a
            /     \
           b       c
         /  \     /  \
        d    e    f    g
       / \  / \  / \  / \
       h  i j  k l  m  n  o

Modified tree:
               a
            /     \
           c       b
         /  \     /  \
        d    e    f    g
       / \  / \  / \  / \
      o  n m  l k  j  i  h

Solution 3 from  this site provides a particularly elegant solution in which it uses a the swap method on the nodes of the even numbered levels of the tree:void
preorder(struct Node *root1, struct Node* root2, int lvl)
{
    // Base cases
    if (root1 == NULL || root2==NULL)
        return;

    // Swap subtrees if level is even
    if (lvl%2 == 0)
        swap(root1->key, root2->key);

    // Recur for left and right subtrees (Note : left of root1
    // is passed and right of root2 in first call and opposite
    // in second call.
    preorder(root1->left, root2->right, lvl+1);
    preorder(root1->right, root2->left, lvl+1);
}

// This function calls preorder() for left and right children
// of root
void reverseAlternate(struct Node *root)
{
   preorder(root->left, root->right, 0);
}

For some reason, though, when the in order traversals of the original and modified versions of the tree are printed, they yield the same output:
Inorder Traversal of given tree
h d i b j e k a l f m c n g o

Inorder Traversal of modified tree
h d i b j e k a l f m c n g o

For some reason, the writers of the article didn't recognize the issue and left this as the final solution as it is the shortest of the three methods I'm assuming. Method 2 in the post is longer, but it produces the correct output.
Is there a bug with the solution that is causing the output for both versions of the tree to be the same?

A:
Is there a bug with the solution that is causing the output for both versions of the tree to be the same?

There is no bug with the algorithm. The bug is that the main function never calls reverseAlternate(), so it simply prints the same tree twice.
Add the missing call (line 76 in the link), and it works perfectly.