I don't understand some parts of the code in the search in linked list

Question: I wrote a linked list and I don't understand how to realize a search element in the linked list.
I understand the first part of the code, but not the part that starts with if(found == true).
Thank you in advance if anyone decides to respond.

struct test_struct
{
    int val;
    struct test_struct *next;
};

struct test_struct *head = NULL;
struct test_struct *curr = NULL;

struct test_struct* create_list(int val)
{
    ...
}

struct test_struct *add_to_list(int val, bool add_to_end)
{
    ...
}

struct test_struct* search_in_list(int val, struct test_struct **prev)
{
    struct test_struct *ptr = head;
    struct test_struct *tmp = NULL;
    bool found = false;

    while (ptr != NULL)
    {
        if (ptr->val == val)
        {
            found = true;
            break;
        }
        else
        {
            tmp = ptr; // here tmp play role of previous pointer
            ptr = ptr->next;
        }
    }

    if (true == found)
    {
        if (prev)
            *prev = tmp;
        return ptr;
    }
    else
    {
        return NULL;
    }
}

Comment: The code is incomplete and hence cannot be understood.
Comment: @Armali  i add some line of the code
Comment: `head` is never defined. `temp` is never defined.
Answer: I assume your test_struct is as following:
struct test_struct
{
    int val;
    struct test_struct *next;
};

I also assume that your head is declared somewhere in your code as following:
struct test_struct *head;

and that your linked list is filled somewhere.
In your search function, you need to use the val attribute that you set, which is the value you are looking for. In the code you posted, it's not used anywhere. Also, there are some typos, using temp instead of tmp.
struct test_struct* search_in_list(int val, struct test_struct **prev) {
    struct test_struct *ptr = head;
    struct test_struct *tmp = NULL;
    bool found = false;

    while (ptr != NULL) {
        if (ptr->val == val) { /* val and not data */
            found = true;
            break;
        } else {
            ptr = tmp; /* tmp and not temp */
            ptr = ptr->next;
        }
    }
    if (found == true) {
        if (prev)
            *prev = tmp; /* tmp and not temp */
        return ptr;
    }
    else {
        return NULL;
    }
}

In this function, the prev attribute is set to tmp at the end of the research. It means that it saves the previous element of the linked list compared to the one that was researched. Keep this only if you have a use for it!
Comment: thanks. but I don't understand why we write prev in the round brackets, and why we don't write curly brackets after if in the case? ``` if (found == true) {
        if (prev)
            *prev = tmp; /* tmp and not temp */
            return ptr;}```
Comment: curly brackets are optional when there is only one instruction in the "if" block. More information here: https://stackoverflow.com/questions/14901919/when-can-i-omit-curly-braces-in-c
Comment: but what means prev in curly brackets?
Comment: I think it's to make sure that the "prev" param is set when the function is called. This way, the "prev" param is optional, and it will be set to the tmp value only if it has been set in the function call.
Comment: thank so much, but i have another question,. so, for what it is used here  pointer to pointer : struct test_struct **prev?
Comment: I invite you to read this thread, that should help you understand: https://stackoverflow.com/questions/18698317/pointers-as-function-arguments-in-c Understanding pointers is a complex subject in C and cannot be explained with only a comment
Comment: Glad I could help. Feel free to mark my answer as accepted if that answered your question properly. Have a good day :)
Comment: I changed the code. I looked at the output. And I came to the conclusion that this is the part when         if(found== true...     and so on         is very important in finding the item! But why? Maybe these lines of code are needed to check? What do you think?


Poisson arrivals happen in the given interval

Question: If $T_m$ is the $m^{\mathrm{th}}$ arrival time of a Poisson process, how to calculate $\mathbb P(T_m < a< T_{m+1} < b)$, where $a$ and $b$ are given times?
Comment: $$
\mathbb P(T_m<a<T_{m+1}<b) = \mathbb P(a<T_{m+1}-T_m<b+T_{m+1}) = \mathbb P(a<T_{m+1}-T_m)\mathbb P(T_{m+1}-T_m < b + T_{m+1}),
$$
by the memoryless property of the exponential distribution.
Comment: @Math1000: That doesn't look right. E.g. consider $a=0$, where the left-hand side is $0$ and the right-hand side isn't.
Comment: Aren't $T_{m-1}-T_m$ and $T_{m+1}$ independent though?
Comment: @Math1000: They are; but I don't see how that justifies either of those two equalities -- certainly not the left one.
Answer: The event $T_m\lt a\lt T_{m+1}\lt b$ occurs exactly if there are exactly $m$ arrivals up to $a$ and then at least one arrival before $b$. If the Poisson process has rate $\lambda$, the probability for this is
$$
\frac{(\lambda a)^m\mathrm e^{-\lambda a}}{m!}\left(1-\mathrm e^{-\lambda (b-a)}\right)=\frac{(\lambda a)^m}{m!}\left(\mathrm e^{-\lambda a}-\mathrm e^{-\lambda b}\right)\;.
$$
Comment: Simply brilliant.


JavaScript or React - database security in single-page website

Question: Welcome stackoverflow community.
I'm doing small project, simple single-page website. It will also contain contact form which takes user to different page. I decided to create a database since on website I will do few responsive features ie. booking calendar where occupied dates won't be available. I wrote all my projects in vanilla js so far. I'm wondering that adding react to this project will be overkill.
I did research and know roughly cons and props for using it but I couldn't find answer if react gives you some extra safety features comparing to using vanilla js over attacks to website, and if yes, does it makes sense to write whole project in react just for those features?
Many thanks for any feedback.
Answer: I don't think you should be rewriting your app in react just for security. If you have any sensitive information. You should be keeping it on the server and not on the front-end.
For a small project. Vanilla JS can be enough. React is just for helping you manage and create UI components. It will not give you any extra security as it is still javascript in the end.


change background of page in theme

Question: I want to change my window background in my theme like this:

But there is no change in page.
I tried:

too.
But all backgrounds change .but i want to change just activity background.
Comment: you can refer this https://stackoverflow.com/questions/10156816/android-how-to-set-background-color-of-all-screens
Answer: If you want only in one you need to define another style class and there to import to your layout file.
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/mainLayout"
 style="@style/MainLayout">
</LinearLayout>

Comment: @OmidRezaHeidari No problem glad to help you.

change background of page in theme


How can I set NODE_ENV=production on Windows?

Question: In Ubuntu it's quite simple; I can run the application using:
$ NODE_ENV=production node myapp/app.js

However, this doesn't work on Windows. Is there a configuration file where I can set the attribute?
Comment: For a multiplatform solution you can find the answer https://stackoverflow.com/a/57509175/11127383
Comment: Does this answer your question? [How to set NODE\_ENV to production/development in OS X](https://stackoverflow.com/questions/9198310/how-to-set-node-env-to-production-development-in-os-x)
Answer: Current versions of Windows use Powershell as the default shell, so use:
$env:NODE_ENV="production"

Per @jsalonen's answer below. If you're in CMD (which is no longer maintained), use
set NODE_ENV=production

This should be executed in the command prompt where you intend to run your Node.js application.
The above line would set the environment variable NODE_ENV for the command prompt where you execute the command.
To set environment variables globally so they persist beyond just the single command prompt, you can find the tool from System in Control Panel (or by typing 'environment' into the search box in the start menu).
Comment: Heads up: "set NODE_ENV=production && " adds a trailing space to the variable. I needed "set NODE_ENV=production&& " to avoid the additional space which breaks node apps like Ghost.
Comment: For anyone still struggling with this: `set NODE_ENV=production && node app`. More conveniently configure your `package.json` accordingly: `"scripts": { "start": "set NODE_ENV=production && node app" }`.
Comment: @Amberlamps that is not a good solution because the NODE_ENV is then just hardcoded for all machines; the real goal is to change the env by machine using an env variable or to pass in the value at the command line, not hardcode it in the package.json file.
Comment: I think using `cross-env` is the better solution to this problem if your team works on mixed operating systems. Answer from @MoOx would be my pick as an answer to this question.
Comment: @ShuruiLiu the command will not output anything, but you can type `echo %NODE_ENV%` to check its current value.
Comment: Thanks  @daw. Your comments should be added to the original answer
Comment: @AlexMills that's why you can add more than one "scripts" item. simply add one for "debug" or whatever you wanna call it and run that on other machines
Comment: The token '&&' is not a valid statement separator in this version.
Comment: Thanks @daw again and set NODE_ENV='production' && does not work either b/c the quote will also be read into NODE_ENV
Comment: This form of configuring an environment variable did not work for me. Instead I used as described by @jsalonen and worked perfectly.
Comment: For me on Windows 8 this works `set NODE_ENV production`. Your example doesn't work on my machine.
Comment: @WooCaSh sounds like you might be in PowerShell in that case, I don't think they changed command prompt's behavior in Win8
Comment: @JaniHartikainen might be true. I use console from WebStorm. Thanks for advice.
Comment: is there anything returns after you type in this command? I didn't get anything at all after I type in this command. (I am trying to run a node project on Windows too)
Comment: using this to switch from development to testing is inconvenient because once you use "set NODE_ENV=testing&& server" then you can't just hit ctrl+c and run node server expecting NODE_ENV to default to 'development' because you just set it to 'testing' for the terminal session. Would be great if node had a --env option that just overrides NODE_ENV temporarily.
Comment: @daw you actually saved me from wasting more time. thanks
Answer: I just found a nice Node.js package that can help a lot to define environment variables using a unique syntax, cross platform.
https://www.npmjs.com/package/cross-env
It allow you to write something like this:
cross-env NODE_ENV=production my-command

Which is pretty convenient! No Windows or Unix specific commands any more!
Comment: While the first answer is true. I think this answer is most reliable and should be used
Comment: Simple and perfectly solves my problem. I was able to build on Linux only. This solved both, Linux and Windows.
Comment: This answer deserves more love, should be the accepted one :)
Comment: This is the best answer for me also
Comment: Worked like magic, thanks.

My error was `'NODE_ENV' is not recognized as an internal or external command, operable program or batch file.`
Comment: we need to boost this answer because it makes more sense than the first one.
Comment: It's still not work for me, sad
Answer: In PowerShell:
$env:NODE_ENV="production"

Comment: Struggled a bit to get this to work from Powershell within Visual Studio Code.  Thought I'd leave solution here.  I was attempting to run a "Gulp" command, while ensuring correct env value was set.  This is what wound up working for me: `$env:NODE_ENV="development"; gulp runMytask`.  Note the semi-colon in there.  The gulp file can use conditional logic on process.env.NODE_ENV.  Unless you set it, it will be undefined.
Comment: `set NODE_ENV=production` did not work for me in powershell but this did. Thanks!
Comment: p.s.: don't forget the $ and the quotes ;)
Comment: Only this solution work for me with windows 10 and webpack 3.8.1
Comment: This works perfect. But, the `cross-env NODE_ENV=production` option is really a better solution if running npm commands from package.json that require the env to be set. It's too easy to leave the env set on dev/prod after using the $env:NODE_ENV option
Answer: It would be ideal if you could set parameters on the same line as your call to start Node.js on Windows. Look at the following carefully, and run it exactly as stated:
You have these two options:

At the command line:
set NODE_ENV=production&&npm start

or
set NODE_ENV=production&&node index.js

The trick for it to work on Windows is you need to remove the whitespace before and after the "&&". Configured your package.json file with start_windows (see below) below. Then Run "npm run start_windows" at the command line.
//package.json

"scripts": {
  "start": "node index.js"
  "start_windows": "set NODE_ENV=production&&node index.js"
}

Comment: It is not necessary to remove the whitespace after the `&&`. You could use `set NODE_ENV=production&& node index.js` Reason: The whitespace between `production` and `&&` is interprated as part of the NODE_ENV. You could use single quotes and whitespaces to solve this problem as well. So this is also valid and should work: `set 'NODE_ENV=production' && node index.js`
Comment: Worked for me. Had to remove the whitespace though "set NODE_ENV=production&&nodemon server.js"
Comment: Would DEF like to know how to get it to work this way.
Comment: Wish I had read down this far before trying the answer above, would have saved me some time. :\
Comment: On a vaguely related note I found that && didn't work as expected on windows when chaining multiple commands together. If in doubt try using | instead
Comment: this worked for me on windows 10 64bit machine from both cmd and power-shell
Comment: try it out and leave your feedback
Comment: @SC_Chupacabra probably don't want to be in production using nodemon, maybe "set NODE_ENV=development&&nodemon server.js" is better :)
Comment: really surprised that having no white space fixed my error!
Comment: Removing WHITESPACE before and after && worked. Thanks.
Answer: You can use
npm run env NODE_ENV=production

It is probably the best way to do it, because it's compatible on both Windows and Unix.
From the npm run-script documentation:

The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an "env" command is defined in your package it will take precedence over the built-in.
Comment: @JonasKello You would use this: `npm run env NODE_ENV=production -- node -e 'console.log(process.env.NODE_ENV)'` The `--` is **mandatory**. Replace `node -e 'console.log(process.env.NODE_ENV)'` with whatever command you want.
Comment: How can we execute another command with the variable set? This does not seem to work: npm run env NODE_ENV=production && echo $NODE_ENV. Probably they are executed in two different shells?
Comment: Does not work for me. It list vars, show the var you specify, but on runtime, var is not ok in process.env.YOUR_VAR...
Comment: From what I can see, this doesn't work at all. From the docs itself, It's only **listing** environment variables, not setting them.
Comment: Tried this with this command: `npm run env NODE_TLS_REJECT_UNAUTHORIZED=0 --  node --inspect ./etc/http-req-standalone.js` and ... nothing happened. I'm not sure this method works on windows.
Comment: This method does not work on windows, but replacing `--` with `&&` should work.

`npm run env NODE_ENV=production && node -e 'console.log(process.env.NODE_ENV)'`
Comment: This worked for me using [cmder](https://cmder.net/) (which essentially uses cmd.exe / PowerShell under the hood) on Windows: `npm run env NODE_ENV=development -- node app.js`
Answer: I wrote a module win-node-env with which you can run your command just like you would in *nix.
NODE_ENV=production node myapp/app.js

It works by creating a NODE_ENV.cmd that sets the NODE_ENV environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env

Comment: exactly what I was looking for! to run with npm scripts, and it even works with other node cli tools like jest. So "set NODE_ENV=debug & cls & jest..." became "cls & NODE_ENV=debug jest"
Answer: My experience using Node.js on Windows 7 64-bit in Visual Studio 2013 is that you need to use
setx NODE_ENV development

from a cmd window. AND you have to restart Visual Studio in order for the new value to be recognized.
The set syntax only lasts for the duration of the cmd window in which it is set.
Simple test in Node.js:
console.log('process.env.NODE_ENV = ' + process.env.NODE_ENV);

It returns 'undefined' when using set, and it will return 'development' if using setx and restarting Visual Studio.
Comment: `cmd` -- not powershell? Ugh, come on windows, get it together.
Comment: your remark about restart of VS code was really useful!
Answer: If you are using Visual Studio with NTVS, you can set the environment variables on the project properties page:

As you can see, the Configuration and Platform dropdowns are disabled (I haven't looked too far into why this is), but if you edit your .njsproj file as follows:
  <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <DebugSymbols>true</DebugSymbols>
    <Environment>NODE_ENV=development</Environment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
    <DebugSymbols>true</DebugSymbols>
    <Environment>NODE_ENV=production</Environment>
  </PropertyGroup>

The 'Debug / Release' dropdown will then control how the variable is set before starting Node.js.
Answer: Here is the non-command line method:
In Windows 7 or 10, type environment into the start menu search box, and select Edit the system environment variables.
Alternatively, navigate to Control Panel\System and Security\System, and click Advanced system settings
This should open up the System properties dialog box with the Advanced tab selected.  At the bottom, you will see an Environment Variables... button.  Click this.

The Environment Variables Dialog Box will open.

At the bottom, under System variables, select New...This will open the New System Variable dialog box.

Enter the variable name and value, and click OK.
You will need to close all cmd prompts and restart your server for the new variable to be available to process.env.  If it still doesn't show up, restart your machine.
Comment: Thank you! I had done all this but it wasn't working until I restarted the server.
Comment: Question - will next.js be able to read these windows system environment variables?  We're deploying to Azure using CI/CD pipelines and want to take advantage of the Configuration Settings in an Azure Web App, which your code (at least in .NET) can read just like reading windows system environment variables without any code changes.  Hope this makes sense :|
Answer: if you are using vs code terminal you have to use this command
$env:NODE_ENV="production"

Comment: This also works for the Windows Powershell Terminal. Thank you @kukab.
Answer: To run your application in PowerShell (since && is disallowed):
($env:NODE_ENV="production") -and (node myapp/app.js)

Note that the text output of what the server's doing is suppressed, and I am not sure if that's fixable. (Expanding on @jsalonen's answer.)
Comment: It didn't work for me: `"debug-windows": "($env:NODE_ENV=\"dev\") -and (node src/dequeue.js)"`
Answer: Just to clarify, and for anyone else that may be pulling their hair out...
If you are using git bash on Windows, set node_env=production&& node whatever.js does not seem to work. Instead, use the native cmd. Then, using set node_env=production&& node whatever.jsworks as expected.
My use case:
I develop on Windows because my workflow is a lot faster, but I needed to make sure that my application's development-specific middleware were not firing in the production environment.
Answer: first in powershell type
$env:NODE_ENV="production"

then type
node fileName.js

It will work perfectly displaying all the outputs.
Answer: For Windows
set NODE_ENV=development && react-scripts start
For Ubuntu, Linux, macOs
NODE_ENV=development react-scripts start
Comment: Welcome to StackOverflow! Please edit your answer to explain what this code does and how it answers the question, so that it is useful to people with similar issues. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer)
Comment: How it answers the question? This is exactly the way to rewrite the command in windows. I don't see what other explanation is needed here.
Answer: For multiple environment variables, an .env file is more convenient:
# .env.example, committed to repo
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

# .env, private, .gitignore it
DB_HOST=real-hostname.example.com
DB_USER=real-user-name
DB_PASS=REAL_PASSWORD

It's easy to use with dotenv-safe:

Install with npm install --save-dev dotenv-safe.
Include it in your code (best at the start of the index.js) and directly use it with the process.env command:

require('dotenv').load()
console.log(process.env.DB_HOST)

Don't forget to ignore the .env file in your VCS.
Your program then fails fast if a variable "defined" in .env.example is unset either as an environment variable or in .env.
Comment: .env files are only convenient for secrets and add an extra step of complexity when setting up when assigning new people to a project or applying changes to them.
Comment: @coiso Without a generic, common place, where do you put *many* env variables? Either in a script file or in an IDE dependent setting, you're even more bound to specific tools. This makes integrating new team members even more harder, I think.
Answer: In case you are using GITBASH terminal
"set NODE_ENV=production"
will not work, what can you do is type
"export NODE_ENV=production"
Comment: I get an error: `'export' is not recognized as an internal or external command, operable program or batch file`
Comment: Try using it with 'set' instead of 'export'
Answer: set NODE_ENV=production & node server.js

Answer: Restart VS code if the NODE_ENV or any other environment variable is not providing correct value. This should work after restart.
Answer: Finally, the best method I could see is as follows.
"set-env-qa": "npm run env APP_ENV=qa",
"start:qa": "npm run set-env-qa && react-native start",

This will make sure we get the correct env setup for the programs. replace react-native-start with whichever next command you want.
Answer: For git bash terminal in vscode it is:export NODE_ENV, instead of set NODE_ENV
Comment: In addition to this being a question specifically about Windows shells, this was already given as an answer [5 years ago](https://stackoverflow.com/a/51861824/1255289)
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: You can install the next plugin now that your commands are operational.
npm install -g win-node-env

Answer: this will not set a variable but it's usefull in many cases.  I will not recommend using this for production, but it should be okay if you're playing around with npm.
npm install --production

Answer: I used npm script for running a gulp task without "&&"
NODE_ENV=testcases npm run seed-db
Answer: In Windows 10 I have used  $env:NODE_ENV="Production"
This worked on my vscode terminal. But if your server is listening first need to stop and set your env variable and start the app again. This way it worked for me.
Answer: If you are looking to set environment variable and run npm script in the same line then use:
$env:BASE_URL="https://example.com"; npm run __your_npm_script__

Answer: It seems that
{
   "start_windows": "set NODE_ENV=test"
}

is not working for me. I'm currently trying this on my Windows machine. When I hit:
npm run start_windows

it would execute on the console without errors but when I try to echo
echo %NODE_ENV%

nothing comes out of it, meaning it does not exist and it wasn't set at all...
Comment: This is not an answer, but a question.
Comment: You've probably overcome this, but your last line would be: `ps aux | grep NODE_ENV` But, you're also not running with the "start_windows" script. Other answers point out that you'd need to do something like: `"set NODE_ENV=test&& node ./index.js"`. Finally, you're setting the envar for that particular session, on that terminal. So, really, your echo or more proper "ps aux" op is invalid. You'd just log-out the setting in your "index.js" or "app.js", whatever your entry is: `console.log(process.env.NODE_ENV);`.
Anyway, I hope that helps more than a downvote.


Trying to "zfs attach" a new disk, how to get correct specification for the disk I'm adding?

Question: I'm migrating data from my old server to zfs on FreeBSD 10.x (I'm actually on FreeNAS 9.10.2-u1 but doing this activity in console so it's pure FreeBSD). My problem is that zpool attach needs a new_device in the correct format or slice/partition information, which I don't know how to provide.
Because of costs, I'm migrating the data in two stages - copying the data from my old mirror to a new zfs pool (without redundancy), then breaking the mirrors on the old server to move the mirror drives over and resilver on the new server, at all stages having 2 copies of the data. SMART stats are all good, ands all disks are "enterprise" type. Although not ideal, so far it's gone well. I've copied over the data, and connected the disks from the old server to the new server - where I'm now stuck on getting the correct args for zpool attach.
Current storage is as follows:
camcontrol devlist identifies the disk devices and model numbers, giving:
ada0 = 6TB disk
ada1 = 4TB disk
ada2 = 6TB disk
ada3 = BOOT MIRROR
ada4 = BOOT MIRROR
ada5 = 4TB disk
ada6 = 6TB disk

glabel status identifies the gptid's for the 5 disks already in use:
gptid/c610a927-01da-11e7-b762-000743144400     ada0p2 - 6TB
gptid/c68f80ae-01da-11e7-b762-000743144400     ada2p2 - 6TB
gptid/3b2b904b-02b3-11e7-b762-000743144400     ada3p1 - BOOT MIRROR
gptid/fb71e387-016b-11e7-9ddd-000743144400     ada4p1 - BOOT MIRROR
gptid/c566154f-01da-11e7-b762-000743144400     ada5p2 - 4TB

zpool status identifies the 3 disks in the data pool so far, by gptid
gptid/c610a927-01da-11e7-b762-000743144400 (from above this is ada0p2, 6TB)
gptid/c68f80ae-01da-11e7-b762-000743144400 (from above this is ada2p2, 6TB)
gptid/c566154f-01da-11e7-b762-000743144400 (from above this is ada5p2, 4TB)

so the new disks to attach are:
ada1 (4TB) - attach to gptid/c566154f-01da-11e7-b762-000743144400 (ada5p2)
ada6 (6TB) - attach to gptid/c610a927-01da-11e7-b762-000743144400 (ada0p2)

disk arriving shortly (6TB): attach on arrival to gptid/c68f80ae-01da-11e7-b762-000743144400 (ada2p2)

Problem:
What I'm stuck on is the actual command to use for attach. zpool attach gives an error whatever I try:
zpool attach ada0p2 ada6
missing <new_device> specification

zpool attach gptid/c610a927-01da-11e7-b762-000743144400 ada6
missing <new_device> specification

I'm guessing it's objecting to the "ada6" and I should be providing some other identifier, or a slice/partition ID instead. But I don't have these; zfs creates them itself when it attaches the disk.
What is the correct command to use here, or what am I missing?
Answer: You have to specify also zpool to which you want to add disk.
# zpool list -v
NAME                         SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT
zroot                       2.72T   204G  2.52T         -     7%     7%  1.00x  ONLINE  -
  mirror                    2.72T   204G  2.52T         -     7%     7%
    gpt/zfs0                    -      -      -         -      -      -
    gpt/zfs1                    -      -      -         -      -      -

# zpool attach zroot gpt/zfs1 ada6

http://docs.oracle.com/cd/E19253-01/819-5461/6n7ht6qvl/index.html


Add background image to block from view

Question: I created a view that list items from a content type. I have a block display for this view. I want to be able to put a different background image on each instances of this block.
Ideally, it could show up as an option in Block Settings > Allowed settings so this way every instance would have its own background image.
A second option would be that there is an other option in Block Settings below Block Name, something like Block Bakgorund. This time the same background image would be use as every instance of the block.
An other option would be to create a custom block that has 2 fields, a background image and a entity reference field on the content type my view was listing. Two problems with this, first this come to the same as re-write the functionality of Views, and second I am not sure if I would be able to create a field that is an entity reference on a block created programmatically (module plugin)
Any solution to this or thoughts?
Answer: I finally had time to make a custom module for that: ctool_views_extender
In your MODULE.module:
<?php

use Drupal\views\Plugin\views\display\Block as CoreBlock;
use Drupal\MODULE\Plugin\Display\Block;

/**
 * Implements hook_views_plugins_display_alter().
 */
function MODULE_views_plugins_display_alter(&$displays) {
  if (!empty($displays['block']['class'])) {
    $displays['block']['class'] = Block::class;
  }
}

In src/Plugin/Display/Block.php:
<?php
/**
 * @file
 * Contains \Drupal\MODULE\Plugin\Display\Block.
 */

namespace Drupal\MODULE\Plugin\Display;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Drupal\ctools_views\Plugin\Display\Block as CtoolsBlock;

/**
 * Provides a Block display plugin that allows for greater control over Views
 * block settings.
 */
class Block extends CtoolsBlock {

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);
    $filtered_allow = array_filter($this->getOption('allow'));
    $filter_options = [
      'background' => $this->t('Background')
    ];
    $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

    $options['allow'] = array(
      'category' => 'block',
      'title' => $this->t('Allow settings'),
      'value' => empty($filtered_allow) ? $this->t('None') : implode(', ', $filter_intersect),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $options = $form['allow']['#options'];
    $options['background'] = $this->t('Background');
    $form['allow']['#options'] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
    $form = parent::blockForm($block, $form, $form_state);

    $allow_settings = array_filter($this->getOption('allow'));
    $block_configuration = $block->getConfiguration();

    if(!empty($allow_settings['background'])){
      $form['override']['background'] = array(
        '#type' => 'managed_file',
        '#title' => $this->t('Background'),
        '#description' => $this->t('Enter background image'),
        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
        '#upload_location' => 'public://backgrounds'
      );
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
    // Set default value for items_per_page if left blank.
    if (empty($form_state->getValue(array('override', 'items_per_page')))) {
      $form_state->setValue(array('override', 'items_per_page'), "none");
    }

    parent::blockSubmit($block, $form, $form_state);
    $configuration = $block->getConfiguration();
    $allow_settings = array_filter($this->getOption('allow'));

    if (!empty($allow_settings['background'])) {
        $background = $form_state->getValue(['override', 'background']);
        $configuration['background'] = $background;
        // fix bug in Drupal which does not put the image as permanent
        $fid = $form_state->getValue(['override', 'background'])[0];
        /** @var \Drupal\file\Entity\File $file */
        $file = \Drupal\file\Entity\File::load($fid);
        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'ctools_views', 'image', 1);
    }

    $block->setConfiguration($configuration);
  }
}

Then all you need to do is output it in a twig template. I use another module that I made to simplify things (get_url_from_fid on github or How to get path of image from file id on SE)
{% set background = '' %}
{% if configuration.background.0 %}
  {% set background = 'background-image: url(' ~     get_url_from_fid(configuration.background.0) ~ ')' %}
{% endif %}

Cheers!
Answer: Finally I decided to patch ctools view block. I have plan to replaced this patch with an object that will extend ctools' view's Block (core/modules/ctools_views/src/Plugin/Display/Block.php) I paste here for anyone to use.
[apache{} patches]$ more ctool-add-bg-to-block.patch
diff --git a/modules/ctools_views/src/Plugin/Display/Block.php b/modules/ctools_views/src/Plugin/Display/Block.php
index 9b72f34..19b64aa 100644
--- a/modules/ctools_views/src/Plugin/Display/Block.php
+++ b/modules/ctools_views/src/Plugin/Display/Block.php
@@ -31,7 +31,8 @@ class Block extends CoreBlock {
       'hide_fields' => $this->t('Hide fields'),
       'sort_fields' => $this->t('Reorder fields'),
       'disable_filters' => $this->t('Disable filters'),
-      'configure_sorts' => $this->t('Configure sorts')
+      'configure_sorts' => $this->t('Configure sorts'),
+      'background' => $this->t('Background')
     ];
     $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

@@ -54,6 +55,7 @@ class Block extends CoreBlock {
     $options['sort_fields'] = $this->t('Reorder fields');
     $options['disable_filters'] = $this->t('Disable filters');
     $options['configure_sorts'] = $this->t('Configure sorts');
+    $options['background'] = $this->t('Background');
     $form['allow']['#options'] = $options;
     // Update the items_per_page if set.
     $defaults = array_filter($form['allow']['#default_value']);
@@ -79,6 +81,16 @@ class Block extends CoreBlock {
       unset($form['override']['items_per_page']['#options']);
     }

+    if(!empty($allow_settings['background'])){
+      $form['override']['background'] = array(
+        '#type' => 'managed_file',
+        '#title' => $this->t('Background'),
+        '#description' => $this->t('Enter background image'),
+        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
+        '#upload_location' => 'public://backgrounds'
+      );
+    }
+
     // Provide "Pager offset" block settings form.
     if (!empty($allow_settings['offset'])) {
       $form['override']['pager_offset'] = [
@@ -270,6 +282,19 @@ class Block extends CoreBlock {
       }
     }

+    if (!empty($allow_settings['background'])) {
+        $background = $form_state->getValue(['override', 'background']);
+        $configuration['background'] = $background;
+        // fix bug in Drupal which does not put the image as permanent
+//      kint($form_state->getValue(['override', 'background'])[0]);
+        $fid = $form_state->getValue(['override', 'background'])[0];
+        /** @var \Drupal\file\Entity\File $file */
+        $file = \Drupal\file\Entity\File::load($fid);
+        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
+        $file_usage = \Drupal::service('file.usage');
+        $file_usage->add($file, 'ctools_views', 'image', 1);
+    }
+
     // Save "Pager offset" settings to block configuration.
     if (!empty($allow_settings['offset'])) {
       $configuration['pager_offset'] = $form_state->getValue(['override', 'pager_offset']);

Comment: Unless I'm missing something you are hacking a contrib. module (
`a/modules/ctools_views/src/Plugin/Display/Block.php`), this is really bad practice as your changes will be lost if you update the module.

You should be able to add your customisations via a custom module.
Comment: @mediaashley I know this is not the best way. I am trying to move that to a custom module but I can't find how to tell Drupal to use my Block class instead of ctools'

Add background image to block from view


Is it OK to cut a player from a rec level football (soccer) team?

Question: I coach a U10 boys recreational soccer team.  In my area, we generally have more players wanting to play than coaches available to field teams.  That said, some degree of turnover on a team seems to be normal but I have noticed lower turnover with each season.
I have a looming problem for this next season.  My current roster is full (it's capped by the league) and all of the players have tentatively indicated they want to return next season.  The parents of a former player recently contacted me and asked if their son could play on my team again next season instead of the competitive team he currently plays on.
So the problem is having a past player who wants to play but possibly not having a slot in the roster for him.
In the past, I have guaranteed slots on the next season's team to returning players.  That has seemed the most "fair", but I'll acknowledge that has created logistical friction when the club has new players needing a team and I can't get the parents of the returning player to provide an answer.  And by "fair", maybe I really just mean easy.
The player wanting to play is a good player, and having him on the team would help pull up the skills for the rest of the team.
Of the players I would consider cutting, their minds simply aren't focused on soccer.  Specifically, they make most of the practices and games, but not all due to other commitments.  And even when they are at a practice or game, they're frequently distracted by something else like the clouds or the grass or ...
On the one hand, that's completely developmentally appropriate.  On the other hand, their absences and lack of focus pull down the rest of the team.  For example, they'll miss plays during a game because they weren't paying attention or they'll interfere with practice because they're aren't following instructions.
My question:
Given my looming problem, I'm trying to figure out if my current guaranteed slot policy is the best approach and if that's truly fair to all of the players involved.
On a competitive or premier team, the answer is easy as there is a stated focus on building the best team and the coach is expected to replace under-performing players with stronger ones when possible.
On a recreational team, the focus is on fair play; skills development; and developing a passion for the sport.  The crux of the question is how to balance between what's fair for an individual player versus what's fair or beneficial for the rest of the team.
Answer: Seems to me this is pretty similar to how our park district does things for sports/gymnastics classes/teams.  They have a slightly different approach.
What they do is have an early signup period, during which the only option is to confirm your enrollment for the next season/year/whatever of the exact class/sport you're in: same exact schedule, etc.  So if you're in Thursday Nights Soccer, you can re-register for Thursday Nights Soccer, but can't change to Tuesday Afternoons or whatever.
Then, a week later, regular signup begins.  This gives parents a week to make up their mind.  After regular signup begins, it's up to first come first serve.  You still can reregister - if there's a spot open, but you could lose your spot if enough new people already applied before you got around to registering.
You could easily do something similar.  Decide on a date.  Tell everyone they have until that date to officially register (pay, confirm explicitly they'll be playing, etc., with an understanding that they will only do this if they absolutely will be playing next year).  Then, if there are some slots open after this period, your returning player is welcome to the slot (as long as he/she pays/commits).  Set that date fairly early - before your current season is done, typically, so you have more leverage.


How to retrieve the data from an url using volley which has no array name?

Question: The image contains the data which has no array name and I need to get the data which is in the image using volley.Help me with the code for it.
Answer: You have to use a JSONArrayRequest . When you parse the response, it's a ready to use JSONArray object. You can loop the array to get your JSONObject items by position.
This has been covered in this thread -> Volley - Sending a POST request using JSONArrayRequest
Answer: String url="https://earthquake.usgs.gov/archive/product/nearby-cities/ci39269503/ci/1593242325224/nearby-cities.json";
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET, url, new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
StringBuilder stringBuilder=new StringBuilder();
<code>            try {

               for (int i=0;i<response.length();i++){
                   JSONObject citiesjsonObject=response.getJSONObject(i);
                   stringBuilder.append("Name : "+citiesjsonObject.getString("name")+
                           "\n"+"Distance : "+citiesjsonObject.getString("distance")+ "\n"
                           +"Population : "+citiesjsonObject.getString("population"));

                   stringBuilder.append("\n\n");
               }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    requestQueue.add(jsonArrayRequest);
</code>


How can I sort multiple two dimensional arrays so that the first row is sorted into bins and the second row is summed up?

Question: I am going to have a number of two-dimensional arrays that I would like to summarize into a single two-dimensional array. The first row is composed of doubles that represent mass, while the second row is composed of doubles that represent intensity.
//example 1 two-dimensional array
[145.56, 246.44, 346.55, 204.78]
[14,      30,       58,      49]

//example 2 two-dimensional array
[151.62, 223.18, 389.78, 266.96]
[67,      56,       23,      47]

I would like to summarize the two-dimensional arrays by sorting the mass doubles in the first row into bins of equal length, and then summing the pertinent intensity double up. So, assuming the mass bins had a length of 50, the summarized two-dimensional array using the two examples above would be:
//tentative example summarized two-dimensional array
[100-150, 150-200, 200-250, 250-300, 300-350, 350-400]
[14,      67,      135,      47,      58,     23     ]

I have so far tried to create a for loop that would first check which bin the mass would fall into by iterating over a nested for loop of the , and then add the intensity to previous intensity values.
double binSize = 50;
double[] binArray = new double[someNumberOfBins]
double[] summedIntensities= new double[numberOfTheirSummedIntensities];
for(i=0; i<twoDimensionalArray.GetLength(1); i++){
    double currentMass= twoDimensionalArray[0,i];
    for(j=0; j<binArray.GetLength(1); j++) {
        if(currentMass> (binArray[j] - binSize) && currentMass <= (binArray[j] + binSize)) {
            double currentIntensity = twoDimensionalArray[1,i];
            summedIntensities[j] += currentIntensity;
         }
    }
//somehow combine the binArray with summedIntensities array into a two dimensional array

However, there are some problems in the a design of this algorithm. Firstly, I do not know how to set up the binArray so that the numbers in it properly reflect the range of in my two-dimensional arrays. I also am not sure how to combine the binArray with the summedIntensities array into a two-dimensional array, or whether this is even practical for this particular case.
Is there another way of making the binArray that is more fitting with my purpose of creating a summarized two-dimensional array, or are there any other glaring problems with this algorithm?
Answer: Here is my algorithm:
Note 1: in result array the first row will be '100', '150', '200'... You can construct a struct or use Dictionary<string,int> if you want it as "100-149", "150-199"...
Note 2: i calculated the interval as [100-149], [150,199], [200,249]... modify last condition to change it if you need to
    static void Main(string[] args)
    {
        double[,] array1 = new double[2, 4] { { 145.56d, 246.44d, 346.55d, 204.78d }, { 14d, 30d, 58d, 49d } };
        double[,] array2 = new double[2, 4] { { 151.62d, 223.18d, 389.78d, 266.96d }, { 67d, 56d, 23d, 47d } };

        double[,] finalArray = DoWork(array1, array2,50);
    }

    private static double[,] DoWork(double[,] arrayLeft, double[,] arrayRight, int binLength)
    {
        //union of arrays
        double[,] newArray = new double[2, arrayLeft.GetLength(1) + arrayRight.GetLength(1)]; //2x8 array
        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < arrayLeft.GetLength(1); j++)
            {
                newArray[i, j] = arrayLeft[i, j];
            }
            for (int j = arrayLeft.GetLength(1); j < arrayLeft.GetLength(1) + arrayRight.GetLength(1); j++)
            {
                newArray[i, j] = arrayRight[i, j-4];
            }
        }

        //sorting first row
        for (int i = 0; i < newArray.GetLength(1)-1; i++)
        {
            for (int j = i+1; j < newArray.GetLength(1); j++)
            {
                if (newArray[0, i] > newArray[0, j])
                {
                    double temp0 = newArray[0, j];
                    double temp1 = newArray[1, j];

                    newArray[0, j] = newArray[0, i];
                    newArray[1, j] = newArray[1, i];
                    newArray[0, i] = temp0;
                    newArray[1, i] = temp1;

                }
            }
        }

        //determine the number of bins and their intervals
        double minMass = newArray[0, 0];                            //145.56
        double maxMass = newArray[0, newArray.GetLength(1) - 1];    //389.78

        double minBinLowerValue = 0; //since you're working with mass i ignore the negative values
        while (minBinLowerValue + binLength < minMass) minBinLowerValue += binLength; //100

        double maxBinHigherValue = minBinLowerValue;
        while (maxBinHigherValue < maxMass) maxBinHigherValue += binLength; //400

        double numberOfBins = (maxBinHigherValue - minBinLowerValue) / binLength; //6

        //creation of result array
        double[,] resultArray = new double[2, Convert.ToInt32(numberOfBins)]; //2x6 array

        //fill intervals to first row
        for (int i = 0; i < resultArray.GetLength(1); i++)
        {
            resultArray[0, i] = minBinLowerValue + binLength * i;
        }

        //fill the sums
        for (int i = 0; i < resultArray.GetLength(1); i++)
        {
            double sum = 0;
            for (int j = 0; j < newArray.GetLength(1); j++)
            {
                if(resultArray[0,i] <= newArray[0,j] && resultArray[0, i] + binLength > newArray[0, j]) //modify this condition
                {
                    sum += newArray[1, j];
                }
            }
            resultArray[1, i] = sum;
        }

        return resultArray;
    }

Answer: Here you go, I used a dictionary to store the summed values. The key is a bin number.
Note: If you want to make your solution better, I would use a class with 2 props (mass and intensity) I did not make this solution because  am not sure if you have the freedom to have a class or if you are stuck with with input you got.
using System;
using System.Collections.Generic;
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] bins1 = { 145.56, 246.44, 346.55, 204.78 };
            double[] values1 = { 14, 30, 58, 49 };

            double[] bins2 = { 151.62, 223.18, 389.78, 266.96 };
            double[] values2 = { 67, 56, 23, 47 };

            int binSize = 50;

            Dictionary<int, double> summedBins = new Dictionary<int, double>();

            AddValuesToSummedBins(binSize, summedBins, bins1, values1);
            AddValuesToSummedBins(binSize, summedBins, bins2, values2);

        }

        public static void AddValuesToSummedBins(int binSize, Dictionary<int, double> SummedBins, double[] Bins, double[] Values)
        {
            int i = 0;
            foreach (double oneBin in Bins)
            {
                int binSet = binSize * ((int) oneBin / binSize);
                if (!SummedBins.ContainsKey(binSet))
                {
                    SummedBins.Add(binSet, Values[i]);
                }
                else
                {
                    SummedBins[binSet] += Values[i];
                }
                i++;
            }

        }
    }
}

Answer: If you are flexible about your data format, you can use LINQ to do this in a very small amount of code.
You would need to store your data pairs as a class with Mass and Intensity properties, instead of separate items in a 2D array.
Assuming this class to store your data:
public class DataElement
{
    public double Mass { get; set; }
    public double Intensity { get; set; }
}

You could use the following function:
public List<DataElement> Summarize(IEnumerable<DataElement> data, int range)
{
    return data.GroupBy(de => Math.Floor(de.Mass / range) * range,
                       (range, g) => new DataElement {
                                         Mass = range,
                                         Intensity = g.Sum(d => d.Intensity)
                                     })
                .OrderBy(de => de.Mass)
                .ToList();
}

This function takes all of your data as a single IEnumerable, and runs it thought LINQ's GroupBy function.
The first argument is an expression that determines how to group items together.  For your purpose, I simply round down to the nearest multiple of the range argument (50 in your example, but anything should work).
The 2nd argument is an expression that returns the final output of a group, given the key of the group (the rounded down Mass), and the elements that were grouped together.  I just return a new DataElement with e Mass of the rounded down Mass, and an Intensity equal to the Sum of the Intentities of the grouped item.
The result is then sorted by Mass before returning the result.
This produces the following output from the input you specified in the question (from LINQPad's Dump function):

You could use it like this (available as a LINQPad file):
void Main()
{
    var data1 = new List<DataElement>{
        new DataElement{Mass = 145.56, Intensity = 14},
        new DataElement{Mass = 246.44, Intensity = 30},
        new DataElement{Mass = 346.55, Intensity = 58},
        new DataElement{Mass = 204.78, Intensity = 49},
    };
    var data2 = new List<DataElement>{
        new DataElement{Mass = 151.62, Intensity = 67},
        new DataElement{Mass = 223.18, Intensity = 56},
        new DataElement{Mass = 389.78, Intensity = 23},
        new DataElement{Mass = 266.96, Intensity = 47},
    };

    var result = Summarize(data1.Concat(data2), 50);
}


Automatic way to classify if a time series has a peak in a particular month/qtr of the year

Question: I have around 20 Million time series(say of product demands or merchant's activity for a few past years). I am looking to develop:

An automated way to classify these time series as being regular or seasonal(Seasonal here means there is peak activity in some part of the year say every April or even April-May-Jun).

For those who are seasonal, I am also looking to tag them with the exact months of their peak activity.

Currently I am exploring a time series clustering based approach on a sample with hope that they will be clustered as per their seasonal patterns. And then build a classifier to classify the remaining into different seasonal time series.
Answer: One possible approach:

Ensure that the time series are stationary (detrend, denoise, remove outliers).
Use a spectral decomposition method (such as FFT) to decompose each time series into the most important frequencies.
Perform some discretisation of the observed signals (quarterly cycles with peak in January etc).
Cluster time series based on presence of matching discretised signals.


Derivative of a curve's velocity vector

Question: Why is that in the equation below the second derivative of the position vector has a minus in the middle instead of plus after the product rule? I didn't get why we can just replace - sign in front of a if that's the reason.

where;
Comment: Alright got it. Forgot the sign in front of y component (i.e. S) in the second derivative, which makes both C and S have the negative sign.
Answer: Just the chain rule.
Note that $\dot{r}(t)=(aC'(t),S'(t))^T$.
Also, $C(t)=\cos\big(\pi-(1-\cos\omega t)\big)$ and
$$
C'(t)=-\sin\big(\pi-(1-\cos\omega t)\big)\cdot \pi \sin(\omega t)\cdot\omega
=\omega \pi\sin(\omega t)\cdot (-S(t))
$$

Derivative of a curve's velocity vector


App crash when try to define rightBarButtonItems

Question: I am using this methods to define navigationItem rightBarButtonItems:
UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"YouTube-icon"]];
UIBarButtonItem *barIcon = [[UIBarButtonItem alloc]initWithCustomView:imageView];

if ([videoArr count] > 0) {
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:barIcon,self.aToZButton, nil];
} else {
    self.navigationItem.rightBarButtonItem = barIcon;
}

[imageView release];
[barIcon release];

And when the debug is on :
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:barIcon,self.aToZButton, nil];

The app crash with:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType isSystemItem]: unrecognized selector sent to instance 0x1e5eecd0'

Edit
I noticed that the crash happen only when i am using rightBarButtonItem and then rightBarButtonItem.
If i use only rightBarButtonItems it's won't crash
Comment: Why are you releasing imageView twice?
Comment: It's mistake , i edit the code
Comment: Show ur code for aToZButton as well
Comment: I create this button in the inteface builder, and connect it with iboutlet
Comment: are you sure self.aToZButton is UIBarButtonItem ???
Comment: Yep, i noticed that the crash happen when i first set rightBarButtonItem an then the rightBarButtonItems, but if i set onlt the rightBarButtonItems it's work.any idea?
Comment: Does it crash if you set just the `rightBarButtonItem` or does it have to be item then items to see the crash?
Comment: have to be item then items and it crash
Comment: ok. remove last two release lines and see if app is still crashing?
Answer: Seems like somewhere down the line you're releasing the object too early(memory management issue).NSCFType is an internal undocumented class in the iOS SDK, the fact behind it showed up here means the memory space of your class got freed before the process get completed.


Anonymous methods cast as pointers

Question: can anyone explain why the code below fails?
<code>type TIDEThemeObserverFunc = reference to procedure(foo: integer);
var fObserverFuncs: TList<TIDEThemeObserverFunc>

function RegisterEventObserver(aObserverFunc: TIDEThemeObserverFunc): Pointer;
begin
  fObserverFuncs.Add(aObserverFunc);
  Result := @aObserverFunc;

  // line below somehow fails
  assert(fObserverFuncs.IndexOf(TIDEThemeObserverFunc(Result)) <> -1);
end;
</code>
I assumed anonymous methods can simply be casted and used around via pointers but that seems like a wrong assumption. Also, any resources explaining how the anonymous methods are implemented under the hood would be great. TIA.
Answer: You should use PPointer(@aObserverFunc)^ instead of @aObserverFunc to avoid the failed assert.
@gabr: thanks for ref to my blog, but I should recommend first to read the Stackoverflow user Barry Kelly blog as a more competent source of information.
Comment: Reference counting for the list should work, as it is of type `TList<(some method reference type)>`. If reference counting broke with generics, even trivial cases like `TList` would be useless.
Answer: Anonymous methods are actually interfaces (more correct - objects implementing an interface).
Read more here: Anonymous methods in Delphi: the internals (written by Stackoverflow user Serg).

Anonymous methods cast as pointers


Statistics: finding the mean of a normally distributed variable.

Question: For a normally distributed variable B variance is (0.714)^2 and mean is x.
If P( x < b < 3.2) = 0.475 find x.
My working:
P ( x < b < 3.2) =  P ( b < 3.2 )- P ( b < * x* )
P ( b < 3.2 ) - P ( b < * x* ) = 0.475
P ( z < [ 3.2 - x / 0.714 ] ) - P ( z < 0 ) = 0.475
P ( z < [ 3.2 - x / 0.714 ] )  - 0.5000 = 0.475
P ( z < [ 3.2 - x / 0.714 ] ) = 0.975
phi ( [ 3.2 - x / 0.714 ] ) = phi (1.960)
3.2 - x / 0.714 = 1.960
x = 1.8005
However this is incorrect, it should be 4.60. In the second to last line if 1.960 is negative this is what you get.
What did I do wrong so that 1.960 is positiv instead of negative?
Comment: If $x=4.60$, then $\mathrm{P}(x < B < 3.2) = 0$.
Answer: Your result is right. You can check it by using your result. $B$ is disributed as
$B\sim\mathcal N(1.8005,0.714^2)$. Thus
$$P ( 1.8005 < B < 3.2)=\Phi\left( \frac{3.2-1.8005}{0.714} \right)-\Phi\left( \frac{1.8005-1.8005}{0.714} \right)$$
$$\Phi\left( 1.96 \right)-\Phi\left( 0 \right)=0.975-0.5=0.475$$

You get the result of $\mu=4.6 \ $ if $$\color{blue}{P( 3.2 < B < x^*) = 0.475}$$
$$\Phi\left( \frac{x^*-x^*}{0.714} \right)-\Phi\left( \frac{3.2-x^*}{0.714} \right)=0.475$$
$$0.5-\Phi\left( \frac{3.2-x^*}{0.714} \right)=0.475$$
$$-\Phi\left( \frac{3.2-x^*}{0.714} \right)=-0.025$$
$$ \frac{3.2-x^*}{0.714} =\Phi^{-1}(0.025)$$
$$ \frac{3.2-x^*}{0.714} =-1.96$$
$$\Rightarrow x^*=\mu=4.59974\approx 4.6$$


Bing maps v8 event passes incorrect pin?

Question: So I'm writing an app using bing maps v8. Unfortunately, it does not have z-index support (despite having z-index functions ...). So I am trying to use layers to accomplish something similar. The issue is when I swap a pin between layers the event begins firing on the correct pin location with the wrong metadata.
Here is how I create the pin
function createImagePin(location, index, objArray)
{
    var obj = objArray[index];
    var smallPin = getSmallPin(obj);

    var pin = new Microsoft.Maps.Pushpin(location,
    {
        visible: true,
        icon: smallPin.data,
        anchor: new Microsoft.Maps.Point(smallPin.width / 2, smallPin.height / 2) //Align center of pushpin with location.
    });

    pin.metadata = {};
    pin.metadata.index = index;
    pin.metadata.dataTarget = obj;
    pin.metadata.isSelected = false;

    Microsoft.Maps.Events.addHandler(pin, 'click', function (e) {

        if(e.targetType === 'pushpin')
        {
            SetRowSelection(e.target.metadata.index);
        }
    });

    Microsoft.Maps.Events.addHandler(pin, 'mouseover', function (e)
    {
        if(e.targetType === 'pushpin')
        {
            SelectPin(e.target);
            ShowInfobox(e.target);
            console.log(e.target.getLocation());
        }
    });

    Microsoft.Maps.Events.addHandler(pin, 'mouseout', function (e)
    {
        if (e.targetType === 'pushpin')
        {
            DeselectPin(e.target);
            HideInfobox();
        }
    });

    return pin;
}

For some reason I keep getting a pin object in the mouseover every time that has the correct location but the incorrect metadata. If I comment out Deselect ... I get the correct both.
Here is how I select and deselect the pin. Based on the example I was given Bing Maps pushpin icon issues
There is NO other code that is touching these pins at the moment ... It seems pretty bizarre to me. It is almost like internally it is only copying some information within the Layer rather then moving all items attached to the object. In fact, if I just comment out the add/remove it stops passing me incorrect data ... though i lose my z-indexing.
function SelectPin(pin)
{
    switch (pin.metadata.dataTarget.ComparableType)
    {
        case "Subject":
            mapLayers.subjectLayer.remove(pin);
            pin.setOptions({ visible: true, icon: largeGreenHouse.data, anchor: new Microsoft.Maps.Point(largeGreenHouse.width / 2, largeGreenHouse.height / 2) });
            break;
        case "Listing Comp":
            mapLayers.compLayer.remove(pin);
            pin.setOptions({ visible: true, icon: largeBlueHouse.data, anchor: new Microsoft.Maps.Point(largeBlueHouse.width / 2, largeBlueHouse.height / 2) });
            break;
        case "Sales Comp":
            mapLayers.compLayer.remove(pin);
            pin.setOptions({ visible: true, icon: largeBlueHouse.data, anchor: new Microsoft.Maps.Point(largeBlueHouse.width / 2, largeBlueHouse.height / 2) });
            break;
        case "Hidden":
            pin.setOptions({ visible: false });
            return;
        default:
            mapLayers.observableLayer.remove(pin);
            pin.setOptions({ visible: true, icon: largeGreyHouse.data, anchor: new Microsoft.Maps.Point(largeGreyHouse.width / 2, largeGreyHouse.height / 2) });
            break;
    }

    mapLayers.selectionLayer.add(pin);
    pin.metadata.isSelected = true;
}

function DeselectPin(pin)
{
    if(!pin.metadata.isSelected)
        return;

    pin.metadata.isSelected = false;
    mapLayers.selectionLayer.remove(pin);
    switch (pin.metadata.dataTarget.ComparableType)
    {
        case "Subject":
            pin.setOptions({ visible: true, icon: greenHouse.data, anchor: new Microsoft.Maps.Point(greenHouse.width / 2, greenHouse.height / 2) });
            mapLayers.subjectLayer.add(pin);
            break;
        case "Listing Comp":
            pin.setOptions({ visible: true, icon: blueHouse.data, anchor: new Microsoft.Maps.Point(blueHouse.width / 2, blueHouse.height / 2) });
            mapLayers.compLayer.add(pin);
            break;
        case "Sales Comp":
            pin.setOptions({ visible: true, icon: blueHouse.data, anchor: new Microsoft.Maps.Point(blueHouse.width / 2, blueHouse.height / 2) });
            mapLayers.compLayer.add(pin);
            break;
        case "Hidden":
            pin.setOptions({ visible: false });
            return;
        default:
            pin.setOptions({ visible: true, icon: greyHouse.data, anchor: new Microsoft.Maps.Point(greyHouse.width / 2, greyHouse.height / 2) });
            mapLayers.observableLayer.add(pin);
            break;
    }

Answer: Hm, it appears to be a data issue not a code issue. My data is getting geocoded into identical lat/long for some properties that don't have the same addresses. As such the rearranging of the array results in a different one with the same position getting 'top position'.


AzureML ParallelRunStep runs only on one node

Question: I have an inference pipeline with some PythonScriptStep with a ParallelRunStep in the middle. Everything works fine except for the fact that all mini batches are run on one node during the ParallelRunStep, no matter how many nodes I put in the node_count config argument.
All the nodes seem to be up and running in the cluster, and according to the logs the init() function has been run on them multiple times. Diving into the logs I can see in sys/error/10.0.0.* that all the workers except the one that is working are saying:
FileNotFoundError: [Errno 2] No such file or directory: '/mnt/batch/tasks/shared/LS_root/jobs/virtualstage/azureml/c36eb050-adc9-4c34-8a33-5f6d42dcb19c/wd/tmp8_txakpm/bg.png'
bg.png happens to be a side argument created in a previous PythonScriptStep that I'm passing to the ParallelRunStep:
bg_file = PipelineData('bg',  datastore=data_store)
bg_file_ds = bg_file.as_dataset()
bg_file_named = bg_file_ds.as_named_input("bg")
bg_file_dw = bg_file_named.as_download()

...

parallelrun_step = ParallelRunStep(
    name='batch-inference',
    parallel_run_config=parallel_run_config,
    inputs=[frames_data_named.as_download()],
    arguments=["--bg_folder", bg_file_dw],
    side_inputs=[bg_file_dw],
    output=inference_frames_ds,
    allow_reuse=True
)

What's happening here? Why the side argument seems to be available only in one worker while it fails in the others?
BTW I found this similar but unresolved question.
Any help is much appreciated, thanks!
Answer: Apparently you need to specify a local mount path to use side_inputs in more than one node:
bg_file_named = bg_file_ds.as_named_input(f"bg")
bg_file_mnt = bg_file_named.as_mount(f"/tmp/{str(uuid.uuid4())}")

...

parallelrun_step = ParallelRunStep(
    name='batch-inference',
    parallel_run_config=parallel_run_config,
    inputs=[frames_data_named.as_download()],
    arguments=["--bg_folder", bg_file_mnt],
    side_inputs=[bg_file_mnt],
    output=inference_frames_ds,
    allow_reuse=True
)

Sources:

https://learn.microsoft.com/en-us/azure/machine-learning/how-to-debug-parallel-run-step
https://github.com/Azure/azure-sdk-for-python/issues/18355


ProFTPD: The meaning of the "TLS Verify Client" and "NoCertRequest" in the TLS configuration

Question: I know that per default FTP is insecure, because it is not encrypted. To avoid this insecure behavior of FTP, I want to set up a TLS encryption in my ProFTPD. Pursuant to this tutorial here: https://www.howtoforge.com/tutorial/install-proftpd-with-tls-on-ubuntu-16-04/ the tls configuration in ProFTPD should look like this:
 <IfModule mod_tls.c>
TLSEngine                  on
TLSLog                     /var/log/proftpd/tls.log
TLSProtocol TLSv1.2
TLSCipherSuite AES128+EECDH:AES128+EDH
TLSOptions                 NoCertRequest AllowClientRenegotiations
TLSRSACertificateFile      /etc/proftpd/ssl/proftpd.cert.pem
TLSRSACertificateKeyFile   /etc/proftpd/ssl/proftpd.key.pem
TLSVerifyClient            off
TLSRequired                on
RequireValidShell          no
</IfModule>

A lot of these directives are self-explanatory, but I still do not know what the directive "TLSVerifyClient" means.
According to the ProFTPD manual:

If off, the module will accept the certificate and establish an
  SSL/TLS session, but will not verify the certificate.
If on, the module will verify a client's certificate and, furthermore, will fail all SSL handshake attempts unless the client presents a certificate when the server requests one.

But I thought the certificate is coming from the server itself, so why should the server accepts certificate requests from the client?
and my second question, what is the meaning of the "nocertrequest" option of the TLSoption directive?
Conforming to the ProFTPD manual, the function of this option is:

Some FTP clients are known to be buggy when handling a server's
  certificate request. This option causes the server not to include such
  a request during an SSL handsh

Here the same question, why would the server send a certificate request to the client, when the server itself have TLS-certificates.
Answer: The TLSVerifyClient directive is about authenticating clients (i.e. "client auth" or "mutual auth"); it is used to determine whether mod_tls will request a certificate from the client, and whether that client-provided certificate must be valid (TLSVerifyClient on), or not (TLSVerifyClient optional).  Some sites want to use a client-provided certificate for access control; only clients presenting a certificate from a CA trusted by the server would be allowed, for example.
The original implementation of mod_tls would always include a request for the client's certificate, regardless of the TLSVerifyClient setting.  Thus there was the "NoCertRequest" TLSOption, for disabling that client certificate request.  Now, however, the NoCertRequest TLSOption has been deprecated in favor of using only the TLSVerifyClient setting; see Bug#4213.
Hope this helps!
Comment: In that situation, there would be no client authentication _using certificates_.  There is still authentication via username/password, of course.
Comment: Thank you really much for your answer. So when i understand you right, the "TLSVerifyClient" is not intended to establish a secure TLS connection, is was designed for client authentication, so that the server could accept the certificate like as a key file. And when I only need a secure TLS connection, I do not need this directive.
Comment: It is intended for client authentication, yes.  Some folks would consider that client authentication as part of a "secure TLS connection", so the wording you use may or may not be universally agreed upon.  But for purposes of protecting the client/server control and data connections using TLS, the `TLSVerifyClient` directive is not _required_; it is used to set additional _policy_ constraints on the authentication.
Comment: Thank you for your response. Client authentication over TLS is not needed for my purpose. To authenticate the clients, I have a MySQL database.

You say, that the original implementation of mod_tls always includes a certificate request. Does the current implementation also always include a certificate request?
Comment: Depends on what you mean by "current implementation".  Per the [Bug#4123](http://bugs.proftpd.org/show_bug.cgi?id=4213) link I mentioned, if you are using ProFTPD 1.3.6rc2 or later, then `mod_tls` does _not_ automatically request a certificate from the client.
Comment: I am using version 1.3.5 of ProFTPD.
Comment: So when I set no TLSVerifyClient and no "NoCertRequest" in ProFTPD version 1.3.5. there are also no client authentication?
Answer: For a more secure protocol, you might consider using SFTP (which proftpd supports). SFTP runs over SSH, so fully encrypted. You might find this related question useful. This tutorial on configuring proftpd to use SFTP may also help.
Comment: Thank you for your answer. As I wrote in my question I set up FTPS on my ProFTPD server and FTPS is also fully encrypted. So I think this should be  sufficient for a secure connection.


How to access all the different instances of an objects variable separately?

Question: I am generating 100 ovals as particles in the initialization method and then I want to move them by a certain amount(lets say x) for n number of iterations. I have written the following code snippet to do that.
private void drawNParticles(Graphics g)
    {
        ArrayList<Integer> list;
        list = new ArrayList<Integer>(Collections.nCopies(n, 0));
        for(int i=0;i<list.size();i++)
        {
           generateParticle(g);
        }
    }

private void generateParticle(Graphics g)
{
    int radius = 4;
    ArrayList<Integer> list= new ArrayList<Integer>();
    list=positionParticles(particle_x,particle_y);
    g.setColor(Color.RED);
    g.fillOval(list.get(0),list.get(1), radius, radius);
}

private ArrayList<Integer> positionParticles(int x, int y)
{
    int radius = 4;
    ArrayList<Integer> list= new ArrayList<Integer>();
    if(this.particle_counter==0)
    {
        x=randomInteger(2,678); // bounds of x between which the particles should be generated
        y=randomInteger(2,448); // bounds of y between which the particles should be generated
        x=x-(radius/2);
        y=y-(radius/2);
        if((x<251&&x>149)&&(y<266&&y>224))
        {
            x=0;
            y=0;
            positionParticles(x,y);
        }
        if((x<541&&x>499)&&(y<401&&y>299))
        {
            x=0;
            y=0;
            positionParticles(x,y);
        }
        this.particle_counter++;
    }
    else
    {
        setXPosition_particle(x);
        setYPosition_particle(y);
    }
    list.add(x);
    list.add(y);
    return list;
}

public void setXPosition_particle(int x)
    {
        this.particle_x=x+5;
        System.out.println("Particle_X:"+this.particle_x);
    }

public void setYPosition_particle(int y)
{
    particle_y=y+5;
    System.out.println("Particle_Y:"+this.particle_y);
}

What I want is that each particle's position should be incremented by 5. But in the output, every particle gets the same value. I am getting a diagonal line across my JPanel. What should I do to access each instance variable separately?
Answer: Why don't you just create a Particule class and maintain a List<Particule> ?
Comment: @learningJava [example using a class to hold the object state](http://stackoverflow.com/a/22123304/2587435)
Comment: Okay. So Do you mean I should create my particles in the class and add them to a list when each is created? How will I access them then? Can you please give a brief example?
Comment: I was writing a poor example but peeskillet gave you a nice one ;) That's what I was talikng about.
Comment: @Dici Got it now. Thanks!. Will try to implement now.
Comment: @learningJava Also you should actually attempt to do what others have suggested in your previous posts, to use [Shapes](http://docs.oracle.com/javase/7/docs/api/java/awt/Shape.html). See more at [2D Graphics](http://docs.oracle.com/javase/tutorial/2d/index.html)
Comment: @peeskillet Yes, I am trying to change the code to use Shapes. Once it works with basic functionality.
Answer: Your first for loop is messing up as is the generateParticle method. You should pass the index, i, into the method, you should not create a new and completely unrelated ArrayList inside the generateParticle method but instead use the ArrayList class field, list, inside of the method.
I also recommend that you not use the paint or paintComponent method to move your particles as you do not have full control over when or if it is called. Instead separate the moving of particles and their drawing by doing the moving say in a Swing Timer, and then simply iterating through the List in the paintComponent method, drawing each point.
Comment: How would that ArrayList class field inside of method work. Do you mean I should put all my particles x and y coordinates in that?


Swift Block value error

Question: I keep getting a finish block error in swift. The error is:

Cannot call value of non-function type'((Array,Array)->())!

There's an image of the error below as well. Here's the code:
var blockFinih: ((_ selectedTags: Array<Tag>, _ unSelectedTags: Array<Tag>) -> ())!

func finishTagController() {
    var selected: Array<Tag> = Array()
    var unSelected: Array<Tag> = Array()

    for currentTag in tags {
        if currentTag.isSelected {
            selected.append(currentTag)
        }
        else {
            unSelected.append(currentTag)
        }
    }
    self.dismiss(animated: true, completion: { () -> Void in
        self.blockFinih(selectedTags: selected, unSelectedTags: unSelected)
    })
}

Answer: Don't specify the argument labels when you call blockFinih. You've defined it to have no argument labels. The parameters selectedTags and unSelectedTags can only be used inside the function, not by the caller.
Change:
self.blockFinih(selectedTags: selected, unSelectedTags: unSelected)

to:
self.blockFinih(selected, unSelected)

Swift Block value error


Need help creating an expression tree for Where clause

Question: I need to create an expression tree, which I can pass along as predicate argument in Where clause to Linq To Enities query.
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source,
    Expression<Func<TSource, bool>> predicate);

Expression tree must be equivalent to where clause specified as below:
var query = context.Products.Select(product =>
    new { product.Name, product.Color });

var arr = "Red;Black".Split(';');
query = query.Where(obj => arr.Contains(obj.Color));

Answer: Googled it out!
var paramExpr = Expression.Parameter(typeof(TSource), "src");
var memberExpr = (MemberExpression)property.Body;

List<Expression> arrayInits = new List<Expression>();

var arrExpr = Expression.Constant(((string)values[0]).Split(new char[] { ';' }));

MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");

var containsExpression = Expression.Call(null, contains, arrExpr, memberExpr);
var containsLambda = Expression.Lambda<Func<TSource, bool>>(containsExpression, property.Parameters);

And it works!
Answer: public static Expression<Func<T, bool>> CreateContainsExpression<T>(T obj, string[] array)
{
    var paramExpr = Expression.Parameter(typeof(T), "obj");
    var arrExpr = Expression.Constant(array);

    var colourPropExpr = Expression.Property(paramExpr, "Color");
    MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");

    var containsExpr = Expression.Call(arrExpr, containsMethod, colourPropExpr);
    return Expression.Lambda<Func<T, bool>>(containsExpr, paramExpr);
}


Does any Probability Distribution Functions Exist that can Model this Problem?

Question: I invented these two problems  which can might correspond to a probability distribution - but I am not sure which ones.
Case 1: Suppose there are 5 "hats" : the first "hat" has 10 red balls, the second "hat" has 10 blue balls", the third "hat" has 10 green balls, the fourth "hat" has 10 grey balls and the fifth "hat" has 10 pink balls.
You first select a random number of hats (each hat has a equal probability of being selected) -  and then from these randomly selected hats, you select a random number of balls (within a given hat, each ball has an equal probability of being selected).
Example:

Iteration 1:  First Hat, Fourth Hat - 5 red balls, 2 grey balls
Iteration 2: First Hat, Second Hat, Fifth Hat - 8 red balls, 1 blue ball, 6 pink balls

Case 2:  Suppose there are 5 "hats" : the first "hat" has 10 red balls, the second "hat" has 10 blue balls", the third "hat" has 10 green balls, the fourth "hat" has 10 grey balls and the fifth "hat" has 10 pink balls. There are also 5 "bins" containing 1000 grams of sand.
You first select a random number of hats (each hat has a equal probability of being selected) -  and then from these randomly selected hats, you select a random number of balls (within a given hat, each ball has an equal probability of being selected). Second, you select a random number of "bins" and scoop out a random weight of sand from each "bin".
Example:

Iteration 1: Third Hat, First Bin, Fifth Bin : 2 green balls, 231 grams of sand, 401 grams of sand

Iteration 2: First Hat, Fourth Hat, Fifth Hat, Second Bin, Fifth Bin :  5 red balls, 1 grey ball, 0 pink balls, 31 grams of sand, 891 grams of sand.

My Question: Are there any probability distributions that correspond to Case 1 and Case 2?
For instance, I am guessing that Case 1 corresponds to 2 different hypergeometric distributions and Case 2 corresponds to 2 different hypergeometric distributions as well as a normal distribution?
Does anyone have any thoughts about this?
Thanks!
Answer: As far as I see it has elements of Mixture model:

first case is :  Poison Mixture model
second case is  two different independent mixture models: Poison Mixture model( same as previous case) and Normal Mixture Model (for bins/sand)
Comment: @ Deno : Thank you for your answer! Why is the first one a Poison Mixture?


Steel percussion mallets

Question: I'm going to be striking a variety of unconventional bells varying in material from steel to brass, bronze and aluminium. I wonder if there is anything against using precision mallets with stainless steel heads rather than the more common aluminium, brass or even plastic and wood varieties? Would it be best to use steel only on those bells that I know are of solid steel construction?
Comment: What end product is in mind? A concert, destruction of bells, etc?
Comment: Hah, no I'm hoping the bells will be intact afterwards! It will be for concerts/performance, but light playing / smaller venues, and mic'ed up if larger venues.
Comment: I should add, one concern is whether the sonic characteristics would be radically different with steel compared to brass heads.
Comment: "sonic characteristics" - if I pick my guitar with the meat of my thumb, I get a different tone than if I pick it with a metal pick.  Some might describe the difference as degrees of "mellow".  I suspect a steel vs a wooden mallet will have a similar impact (pun intended) on your bells.
Answer: There are so many variables with mallet percussion:

the (in this case) bells themselves
the mallets: material, size, shape, weight
the impact: position, angle, force, phase

In your comment, you seem to be concerned with both the potential for damage and the sound quality.
Steel (or other metal) heads will have the potential for scratching or otherwise damaging the bells.  Steel is certainly harder than brass, which makes its potential for causing damage greater.  Whether or not damaging occurs will mainly be determined by the impact.
Different mallet material will certainly affect the sound, and whether these changes are acceptable/desirable is really something you (or the percussionist) will have to determine with experience and experimentation.

Steel percussion mallets


How do I programmatically create a node with an entity reference (to an user)?

Question: It is kind of strange because my code creates the node with the referenced user uid in node_field_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node__field_user, so I guess I should insert it there too.
But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.
This is my code:
  $node = Node::create(['type' => 'nodetype']);
  $node->set('title', $username );
  $node->uid->entity = $userId;
  $node->enforceIsNew();
  $node->save();

Comment: Is this about the core base field for the node owner or a user reference field you have added to the content type?
Answer: Set owner $node->setOwnerId($uid);
Set field reference $node->field_user[] = $uid;
Comment: Thanks a lot! Worked perfectly, although I don't really know where is this field_user[] coming from.
Comment: @Rajo – The question title states you want to set a reference field to a user.


How to raise all values to the power of 2, but keep their original sign

Question: How do I raise all values for the vector v = [4,7,-2,9,3,-6,-4,1]to the power of 2, but keep their original sign ?
Comment: Um... squaring a negative number makes it positive. Why do you want to do this?
Comment: Could you add the expected output?
Comment: yes the expected output will be v = [16,39,-4,81,9,-36,-16,1]
Comment: What have you tried?
Do you know how to do this for a single number? (i.e., `-x -> -x^2)?
Do you know how to square a vector of numbers, without keeping the sign bit?
Comment: Cocomac it is a an excercise about modifying vectors
Answer: I like @Sören's method better, but if you prefer not to have to import math for some reason, this will work.
>>> v = [4,7,-2,9,3,-6,-4,1]
>>> result = [x*abs(x) for x in v]
>>> print(result)
[16, 49, -4, 81, 9, -36, -16, 1]

We do x * abs(x) and to keep the sign. If the original number is positive, both x and abs(x) will be positive, yielding a positive answer. If the original is negative, x will retain the original sign, meaning we get a negative.
I use a list comprehension, and then wrap it in int(...) to make it an int again (from a float).
Comment: You can just to `x * abs(x)`
Comment: That won't work for `x == 0`, and it's simpler and likely faster to use a conditional expression to select `1` or `-1` as appropriate for the value of `x`.
Comment: the "int" part make no sense, the abs of an int is an int
Comment: @EdwardPeters Thanks, I've updated it to that. `x == 0` wasn't in the list of cases it needs to support
Comment: @cocomac I like your's, because it doesn't overflow.
Comment: @Copperfield you are fully right. In an older revision I was using division and abs to find the sign. This method is better, but I forgot to remove the int.
Answer: >>> from math import copysign
>>> v = [4,7,-2,9,3,-6,-4,1]
>>> [int(copysign(x*x,x)) for x in v]
[16, 49, -4, 81, 9, -36, -16, 1]

The copysign function basically does what you want: Return the first argument, but with the sign of the second. Except that copysign always returns a float, so if you want ints, you cast them back. (Beware of overflow!)


Proving that Jacobian of Composition is equal to Composition of Jacobians using epsilon-delta

Question: Let us have functions $\mathrm{f}: \mathbb{R}^n \rightarrow \mathbb{R}^m$ and $\mathrm{g}: \mathbb{R}^m \rightarrow \mathbb{R}^k$ such that $\mathrm{f}$ is differentiable at some point $\mathrm{a} \in \mathbb{R}^n$ and $\mathrm{g}$ is differentiable at some point $\mathrm{f(a)} \in \mathbb{R}^n$. Let us denote the Jacobian of $\mathrm{f}$, evaluated at $\mathrm{a}$, as $\mathrm{T_a f}$ and the Jacobian of $\mathrm{g}$, evaulated at $\mathrm{f(a)}$, as $\mathrm{T_{f(a)} g}$.
I am aware that the function composition $\mathrm{g\circ f}$ is differentiable at $\mathrm{a}$ and the Jacobian of $\mathrm{g\circ f}$, evaluated at $\mathrm{a}$, is equal to:
$\mathrm{T_a g\circ f=T_{f(a)} g (T_a f)}$
As we all know, derivatives are defined using the concept of limit, which involves epsilon-delta. When it comes to the chain rule for differentiation of scalar-valued functions, aka when $k=1=m$, I am aware of how to prove it on the epsilon-delta level. However, I have yet to see the same for for differentiation of vector-valued functions - from sources like Rudin (Theorem 9.15 in Principles of Mathematical Analysis) and Apostol (Theorem 12.9 in Multivariable Differential Calculus), they end up using remainder functions without rigorously proving that it fulfills the epsilon-delta condition.
I have decided to take up the task myself and have ran into a roadblock that I'm not sure how to get past. First, let me show you what I've done so far:
We have two situations we can deal with:

there exists a neighborhood around $\mathrm{a}$ such that its image under $\mathrm{f}$ is constant
there does NOT exist such a neighborhood

I have successfully dealt with the first situation, with my proof being as follows:
Let $\delta$ be the radius of the neighborhood around $\mathrm{a}$ where $\mathrm{f}$ is constant. Let $\mathrm{x}$ be a point within this neighborhood Obviously, the following is true:
$0 < \lvert \mathrm{x - a} \rvert < \delta \Rightarrow \mathrm{f(a) = f(x)} \Leftrightarrow \lvert \mathrm{f(x) - f(a)} \rvert = 0 < \lvert \mathrm{x - a} \rvert$
Because $\mathrm{f}$ is constant in this neighborhood, that also means:
$\mathrm{\lvert T_a f(x-a) \rvert} = 0 < \lvert \mathrm{x - a} \rvert$
Now then, if we look at the expression $\mathrm{g(y) - g(f(a)) - T_{f(a)}g(y - f(a))}$, if we define $\mathrm{y:=f(x)}$, the expression becomes equal to $\mathrm{g(f(x)) - g(f(a)) - T_{f(a)}g(T_{a}(x - a))}$. For any $\mathrm{x}$ inside the $\delta$ neighborhood around $\mathrm{a}$, this expression evaluates to $\mathrm{g(f(a)) - g(f(a)) - T_{f(a)}g(\boldsymbol{0})} = \boldsymbol{0} - \boldsymbol{0} = \boldsymbol{0}$. As a result, we have:
$\mathrm{(\forall \epsilon > 0)(\exists \delta > 0)(\forall x \in \mathbb{R}^n):0 < \lvert x - a \rvert <\delta \Rightarrow \lvert g(f(x)) - g(f(a)) - T_{f(a)}g(T_{a}f(x - a)) \rvert = 0 < \epsilon \lvert x - a \rvert}$
This ends the proof for the first situation.
Now moving on to the second situation, which is where I'm struggling:
Because $\mathrm{g}$ is differentiable at $\mathrm{f(a)}$, there is a $\delta_1$ neighborhood around $\mathrm{f(a)}$ where $\mathrm{g}$ is defined.
Because $\mathrm{f}$ is differentiable at $\mathrm{a}$, it is also continuous, and as a result, for any value of $\delta_1$, there must exist a $\delta_2$ neighborhood around $\mathrm{a}$ such that $\mathrm{\lvert f(x) - f(a) \rvert < \delta_1}$. Choose $\delta_2$ so that the image of this neighborhood, under $\mathrm{f}$ is a subset of the domain of $\mathrm{g}$. Then we have:
$\mathrm{(\forall \epsilon > 0)(\exists \delta_2 > 0)(\forall x \in \mathbb{R}^n):0 < \lvert x - a \rvert <\delta_2 \Rightarrow \lvert g(f(x)) - g(f(a)) - T_{f(a)}g(f(x) - f(a)) \rvert < \epsilon \lvert f(x) - f(a) \rvert}$
And this is the roadblock I have yet to overcome. I do not know how to get from the above statement to the below statement:
$\mathrm{(\forall \epsilon > 0)(\exists \delta_2 > 0)(\forall x \in \mathbb{R}^n):0 < \lvert x - a \rvert <\delta_2 \Rightarrow \lvert g(f(x)) - g(f(a)) - T_{f(a)}g(T_{a}f(x - a)) \rvert < \epsilon \lvert x - a \rvert}$
There were two things I thought of but ultimately either cannot work or lead to further dead ends:

I first thought of using the property $\lvert a \rvert < b \Leftrightarrow -b < a < b$. However, we are not dealing with scalars inside the norm here, we are dealing with vectors, so this goes right out the window.
I thought of using the identity $\mathrm{\lvert T_{a}f(x - a) \rvert \leq \lvert f(x) - f(a) \rvert}$. However, I can't break open the norm of sum/difference of vectors, so if use of this identity is necessary, I'm not sure how to use it. It turns out this idea was false to begin with.

This leads me to the following two questions:

Is this a fruitful approach to trying to prove the multivariable differentiation chain rule on the epsilon-delta level/Is the use of asymptotic remainder functions to prove this unavoidable?
If the answer to the above question is yes, what am I missing?

Finally, to anyone who wonders why I do not like the use of remainder functions, it is because I often see them being used as a way to pay lipservice to epsilon-delta but ultimately evade the concept. Considering how fundamental the concept of chain rule is to differentiation, I consider the use of remainder functions to try to "prove" this unacceptable, and I am extremely disappointed that people like Rudin and Apostol would do such a thing. And the reason why I am being very uptight about epsilon-delta is because a lot of wishy-washy Calculus I infinitesimal tricks completely fall apart when dealing with vector-valued functions, and I'm doing this to try to rescue my understanding of this subject.
Comment: There is no such "identity" as "$\mathrm{\lvert T_{a}f(x - a) \rvert \leq \lvert f(x) - f(a) \rvert}$".
Comment: In "$\lvert g(f(x)) - g(f(a)) - T_{f(a)}g(f(x) - f(a)) \rvert < \epsilon \lvert f(x) - f(a) \rvert$", replace $f(x) - f(a)$ by $T_af(x-a)+o(x-a)$.
Comment: If $f$ is constant on a neighbourhood of $a$ then so is $g \circ f$ and that case is trivial. It is also bizarre you considered it in the first place.
Comment: Also, check my answer here: https://math.stackexchange.com/questions/3606106/the-proof-of-several-variable-calculus-chain-rule/3606680#3606680 or here https://math.stackexchange.com/questions/2216797/frechet-derivative-chain-rule/2217002#2217002
Comment: You can find a careful $\delta$-$\eta$-$\epsilon$ proof in Chapter 3 of my *Multivariable Mathematics*.
Answer: Here is a literal translation of my proof of the chain rule in my "Fundamentos de calculo" (in Spanish), which I can post here since I own the rights. In the vector case, $\varepsilon$-$\delta$ method is superseded by topological arguments since we are working not with intervals but with balls. The little-oh notation is precisely this and it is not at all informal as you believe; it really is not the concern of mathematics whether you understand this or not, for her to remain true.
Theorem. Let $U$, $V$ and $W$ three normed spaces, $A$ a subset of $U$ and $B$ one of $V,$ $u$ a point in $A$ and $v$ one in $B$. Suppose $f:A \to V$ is differentiable at $u,$ that $f(u) = v$ and that $g:B \to W$ is differentiable at $v.$ Then, $g \circ f$ is differentiable at $u$ and, also,
$$
D(g \circ f)(u) = Dg(f(u)) \circ Df(u).
$$
Proof. Since $f$ is differentiable at $u$, there are $r_f > 0$ and a function $h \mapsto \tilde\epsilon_f(u; h)$ from $B_U(0;r_f)$ to $V$ such that for all $h \in B_U(0;r_f)$,
$$
f(u + h) = f(u) + Df(u) \cdot h + \|h\| \tilde\epsilon_f(u; h) = v + Df(u) \cdot h + \|h\| \tilde\epsilon_f(u; h),
$$
where $\lim_{h \to 0} \tilde\epsilon_f(u; h) = 0.$ Analogously, for $g$ at $v$ there exist $r_g > 0$ and $\tilde\epsilon_g:B_V(0;r_g) \to W$ such that $\lim_{k \to 0} \tilde\epsilon_g(v; k) = 0$ and that for all $k \in B_V(0;r_g)$
$$
g(v + k) = g(v) + Dg(v) \cdot k + \|k\| \tilde\epsilon_g(v; k).
$$
By virtue of the triangle inequality and the fundamental inequality of linear functions,
\begin{align*}
\|Df(u) \cdot h + \|h\| \tilde\epsilon_f(u; h) &\leq \|Df(u)\| \|h\| + \|h\| \|\tilde\epsilon_f(u; h)\|\\
&= \left( \|Df(u)\| + \|\tilde\epsilon_f(u; h)\| \right) \|h\|.
\end{align*}
As $\lim_{h \to 0} \|\tilde\epsilon_f(u; h)\| = 0$, there exists $\delta > 0$ such that if $h \in B_U(0;\delta)$ then $\|\tilde\epsilon_f(u; h)\| \leq 1.$ Define
$$
r = \dfrac{1}{2}\min\left\{ \dfrac{r_g}{\|Df(u)\| + 1}, \delta, r_f \right\}.
$$
Then, the relation $\|h\| < r$ implies
\begin{align*}
\|Df(u) \cdot h + \|h\| \tilde\epsilon_f(u; h)\| &\leq \left( \|Df(u)\| + \|\tilde\epsilon_f(u; h)\| \right) \|h\| \\
&\leq \left( \|Df(u)\| + 1 \right) \|h\| \leq \dfrac{1}{2} r_g < r_g
\end{align*}
and, therefore, $Df(u) \cdot h + \|h\| \tilde{\epsilon_f(u; h)}$ belongs to $B_V(0;r_g).$ Therefore, for $h \in B_U(0;r)$, one has, by writing $k(h) = Df(u) \cdot h + \|h\| \tilde\epsilon_f(u; h),$
\begin{align*}
(g \circ f)(u + h) &= g(f(u + h)) = g(v + k(h))\\
&= g(v) + Dg(v) \cdot k(h) + \|k(h)\| \tilde\epsilon_g(v; k(h)) \\
&= g(v) + Dg(v) \cdot \Big( Df(u) \cdot h \Big) + \|h\| Dg(v) \cdot \tilde\epsilon_f(u; h) + \|k(h)\| \tilde\epsilon_g(v; k(h)) \\
&= g(v) + \Big( Dg(v) \circ  Df(u) \Big) \cdot h + \Gamma(h),
\end{align*}
where $\Gamma$ is definided by $\Gamma:B_U(0;r) \to W$,
$$
\Gamma(h) = \|h\| Dg(v) \cdot \tilde\epsilon_f(u; h) + \|k(h)\| \tilde\epsilon_g(v; k(h)).
$$
To conclude the theorem, one must show $Dg(v) \circ Df(u)$ is a continuous linear function and that one can write $\Gamma(h) = \|h\| \tilde{\Gamma}(h),$ where $\tilde\Gamma(h) \to 0$ as $h \to 0.$ The first of these two claims is a consequence that the composition of continuous functions is continuous and likewise for linear functions. To see the second, define $\tilde{\Gamma}(h) = \dfrac{\Gamma(h)}{\|h\|}$ when $h \neq 0$ y $\tilde{\Gamma}(0) = 0;$ to see  that $\tilde{\Gamma}(h) \to 0$ as $h \to 0$ we use again the triangle and fundamental inequalities
\begin{align*}
\|\tilde{\Gamma}(h)\| &\leq \|Dg(v)\| \|\tilde\epsilon_f(u;h)\| + \dfrac{\|k(h)\|}{\|h\|} \|\tilde\epsilon_g(v;k(h))\| \\
&\leq \|Dg(v)\| \|\tilde\epsilon_f(v;h)\| + \left( \|Df(u)\| + 1 \right) \|\tilde\epsilon_g(v;k(h))\|,
\end{align*}
by hypothesis, $\|\tilde\epsilon_f(u;h)\| \to 0$ and since $k(h) \to 0,$ we also have $\|\tilde\epsilon_g(v;k(h))\| \to 0,$ then $\tilde\Gamma(h) \to 0.$ $\blacksquare$


Not getting total value of input tags

Question: Why my codes is not getting the total value of each row?, its getting only the first row value.
tried to insert it into .each function, but its not functioning
function calc_total()
{
  total=0;

  $('#po_total_amount').each(function() {
    total += parseInt($(this).val());
  });

  $('#totalPrice').val(total.toFixed(2));

}

get the grand total of each rows.
Comment: [Welcome to StackOverflow](http://StackOverflow.com/tour) - Please read our [ask] page and edit your question to improve it.
Good questions tend to receive quick, better answers from the community.
For starters, Please include a [mcve] to your question.  Otherwise it may be impossible to tell *exactly* where the issue lies.
Comment: Based on what I can see, you're iterating over all elements with the ID `po_total_amount`. But ID's **must** be unique, so you will only ever get one element this way.
Comment: ids are singular....
Answer: You need to select your inputs differently so you can add their total. Id's must be unique so it won't let you .each a single element. If you give them each a class with the same name you can do it like this:

var total = 0;
$('.po_total_amount').each(function() {
  total += parseInt($(this).val());
});

$('#totalPrice').val(total.toFixed(2));

<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="4">
<input type="input" class="po_total_amount" value="90">
<input type="input" id="totalPrice">
Comment: No problem,  As the asker, you have a special privilege: you may accept the answer that you believe is the best solution to your problem.

Not getting total value of input tags