PHP - Curly Bracket Parsing

Question: so I have an array, the array is:
<?php
$config = array('site_name' => 'SomeName');
?>

Now I want to echo it.
<title><?php echo $config['site_name']; ?></title>

But I have seen some websites using:
<title>{site_name}</title>

Is it possible to do so? If so can you help me out?
Comment: Search for a PHP template engine.
Comment: This is template syntax. I guess either smarty or twig.
Comment: no you cant use it by php. You can attain this by using smarty
Comment: you also use  with short_open_tag enabled in php.ini
Comment: Have a look at this https://github.com/bobthecow/mustache.php this may interest u.
Comment: aconrad that was a good one, but I want something like that to shorten my code, plus other's who are suggesting me a template engine, I am making my own......
Comment: This question appears to be off-topic because it is asking for personal support.
Comment: I am not asking for personal support @hakre I am looking for the source of {} brackets so everyone can shorten their code and utilize the code.
Comment: You must have confused things, this is not pure PHP what you're asking about. Which btw. would is documented here: http://php.net/docs - Which brings me to the point that you should might have thought about that not finding the source might be a hint that the source is not where you think it is and this probably isn't PHP even and you should have made that more prominent while asking, otherwise it's just too broad.
Answer: That syntax is not a valid syntax to echo a statement with PHP, it's the smarty framework who uses that, which is nothing but a template engine.

Also, don't confuse that syntax with something like
<title><?php echo "This is a {$title[0]}"; ?></title>

Which is a valid syntax in PHP, but you need to use the curly braces here, as you are echoing an index of an array.. For more information, you can read an answer here..

As you commented that you want to shorten up your codes, than an alternate way to echo in PHP is to use <?= but before that, do have a read here.
Or else, declare a function with shortest name like
function e($string) {
    echo $string;
}

e('Echo This String'); //Or
e($string);

Comment: @user3152750 You are going too fast, learn PHP first...
Comment: @user3152750 Err, I'd recommend you stick with native PHP; template engines for `{replacements}` are slower and often feature-limiting. If you can't do it with native, then you can't do it anyway.
Comment: @user3152750 Am not doubting your knowledge but you are unable to understand the construct here, you are saying that my answer is [incorrect](http://stackoverflow.com/questions/21185360/php-curly-bracket-parsing/21185395?noredirect=1#comment31897636_21185419) but you are asking me to explain you how to build a google search engine, without you learning relevant programming languages
Comment: I am doing this to shorten the code, not to extend the code.
Comment: @user3152750 So where am saying you to even extend your code? I just explained what you asked.. any mistakes?
Comment: He doesn't really need the curly braces there. It's needed when trying to fetch array values inside of double quote strings.
Comment: I want to just fetch the array stuff in braces {} so i dont have to write <?php bla bla you know?
Comment: @user3152750 Am not getting you... I just edited my answer, you can refer that if it helps you or simply ignore :)
Comment: Errrr I simply mean, that I want to replace the text " to just {site_name}
Comment: Er excuse me? I do know PHP, and I am trying to widen my knowledge in PHP day by day..... :(
Comment: ......................... @Mr.Alien

PHP - Curly Bracket Parsing


Copy/Past from vim command-line mode

Question: Is there a way to read (yank) or/and write (paste) to the buffer form the vim's command-line mode ?
I mean beside the norm  command ?
for example:

how can I put the content of register 'a' into line 5, position 6 from the command-line, without using the normal command?
how to store the letters in register 'b' from the current buffer from position (line 3, col 4) till 5, 2 ?
Comment: What you describe is pretty much the purpose of `:normal`. Why not use it?
Comment: @phd, no, because all those are line-wise, which is not what OP wants.
Comment: I think you're looking for commands like [`:delete`](https://vimdoc.sourceforge.net/htmldoc/change.html#:delete), [`:yank`](https://vimdoc.sourceforge.net/htmldoc/change.html#:yank), [`:put`](https://vimdoc.sourceforge.net/htmldoc/change.html#:put).
Answer:
how can I put the content of register 'a' into line 5, position 6 from the command-line, without using the normal command?

The built-in editing-related Ex commands are all line-wise by design so they can't be used for charater-wise edits. They simply don't know anything beyond line numbers. That is the job of normal mode and executing normal mode commands in the command-line is done via :normal.
This would be one way to do what you want with :normal:
:5normal 5l"ap

And this would be a substitution-based alternative:
:5s/\%>6c/\=getreg("a")/

And this would be a vimscript-based alternative:
:call getline('5')->substitute('\%>6c', getreg('a'), '')->setline('5')

Pick your poison.

how to store the letters in register 'b' from the current buffer from position (line 3, col 4) till 5, 2 ?

There is no way to do that with the built-in editing-related Ex commands, for the reason mentioned above.
Just use :normal, that is what it was made for.

Copy/Past from vim command-line mode


How to find a database location on server using phpmyadmin?

Question: I am pretty new to managing servers, right now I have trouble to find the location of our database. I see the DB in phpmyadmin, is there a way to find the real location using phpmyadmin ?
Running ubuntu 12.04 server
Answer: First, get rid of phpMyAdmin. It's just a giant security hole, and doesn't even have a very pretty interface. You'll find that almost no professional DBAs or system administrators will go anywhere near it. It's not even really necessary, since the basics of SQL aren't hard to pick up.
Second, the database files themselves are in MySQL's datadir, so just check that in /etc/my.cnf or ask MySQL where it is.
SHOW VARIABLES LIKE 'datadir';

Comment: I am using the PhpMyadmin only on my private virtual machine, of course I understand that this is a big security risk, but anyway I don't understand why my Question is downvoted without giving me some info why. I am learning.
Comment: You will have to ask the people who downvoted your question. I am not a mind reader!
Comment: Very good questions. I am an amateur server administrator. To be more exact, I am a businessman that manage my own server and write my own code. This question helps me a lot. But this place is full with snobbish full time server administrator that just look down to anyone that doesn't know the basic.


Postfix and Dovecot - No encryption on SMTP

Question: Currently I'm working on my very own mail server but as for now I can't get SMTP up correctly.
I use Dovecot with postfix.
When I try to add my server to my mail client it tells me:
Outgoing: SMTP (my servers address):587, No SSL, Authentification: Normal password
I don't know why I get this result since I thought I had everything set up.
I have no experience with postfix until today so I have no idea what's missing or wrong.
System: fresh Debian 10 x64,
installed postfix, dovecot-core, dovecot-imapd and dovecot-pop3d.
Here is my postfix main.cf: https://pastebin.com/S17jWDQd
Here is my postfix master.cf: https://pastebin.com/W0nynZG6
Here is my dovecot.conf: https://pastebin.com/tMD90Znn
Most of these contents are copied from an iRedMail installation so I think I missed something while copying and modifying for my own use.
Here are my mail logs:
root@bgrsld-mail0:~# tail /var/log/mail.info
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: unsupported dictionary type: pcre (/usr/lib/postfix/postfix-pcre.so: No such file or directory)
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: connect from unknown[192.168.2.110]
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: pcre:/etc/postfix/command_filter.pcre is unavailable. unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: pcre:/etc/postfix/command_filter.pcre lookup error for "EHLO we-guess.mozilla.org"
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: NOQUEUE: reject: CONNECT from unknown[192.168.2.110]: 421 4.3.0 bgrsld-mail0.intern.bdevgw.de Server local data error
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: disconnect from unknown[192.168.2.110] commands=0/0
Jul 17 17:56:27 bgrsld-mail0 postfix/anvil[7456]: statistics: max connection rate 1/60s for (submission:192.168.2.110) at Jul 17 17:53:07
Jul 17 17:56:27 bgrsld-mail0 postfix/anvil[7456]: statistics: max connection count 1 for (submission:192.168.2.110) at Jul 17 17:53:07
Jul 17 17:56:27 bgrsld-mail0 postfix/anvil[7456]: statistics: max cache size 1 at Jul 17 17:53:07
root@bgrsld-mail0:~# tail /var/log/mail.err
Jul 17 17:33:46 bgrsld-mail0 postfix/submission/smtpd[7335]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7444]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7444]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7444]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7451]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7451]: error: unsupported dictionary type: pcre
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7451]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
root@bgrsld-mail0:~# tail /var/log/mail.warn
Jul 17 17:36:31 bgrsld-mail0 postfix/submission/smtpd[7451]: warning: pcre:/etc/postfix/command_filter.pcre lookup error for "EHLO we-guess.mozilla.org"
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: dict_nis_init: NIS domain name not set - NIS lookups disabled
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: unsupported dictionary type: pcre (/usr/lib/postfix/postfix-pcre.so: No such file or directory)
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: unsupported dictionary type: pcre (/usr/lib/postfix/postfix-pcre.so: No such file or directory)
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: unsupported dictionary type: pcre (/usr/lib/postfix/postfix-pcre.so: No such file or directory)
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: error: unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: pcre:/etc/postfix/command_filter.pcre is unavailable. unsupported dictionary type: pcre
Jul 17 17:53:07 bgrsld-mail0 postfix/submission/smtpd[7454]: warning: pcre:/etc/postfix/command_filter.pcre lookup error for "EHLO we-guess.mozilla.org"

Comment: What is your Linux distribution? How did you install Postfix?
Comment: Systeminformation added above the config files. Installed via apt.
Comment: The Postfix `main.cf` tells nothing about how *submission* is configured, as it's configured in the `master.cf`.
Comment: added master.cf to post
Answer: The obvious fix for the error shown is to install the postfix-pcre package to provide that capability. The Mozilla autodetection should then be able to talk to Postfix.
Comment: ok that fixed it. Thanks. Didn't knew what that is and since it's also listed as "warn" I didn't thought it would really matter to work on this [facepalm]


How do I hide the authoring information?

Question: I installed Drupal 8.2.4 and the IceMagic-8.x-1.0 theme.
How do I hide the authoring information on articles?
Answer: Edit the node type, in the "Display settings", there is a checkbox "Display author and date information", turn that off.
Comment: Yes, I think that's what I did. The URL is http://MY_SITE/admin/structure/types/manage/article, then in the vertical tab I chose "Display Settings" and unchecked "Display author and date information". But the author info and date still shows on articles.
I am working with a multisite solution, with only one core Drupal installation. I edited sites.php, created 2 folders, etc., and disabled authoring info on both sites, but it doesn't work on either site.
Can it be a bug of the IceMagic theme?
Comment: Could be, yes. check its node.html.twig template and compare it to the default in the classy theme.
Comment: In      Home > Administration > Structure > Content types > Display Settings  (Display author and date information), I've had already turned it off, but the author and date still show. Even after clearing the cache.
Comment: By the way, ther is an option to make the images responsive in      Home > Administration > Appearance >Appearance settings > (Ice Magic) > Images > Responsive Images, that doesn't work either. I had to edit the styles.css and add  "img { max-width: 100%; height: auto; }". Did you tried it with IceMagic?
Comment: No, not field display settings. *Edit* the node type, then in the vertical tab.
Comment: Thanks! The problem is exactly in that file, on the mbase theme.
It's not a bug, it's a different behavior based on different variables.
I edited it and solved the problem.


Exclude Latest Article From View?

Question: I'm working with Views 3, and I'm trying to figure out how to best accomplish the following scenario:
On my front page, I'd like to have my articles set up as follows:
On the left, a large thumbnail is shown for the latest article. This accounts for the Title, Author, Post date, and a short summary with a comment count.
To the side, I have a block created in Views that would show the previous three articles with smaller thumbnails, author information, post date, summary, and comment counts.
What I need to know is this: How can I set up both Article views so that:
-The view on the left only shows the absolute latest article.
-The view on the right always excludes the latest article from the listing.
Answer: You have to create a view with two displays of type block. Arrange some region or panel method to display them in side by side fashion.
Create view, select its type as node, choose fields and filters according to your requirement.
For View display having latest item:
Click Pager from your view settings and define Items per page as 1 and set sort order Date created/posted as descending.
For View display having next three items:
Click Pager settings and define Items per page as 3 and set Offset as 1 and define the same date order as for the previous view display.
Thumbnails settings:
While selecting your fields particularly selecting image field (must be part of your post's content type) as thumbnail for post, choose image style. The image style are thumbnail sizes and formats. See the interface on example.com/admin/config/media/image-styles to add your custom image forma-tors so that a proper thumbnail can appear on each view display.
Comment: Thanks, guys! That was exactly what I needed to know, it works exactly the way I want it to! :)
Comment: @John if this answer helped you solve your problem, please consider marking the answer as 'accepted'. [How to accept answers](http://drupal.stackexchange.com/faq#howtoask)
Answer: In pager options set offset to 1.
Comment: Nice tweak. +1. Maybe the easiest.

Exclude Latest Article From View?


Relatively prime polynomials

Question: If $f(x)$ is relatively prime to $p(x)$ in $F[x]$ prove that there is a polynomial $g(x) \in F[x]$ such that $f(x)g(x) ≡ 1_F \pmod{ p(x)}$.
Now it has just occured to me that this is a field we are working in and not a ring because we are using an $F$. This is just an assumption, so I don't know if I am correct still. (I don't think it matters in the end.)
My attempt:

Let $g(x)$ be a polynomial in $F(x)$. If $f(x)$ is relatively prime to $p(x)$ then there exists a polynomial $f(x)a(x) + b(x)p(x) = 1_F \mod p(x)$.
But this means that $f(x)a(x) = 1_F \mod p(x)$. Let $a(x) = g(x)$. Done.
Comment: @DonLarynx: If you take your first equality (which is just a congruence), you are assuming what you are trying to prove. You must first have $f(x)a(x)+b(x)p(x)=1_F$. Now mod out by $p(x)$.
Comment: Done, after you have proved the existence of $a(x)$ and $b(x)$.
Comment: In your attempt, everything looks good except that the first equality shouldn't be modulo $p(x)$; it is just an equality.
Comment: @egreg then I have to essentially prove the division algorithm don't I? I don't know if I have time on that for a 10-minute quiz (it may possibly pop up on the quiz).
Comment: @Clayton $f(x) \cong f(x) \mod p(x)$. It's one of the congruence axioms.
Comment: @DonLarynx If that's given as known, then what you did is correct.
Comment: @egreg usually our quizzes have taken one minute to solve (seriously). If what is given as known? (the problem is complete here).
Comment: If the existence of $a(x)$ and $b(x)$ such that $f(x)a(x)+g(x)b(x)=h(x)$, where $h$ is a greatest common divisor of $f(x)$ and $g(x)$, can be used, then you're done.
Comment: @Clayton, I see what you mean. Thank you.
Answer: The existence of an inverse of $f(x)$ modulo $p(x)$ is a direct consequence of the fact that, with the euclidean algorithm, one can prove

for all $f(x)$ and $g(x)$ in $F[x]$, there exists $a(x)$ and $b(x)$ such that $f(x)a(x)+g(x)b(x)=h(x)$, where $h(x)$ is a greatest common divisor of $f(x)$ and $g(x)$.

I use "a" because the greatest common divisor is determined up to a multiplicative constant. Saying that $f(x)$ and $p(x)$ are coprime means that $1$ is a greatest common divisor.
So you're correct, if the quoted theorem can be used in your test.

Relatively prime polynomials


Directed Multigraph or Directed Simple Graph?

Question: I have the following two questions in my book:
Question # 1

Determine whether the graph shown has directed or undirected edges, whether it has multiple edges, and whether it has one or more loops.

Because Graph (7) has multiple edges (as the book says "A Directed graph may have multiple directed edges from a vertex to a second (possibly the same) vertex are called as directed multigraphs") and it also has loops at vertex c and e. Similar is the case with Graph (9). They should both be Directed Multigraphs but the book says that Graph(7) is a directed graph only and Graph (9) is a Directed Multigraph. Why Graph(7) is only a directed graph instead of a directed multigraph?
Question # 2

Describe a graph model that represents whether each person at a party knows the name of each other person at the part. Should the edges be directed or undirected? Should multiple edges be allowed? Should loops be allowed?

I think the graph should be directed because its not necessary that if A knows the name of B then B would also the know the name of A. Moreover, because of this reason I think that the graph should have multiple edge but the answer at the back of the book is different. The book says that the the graph should be directed but it should not have multiple edges. Why is that?
Thanks!
Answer: Read a bit more carefully the definition that your book gives: "A directed graph may have multiple directed edges from a vertex to a second (possibly the same) vertex are called as directed multigraphs."
The key thing to notice here is that the multiple directed edges have the same origin and destination. Thus, in your first graph there is only one directed edge from vertex $c$ to vertex $d$ (and also only one directed edge from $d$ to $c$). So this graph is just a directed graph. On the other hand, in the second graph, there are two edges from $e$ to $d$, and two edges from $b$ to $c$. So this graph is a directed multigraph.
Comment: Thank you Casteels but what about the loop at c in graph(7)? A simple directed graph doesn't have a loop.
Comment: You didn't mention simple in your question, but yes it is not simple because of the loops.
Comment: I didn't mention it because I thought "simple directed" and "directed" graphs are the same thing. Thanks for clearing that!
Comment: No problem. Yeah it can be a bit confusing sometimes because very often writers will say "graph" when they really mean "simple graph". Usually in this case there will be a note at the beginning saying something like "all graphs considered are simple graphs."


NGINX force HTTPS except for some user agents on AWS Elastic Beanstalk

Question: I have a partial NGINX config file that gets pulled into a main NGINX config file automatically by AWS Elastic Beanstalk. I have two instances running, one EC2 web server running PHP and another that's an SQS worker.
I had set up my config file to force HTTPS using:
location / {
    try_files $uri $uri/ /index.php?$query_string;
    gzip_static on;

    return 301 https://$host$request_uri;
}

This worked great for forcing HTTPS, but I was running into issues with both the ELB health monitor failing due to a 301 (expected 200), and the SQS queue also failing due to returning a 301 -- the queue is triggered by a POST from a configured cron job, which seemed to not work with the 301 redirect:
version: 1
cron:
 - name: "schedule"
   url: "/worker/schedule"
   schedule: "* * * * *"

This is using a package that listens for the POST request to that URL and then kicks off jobs.
To fix those issues, I tried this to check for the appropriate headers and turn off the redirect:
location / {
    try_files $uri $uri/ /index.php?$query_string;
    gzip_static on;

    set $redirect_to_https 0;
    if ($http_x_forwarded_proto != 'https') {
        set $redirect_to_https 1;
    }

    if ($http_user_agent ~* '^ELB-HealthChecker\/.*$') {
        access_log off;
        set $redirect_to_https 0;
    }

    if ($http_user_agent ~* '^aws-sqsd\/.*$') {
        set $redirect_to_https 0;
    }

    if ($redirect_to_https = 1) {
        return 301 https://$host$request_uri;
    }
}

This worked for the ELB health check (200), but the SQS worker is still failing, but now with a 404.
The only config that has working correctly on the SQS worker is a stripped down version (which I'm deploying manually right now specifically to the worker):
location / {
    try_files $uri $uri/ /index.php?$query_string;
    gzip_static on;
}

Here is a screenshot of the successful POST request using the above config:

So the question is, how do I set up my config file to ignore the HTTPS 301 redirect for both the ELB health check and the SQS queue without having to deploy separate NGINX config files?
Comment: Look [here](https://serverfault.com/questions/674900/nginx-if-statement-inside-location-returns-404/674901). "If" is evil and should be avoided, because it disrupt normal nginx behavior. Try [map](https://serverfault.com/questions/316541/check-several-user-agent-in-nginx) instead.
Comment: How would I use that in my case? It seems like I would end up with if's regardless of where I check for the UA.
Answer: This is a classic instance of the "If is evil" NGINX scenario. There's a whole page dedicated to explaining how and why using if directives inside the location block can be problematic/give completely unexpected results.
I would recommend using NGINX map for UA routing. Or if you must use the if inside location, at least replace return 301 with rewrite as the latter is much more stable inside location blocks. Best of luck!
Comment: Thanks for the reply. I did previously have `rewrite ^ https://$host$request_uri? permanent;` instead of the 301, but various sites/articles said basically the opposite that you did about rewrite, so I changed it to the return. As for the `map` functionality, how would I use that in my case? It seems like I would end up with if's regardless of where I check for the UA.
Comment: Why do you consider `rewrite` safe in this case? Nginx page tells that only 100% safe things are `return` and `rewrite ... last`. In this case, `rewrite ... last` is not an option since 301 redirect is desired.
Answer: One could use map as follows:
map $http_x_forwarded_proto $proto {
    default 1;
    "~^https$" 0;
}

map $http_user_agent $agent {
    default 1;
    "~*^ELB-HealthChecker\/.*$" 0;
    "~*^aws-sqsd\/.*$" 0;
}

The maps need to be defined in http level in configuration.
Then, in the location, one would have:
if ($proto$agent = "11") {
    return 301 https://$host$request_uri permanent;
}


Compiling PHP 5.1.6 from source - php -v and phpinfo() version discrepancy

Question: I have just bought a VPS running Ubuntu and I need to install the LAMP stack with PHP 5.1.6. The VPS came with no PHP installed (checked this from the shell with php -v) and with Apache/2.2.12 installed. I installed PHP 5.1.6 from source and compiled it with Apache 2.2 (using libapache2-mod-php5), tried a phpinfo() test which worked fine, however, phpinfo() shows the PHP version as 5.2.1 (with JSON enabled), whereas running php-v in the shell shows as 5.1.6. Anyone any ideas what might be happening here? I need to ensure I am running PHP 5.1.6.
Thanks in advance for any help!
Comment: Isn't this a question for SuperUser?
Comment: It's a plain unsupported VPS which I need to configure myself, which is fine, as long as i can get past this issue
Answer: php -v gives you the version of the cli installation of php, while phpinfo will give you the version which got installed as apache module.
If you are not using cli php anywhere, you should be fine with running php scripts off apache.
But ideally you should fix this.
Comment: Thanks s1d. The problem is i need to use version 5.1.6 with apache (for web devt), so i need to reconfigure it. I ran ./configure again this time using "--with-apx2=/path/to/apxs" (which i missed out last time) - but after restarting apache i still have PHP 5.2.1 showing. Do i have to remove the libapache2-mod-php5 module (not sure how to do this other than reinstalling apache) and rerun ./configure?
Comment: I think the issue is this that your apache and libapache2-php5-mod have been installed via ubuntu packages while you have compiled php from source.

When you installed libapache2-php5-mod via apt-get install, it would have taken the relevant php package from the repo as a dependency, as seen in http://packages.ubuntu.com/hardy/libapache2-mod-php5

You will need to uninstall apache, and then install apache from source instead of using the ubuntu repos to do what you wish to do.
Comment: Ah that makes sense, I did use apt-get to install libapache2-php5-mod. Ok, so i need to uninstall apache and reinstall from source, along with all the necessary modules, time to check the docs for how to do that properly!


Como adicionar ao AbstractTableModel um combobox populado por informação do banco de dados?

Question: Gostaria de saber se é possível implementar um combobox em um AbstractTableModel de maneira q o mesmo receba informações diretamente do banco de dados para o preenchimento. se possível alguém poderia me dar um exemplo?
Como sempre usei DefaultTable, eu não entendo muito sobre AbstractTableModel, e por isso da pergunta.
Answer: AbstractTableModel é uma implementação abstrata que serve como base para se criar uma "modelagem" de dados em uma JTable, não tem relação alguma com combos.
Para modelar dados em JComboBoxes, você pode usar a classe DefaultComboBoxModel, que também é uma implementação de modelagem de dados, porém ela é concreta e geralmente atende a maioria das necessidades ao se usar combos, principalmente quando se vai preencher com tipos primitivos e Strings.
Se precisar de algo mais especifico que esta implementação não resolva, você precisa criar sua própria implementação, ou sobrescrever a implementação do método toString() da classe que representará o objeto que populará o combo, depende da complexidade do que se quer fazer.
Nos links abaixo tem alguns exemplos de implementação:

Preencher JComboBox com um objeto
Popular JComboBox com Strings e IDs trazidos do banco de dados

Eu costumo muito utilizar uma implementação genérica que criei, assim não preciso implementar um modelo para cada tipo de objeto criado que vou preencher um combo, mas para que ela funcionar corretamente, seu bean precisa ter o método toString() sobrescrito. Neste link há um exemplo de implementação dela.

Relendo a pergunta, creio que a duvida possa estar relacionada também a como adicionar um combo ao editor de alguma célula/coluna numa tabela, e para isso, você não usará models, pois não se trata de uma alteração do modelo de preenchimento, e sim, da exibição de células da tabela, através da interface TableCellRenderer, que contém os métodos necessários para você criar uma forma personalizada de renderizar as células, e da interface TableCellEditor, que contém os métodos necessários para criar uma forma personalizada de se renderizar a célula quando entrar em modo de edição. Se quiser ler mais a respeito, recomendo os tutoriais oficiais da documentação: How to Use Tables e How to Use Combo Boxes.


How to find silverlight version using google analytics

Question: I have a website which runs on silverlight. I am using google analytics to measure trends and understand user behaviour and I wonder how do i find (1) if user have silverlight pre-installed (2) if silverlight already installed, what version is that(3) If we made user installed silverlight.
I know that Google Analytics can detect flash version by default, how do i make it detect silverlight version as well.
Answer: Dunno if GA will eventually add it in, but until then...
You can grab a helper file called Silverlight.js file from microsoft, to be included on your page. The file gives you easy methods for finding out answers to those questions, and then you would pass record that data using custom variables


Kedro - how to set max_workers when running pipelines with ParallelRunner?

Question: I'm using Kedro version 0.18.7 and python 3.9 in WSL2.
I'd like to run nodes of my pipeline in parallel by running the command kedro run --pipeline <pipeline_name> --runner ParallelRunner. According to the documentation ParallelRunner, it should be possible to define the maximum number of CPU cores to use (using max_workers), but I am struggling to find out how to use this argument. Apparently I cannot just add it to the command like --runner ParallelRunner --max_workers 4.
Does somebody know how to set max_workers for ParallelRunner?
Previous discussions on max_workers are from older versions of Kedro (for example github issue). I guess I need to create a file somewhere in the project directory and write relevant code, something like runner=ParallelRunner(max_workers=4) (cli.py? run.py? settings.py?), but other than that I am lost.
Any tips or guidance would be appreciated.
Answer: One way that can work is by creating a kedro session to run your pipeline.
ref: https://docs.kedro.org/en/stable/kedro.framework.session.session.KedroSession.html#kedro-framework-session-session-kedrosession
from kedro.framework.session import KedroSession
from kedro.framework.startup import bootstrap_project
from kedro.runner import ParallelRunner
from pathlib import Path

bootstrap_project(Path("<project_root>"))
with KedroSession.create() as session:
    session.run(pipeline_name=<pipeline-name>, runner=ParallelRunner(max_workers=4))

Comment: Thanks a lot! Your solution worked for me with just a minor modification:

```session.run(pipeline_name=, runner=ParallelRunner(max_workers=4))```


HTML close tag print in my page

Question: Data or value in $description from database is

Henry

My HTML Code
<input type="textbox" id="textbox" value=""/>
<input type="hidden" id="hidden" value="<?php echo $description; ?>"/>

Output :
If the code be
<input type="hidden" id="hidden" value='<?php echo $description; ?>'/>

Its working fine !..Any one please tell me the issue ?
Comment: Your quotes are conflicting. Shouldn't you escape the HTML code as well?
Answer: You are trying to have HTML code inside the value of a hidden input in a form? That doesn't sound right.
If you need to keep it as it is, you should at least use htmlentities to make it a string:
<input type="hidden" id="hidden" value="<?php echo htmlentities($description); ?>"/>

An example:
<?php
$str = "A 'quote' is bold";

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>

Answer: look at the different between " and ':
if your code is :
 $description =
Henry

and
 <input type="hidden" id="hidden" value="<?php echo $description; ?>"/>

so it's actually means
  <input type="hidden" id="hidden" value="
Henry
"/>

and the " that before the url closes the "value", so the value is actually -
  value="
<a href="

so try to use ' instead of " on the url (google) OR in the value (not both).
Answer: Your code becomes like this...
<input type="hidden" id="hidden" value = "
 Henry
 "/>

You can divide this as...
<input type="hidden" id="hidden" value = "

Henry

"/>
That's how you get Henry"/>
Answer: Here comes 2 issues,

First of all use htmlentities to convert all applicable characters to HTML entities.
htmlentities($description);

And Its fair to use Single quote instead of double quotes. Ref link

By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39). Single quote marks can be included within the attribute value when the value is delimited by double quote marks, and vice versa
Answer: This is how your browser sees the code:
<input type="textbox" id="textbox" value="
Henry

"/>

See how the double-quotes don't make sense?
If you want to keep double-quotes you need to go with htmlentities.
$description = htmlentities($description);

<input type="hidden" id="hidden" value="<?php echo $description; ?>"/>

Also, your link "www.google.com" will point to a page called www.google.com RELATIVE to your directory. Be sure to use ABSOLUTE path: http://www.google.com
Answer: A simple replace in here like this

Henry

or like this
<input type="textbox" id="textbox" value=""/>
<input type="hidden" id="hidden" value='<?php echo $description; ?>'/>

but not both should do the trick.
Answer: http://php.net/manual/en/function.strip-tags.php
Try this:
div>Henry

<input type="textbox" id="textbox" value=""/>
<input type="hidden" id="hidden" value='<?php echo strip_tags($description); ?>'/>

HTML close tag print in my page


Como fazer a sombra em um texto

Question: Bom dia, em um projeto que estou desenvolvendo ele tem um tipo de "sombra" para deixar um texto branco mais visível dentro da imagem, o problema é que já tentei ambos Text-Shadow e Box-Shadow na div do texto mas não se tem o resultado esperado, o Text conseguiu colocar uma sombra mas uma sombra não tão destacada.
Gostaria de uma ajuda em como proceder, eis abaixo a imagem do Wireframe do site, o HTML, e o CSS.
Wireframe:

.item-segmento {
  text-align: center;
  margin: 25px 0;
  overflow: hidden;
}

.item-segmento span {
  transition: all .5s ease;
  color: #FFF;
  font-size: 18px;
  text-transform: uppercase;
  text-shadow: 0px 0px 20px #000000;
}

.img-segmento {
  height: 300px;
  margin-bottom: 10px;
  position: relative;
}

.img-segmento>img {
  object-fit: cover;
  width: 100%;
  height: 100%;
  border-radius: 100%;
}

.img-segmento .segmento-titulo {
  transition: all .5s ease;
  position: absolute;
  top: 5%;
  left: 5%;
  width: 90%;
  height: 90%;
  display: table;
  color: #FFF;
}

.item-segmento .segmento-titulo>div {
  color: #FFF;
  vertical-align: middle;
  display: table-cell;
}

          Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Comment: Alex tem com vc editar a pergunta e colocar uma imagem de como vc gostaria que ficasse? Pq pelo que parece o text-shadow já está funcionando, só não deu para entender o efeito que vc pretende.
Comment: Anderson o jeito que eu quero que fique, é justamente igual a o que está no Wireframe.
Answer: Tente
text-shadow: 2px 2px #FF0000;

Answer: Use o atributo em seu css
para texto use
text-shadow: 0 0 3px #000;

para divs use
box-shadow: 0 0 5px #000;

é bom você da uma estudada sobre esses atributos para facilitar na edição de seus estilos.
Answer: Acho que a melhor forma para esse efeito não é com text-shadow e sim colocando um radial-gradiente por traz do texto.

Na classe .img-segmento .segmento-titulo vc coloca o gradiente no fundo, indo do preto para transparente. Depois disso vc coloca o text-shadow menor para dar mais definição nas letras. Vc pode controlar o tamanho e a cor do radial-gradiente nessa propriedade
background-image: radial-gradient(at center, rgba(0,0,0,0.95) 0%,transparent 50%, transparent 50%);
Ficaria assim o ajuste.

  .item-segmento {
    text-align: center;
    margin: 25px 0;
    overflow: hidden;
  }

  .item-segmento span {
    transition: all .5s ease;
    color: #FFF;
    font-size: 18px;
    text-transform: uppercase;
    text-shadow: 0px 0px 3px #000000;
  }

  .img-segmento {
    height: 300px;
    margin-bottom: 10px;
    position: relative;
  }

  .img-segmento>img {
    object-fit: cover;
    width: 100%;
    height: 100%;
    border-radius: 100%;
  }

  .img-segmento .segmento-titulo {
    transition: all .5s ease;
    position: absolute;
    top: 5%;
    left: 5%;
    width: 90%;
    height: 90%;
    display: table;
    color: #FFF;
    background-image: radial-gradient(at center, rgba(0,0,0,0.95) 0%,transparent 50%, transparent 50%);
  }

  .item-segmento .segmento-titulo>div {
    color: #FFF;
    vertical-align: middle;
    display: table-cell;
  }
<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />

          Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Comment: Funcionou perfeitamente. Você tem meus sinceros agradecimentos amigo, abraço!
Comment: Fico feliz em ter ajudado
Answer: Aparentemente o text-shadow está funcionando, se não gostou do resultado eu recomendo você utilizar filtros, como no exemplo:

Na segunda imagem eu apenas utilizei o filter: brightness(60%);, assim o texto fica mais visível.

Como fazer a sombra em um texto


Error 500 on accessing update.php

Question: Long ago I got a message about updates to my modules. I've updated the modules.
But I received a message to update the database.
I want to run the update.php script but I encounter the following error message:

Server error.
The website encountered an error while retrieving http://MYSITE.COM/update.php. It may be down for maintenance or configured incorrectly.
  Here are some suggestions:
  Reload this webpage later.
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

I do not remember which modules got updated.
Please help me.
Comment: Can you have a look at your apache error logs in order to detect what the problem could be and post the error message in your question ?
Answer: The errors output to Apache are often somewhat cryptic.
You probably want to check the Drupal Reports page, dblog, and the Apache logs.
This sounds like one of the new updates has a problem in the .install or cannot be loaded (permission problems, although that comes proper from Drupal, I never had that problem on an upgrade.)
To test whether the PHP code is invalid, you can run
 php <filename>

The update.php will generate some errors, but it should not tell you it cannot parse it. All the module .install should not generate any errors (a very few modules have code outside functions and those will generate errors, but again no syntax error.) Those syntax error are reported by Apache.
Answer:
Make sure to be logged in as user 1 before going to update.php.
Make sure update.php is in the drupal root directory.
Make sure update.php has correct permissions such as 755. (Credit arjan)

chmod 755 update.php

Make sure there aren't any .htaccess rules denying access to update.php

grep update .htaccess

I usually install drush and run updb in order to run all outstanding updates.
Comment: update.php is in the drupal root directory.but, how to check denying access by .htaccess?
Comment: I would take Letharion's advice and verify the error log before reading through the sites .htaccess file. If you still want to verify the htaccess file I would start by looking in the drupal root directory for a file named .htaccess and search through for any lines referencing update.php
Comment: Another idea is to check the file permissions of the update.php (and the document root folder). For example, if your document root folder has overly permissive settings (like 777) you often get a 500 internal server error.
Answer: First of all, in the future, always take backups, of both your code, and your modules, prior to updating, so you can easily revert in this type of situation.
Error 500 means that your webserver attempted to parse the code in your update.php file, but failed. The first thing you need to do, is check your servers error log, and find all error messages that are timestamped with the time of your last attempt to execute the script. If you don't know where the logs are, you need to ask your hosting provider.
Regardless of the error message, it could be worth replacing the files in your Drupal install with a fresh set. Download the latest version of your major Drupal version, and copy your sites directory over there. This could fix the problem for example if either your update.php file, or others that it depends upon, has become corrupted somehow.

Error 500 on accessing update.php


How do I remove the install files for Server 2008 SP1

Question: Windows 7 SP1 allows the user to utilize the "Disk Cleanup" utility to remove unused backup files for uninstalling the service pack.  How do I do this in Server 2008 R2?
Answer: The easiest solution is to use the dism utility:
DISM /online /cleanup-Image /spsuperseded
Comment: On a side note, if you want to install the desktop cleanup tool on W2K8 you need to install the Desktop Experience feature.
Comment: that is definitely the other way to go.


Room Android - Array of float, integer, double,.... - You can consider adding a type converter for it

Question: I'm just begin with Room-Android.
I try to persist one of my model which one of the fields is an array:
float[] values;

I got this error at the compilation:
Error: Cannot figure out how to save this field into database.
You can consider adding a type converter for it.

I created a type converter:
public static class ConverterFloatToString {

    @TypeConverter
    public String JSONArrayfromFloatArray(Float[] values) {
        JSONArray jsonArray = new JSONArray(Arrays.asList(values));
        return jsonArray.toString();
    }

    @TypeConverter
    public float[] JSONArrayToFloatArray(String values) {
        try {
            JSONArray jsonArray = new JSONArray(values);
            float[] floatArray = new float[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                floatArray[i] = Float.parseFloat(jsonArray.getString(i));
            }
            return floatArray;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

and i assigned to the field:
@TypeConverters(ConverterFloatToString.class)
float[] values;

But i still get the same error.
Cannot figure out how to save this field into database.
You can consider adding a type converter for it.

What is wrong please?
Answer: Ok i made a mistake in my type converter.
JSONArrayfromFloatArray(Float[] values) -> JSONArrayfromFloatArray(float[] values)

And i changed my converter to this:
public static class ConverterFloatToString {

    @TypeConverter
    public static String JSONArrayfromFloatArray(float[] values) {
        JSONArray jsonArray = new JSONArray();
        for (float value : values) {
            try {
                jsonArray.put(value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonArray.toString();
    }

    @TypeConverter
    public static float[] JSONArrayToFloatArray(String values) {
        try {
            JSONArray jsonArray = new JSONArray(values);
            float[] floatArray = new float[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                floatArray[i] = Float.parseFloat(jsonArray.getString(i));
            }
            return floatArray;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

But i'm not fan of this solution, with these conversions an error could happen... If you have better solution i take it ;)


Recurrence relation for number of ternary strings that contain two consecutive 2s

Question: Q: A string that contains only 0s, 1s and 2s is called a ternary string.
Find a recurrence relation for the number of ternary strings of
length n that contain two consecutive 2s.
I don't really understand the question, can someone help me?
Comment: Funny that this is the [second](https://math.stackexchange.com/questions/2721200/clarification-on-recurrence-relation) [duplicate](https://math.stackexchange.com/questions/2721152/ternary-string-finding-recurrence-relation) asked within an hour.
Answer: The question means: if $T_2(n)$ is the number of strings of length $n,$ which contain two consecutive twos then find some function $f$ such that $T_2(n) = f(T_2(n-1), \dotsc, T_2(1)).$
Answer: You define $A(n)$ as the number of ternary strings of length $n$ that contain two $2$s in a row.  If you didn't have the restriction there would be $3^n$ ternary strings of length $n$.  However, $A(0)=A(1)=0$ because there isn't room for two $2$s in a row.  $A(2)=1$ because the only length $2$ string that contains two $2$s in a row is $22$.  You are expected to find an equation of the form $A(n)=aA(n-1)+bA(n-2)+$ maybe some more terms by thinking about how you can form a string of length $n$ that has two $2$s.  One way is to start with a string of length $n-1$ that already has two $2$s in a row and append any digit.
Comment: Somone told me that equation is $$A(n) = 2A_{n-1}+ 2A_{n-1} +3^{n-2}$$, but why $A(n) = 2A_{n-1}$?


What differences are between $\mathbb{E}^n$ and $\mathbb{R}^n$

Question: What differences are between the two notations $\mathbb{E}^n$ and $\mathbb{R}^n$?
Do they represent/define the same  space set with the same structure(s)?
Thanks and regards!
Comment: They're the same object.  Usually $\mathbb E^n$ has the implication of interpreting it as a geometric object -- Euclidean space.  $\mathbb R^n$ tends to be a little more flexible in its interpretation but sometimes one might think of it just as a vector space over $\mathbb R$, so there is a chosen point in the space called the origin -- this point you basically forget about when thinking about $\mathbb E^n$.
Comment: Define what you mean by *space*.
Comment: @lhf: I mean a set with some structure(s).
Answer: In my experience $\mathbb{E}^n$ tends to refer to Euclidean $n$-space in the context of a metric space - in particular when comparing to other metrics you could put on the same set (for example, a hyperbolic metric).  $\mathbb{R}^n$ refers to $n$-space under pretty much all other contexts - as a topological space, a vector space, a set, an abelian group, or any other situation where it's not important to distinguish between the standard Euclidean metric and other metrics on $\mathbb{R}^n$.
Answer: I am not sure if this is standard notation, but if an author distinguishes between $\mathbb{R}^n$ and $\mathbb{E}^n$, the former may refer to the real $n$-vector space, whereas the latter also include the structure of an inner product space.
The Wikipedia article seems to agree with this.
Answer: In my experience $R^n$ is a model for $E^n$. $E^n$ is the axiomatic description of Euclidean space, while $R^n$ is a particular model, i.e., it satisfies the axioms of Euclidean space.
Comment: Thanks! (1) This reply seems consistent with http://planetmath.org/encyclopedia/EuclideanVectorSpace2.html . (2) I was wondering what the axiomatic description of Euclidean space is? Is the definition of dot product part of it? Does it require the underlying set to be an algebraic structure so that the dot product can make sense?
Answer: Tim: I think:
PlanetMath: Euclidean vector space
should also help. I was thinking more of $R^n$ more as a choice of coordinates for $E^n$, than as a model
Comment: Thanks! I guessed you are the same gary replied earlier. (1) In the link you gave, $\mathbb{E}^n$ is defined as a metric space, I was wondering how to understand a choice of coordinates for a metric space $\mathbb{E}^n$? (2) By "a model for $\mathbb{E}^n$" here and earlier, do you mean  an example of $\mathbb{E}^n$?


Equality of Real Numbers

Question: Is the following statement provable from the axioms of $\mathbb{R}$?
If $\forall \epsilon>0$, $|r-s|\leq \epsilon$, then $r=s$.
Comment: Which axioms are you referring to?
Comment: Something like this: http://people.reed.edu/~davidp/112/handouts/axioms.pdf
Comment: This will become easier once you don't consider the superfluous $=$ in the $\leq$.
Comment: So the axioms are the axioms for a complete ordered field.
Comment: You might also want to consider moving the "if" past the quantifier.
Answer: Yes. Suppose $r \neq s$ for contradiction. Then $r - s \neq 0$ and take $\epsilon = |r - s|/2 > 0$.
Answer: yes, it should be. I would try it in the following way:
Assume that $r \neq s$ and define $\epsilon := \frac{|r-s|}{2}$ . Then we have $\epsilon >0$ and $|r-s| > \frac{|r-s|}{2}$ , by contraposition we have a proof.
I think that it is well-known that the stuff that i used can be derived from any kind of axioms for the real numbers.

Equality of Real Numbers


Conditonal Density Function

Question: $$f_{X,Y}(x,y)= \begin{cases}
   (x-y)   & 0 \lt x \lt 1, & -1 \lt y \lt 0 \\
   0       & \text{elsewhere}
  \end{cases}$$
How can I find  the conditional density function $Y$
$$f_Y(y | X \le0)$$
Comment: Since apparently $f_{X,Y}(x,y) =0$ for $x \le 0$, this may not be a meaningful question
Comment: Yes I know. Actually that is why I asked. What do we say about it? Do we say "The conditional density does not exist"?
Answer: The conditional density for $f_Y$ conditioned on $X < 0$ is not well defined because the event $X<0$ can never happen.

Conditonal Density Function


How to use Equal in models passed to view

Question: I am having to use if/else statements to output a currency value tied to a selection the user makes. Something like:
@if (Model.ProcessingRadioButtons.Equals("Standard"))
{
    @Html.DisplayFor(m => m.priceProcessingStandard)
}
else if (Model.ProcessingRadioButtons.Equals("Expedited"))
{
    @Html.DisplayFor(m => m.priceProcessingExpedited)
}
else if (Model.ProcessingRadioButtons.Equals("Urgent"))
{
    @Html.DisplayFor(m => m.priceProcessingUrgent)
}

But it is not displaying anything based on the radio button I select, so I know that the if/else if statements are wrong. I turned the last else if into an else and took out the (Model.ProcessingRadioButtons.Equal("Urgent")) and it displays 500 (see below for price entities).
This is the enum for the radiobutton:
public enum Processing
{
    Standard,
    Expedited,
    Urgent
}

And the radio button entity (using helpers to accomplish the radio button):
public Processing? ProcessingRadioButtons { get; set; }

These are the entities for price:
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceProcessingStandard = 0;

[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceProcessingExpedited = 250;

[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal priceProcessingUrgent= 500;

Any guidance?
Answer: If ProcessingRadioButtons is an enum you need to compare to that - not to a string. Try ...   .Equals(Processing.Standard) instead.
Comment: Doesnt matter to me. As far as I can see we both suggested the same thing, with different flavors of equality comparisons only. The display of the currency symbol doesn't have to do with the if-statement, but with how the DisplayFor-function is used. Glad it worked out for you though!
Comment: Although your answer is correct and you answered first, gave credit to Romias. In both instances I had to "Resolve" the namespace issue with using `Processing`, in which case its `Namespace.ViewModels.MyData.Processing`. But your solution would not display the currency sign `$` in the view and I am not sure why.
Comment: http://stackoverflow.com/questions/9797715/how-can-i-sum-two-different-selections-passed-to-model. Having started the question then getting caught up at work I forgot to ask the second part of my question (note that I changed the title here)
Answer: Are you sending a model with the ProcessingRadioButtons property set?
Aside that, why not using:
@if (Model.ProcessingRadioButtons == Processing.Standard)

it is simpler and don't relies on magic strings.
Comment: Thanks. Your solution allows the currency sign `$` to display. Not sure why, otherwise both answers are correct but yours is more succinct.
Comment: Any thoughts as to why I have to "Resolve" `Processing` to be `Namespace.ViewModels.MyData.Processing`? I have the `@using` statement obviously.
Comment: instead of placing the "@using" statement, you can simple use the full qualified name... in your case "Namespace.ViewModels.MyData.Processing"... and si if that is the correct one, and the move it to the @using.
Comment: http://stackoverflow.com/questions/9797715/how-can-i-sum-two-different-selections-passed-to-model. Having started the question then getting caught up at work I forgot to ask the second part of my question (note that I changed the title here)


Rule of Thumb for minimum length of time series for AR(1) estimation

Question: I have a data set of 350 points, I want to estimate the lag 1 auto correlation for different sub-sets of the data.
More precisely I want to take non overlapping windows of length 1,2,3....n and calculate the auto correlations of these sub-sets. So for n equal to 2 I take every second observation similarly for n=3 I take every third observation and so on.
Just wondered roughly what the maximum value of n I can realistically work with? Even with n=10 I'm down to 35 observations.
Kind Regards
Baz
Answer: Strictly speaking, it depends on the signal/noise ratio in your dataset. The smaller the variance of the white noise component, the fewer observations one needs.
Note also that all you need to estimate ACF for AR(1) is the autoregression coefficient, $\phi$, because the correlation between points $h$ time steps apart is equal to $\phi^h$. That is, if you assume AR(1) for the original process you don't need to do any subsetting to estimate autocorrelations.


numpy - efficiently filter select random samples with stochastic constraint

Question: I want to get N random samples with numpy, filtered so that a criteria is met. I'm unhappy with my current implementation; it is too slow for large values of N (say 100,000). How can I more efficiently filter these samples to meet the condition that an associated standard uniform random samples will be less than f/g? There has to be a faster way to implement this code.
import numpy as np
from scipy.special import gamma
import matplotlib.pyplot as plt
def f(x): return 1. / gamma(3) * x * np.exp(-1 * x)
lambd = .2
c = 1 / lambd / gamma(3) * (2./(1-lambd)) ** 2 * np.exp(-1 * (1 - lambd) * (2. / (lambd - 1)))
def g(x): return c * lambd * np.exp(-1 * lambd * x)
x = np.linspace(0, 50, 1000)
samples = []
N = 100
while len(samples) < N:
    randou = np.random.uniform(0, 1)
    randoh = c * np.random.exponential(0.2)
    if randou <= f(randoh) / g(randoh): samples.append(randoh)
plt.hist(samples, 100, normed=True, label='Simulated PDF')
plt.plot(x, f(x), label='True PDF', lw=2)
plt.xlim(0, 10)
plt.show()

I also tried to generate the samples in one go then filter those in a while loop, but I'm not sure how much faster this method actually is:
samples = np.random.uniform(0, 1, 100000)
hsamps = c * np.random.exponential(0.2, 100000)
N = 100
idx = np.array([True, False])
while len(idx[idx==True]) > 0:
    idx = samples > ( f(hsamps) / g(hsamps))
    samples[idx] = np.random.uniform(0, 1, len(idx[idx==True]))
    hsamps[idx] = c * np.random.exponential(0.2, len(idx[idx==True]))

Answer: To take advantage of NumPy's speed, you'll want to work with large arrays instead of individual scalars processed in a loop. So for example, you could generate N samples like this:
    randous = np.random.uniform(0, 1, size=N)
    randohs = c * np.random.exponential(0.2, size=N)

and then select those that pass your filter like this:
    mask = randous <= f(randohs) / g(randohs)
    return randohs[mask]

The only problem is there is no guarantee that randohs[mask] has the desired number of values (or any values at all). So we might have repeat this until we generate enough samples:
while len(samples) < N:
    randohs = generate_samples()
    samples.extend(randohs)
samples = samples[:N]

Despite using a while-loop, this will still be far faster than generating samples one at a time.

import numpy as np
from scipy.special import gamma
import matplotlib.pyplot as plt

def f(x):
    return 1. / gamma(3) * x * np.exp(-1 * x)
def g(x):
    return c * lambd * np.exp(-1 * lambd * x)

def generate_samples(N=10**5):
    randous = np.random.uniform(0, 1, size=N)
    randohs = c * np.random.exponential(0.2, size=N)
    mask = randous <= f(randohs) / g(randohs)
    return randohs[mask]

lambd = .2
c = (1 / lambd / gamma(3) * (2./(1-lambd)) ** 2
     * np.exp(-1 * (1 - lambd) * (2. / (lambd - 1))))
x = np.linspace(0, 50, 1000)

samples = []
N = 10**5
while len(samples) < N:
    randohs = generate_samples()
    samples.extend(randohs)
samples = samples[:N]

plt.hist(samples, 100, density=True, label='Simulated PDF')
plt.plot(x, f(x), label='True PDF', lw=2)
plt.xlim(0, 10)
plt.show()


Laravel8 Has One Of Many

Question: I'm relatively new to Laravel 8 and I have problem figuring what should I do when I need a relationship Has One Of Many
In the doc of Laravel 8 It's not very well documented.
My User can have only one Job.
I have a tables Jobs where I list all available Job
{ id, name, timestamps }
Should I create a job_id in the User table to store the id of the Job
or
Should I use a Many To Many with a job_user table
Is there a better way to create a Has One of Many relationship.
Comment: @PalakJadav If I understand right in the user table I add job_id and in the user model I create a hasone relationship. Will I be able to access the job->name from the User model
Comment: If I understand your question properly you just need `hasOne()` relationship with a foreign key in one of the tables.
Comment: in the user table you need to store job_id and use hasOne() relationship
Comment: yes you will @MathieuB
Answer: you relation is quite simple:
Job hasMany users
User hasOne Job
so, in the users table you should add job_id and link it to jobs table.
  public function up()
    {
        Schema::table('users', function (Blueprint $table) {
               $table->unsignedBigInteger('job_id');
               $table->foreign("job_id")->references('id')->on('jobs');
        });
    }

and make sure this migration comes after creating both users and jobs tables.
according to Laravel doc,the relation should be setup like this:
in User model:
class User extends Authenticatable
{
   public function job()
    {
        return $this->belongsTo('App\Models\Job', "user_id");
    }
}

and for Job model:
class Job extends Model
{
   public function users()
    {
        return $this->hasMany('App\Models\User', "user_id");
    }
}

Comment: since User can have only one Job, there is no many to many
Comment: Sound good but this also need a Pivot Table or not.
Comment: pivot table is needed only for many to many relations
Comment: In the User Modal in the Job function I user "hasOne" instead of belongsTo. Any tought on this. return $this->hasOne(Job::class,'id','job_id');

Laravel8 Has One Of Many


Practice advice for a fledgling clarinetist?

Question: I guess calling myself a clarinetist is an overstatement, but the clarinet is definitely something that I want to get better at and more comfortable with. Truth be told, I hadn't always taken the clarinet, or music in general seriously, and as a result I missed a lot of opportunities when it came to having a better understanding of it. This is something I definitely regret, and I want to make it right. However, with no real guide or tutor, I'm not sure where to start, and I constantly feel out of my depth. I know this is a somewhat broad topic, at least when it comes to music, but I generally want to get better at understanding written music, and developing a better sense of rhythm. So I guess any resources would be helpful, hopefully this request doesn't come across as too vague.
Thanks in advance,
Answer: I would recommend two things, in order of priority. Neither are clarinet specific.

If at all possible, get a teacher. Even if you just take a couple of lessons. It'll help to get you on the right track when it comes to basic technique. Wind instruments can be a little harder to start out on than keyboard or guitar.
Join a band. It's important for a few reasons. You'll get motivation to practice, the opportunity to observe other more experienced players up close, and exposure to music. In my opinion, the best way to learn and understand music is to play a lot of it. Sure, you'll be out of your depth at the start. Give it a go. You might surprise yourself.
I'm part of a program that involves multiple concert/wind/marching/big bands. That includes one for kids who have been playing for two hours, and one at the other end of the scale. We did have a program for adult beginners at one stage, although it's not currently active. See if you can find something similar.
Comment: Both, obvious, sound reasons. Once in a band, he'll find friends with whom he can play separately, who will show new things, etc. etc.+1
Answer: You need to get a teacher, who'll probably stress the following items.
1) Be obsessive about maintaining good posture. if you dont', you can't ...
2) be obsessive about proper breathing and diaphragm control.  Make long tones part of every practice session.
3) You start playing a note with a release, not a build-up of control.  That is, you need to have inhaled, set your abdomen up, put your tongue onto the reed, and have air pressure applied.  The note starts when you take your tongue off the reed.
There's lots more, of course, but I always viewed those as critical to producing proper tone and pitch support.
Answer: I know this was said already, but DEFINETLY try to get a teacher. It's not always possible- I'm trying to find a flute teacher myself, but there aren't any in my area. Or, if that's impossible, try to play in a group or a band. Other people can help keep you motivated.
Get a few different music books. I recommend Essential Elements for complete beginners. If you're past that stage, I can't really give you a name,(since I suck so far :) Go to your local music shop and skim through different books. Try to have more than one, as they will offer a broader spectrum of material.
You can watch video lessons on YouTube. I know there are teachers who post flute lesson videos, there must be something like that for clarinet too. Video lessons are, of course, a poor sibstitute for a real human being, but they're better than nothing.


Finite group of two generators

Question: My question is simple :
Any finite group of two generators is cyclic, semidirect sum, or direct sum ?
Answer: None of the above.
A group generated by two elements is not necessarily cyclic...That requires that a group be generated by one element.
Consider, now, the dihedral group $D_8$, which is generated by two elements. It isn't cyclic and it can't be represented as a (non-trivial) direct product.
Nor is it necessarily a semidirect product. As Dan suggests: consider the alternating group $A_5$ which can be generated by two elements.
Answer: No. The group $A_5$ is generated by $(123)$ and $(12345)$. It isn't cyclic and cannot be represented as a nontrivial semidirect product, let alone a direct product.
Answer: Every symmetric group $S_n$ is generated by two elements $(1,2,\ldots,n)$ and $(1,2)$. Every group is embedded into a symmetric one. So the structure of groups with two generators can be arbitrarily complicated.

Finite group of two generators


How to correctly create a date condition using moment js

Question: There is a table with data and dates. Please help me to make a correct condition so that when it is triggered, the date will be coloured in different colours.
The table has a Deadline column. I need the date to be colored red 5 days before the deadline, and gray after the date has passed. In other cases it is black. All in all I'm not really getting it right. The date in the column is written in this order 2023-02-01
moment(currentRow["Deadline"]).fromNow() >= "in 5 days"?'#f50202' : moment(currentRow["Deadline"]).fromNow() > "in 0 days"?
'#0d0d0d' : '#999999'

Tried working with a simple condition if the deadline date is less than the current text is greyed out.
I can't find a solution to the more complex condition yet.
Answer: moment's fromNow method returns a string, so you are comparing strings, not relative times.
The >= operator will compare the strings character by character until it reaches different characters, then returns the result of that comparison. So "2 hours ago" >= "1 year ago" will return true when you might expect it to return false. Similarly "in 5 minutes" >= "in 4 years" will also return true.
What you need is something like:
moment(currentRow["Deadline"]) >= moment().add(5, 'days')

or, if you want to just compare the date and ignore time:
moment(currentRow["Deadline"]) >= moment().add(5, 'days').startOf('day')

Note that if currentRow["Deadline"] does not resolve to a format understood by moment.js, you should also include the format so that it is parsed correctly, otherwise it will fall back to implementation dependent heuristics for parsing.
Comment: Thank you very much for your reply.
Your first option works.
There is another problem though, I need the deadline date, which is later than today, to be greyed out. It is still coloured red. Can you tell me how to do it?
Conditionally there is a date 2023-01-05 it should be colored in gray because it is later than today. And date 2023-02-08 continues to be red until 2023-02-08 is on the calendar.
Comment: You just use similar code for other parts of the condition, so something like `moment(currentRow["Deadline"]) >= moment().add(5, 'days')?  : moment(currentRow["Deadline"]) >= moment().startOf('day')?  : `. So if the date is 5 or more days in the future, it's green. If it's 0 to 4 days in the future, it's red. Otherwise, it must be in the past so it's grey.


Diferenças entre formas de referenciar um namespace

Question: Eu gostaria de entender porque em alguns exemplos de códigos, as pessoas importam as classes da seguinte forma:
use \Firebase\JWT\JWT;

e não apenas:
use Firebase\JWT\JWT;

Existe alguma diferença em iniciar com uma "\"?
Nos meus testes para as minhas classes o resultado foi exatamente o mesmo para as duas formas de uso. Por isso, gostaria de saber se existe de fato uma diferença ou é apenas opcional.
Answer: Nesse caso não existe nenhuma diferença.
Porém imagine o seguinte cenário:
Você tem a classe App\User e a classe Services\User.
namespace App\User;

public function teste() {
   $services = new Services\User;
}

Esse exemplo provocaria um erro visto que ele iria procurar em App\User\Services\User
Já se a barra fosse colocada antes a classe seria encontrada, pois ele iria usar \Services como a raiz.
Quando usamos o use ele desconsidera o namespace atual, não sendo necessário utilizar a \.
Comment: Sim isso eu entendo. O problema é que costumo ver essa contra "\" no inicio do próprio "use". Isso que não faz muito sentido para mim.


Count data and proportion covariates: best practices

Question: I'm working with spatial data and I have the following log-linear model for count data. Let $y \sim Poisson(\lambda_{i})$ such that
$$
\log \lambda_{i} = \text{x}_i^\top\beta_{} + \epsilon_{i}
$$
such that $\epsilon_{ij}$ is the spatial effect at site $i$.
I have counts for each site that I want to analyze as a response variables and other auxiliary counts that the literature says are related and may drive the counts up or down. My question is what's the best practice for count data as covariates, should I use

Raw counts;
Proportions (I know the total population at each site);
$z$-scores.
Answer: The formal parameter for Poisson is $P(\mu)$, where $\mu=n \lambda$.  The rate parameter you are listing $\lambda=\frac{\mu}{n}$ is the ratio of number of events (failures) divided by a denominator such as time, area, or sub-population size from which the events were based.  Each row in Poisson regression usually represents an $i$th sub-population with some outcome failure(success) event of interest tallied in the numerator, divided by the sub-population size or total follow-up time (person-years) in the denominator.  What makes the problem Poisson is that $n\lambda(1-\lambda)<5$.  For example, a Binomial, $B(n,p)$,  approximates Poisson whenever $npq<5$, where $q=1-p$.
See this answer for data setup to understand the rate parameter, $\lambda$.


Solving a second-degree exponential equation with logarithms

Question: The following equation is given:
$8^{2x} + 8^{x} - 20 = 0$
The objective is to solve for $x$ in terms of the natural logarithm $ln$.
I approach as follows:
$\log_8{(8^{2x})} = \log_8{(-8^{x} + 20)}$
$2x = \log_8{(-8^x + 20)}$
$2x = \dfrac{ \ln{(-8^{x} + 20)} }{ \ln{8} }$
$x = \dfrac{ \ln{(-8^{x} + 20)} }{ 2\ln{8} }$
and at this point I'm unable to proceed.
Answer: Hint: Make the substitution $u=8^x$.  Now the equation becomes $u^2+u-20=0$.
Answer: We have $$(8^x)^2+8^x-20=0$$
$$\implies8^x=\frac{-1\pm\sqrt{1-4(-20)}}2=-5,4$$
For real $x,8^x>0$
Then $8^x=4\implies x\ln8=\ln4$
But $\ln8=\ln(2^3)=3\ln2$ and $\ln4=\ln(2^2)=2\ln2$
Comment: The solution must be in terms of the natural logarithm.
Comment: @user146046, $$x=\frac{\ln(-5)}{\ln8}$$ is in natural logarithm, right?
Comment: Non-permissive of non-real solutions.
Comment: @user146046, I think, you meant this


Is my regression network overfitting or is my simulated MRI training data unrepresentative of real MRI val/test data?

Question: I have been working on a regression task for the past one year and I am stuck. My project is to simulate voxel-wise MRI data using a physics-based function and train a neural network using that data to predict a continuous number (T2 of tissue). Essentially, my training set consists solely of simulated data and my validation/test sets consist solely of real MRI voxelwise data collected from healthy volunteers. Below is the learning curve I get when training a neural network with a linear activation unit as its output:

Below is the histogram of predicted T2 values from this model, when I tested it on the test set consisting of real MRI data. The model seems to mainly, but not only, predict one value.

I then tried training the same model architecture with only real data (i.e. training/val/test sets all consist of real MRI data from healthy volunteers). I got the following learning curve and histograms:

The histogram looks better now as it seems to predict a range. The model also seems to converge as the validation and training losses are low and have similar values. Based on this, is it the case that my model when trained on simulated data is overfitting and I need to introduce regularization (e.g dropout)? Or is it the case that, given that the model converges for the real data, my simulated data is simply not realistic enough when compared with the real data?
Would be grateful for any advice on how to progress further! Thanks!
Edit 1: I am going to try and implement a training-val set, which would contain some data from the original training set. The training-val and training sets would be independent data sets composed of simulated MRI data. Will try plotting that as well as the original validation set containing the real data to see if that can shed insight into whether this is a data mismatch problem. Will keep you posted!
Edit 2: Here is the histogram of the real and the simulated T2 ground truth data used to test and train the model respectively. Please note the following. Firstly, the simulated data has more values at higher ground truth T2s when compared to the real ground truth distribution because the real ground truth data only consists of healthy T2 values (which are lower) whereas the simulated ground truth data consists of both healthy and diseased T2 values (which are lower and higher, respectively). Secondly, the simulated, training data consists of 48,000 samples whereas the real validation and test data consists of 1,801 samples each (so 3,602 real data samples in total). The models will later be tested on diseased real data as well, but for now I only have access to data from healthy volunteers...
Comment: Can we see ground truth (value to be predicted) for both simulated and real-world data in a histogram too?
Comment: since your predictions are consistently too small, I see two possibilities to consider: 1) your simulator just produces smaller values (so is unrealistic and needs to be updated) 2) there is domain shift in the feature space (so we need to employ some transfer learning tricks). the comparative histogram will inform us if it's 1.
Comment: Hello @JohnMadden, thank you for your comment and apologies for the delay in responding. Have now added in the histogram for the real and simulated ground truth T2 data. Would be grateful for your advice based on this...
Comment: "the real ground truth data only consists of healthy T2 values (which are lower) whereas the simulated ground truth data consists of both healthy and diseased T2 values" this is at least part of the issue; I would check out transfer learning strategies, or just focus on healthy simulated data until you get the real diseased data.
Answer: Firstly, you do seem to be getting some learning here, so your project looks good. The RMSE looks reasonable, since it is small compared to the squared values, but $R^2$ would be a better indicator.
I see that the model never predicts values above 45. Are they missing from the training data? If so, add them. If not, you seem to need to add more, or reconsider you loss function.
The tendency to predict one value often is odd, and is likely to due to either the training data or the loss function - I suggest checking them both.
Comment: Hello, thank you for your comment and apologies for the delay in responding. I have edited my original post to include a histogram of simulated and real ground truth T2 values. The model trained using only the real data was used to check the learning curve to see if the train and val losses converge and are similar. I am using the mean_squared_error as the loss function. Could the reason why the model is predicting only one value when using simulated data be due the use of a linear activation function for the output layer? Would be really grateful for any help you can provide me with on this!!
Comment: There's nothing wrong with using a linear function for the output layer, it is quite common. (If two consecutive layers are both linear, then the composite function must also be linear, so the second layer adds no power. But that is not an issue here.)


What does it mean to explicity exhibit something (modulo a proof of its existence) which cannot be explicitly exhibited?

Question: I was reading this answer that no free ultrafilter can be exhibited on the natural numbers.
I have as a theorem that if the Collatz conjecture is true then the following is a free ultrafilter on the natural numbers:
Let $f(x)=(3x+2^{\nu_2(x)})/2$
where $2^{\nu_2(x)}$ indicates the highest power of $2$ that divides $x$ while still giving an integer quotient so for example $2^{\nu_2(24)}=8$.
Let $f^n(x)$ indicate the $n^{th}$ iterate of $f(x)$
Let $F_y$ be the filter at $y$ and be defined as the set of integers $x$ such that there is some $n\in\Bbb N$ such that $f^n(x)=y$, ordered by $n$.  So for example $3\preceq5\preceq8\preceq16\ldots$
Then it is a theorem that if the Collatz conjecture is true, the set of all subsets of $N$ with the order inherited from $F_y:y\in\Bbb N$ is a free ultrafilter on $\Bbb N$.
I'm using this definition of free ultrafilter.  Is it compatible with the one in use in Noah's answer?
Question
It appears to me that I have explicitly exhibited a free ultrafilter on $\Bbb N$ (modulo the small matter of a proof of the Collatz conjecture), yet such a thing can not be explicitly exhibited.  What implications does this have for a proof of the Collatz conjecture?  Does it mean nothing more than; such a proof will necessarily require the axiom of choice?  Does it mean the proof cannot be explicitly exhibited?
I was curious a good long while ago about the possibility some apparently hard theorems could be unprovable or equivalent to the Godel sentence of a system.  This reminds me of that hypothesis. Certainly the Collatz conjecture is "an arithmetical statement which claims that no number exists with a particular property", and therefore among the candidates for a Godel sentence.
Is it possible that this proves no arithmetical statement expressible in Peano arithmetic can disprove the Collatz conjecture, and therefore that the conjecture is true?
Comment: Oh, I think I understand (part of) the confusion here. You've linked to the definition of "ultrafilter on a poset". When people talk about an ultrafilter on a set $X$, they don't mean "equip $X$ with some partial ordering and consider an ultrafilter on that poset". Instead, they mean "ultrafilter on the Boolean algebra $\mathcal{P}(X)$" (which is the set of all subsets of $X$ ordered by $\subseteq$). So the definition relevant for the notion of "free ultrafilter on $\mathbb{N}$" is a bit further down on the Wikipedia page you link to, in the section on ultrafilters on power sets.
Comment: What do you think the definition of "ultrafilter" is? I don't see any way to interpret the phrase "the set of all integers with the order inherited from $F_y:y\in\mathbb{N}$" so that it describes an ultrafilter.
Comment: Well, it remains the case that what you've written does not seem to define an ultrafilter. Can you try again to define it? Precisely which sets of natural numbers are in the ultrafilter?
Comment: It's not enough to *feel like* some construction "conceptually fits the model" of a free ultrafilter or say things like "surely this can be done". You have you actually check the definition. As someone who has worked a lot with ultrafilters, I do not share your intuition - I see no reason at all why the concepts of "orbits of a function" and "free ultrafilter on $\mathbb{N}$" should have anything to do with one another. An ultrafilter $U$ on $\mathbb{N}$ has to decide *for EVERY set $A$* whether $A$ or the complement of $A$ is in $U$. Making all these choices is where AC is useful...
Comment: how is your $F_y$ even a filter? isn't it a set of natural numbers?
Comment: It could also mean that the Collatz conjecture is false which would be compatible with your result. This would however be quite surprising (Personally, I would enjoy it however!) , so please check the proof again whether you really established this result.
Comment: Of course , it is possible that Collatz is unprovable in PA , it could even be unprovable in ZFC , assuming it is true. Even more , it could be not disprovable in ZFC if it is false. I heard from claims that this can be ruled out , but with no argument. It is only ASSUMED that ZFC is strong enough to prove all "natural" statements.
Comment: @Peter the proof is quite simple.  Think of the filter as simply the set of natural numbers which get to $1$ in fewer than $n$ "odd" steps.  There is no upper bound on Collatz sequence length, which is what makes it free. I take your point about Collatz possibly being false, but I want to understand what does it mean for the proof, assuming the Collatz conjecture is true. Simply because, I am working on it on the assumption it's true in which case the answer to this signposts methods for me.
Comment: Noah says that what you call "exhibit" is rather technical. It may well be the case that your alleged free ultrafilter is "hard to define". I have absolutely no idea.
@Noah Schweber
Comment: 1/ The $F_y$ you exhibit is not a free ultrafilter. You pick some natural $y$ and define $F_y$ as the set $\{ S \subseteq \mathbb{N} \mid \forall x \in S. \exists n \in \mathbb{N}. f^n(x) = y \}$. If this set was an ultrafilter at all, then we'd either have the even numbers contained inside it, $2\mathbb{N} \in F_y$, or else their complement, the odd numbers with $2\mathbb{N} + 1 \in F_y$. But it's immediate that neither of these sets belong to $F_y$, no matter how you choose $y$.
Comment: @it'sahirecarbaby: Well, your view was mistaken. There are plenty of non-free ultrafilters that fail to contain $2\mathbb{N}$, take e.g. $\{S \subseteq \mathbb{N} \mid 67 \in S \}$.
Comment: You don't need to understand the general definition of an ultrafilter on a Boolean algebra. An ultrafilter on $\mathbb{N}$ is a set $U$ of subsets of $\mathbb{N}$ such that: (1) if $A$ and $B$ are in $U$, then $A\cap B$ is in $U$, (2) if $A\in U$ and $A\subseteq B$, then $B\in U$, and (3) for every set $A$ or natural numbers, exactly one of $A$ or its compliment is in $U$. The set of all orbits of $f$ is obviously not an ultrafilter, since it is not the case that every set is either an orbit of $f$ or the complement of an orbit of $f$.
Comment: 2/
To show that $2\mathbb{N} \not\in F_y$, pick the smallest integer $2^k$ that is larger than $y$. You have $f(2^k) = \frac{3\cdot 2^k + 2^k}{2} = {4\cdot 2^k}{2} = 2^{k+1}$. By induction, $f^n(2^k) = 2^{k+n}$. Thus, it's clear that $f^n(2^k)$ will never hit $y$. If $2\mathbb{N}$ was in your purported ultrafilter, $f^n(e) = y$ would eventually happen for any even $e$. But since $2^k$ is even, and we established that it doesn't happen for $2^k$, this means that the set $2\mathbb{N}$ is not contained in your ultrafilter.
Comment: 3/ To show that $2\mathbb{N} + 1 \not\in F_y$, we can argue as follows. If $y$ itself is even, then $q = \frac{2^y - 1}{3}$ is odd, and if $3 < y$ then $y < q$. Moreover, $f(q)$ is a power of two, so again $f^n(q)$ only hits $q$ and powers of $2$. Hence, it never hits $y$, so the set of odd numbers does not belong in $F_y$. If $y$ is odd, the same argument works with $2^{y+1} -1$ instead. The special case $y=1$ is handled easily. All in all, we see that $F_y$ cannot be an ultrafilter at all, for any choice of $y$.
Comment: @Z.A.K. thanks for your help. $F_y$ are proper filters and therefore cannot be free filters at all let alone free ultrafilters.  But the maximal filter over all $F_y$ is a free ultrafilter.
Comment: @AlexKruckman I'm using this definition - I'll add to the question: https://en.wikipedia.org/wiki/Ultrafilter#Ultrafilters_on_partial_orders  and I have edited slightly to make build the ultrafilter out of members of the power set rather than members of $\Bbb N$ itself.
Comment: @AlexKruckman thanks I knew there were nuances in the types of Ultrafilter. Nevertheless I don't yet see that this is fatal to the premise of the question.
Comment: @AlexKruckman it's going to take me time to define it carefully and without error using that boolean algebra definition I am currently unable to parse but I continue to think the set of all orbits of $f$ ordered by their orbit direction conceptually fits the model of an ordered set of subsets of $\Bbb N$ and is a free ultrafilter.
Comment: @AlexKruckman I'm struggling to pin it down - maybe you can help me? https://math.stackexchange.com/q/4772341/334732 . Surely there is a standard model for an ultrafilter which describes the orbit of a function which acts transitively on a set?
Answer: The claim that the proof of the Collatz conjecture would imply the existence of a free ultrafilter would establish that the Collatz conjecture cannot be proved in ZF.  This is because ZF does not prove the existence of a free ultrafilter.  Similarly, ZF+ACC does not prove the existence of a free ultrafilter, and therefore (if your claim is correct) would not be able to prove the Collatz conjecture, either (here ACC is the axiom of countable choice).  Even the stronger system ZF+ADC cannot prove the existence of a free ultrafilter and therefore would be unable to prove Collatz (here ADC is the axiom of dependent choice).  One would need a stronger version of the axiom of choice, such as for example the axiom of choice for families indexed by the continuum, if one is to have any hope of establishing Collatz.  Of course, as mentioned in the comments it is not known whether even the full ZFC would prove it.  I notice that there is some doubt in the comments whether your $F_y$ can be used to get an ultrafilter (without using choice), which I haven't checked, so my remarks are contingent on the possibility of doing so, which needs to be established.
Comment: What is a "maximal filter over all $F_p$" exactly?  Does its construction involve the axiom of c choice?  Clearly if it does, this changes the situation considerably.  @it's
Comment: If I understand your definition correctly, $F_y$ is a subset of $\mathbb N$, in other words an element of $\mathcal P(\mathbb N)$.  Since $y$ ranges over $\mathbb N$, there are only countably many such $F_y$.  Therefore what you constructed is a countable collection of sets.  However, an ultrafilter is necessarily an *uncountable* collection of members of $\mathcal P(\mathbb N)$.  Therefore what you constructed cannot be an ultrafilter.  If it is a filter, then one could find a maximal filter containing it, i.e., an ultrafilter.  However, the existence of a maximal filter containing a given ..
Comment: Thanks for this. The commenter simply thought I was claiming each proper $F_y$ was a free ultrafilter for some individual $y$ but it clearly cannot even be free as it is a principal filter. Rather than I meant the maximal filter over all $F_p$, which is a free ultrafilter.
Comment: Not sure if this answers your query but if the Collatz conjecture is true then the filter over all $F_p$ has a partial order over all of $\Bbb N$. If Collatz fails, not all natural numbers are connected to a common successor by the order relation.
Comment: Is $F_y$ supposed to be a member of your "ultrafilter"? @it's
Comment: The order relations of every $F_y$ are inherited by my free ultrafilter.
Comment: ... one depends on the axiom of choice.  @it's
Comment: Thank-you for that. Are you using this definition of ultrafilters: https://en.wikipedia.org/wiki/Ultrafilter#Ultrafilters_on_partial_orders


SSJS for resource href in themes

Question: We have multiple applications sharing single css for themes. So we want to move this common CSS and resources into common database, and refer them in themes dynamically.
I can refer these css using following hardcoded path :
<resource>
    <content-type>text/css</content-type>
    <href>/.ibmxspres/domino/common/designstore.nsf/custom_layout.css</href>
</resource>

This way it is working fine. But we want to fetch the database path from configuration. So that '/common/designstore.nsf' path don't have to be hard coded in themes.
I tried putting designstore db path in sessionScope variable beforeRenderResponse of a Xpage. And referred scope var in themes.
<resource>
    <content-type>text/css</content-type>
    <href>#{sessionScope.commonCSSPath}</href>
</resource>

Where sessionScope.commonCSSPath = "/.ibmxspres/domino/common/designstore.nsf/custom_layout.css"
Please let me know if we can compute the db path in resources, or any other way to refer CSS files from other databases using computed path.
Thank you in advance.
Comment: As far as I know you can not use any dynamic code for resource attributes in themes. You can only use hardcoded static text, nothing else.
Answer: Try calculating the href value using Javascript instead of EL:
<resource>
    <content-type>text/css</content-type>
    <href>#{javascript:sessionScope.commonCSSPath}</href>
</resource>

I am not sure if the timing of beforeRenderResponse and when a theme kicks in, makes it possible to reference a sessionScope variable. Let us know how it goes.
--
Update:
I use the following in a theme to determine the rendered property of a field and it works:
<control>
    ...
    <property>
        <name>rendered</name>
        <value>#{javascript:document.isEditable()}</value>
    </property>
</control>

I also use a function to determine the value property where the function is a SSJS function that looks up a value in a profile document:
<control>
    ...
    <property>
        <name>value</name>
        <value>#{javascript:getNecessaryValue("SetupProfile", "fieldWithValue")}</value>
    </property>
</control>

Hopefully this can inspire you to achieve what you want.
Comment: Thank you for sharing the code. Yes for Controls it is working fine,  tags I can use SSJS or EL to get the dynamic values. But for Resources it is not working. I am not sure how to pass dynamic values to  tag. It is not taking SSJS/EL...
Comment: Javascript is also not working. I tried putting sessionScope variable in all 5 events of xpage, still not working. Any other way? Is it possible to use datacontext in themes? something like data source?
Comment: I have added an example of using document.isEditable() and of using a function in a theme. Maybe this can inspire you to do what you want?

SSJS for resource href in themes


Xcode 6: How to solve Precompile prefix Header error

Question: I just moved an app i've been working on from Xcode 5, onto another computer running Xcode 6, (working fine on Xcode 5)
I now get the following error

I assume this was an issue with a missing .pch file, when I look into this dir i found the file but its called TMU-Prefix.pch instead of TMU_4.0-Prefix.pch
I figured my prefix header must be set incorrectly so I went in to build settings to change that and to my surprise my build settings is looking for the right file

This file which does indeed exist in my directory . . .
I'm clueless as to this error
upon search I came upon this post where Xcode 6 requires creating a separate .pch file i did and yet no success
As always, Any help is much appreciated
Comment: do u try Clear build folder after move the project?
Comment: yes I did :( - no success
Comment: Did you find the problem/fix? Were any of the answers correct? Can you accept or vote up or comment it to let us know if/how you fixed this?
Answer: When you see compiler errors looking for files that exist you should straight away realise that there is a naming issue conflict somewhere in the build settings of one of your targets, this was simply the case for me : mind boggling - but this post paved the way towards the answer
Answer: you need to check you project name (e.g Demo) and project test name (e.g DemoTests.m ) must be same. if both name are not same then rename same as to Demo
Comment: FYI: double click the value to see if that's the actual value or the resulting value after substitution (expansion?); for example the value may actually be "${PROJECT}/${TARGET}-Prefix.pch" which may be right for the main target but wrong (not exist) for a secondary target. It might should be "${PROJECT}/${PROJECT}-Prefix.pch" or just hard coded to what you expect ("TMU_4.0/TMU-Prefix.pch").
Answer: check both the project file build settings and target file build settings.If in any of the file its is incorrectly specified you will get error.
Comment: FYI: target settings override project settings. If all targets share the same .pch file then only define it in the project settings; If you have per-target .pch files then define them in the target settings.


Sorting through images but need to stop on the last image instead of closing out the window

Question: This is the function currently,
<code>  $("#btnNextImage").click(function (e) {
                 var win = window.opener.parent;
                 win.postMessage('next', '*');
                 window.close(); //close current tab before opening new tab
                e.preventDefault();
            });
</code>
This will go through the images when clicking on the btnNextImage but when I get to the last image of the results, the window closes out. I want it to check to see if the image is last and if so prompt an alert asking whether or not the user wants to stay on the window or close it.
Comment: Want to remind you that SO is not a free coding service. A tip that I can give you is to have a number ID on each image, and then check which one you are on, and if you are on the last one have a special `if` that catches that.
Comment: So how would you know it is the last? We have no clue how you get that from the information you provided.
Answer: Put an Id on each of your images, then check if its the last, with a simple if($("#lastId"))
Then use the confirm method prompt users if you need to close windows
https://www.w3schools.com/jsref/met_win_confirm.asp


Put a category of column's non-null count as a separate column

Question: I have to first calculate the number of values in a column (include duplicates too). After that I have to assign a pool range.
Example pool ranges: (1000-3000), (3001-7000), (7001-20000), (20001-500000).
Suppose we get the count of total number of values as 4500 in column A and 8500 in column B. 4500 will be in range (3001-7000) and 8500 in (7001-20000).
There are columns C and D in which I have to return this range value. Column C contains information for column A, so column C will populate with values (3001-7000). Similarly, column D contains information for column B, so column D will populate with values (7001-2000). How can we achieve this in PySpark?
Comment: - How do you determine pool ranges,? Is it stored in any table? - Will column C and column D have same data across the column?- Kindly provide your attempt and challenges faced.
Comment: Hi @Aswin i have already mentioned in question  that Column C will store pool range for column A and column D store for  column B. All these 4 columns are in same table.                    Pool ranges we can give depending on the requirement . We can give pool ranges in different table also.       Coming to your second questions please refer the SS that i have pasted
Comment: But the challenge here is we first need to get total count of column and put the pool range value in its relative column. I hope it will help you in understanding the problem.
Answer: Counting the non-null values is easy in Spark (df.summary("count")), but you will need to provide the pool ranges somehow. In the following example I provided pool ranges as a list of lists (one: 1 -> 2, another: 3 -> 10).
Inputs:
from pyspark.sql import functions as F
df = spark.createDataFrame(
    [(1111, 2222),
     (1111, None),
     (1111, None),
     (None, None)],
    ["col1", "col2"])

ranges = [
    [1, 2],
    [3, 10]
]

Script:
cols = ["col1", "col2"]
df = df.replace("", None)
summary = df.agg(*[F.count(c).alias(c) for c in cols]).head().asDict()
col_rng = {}
for c, cnt in summary.items():
    for r in ranges:
        if r[1] >= int(cnt):
            col_rng[c] = f"{r[0]}->{r[1]}"
            break

df = df.withColumn("range_col1", F.lit(col_rng["col1"]))
df = df.withColumn("range_col2", F.lit(col_rng["col2"]))

df.show()
# +----+----+----------+----------+
# |col1|col2|range_col1|range_col2|
# +----+----+----------+----------+
# |1111|2222|     3->10|      1->2|
# |1111|null|     3->10|      1->2|
# |1111|null|     3->10|      1->2|
# |null|null|     3->10|      1->2|
# +----+----+----------+----------+


SQL SUM based on prior SUM result

Question: Been working with C# for a while and seem to have forgotten some basic SQL
After much Googling around, just can't seem to get anywhere.
How do I use the 'Result' of a sum as an input to another function?
Looking for option A rather than B
a) SELECT Col1,Col2, SUM(Col1*Col2) AS 'Result', SUM(Result/10) AS 'Final' FROM ... GROUP BY
b) SELECT Col1,Col2, SUM(Col1Col2) AS 'Result', SUM(SUM(Col1Col2)/10) AS 'Final' FROM ...
Answer: You don't.  The correct calculation would seem to be:
<code>SELECT Col1, Col2, SUM(Col1*Col2) AS Result,
       SUM(Col1 * Col2 / 10) AS Final
FROM ...
GROUP BY
</code>
SQL in general does not allow you to re-use aliases in an expression.  So, you need to repeat the expression, use a CTE, or use a subquery.
In addition, nested aggregation functions are not supported by Standard SQL.
Comment: Yeah, option B was the only way I could come up with without CTE. Thank you

SQL SUM based on prior SUM result