Why does Lionel Messi "have" to leave Barcelona?

Question: From the Lionel Messi wikipedia article (emphasis mine):

On 1 July 2021, Messi became a free agent after his contract expired,
with negotiations on a new deal complicated due to financial issues at
Barcelona. On 5 August, Barcelona announced that Lionel Messi would
not be staying at the club, despite both of the parties reaching an
agreement and were due to sign a contract that day. The club cited
financial and structural obstacles posed by the La Liga regulations as
a reason for Messi's departure.

I don't get what's going on here. If Messi and the club reached an agreement, what exactly stopped them from simply signing the contract? Is it possible to deduce the reason from the information that is publicly available?
Answer: The stumbling block seems to have been the La Liga salary cap; while Messi and Barcelona reached an agreement they were both happy with, the league were not happy with the contract under their salary cap/financial fair play rules.
There's some more details in this BBC article in which gives some details of the potential contract arrangement, in particular that Messi's wages for 2 years of playing would actually be paid over 5 years.
Comment: Sure, I imagine Barcelona would have been able to fit [13300 euros per year](https://countryeconomy.com/national-minimum-wage/spain) into the 2.24 _billion_ euro wage cap. At some point though, however much Messi may like Barcelona, there's only a certain amount of money he's prepared to give up. Also, both players' unions and the league take a dim view of players being dramatically underpaid - the union because it risks depressing wages for all their other members, and the league because it increases the chances of "off the books" deals being made.
Comment: So Messi basically could've stayed, but only if he'd been willing to accept a (probably substantial) pay cut?
Comment: As noted in the BBC article, the agreement which was reached _already_ had Messi taking a 50% pay cut, and that still wasn't enough to get Barcelona under the salary cap.
Comment: That means he could've theoretically gone even lower (below the cap) and stayed?
Comment: "Messi's wages for 2 years of playing would actually be paid over 5 years" – Why would anyone think that this was going to work? I mean, it is such a blatantly obvious violation of the spirit of the rules.
Comment: @JörgWMittag 1) I suspect it was partially a face-saving deal for Barcelona - "it's not our fault, we had a deal, the nasty people at La Liga rejected it, don't blame us!" 2) Barcelona wouldn't the first club to try this sort of thing - perhaps most notably the [New Jersey Devils and Ilya Kovalchuk](https://www.thestar.com/sports/hockey/2010/09/13/devils_lose_two_draft_picks_fined_3_million_for_circumvention_of_cba.html) who agreed to a 17 year deal which ran well past when everybody knew Kovalchuk was going to have retired.


Grunt concat not working during watch task

Question: If I run 'grunt concat' it compiles my JS files as per the Grunt file (line 82). However, it doesn't concatenate when I'm doing 'grunt watch' (line 107).
From what I can see, my file is ok but I'm fairly new to grunt so would love to see if you guys can see an issue.
Here is my full Grunt file...
<code>    // All scripts to be included in project go here
    var _SCRIPTS = [
      'js/prefixfree.js',
      'js/jquery-1-10-2.js',
      'js/ie-detect.js',
      'js/application.js'
    ];

    var _PORT = 7777;

    module.exports = function(grunt) {

      // load all grunt tasks
      require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

      // Project configuration.
      grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        connect: {
          server: {
            options: {
              port: _PORT,
              base: 'prototype'
            }
          }
        },

        htmlvalidation: {
          options: {

          },
          files: {
            src: ['prototype/*.php']
          },
        },

        jshint: {
          beforeconcat: _SCRIPTS,
          afterconcat: ['js/main.js']
        },

        csslint: {
          check: {
            src: ['css/*.css']
          },
          strict: {
            options: {
              import: 2
            },
            src: ['css/*.css']
          },
          lax: {
            options: {
              import: false
            },
            src: ['css/*.css']
          }
        },

        compass: {
          dev: {
            options: {
              config: 'config.rb',
              force: false
            }
          }
        },

        uglify: {
          options: {
            banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
          },
          dist: {
            files: {
              'js/main.js': ['js/main.js']
            }
          }
        },

        concat: {
          options: {
            stripBanners: true,
            banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
              '<%= grunt.template.today("yyyy-mm-dd") %> */',
          },
          dist: {
            src: _SCRIPTS,
            dest: 'js/main.js',
            nonull: true
          },
        },

        cssmin: {
          add_banner: {
            options: {
              banner: '/* <%= pkg.name %> - v<%= pkg.version %> - ' +
              '<%= grunt.template.today("yyyy-mm-dd") %> */',
            },
            files: {
              'css/style.css': ['css/style.css']
            }
          }
        },

        watch: {
          concat: {
            files: ['js/**/*.js', '!js/main.js'],
            tasks: 'concat',
            options: {
              spawn: false,
            },
          },
          sass: {
            files: ['sass/**/*.scss'],
            tasks: ['compass:dev'],
            options: {
              spawn: false,
            },
          },

          /* watch and see if our javascript files change, or new packages are installed */

          /* watch our files for change, reload */
          livereload: {
            files: ['*.html', 'css/*.css', 'img/*', 'js/*.js'],
            options: {
              livereload: true
            }
          },
        }

      });

      // Default task (Watch)
      grunt.registerTask('default', ['watch']);
      // grunt.registerTask('default', [  'preprocess:dev', 'watch']);

      // Watch with localhost (For Static Templates)
      grunt.registerTask('watch_with_server', [ 'connect:server', 'watch']);

      // TESTING

        // Run all tests
        grunt.registerTask('allTests', [ 'jshint:beforeconcat', 'concat', 'jshint:afterconcat', 'cssLint', 'htmlvalidation']);

        // JS Testing
        grunt.registerTask('jsHint', ['jshint:beforeconcat', 'concat', 'jshint:afterconcat']);

        // CSS Testing csslint
        grunt.registerTask('cssLint', ['csslint:check']);
        grunt.registerTask('cssLintLax', ['csslint:lax']);
        grunt.registerTask('cssLintStrict', ['csslint:strict']);

        // HTML Vaidation
        grunt.registerTask('htmlTest', [ 'htmlvalidation']);
        grunt.registerTask('printenv', function () { console.log(process.env); });

      // Concat and uglify js and minify css for release
      grunt.registerTask('release', [ 'concat:dist', 'uglify', 'cssmin']);

    };
</code>
Many thanks
Comment: Do you get any errors? Does `grunt watch` not fire anything when you save a `.js` file? Try running with the `--verbose` option to see if anything interesting comes up. Lastly, I usually see the `tasks` option as an array. I know the docs say it can be either, but maybe try `tasks: ['concat']`?
Comment: I didn't get any errors. The altered files were showing as changed in terminal but concat wasn't running. I managed to get it working by moving 'livereload' above 'concat'. That seems odd to me as a solution but it's working. Thanks!
Answer: I managed to get it working by moving 'livereload' above  'concat' in the watch task. No idea why this would make a difference but it's working!
If anyone has any insight on why this would affect it I'd love to know.
Answer: add this and see:
<code>livereload: {
     files: ['*.html', 'css/*.css', 'img/*', 'js/*.js'],
     options: {
         livereload: true
     }
},
options: {
    livereload: true
},
files: '<%= options.watch.files %>',//might have to change this line
tasks: ['default', 'notify:watch']
</code>


Change URI format during harmonization

Question: I am currently working on MarkLogic using Data Hub.
Is there a way you can change a document's URI during harmonization before it gets written to the Final Database?
Current URI Format after Load:
/Entity/123456.xml

Desired URI Format after Harmonization
/Entity/Location/123456.xml

where     Entity is a constant value, Location is a dynamic variable
I saw one related article but it changes the URI if the document is already in the database. I am thinking of doing it during harmonization before the document is written in the FINAL database.
Answer: Inside writer.xqy you can write your first line as-
let $newuri:="Entity"||($Location)||"123456.xml" (: Or use fn:concat() :)

At the last line of writer.xqy where you will be using xdmp:document-insert just change the $id to $newuri.
Hope That Helps !

Change URI format during harmonization


Where do I make a feature request to drupal.org?

Question: What is the best place to make a feature request about the drupal.org website?
I probably spent an hour searching.  There is/was the redesign project, there is the drupal.org issue queue but I was refused access.
FYI - I'd simply like to suggest that project owners have a tab for "roadmap" or "project Future".  Sure, the summary page can include that but often it is crammed with things and maintainers forget to talk about what plans they have, what they need, etc.
Comment: this question appears to be off-topic - please see the help section of this site, including the 'What Topics can I ask about' - in the 'and it is not about' you will find 'Issues about drupal.org, or any of its sub-domains'
Comment: Thats odd.  I was told that is what the community tag is for.  If not you should probably delete it.  http://meta.drupal.stackexchange.com/q/3238/12432.
Comment: I humbly disagree as I think it is appropriate.  Also the reference has a footnote qualifying it:Bugs found on modules, Drupal itself, or Drupal.org (and its sub-domains) should be reported in the appropriate issue queue on Drupal.org.
Security issues should be reported following the process defined on How to report a security issue.
Comment: This question is not about a bug report. It is asking in which drupal.org queue ask a specific feature request. The OP shows to know some of the existing project queues used on drupal.org and asks what the better project queue is. I admit it, it's not quite easy, to understand this.
Answer: Generally speaking, the correct place to post feature requests for Drupal.org is the Drupal.org customization project issue queue.
However, you also wrote:

FYI - I'd simply like to suggest that project owners have a tab for "roadmap" or "project Future".

If you just want to suggest that project owners publish a "roadmap", you can add that suggestion to the community documentation. It is a wiki so you don't request anything - you just do it (like I just did).
If you want to actually modify the project page layout by having a feature where project owner's may add an addtional tab for "Roadmap" to the page summary, you request this in the Project module's issue queue
Finally, I shall not suggest you use the Webmasters issue queue for any type of feature requests.  The Drupal.org webmasters issue queue is for reporting spam, broken links, or user account problems at Drupal.org - and that is about it.  My experience is that nothing much happens to feature requests posted there, even if the request just involves flipping a trivial setting in a module already installed. The webmasters obviously have the power to do this, but they do not make decisions about such things.  They usually move feature requests to the Drupal.org customization project, and bug reports to the Infrastructure project.
Answer: There are indeed quite a few "projects" on Drupal.org that might be a candidate for suggesting such feature request. My best bet for you would be the "projects" Project or Project Issue Tracking.
However, are you sure you want to suggest such feature? Things like "roadmap" are typically located already in either of these areas on drupal.org (related to a specific module and/or distribution):

in the module's issue queue (often using "roadmap" or "release" in the issue title or issue summary), such as for the Forena module.
within the community documentation, which you should be able to find via the "Read documentation" link on the project pages.
on the module's project pages, such as for the ArrayShift distribution.

The technique that I believe works best so far, is what I've started to use in (eg) the Charts module. I.e using issues such as Charts 7.x-2.0 Release and
Charts 7.x-3.x Release. These are "parent" issues to which other issues are referring to as their "parent" issue. Combined with the status (color) of each child issue you then also get an idea of the progress of such release. Checkout those parent issues to see that technique at work.
If such feature ever gets requested/implemented, I'd assume/expect it to be another field without the "Resources" section when you edit the project page of a module,  where today you can already enter links to Demos, Screenshots, Community docu, etc). These links, if provided, are then shown within the "Resources" block when viewing the project pages.
Answer: I will answer this question basing on what I learned in the period I was site maintainer on drupal.org. My answer doesn't reflect in any way what the current site-maintainers think, or the thought of the maintainers of any module.
The first project queue one would think is the one for the Project module since Drupal.org is effectively using that module, but I think it's improbable the current maintainer would plan to add such feature, if that is not generic enough to be applied to other sites as well. The answer is probably going to be something on the lines of "If you want to implement that feature, you can implement it in a custom module."
Drupal.org does use custom modules to implement those features that are not currently used in any module, or to alter how some of the features are implemented in existing modules.
If the feature request involves writing code, then the project queue for Drupal.org customization project is the best choice. In this case, I would also provide a patch for such feature to be implemented.
If the feature request is about a module to enable, I would use the Drupal.org site-maintainer project queue, since some of the site-maintainers have the permission to enable modules on Drupal.org.
In both the cases, be ready to convince other users this is really necessary. In the case of custom code, it is much preferable to be ready to provide a patch for one of the custom modules used on Drupal.org, if one of the maintainers find the feature request interesting.


Python 3.5 Factorial

Question: i = input("Enter number", )
for i in range(i):
    i= i *(i+1)
    print(i)

I am trying to generate a factorial for any number the user inputs using the above code. How can I achieve this with the above code, without using the python factorial function. How I can also do it with the factorial function?
Comment: Please create a [mcve].  With sample input, show actual code and current/desired results.
Answer: you can do it recursively also in this way
def recur_factorial(n):
   """Function to return the factorial
   of a number using recursion"""
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

print recur_factorial(5)

You can take input from user in the form of  the integer and then pass in the factorial function
Answer: use this function math.factorial(value) by importing math library in python.
Answer: You are modifying i while iterating over it. Could you try:
i = int(input("Enter number", ))
f = 1
for j in range(i):
    f = f * (j+1)

print(f)

Comment: It gives the error message: TypeError: 'str' object cannot be interpreted as an integer
Comment: I added a conversion of the input to int in my code
Answer: While using recursions you should use tail recursive functions like
def factorial2(x, fac):
   if x == 1:
     return fac
   else:
     return factorial2(x-1, x*fac)

factorial2(value_here,1)

You can use the built-in function with simple :
import math
math.factorial(value_here)

Comment: No need for the parentheses .
Comment: yes, but i always use when i can, for maybe its from math, but i really like things explicit
Comment: Sure, but it is bad Python style.
Comment: Its just a code example but yes, like i said i know, on software i use the style guides assigned to the project (mostly always pep 8 + google style) , and you only use () on if statements, according to pep 8, if the conditions space break lines, but the main point is still right

Python 3.5 Factorial


Using Jetty to serve a web application

Question: I am using Jetty for the first time to deploy a GWT web app connecting to a Restlet API and I am trying to understand the best way to use it.
I want to make it embeddable so that I can update config during run-time (allowing me to add new domain names etc).
Our web server currently runs Apache to serve a PHP web app and this will be our first time deploying a GWT app and using Jetty.
Is it possible to use Jetty in parallel with Apache (both serving requests on port 80) and since I am embedding it do I use Apache before it reaches Jetty? So Apache receives request and forwards to Jetty?
Answer: Both server cannot run on same port. But you can run both on same machine. So use a separate port for jetty.
Jetty receives the request through its own port and doesn't depend on other server.

Using Jetty to serve a web application


Nginx in front of Varnish sometimes produces "upstream prematurely closed connection while reading response header from upstream" error

Question: I have Nginx(1.9.9) on front of Varnish(4.1.0) on the same server.
<code>//nginx
upstream varnish {
    server 127.0.0.1:8391;
    keepalive 16;
}

location ~ \.php$ {
     proxy_pass http://varnish;
     proxy_http_version 1.1; #for 1.0 varnish shows blank page
     proxy_set_header Connection "";
     proxy_redirect off;

     proxy_set_header Host $host:$server_port;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Forwarded-Proto $scheme;

     proxy_read_timeout 600;
     proxy_send_timeout 600;
     proxy_connect_timeout 600;
}

//varnish
DAEMON_OPTS="-a :8391 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,1024m"
</code>
For 0.001% of requests nginx shows error:
<code>[error] 5331#5331: *7392847 upstream prematurely closed connection while reading response header from upstream, client: xx.xx.xx.xx, server: _, request: "GET /home HTTP/1.1", upstream: "http://127.0.0.1:8391/index.php?q=/home", host: "xxx", referrer: "xxx"
</code>
Playing with proxy_buffers didn't help.
Comment: Check varnish logs for those requests. Also, why nginx in front of Varnish?
Comment: Check if varnishd wasn't it killing the child process while processing this URL.
Comment: Nginx for ssl http2. varnishlog don't shows this requests
Answer: We had this very same issue, using Nginx for SSL and HTTP2, Varnish for caching and Apache for the actual web serving.
I noticed it was only happening on requests that we had set to bypass Varnish. For some reason, years ago, we used return(pipe) in our VCL file for those. I changed it from return(pipe) to return(pass) and, voilà, problem solved.
Obviously you'll need to look at your VCL and make sure that return(pass) works for your scenario, but in most places it likely will be the answer.
Comment: I'm unsure but why do you do double caching? nginx can cache, vanish do the same?


Is this deduction valid for a abelian group G and dG?

Question: We know that, any abelian group G can be written as a direct sum of dG and a reduced subgroup R (where dG is the subgroup generated by all divisible subgroups of G). Is it true that R is isomorphic to G/dG?
Comment: Yes, it is true.
Answer:
If G is written as the direct sum A⊕B, then B is always isomorphic to G/A.

Write elements of G as ordered pairs (a,b) and define the homomorphism from G to B by mapping (a,b) onto b.  The kernel is precisely those (a,b) with b=0, that is, the kernel is precisely A⊕0 = A.  The image is all b for b in B, that is, the image is precisely B.  The first isomorphism theorem then gives that the image, B, is isomorphic to the source mod the kernel, G/A.


Find a maximum of the function

Question: Let $a \in \mathbb{R}^n$ be such that $\| a \| <1$. Find a maximum of the function $$\{ x \in \mathbb{R}^n \: : \: \| x \| \le1 \} =\mathbb{B}^n \ni x \mapsto \frac{\| x-a \|^2}{(1-\langle a,x \rangle)^2} \in \mathbb{R}.$$
One can prove (using necessary condition for having extrema and writing $x$ in some orthogonal basis $a,b_1,...,b_{n-1}$) that it is achieved for boundary $x=a+b$ (with norm $1$) and $b \in \text{span}\{b_1,...,b_{n-1}\}$. The maximum is then equal to $\frac{1}{(1-\| a\|^2)^2}$. Since the computations are quite long (and I suspect that there is a simpler solution) I would like to ask You for help with finding one.
Answer: Write $x=\lambda a + b$ with $b \bot a$, with $\|x\|^2 = \lambda^2 \|a\|^2 + \|b\|^2 \le 1 $.
${\|x-a\|^2 \over (1-\langle x , a \rangle )^2} = { (1-\lambda)^2 \|a\|^2+ \|b\|^2\over (1-\lambda \|a\|^2)^2} $.
It is clear that if $\|x\|^2 <1$ we can increase $\|b\|$, hence at a $\max$ we have
$\lambda^2 \|a\|^2 + \|b\|^2 = 1 $.
Hence the problem is to choose $\lambda$ with $|\lambda| \le {1 \over \|a\|}$, to maximise
$c(\lambda)={ (1-\lambda)^2 \|a\|^2+ 1-\lambda^2 \|a\|^2 \over (1-\lambda \|a\|^2)^2} = { 1+ \|a\|^2 -2 \lambda \|a\|^2 \over (1-\lambda \|a\|^2)^2}$.
Since $c'(\lambda) = {2 \|a\|^4 (\lambda-1) \over (1-\lambda \|a\|^2)^3}$, we see that $c$ is maximised with $\lambda = 1$ with
value $c(1) = {1 \over 1-\|a\|^2 }$.
Hence the solution is $x=a+b$ where $b \bot a$ and
$\|b\|^2 = 1- \|a\|^2$.

Find a maximum of the function


String Matching with word dictionary with R

Question: I have a word table (wt) like this (3 by 3 )
ungrateful    mango       uncertain
hobby       prejudicial   meat
persecution   bird        honest

and a word dictionary (dict)
persecution
overpowering
prejudicial
offense
ungrateful
uncertain
musical
murderous
detest
youth

I want to search all words in the wt with the dict and if any word match with the dictionary, that will give the dictionary word position in the word table, and the words which do not match will be automatically deleted.
    wt <- matrix(c("ungrateful","mango", "uncertain","hobby", "prejudicial", "meat","persecution","bird","honest"), nrow = 3, ncol = 3, byrow = TRUE)
    dict<- matrix(c(
"persecution",
"overpowering",
"prejudicial",
"offense",
"ungrateful",
"uncertain",
"musical",
"murderous",
"detest",
"youth"), nrow = 10, ncol = 1, byrow = FALSE)

for (i in 1:nrow(df)){
        for (i in 1:col(df)){
                x[i,j ] <- charmatch(df[i,j],dict_word)
        }
}

But this is giving error, when I am expecting output like this
     [,1] [,2] [,3]
 [1,]  5         6
 [2,]      3
 [3,]  1

I am pretty new in R and don't have good idea about the syntax . please help.
Answer: The match function returns the position of matches of its first argument in its second. (If there's more than one match, only the position of the first match is returned.) Then we convert that to a matrix corresponding to the positions of the wt matrix.
matrix(match(wt, dict), nrow=nrow(wt))

     [,1] [,2] [,3]
[1,]    5   NA    6
[2,]   NA    3   NA
[3,]    1   NA   NA

Comment: OMG, that was this easy! Thanks a lot really. I was trying so many things.
Comment: @bipu You can click the check mark on the left of the answer to "accept" it, indicating that it solved your problem.
Comment: @eipi10, I was looking for some suggestions on how we can get the data for some specific equivalent column of the match from 2nd dataset. I have posted the question at -  http://stackoverflow.com/questions/42749447/r-fuzzy-string-match-to-return-specific-column-based-on-matched-string   It would be great help if you can suggest something
Answer: In the same way as @epi10 mentioned above, charmatch
matrix(charmatch(wt,dict), nrow = nrow (wt))

and pmatch
matrix(pmatch(wt,dict), nrow = nrow (wt))

works as well.


Understanding ClassLoaders in Java

Question: I'm fairly new to the JVM and ClassLoaders. I have these two classes:
public abstract class CoreModule extends Entity

public final class EventManager extends CoreModule

At the start of the program, I create an instance of EventManager. So I understand that the JVM knows what Entity class is and how to load it (that is, it knows what ClassLoader to use), since EventManager is a grand-child. But when an Entity instance is passed by some serialization mechanism, it throws ClassNotFoundException. I have to manually set the ClassLoader to use (Event.class.getClassLoader()).
How come the JVM does not know what Event class is or how to load it if it already did it?
Comment: Can you provide more details about infrastructure?
Comment: Sorry, but I don't know what you mean by "infrastructure". The JVM proper is Dalvik.
Comment: Is it webapplication or desktop application?are you using any frameworks? are you using any special classes for serialization etc.,
Comment: @thinksteep It's hardly a webapplication/desktop application running on an Android phone.
Comment: It's a standard Android service.
Answer: Actually the JVM does not figure this out "magically".
It is all based on a system class loader which will vary depending on the environment you use. Then each thread has a context ClassLoader which derives from this automatically.
The context ClassLoader you can change by using Thread.setContextClassLoader
If your serialization code should be able to resolve a class not visible from the context ClassLoader you need to set this the way you did.
Comment: Thank you, I understand now that when de-serialization is done, it's a system thread that does it, and thus, it doesn't know about my class.
Answer: Just by creating an instance of EventManager you didn't show the JVM how to load it. In fact, you're not talking to the JVM here. You're talking to one specific classloader, and when that same classloader is not in charge at the time of deserialization, you can get an error. That's why your problem is all about what clasloader is in charge at what point.
Comment: Thanks for the answer, I understand the class loading mechanism much better now.

Understanding ClassLoaders in Java


Is Chrome Lighthouse Broken for Mobile Testing?

Question: Here are Chrome Lighthouse scores for three top sites: Uber, AirBnB, and Pizza Hut. Testing is conducted with Mobile selected:

The scores don't seem to match up with the actual mobile page load speed - and seem impossibly low for top high-traffic sites like these.
UBER

AirBnB

PIZZA HUT

Is Chrome Lighthouse broken for mobile testing?
Answer: This is working as expected. Lighthouse, by default and with the settings you showed, throttles the network speed and CPU (simulated). See https://github.com/GoogleChrome/lighthouse/blob/master/docs/throttling.md
Comment: No, it's meant to emulate low end mobile devices and network speeds.

(source: I'm a core contributor to Lighthouse)

see this nice ~1 minute clip from my colleague for a nice summary on why we target low end devices: https://youtu.be/XxvHY4wC8Co?t=95
Comment: you're welcome!

As a lab tool, we're just providing you insights on where you can improve the page experience/metrics. Look to field data (as found in PageSpeed Insights or Search Console) for a closer look into how Google sees the page performance wrt. search signals.

I believe this is the latest on the subject: https://developers.google.com/search/blog/2021/04/more-details-page-experience
Comment: Yes, but I **think** it's just supposed to emulate normal mobile phone network/CPU speeds -- and those sites do work on most mobile phones.
Comment: It's awesome to hear from you! Okay, this resolves this question -- much appreciated! Is there a link for info to help developers evaluate the Google PageRank impact (if any) of a low score here?
Comment: Connor, could you please also take a look at my previous Lighthouse question on SO, [here](https://stackoverflow.com/questions/66805578/understanding-chrome-lighthouse-clear-storage-option)?  I'm trying to understand the "Clear Storage" option.


Drush won't run, 'status' shows web directory twice

Question: I have a multi-site Drupal 8 install and Drush has stopped working. All Drush commands fail with a "Bootstrap failed" error.
"Drush status" shows the /web dir twice as the root. Manually adding the root (--root:path) results in the same 'Bootstrap Failed" error
Any idea why the web directory would show twice in the root?
<code>SITE@mi3-sr25 [~/public_html/web]# drush status
 PHP binary    : /opt/alt/php73/usr/bin/php
 PHP config    : /opt/alt/php73/etc/php.ini
 PHP OS        : Linux
 Drush script  : /home/SITE/.composer/vendor/drush/drush/drush
 Drush version : 9.7.3
 Drush temp    : /tmp
 Drush configs : /home/SITE/.composer/vendor/drush/drush/drush.yml
 Drupal root   : /home/SITE/public_html/web/web
</code>
I've tried Drush 9 and 10. Checked for any duplicate directories, temporarily removed .htaccess No change.
Comment: Instead of editing your question with SOLVED, you should add an answer with the SOLVED info.
Answer: The problem was that there were copies of the composer.json and composer.lock files in the /web directory. I removed those and now everything is working.
Answer: For me this was happening because I was calling an 'external' drush on the system.
While at the same time, a 'local' drush was inside the vendor/ folder via composer requirements.
Same effect: webroot shows twice. Some drush commands running twice.
I simply moved on and started calling the drush inside vendor/, using a symlink for convenience.


Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?

Question: I have the following python code:
class FooMeta(type):
    def __setattr__(self, name, value):
        print name, value
        return super(FooMeta, self).__setattr__(name, value)

class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123
    def a(self):
        pass

I would have expected __setattr__ of the meta class being called for both FOO and a. However, it is not called at all. When I assign something to Foo.whatever after the class has been defined the method is called.
What's the reason for this behaviour and is there a way to intercept the assignments that happen during the creation of the class? Using attrs in __new__ won't work since I'd like to check if a method is being redefined.
Comment: this exact issue is the reason why metaclass syntax has changed in py3!
Answer: A class block is roughly syntactic sugar for building a dictionary, and then invoking a metaclass to build the class object.
This:
class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123
    def a(self):
        pass

Comes out pretty much as if you'd written:
d = {}
d['__metaclass__'] = FooMeta
d['FOO'] = 123
def a(self):
    pass
d['a'] = a
Foo = d.get('__metaclass__', type)('Foo', (object,), d)

Only without the namespace pollution (and in reality there's also a search through all the bases to determine the metaclass, or whether there's a metaclass conflict, but I'm ignoring that here).
The metaclass' __setattr__ can control what happens when you try to set an attribute on one of its instances (the class object), but inside the class block you're not doing that, you're inserting into a dictionary object, so the dict class controls what's going on, not your metaclass. So you're out of luck.

Unless you're using Python 3.x! In Python 3.x you can define a __prepare__ classmethod (or staticmethod) on a metaclass, which controls what object is used to accumulate attributes set within a class block before they're passed to the metaclass constructor. The default __prepare__ simply returns a normal dictionary, but you could build a custom dict-like class that doesn't allow keys to be redefined, and use that to accumulate your attributes:
from collections import MutableMapping

class SingleAssignDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)

    def __getitem__(self, key):
        return self._d[key]

    def __setitem__(self, key, value):
        if key in self._d:
            raise ValueError(
                'Key {!r} already exists in SingleAssignDict'.format(key)
            )
        else:
            self._d[key] = value

    def __delitem__(self, key):
        del self._d[key]

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    def __contains__(self, key):
        return key in self._d

    def __repr__(self):
        return '{}({!r})'.format(type(self).__name__, self._d)

class RedefBlocker(type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        return SingleAssignDict()

    def __new__(metacls, name, bases, sad):
        return super().__new__(metacls, name, bases, dict(sad))

class Okay(metaclass=RedefBlocker):
    a = 1
    b = 2

class Boom(metaclass=RedefBlocker):
    a = 1
    b = 2
    a = 3

Running this gives me:
Traceback (most recent call last):
  File "/tmp/redef.py", line 50, in <module>
    class Boom(metaclass=RedefBlocker):
  File "/tmp/redef.py", line 53, in Boom
    a = 3
  File "/tmp/redef.py", line 15, in __setitem__
    'Key {!r} already exists in SingleAssignDict'.format(key)
ValueError: Key 'a' already exists in SingleAssignDict

Some notes:

__prepare__ has to be a classmethod or staticmethod, because it's being called before the metaclass' instance (your class) exists.
type still needs its third parameter to be a real dict, so you have to have a __new__ method that converts the SingleAssignDict to a normal one
I could have subclassed dict, which would probably have avoided (2), but I really dislike doing that because of how the non-basic methods like update don't respect your overrides of the basic methods like __setitem__. So I prefer to subclass collections.MutableMapping and wrap a dictionary.
The actual Okay.__dict__ object is a normal dictionary, because it was set by type and type is finicky about the kind of dictionary it wants. This means that overwriting class attributes after class creation does not raise an exception. You can overwrite the __dict__ attribute after the superclass call in __new__ if you want to maintain the no-overwriting forced by the class object's dictionary.

Sadly this technique is unavailable in Python 2.x (I checked). The __prepare__ method isn't invoked, which makes sense as in Python 2.x the metaclass is determined by the __metaclass__ magic attribute rather than a special keyword in the classblock; which means the dict object used to accumulate attributes for the class block already exists by the time the metaclass is known.
Compare Python 2:
class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123
    def a(self):
        pass

Being roughly equivalent to:
d = {}
d['__metaclass__'] = FooMeta
d['FOO'] = 123
def a(self):
    pass
d['a'] = a
Foo = d.get('__metaclass__', type)('Foo', (object,), d)

Where the metaclass to invoke is determined from the dictionary, versus Python 3:
class Foo(metaclass=FooMeta):
    FOO = 123
    def a(self):
        pass

Being roughly equivalent to:
d = FooMeta.__prepare__('Foo', ())
d['Foo'] = 123
def a(self):
    pass
d['a'] = a
Foo = FooMeta('Foo', (), d)

Where the dictionary to use is determined from the metaclass.
Answer: There are no assignments happening during the creation of the class. Or: they are happening, but not in the context you think they are. All class attributes are collected from class body scope and passed to metaclass' __new__, as the last argument:
class FooMeta(type):
    def __new__(self, name, bases, attrs):
        print attrs
        return type.__new__(self, name, bases, attrs)

class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123

Reason: when the code in the class body executes, there's no class yet. Which means there's no opportunity for metaclass to intercept anything yet.
Answer: Class attributes are passed to the metaclass as a single dictionary and my hypothesis is that this is used to update the __dict__ attribute of the class all at once, e.g. something like  cls.__dict__.update(dct) rather than doing setattr() on each item.  More to the point, it's all handled in C-land and simply wasn't written to call a custom __setattr__().
It's easy enough to do whatever you want to the attributes of the class in your metaclass's __init__() method, since you're passed the class namespace as a dict, so just do that.
Answer: During the class creation, your namespace is evaluated to a dict and passed as an argument to the metaclass, together with the class name and base classes. Because of that, assigning a class attribute inside the class definition wouldn't work the way you expect. It doesn't create an empty class and assign everything. You also can't have duplicated keys in a dict, so during class creation attributes are already deduplicated. Only by setting an attribute after the class definition you can trigger your custom __setattr__.
Because the namespace is a dict, there's no way for you to check duplicated methods, as suggested by your other question. The only practical way to do that is parsing the source code.


Kendo UI Detailstemplate in Grid Fails Validation

Question: I am using Kendo UI in my ASP.NET MVC 4.0 application.
I have a grid with detailed templates
in my details template i have a form
  @(Html.Kendo().TabStrip()
            .Name("TabStrip_#=UserID#")
            .SelectedIndex(0)
            .Events(e => e.ContentLoad("UserDetailsEditable"))
            .Items(tab =>
            {
                tab.Add().Text("User Details")
                    .LoadContentFrom("UserDetails", "User", new { UserID = "#= UserID #"});
            })
            .ToClientTemplate()

)
This form is not firing validation derived from Model Data annotation.
That because it is not recognizing my validation scripts
 @Scripts.Render("~/bundles/jqueryval")
  bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

if I move this reference @Scripts.Render("~/bundles/jqueryval")
from layout.cshtml to Form view validations will work
but my form post will be done multiple times.
because my script reference will be loaded multiple time for each details template.
How can i over come this problem?
Solution:
I have split jQuery Val bundle
  //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //           "~/Scripts/jquery.unobtrusive*",
            //           "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/unobtrusive").Include(
                       "~/Scripts/jquery.unobtrusive*"));

in my layout i gave only  @Scripts.Render("~/bundles/unobtrusive")
in all my form views i gave  @Scripts.Render("~/bundles/jqueryval")
that solved the problem.
Hope this can help others
Comment: Shouldn't you put your solution in an answer and mark it as the solution? Until you do that this will continue to be marked as "unanswered."
Comment: @jebar8 I was bit confused with Stack overflow terms of answering own question. Any way answered. Thank you
Answer: I have split jQuery Val bundle
 //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //           "~/Scripts/jquery.unobtrusive*",
            //           "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/unobtrusive").Include(
                       "~/Scripts/jquery.unobtrusive*"));

in my layout i gave only @Scripts.Render("~/bundles/unobtrusive")
in all my form views i gave @Scripts.Render("~/bundles/jqueryval")
that solved the problem. Hope this can help others


routing for dynamic block for custom entity

Question: For a custom entity I have created several dynamic blocks. But the blocks are not displayed. They are placed in admin/structure/block. Below is an example of block 1.
myentity.routing.yml:
myentity.blocks:
  path: '/collection/{myentity}'
  defaults:
    _title: 'Stuff collection'
  requirements:
    _permission: 'access content'
    myentity: \d+
  options:
    parameters:
      myentity:
        type: entity:myentity
        bundle:
            - a

Part of src/Plugin/Block:
namespace DrupalCorePluginBlock;

use DrupalCoreBlockBase;

/**
 * Provides a 'Collection' block.
 *
 * @Block(
 *   id = "collection_block 1",
 *   admin_label = @Translation("Collection: Stuff"),
 *   category = @Translation("My Collection"),
 *   context_definitions = {
 *     "myentity" = @ContextDefinition("entity:myentity", label = @Translation("Myentity ID"))
 *   }
 * )
 */
class MyentityBlock1 extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $myentity = $this->getContextValue('myentity');
    return [...];
}

If I replace myentity with node, it works, but for a custom entity I probably need to define something more. But what?
Comment: Maybe this: `$myentity = \Drupal::service('current_route_match')->getParameter('myentity');`
Answer: You can follow Providing global context variables. You have to create a new service to provide a context variable for your custom entity. You can use some entity node, user, taxonomy_term... because them already define.
https://git.drupalcode.org/project/drupal/-/blob/9.3.x/core/modules/taxonomy/taxonomy.services.yml#L7
  taxonomy_term.taxonomy_term_route_context:
      class: Drupal\taxonomy\ContextProvider\TermRouteContext
      arguments: ['@current_route_match']
      tags:
        - { name: 'context_provider' }

https://git.drupalcode.org/project/drupal/-/blob/9.3.x/core/modules/taxonomy/src/ContextProvider/TermRouteContext.php#L48
 /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $result = [];
    $context_definition = EntityContextDefinition::create('taxonomy_term')->setRequired(FALSE);
    $value = NULL;
    if ($route_object = $this->routeMatch->getRouteObject()) {
      $route_parameters = $route_object->getOption('parameters');

      if (isset($route_parameters['taxonomy_term']) && $term = $this->routeMatch->getParameter('taxonomy_term')) {
        $value = $term;
      }
      elseif ($this->routeMatch->getRouteName() == 'entity.taxonomy_term.add_form') {
        $vocabulary = $this->routeMatch->getParameter('taxonomy_vocabulary');
        $value = Term::create(['vid' => $vocabulary->id()]);
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition, $value);
    $context->addCacheableDependency($cacheability);
    $result['taxonomy_term'] = $context;

    return $result;
  }

Comment: Thanks for your help. With the taxonomy example, I was able to quickly add the missing code.


Validar todos os inputs no SUBMIT

Question: Tenho uma função que valida meus campos no evento focusout, porém, agora preciso percorrer todos os campos no submit do form, sei que deveria usar um for, mas não sei como.
$("input[type='text'],textarea").focusout(function () {
    validar($(this))
});

$("#formcontato").submit(function (event) {
    event.preventDefault();
    //O for entraria aqui?
});

$('input, textarea').keypress(function (e) {
    if (e.which == 13 && validar()) {
        request();
        return false;
    }
});

function request() {
    $.ajax({
        url: "minha api...",
        method: "POST",
        data: $(this).serialize(),
        dataType: "json",
        beforeSend: function () {
            //antesEnvio();
        },
        success: function () {
            //sucessoRequest();
        },
        error: function () {
            //erroRequest();
        }
    });
}

function validar(input) {
    var valido = false;
    if (input.attr("id") === "email") {
        var filtro = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (filtro.test(input.val())) {
            input.css("border-color", "green");
        } else {
            input.css("border-color", "red");
            valido = false;
        }
    }
    else if (input.val() === "") {
        input.css("border-color", "red");
        valido = false;
    }
    else if (input.val() != "") {
        input.css("border-color", "green");
    }

    return valido;
}

Comment: Uma forma fácil é definir variáveis globais com o valor false para cada validação, caso passem irão recebendo true, na hora do submit basta verificar se todas estão true.
Answer: Seguindo o mesmo padrão de validação que vc está usando agora, digo para fazer o seguinte:
Primeiro vc deve fazer sua função validar() retornar true sempre que o campo estiver OK, e continuar retornando false quando algo estiver errado no preenchimento do campo.
Depois é só colocar o código abaixo no submit do seu form.
Ficaria assim:
$("#formcontato").submit(function (event) {
    event.preventDefault();
    var success =[],
        inputs = this.elements;

    for (var i = 0, length = inputs.length; i < length; i++ {
        success.push(validar($(inputs[i])));
    }

    if (success.indexOf(false) >= 0) {
        return;
    }

    this.submit();
});

Explicando o que fiz:
A variável success é um array. A cada loop do for a função validar() vai retornar true ou false (se o campo estiver ok ou não), e esse retorno sempre é inserido na variável array success através do método push().
O método push() serve para inserirmos um novo valor no final de um array.
Ou seja, ao final do loop nosso array estará preenchido com vários true e false.
Seguindo...
O método indexOf() serve para buscarmos em um array um determinado valor. Se ele encontra o valor passado como argumento ele retorna a posição dentro do array (índice) onde o valor se encontra. Se ele NÃO encontra ele simplesmente retorna o valor -1.
No nosso caso eu verifico se no array success existe algum FALSE. Se tiver, eu interrompo o script antes de chamar o submit() manualmente.
Comment: Muito obrigado, me salvou. Mas poderia me explicar a função? Minhas dúvidas são o que esses trechos:                              success.push(validar($(inputs[i])));   ------ success.indexOf(false) >= 0
Comment: @TiagoSilveira, editei a minha resposta para sanar suas dúvidas. :)
Answer: Para validar texto e e-mail no submit você pode combinar o type mais required do HTML5 que ele não irá permitir a submissão se o dado for inválido.
Exemplo

<form>
    <input type="email" required>E-mail

    <input type="text" required>Texto

    <input type="submit">Enviar
</form>

Validar todos os inputs no SUBMIT


Cauchy Riemann Equation Complex Variable

Question: For any function $b=\ln[(x-1)^2 + (y - 1)^2 ]$ is harmonic and does not include the point $(1,2). $
Find a function $a$ such that $a + ib$ is analytic.
Express $a + ib$ as a function of $z.$
Comment: Hi and welcome to the site. Please learn LaTeX and MathJax typesetting. It will help getting good responses.
Comment: Maybe I do. But first you need to learn how to ask people in a way that makes them want to help you.
Comment: Hint: $b = \int b_y\,dy = \int a_x\,dy$.
Comment: @mathreadler Respected Sir you got me wrong. I apologize. I was just asking that do you know how to solve then please tell me.
Comment: No harm done in this case, but as a general rule of thumb it can be a good idea to ask the question in a more humble manner and also show any own attempts especially if it looks like it could be a homework question. Otherwise it is easy to attract both minus votes and candidacy for closure.
Comment: @mathreadler Thank you Sir for helping me. I have got the answer. Sorry to say but it's in one hand how to take one thing as positive or negative. I am being nice to you still but I didn't understand your above comment. I neither understand the thumb up thing. I will recommend everyone to take everything as a positive and don't show ego. Ego can ruin anyone. Thanks again. No hard feelings.
Answer: Move the point $(1,1)$ (not $(1,2)$, as indicated) to $(0,0)$.Then we are given the harmonic function $$h(x,y):=\log(x^2+y^2)=2\log|z|\ ,$$
whereby $z:=x+iy$. Now we all know that $z\mapsto\log|z|$ is the real part of the analytic function
$${\rm Log}(z):=\log|z|+i\>{\rm Arg}(z)\ ,$$
which is defined in the complex plane with the negative real axis removed. The expression ${\rm Arg}(z)$ appearing here is the principal value of the argument, i.e., the polar angle $\phi$ of $z$ restricted to $-\pi<\phi<\pi$. It follows that a function $z\mapsto b(z)$ of the required kind is given by $b(z)=2\>{\rm Arg}(z)$. But there is no function $z\mapsto b(z)\in{\mathbb R}$ of the required kind that is defined in the full punctured plane $\dot{\mathbb C}$.


Sorting elements on page Alphabetically

Question: I am trying to sort the text content of divs on a page on button click.
JS Fiddle Link:
https://jsfiddle.net/Jamescodes/4k7xonqv/188/
HTML
  <button id="myBtn">
    Sort Em!
  </button>

Steve

Dex

Bob

Colin

James

Margie

Albert

CSS
.red {
  color: red;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}

.cyan {
  color: cyan;
}

.blue {
  color: blue;
}

.purple {
  color: purple;
}

div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}

button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}

JavaScript
function sortThem(s) {
  console.log('sorting');
  Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort(ea, eb) {
    var a = ea.textContent.trim();
    var b = eb.textContent.trim();
    console.log(a, b);
    if (a.textContent  b.textContent) return 1;
    return 0;
  }).forEach(function(div) {
    div.parentElement.appendChild(div);
  });
}
// call it like this
document.getElementById("myBtn").addEventListener("click", function() {
  sortThem('div.sortme')
});

the divs are not being sorted as i would expect them to be when i call the function on click. can someone help me understand why?
Comment: do you want to sort them only when clicket on sort button ? and also , do you want to have same color after sorted ?
Answer: maybe it is safer to have it in a parent container like this, and simplify your code.

const sortThem = (parentId, selector) => {
  const parent = document.getElementById(parentId);
    const divs = [...parent.querySelectorAll(selector)];
  divs.forEach(div => div.remove());
  divs.sort((a, b) => (a.innerText > b.innerText) ? 1 : -1);
  divs.forEach(div => parent.append(div));
}

document.getElementById("myBtn").addEventListener("click", function() {
  sortThem('parent', 'div.sortme')
});
.red {
  color: red;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}

.cyan {
  color: cyan;
}

.blue {
  color: blue;
}

.purple {
  color: purple;
}

div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}

button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}
 <button id="myBtn">
   Sort Em!
 </button>

Steve

Dex

Bob

Colin

James

Margie

Albert

Answer: In the sort function, you should be comparing a and b instead of comparing a.textContent and b.textContent

    function sortThem(s) {
      console.log('sorting');
    Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) {
      var a = ea.textContent.trim();
      var b = eb.textContent.trim();

        if (a  b ) return 1;
        return 0;
    }).forEach(function(div) {
        div.parentElement.appendChild(div);
    });
}
// call it like this
  document.getElementById("myBtn").addEventListener("click", function(){
    sortThem('div.sortme')
  });
red {
 color: red;
}
.orange {
 color: orange;
}
.yellow {
 color: yellow;
}
.cyan {
 color: cyan;
}
.blue {
 color: blue;
}
.purple {
 color: purple;
}
div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}
button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}
  <button id="myBtn">
    Sort Em!
  </button>

Steve

Dex

Bob

Colin

James

Margie

Albert

Sorting elements on page Alphabetically


Why need to pass jQuery object as parameter to closure?

Question: To avoid global variables in JavaScript code I many times seen that people use this construct:
(function($) {
    // here code
    // here code
})(jQuery);

So I have questions: why we need to declare function argument as $ and why we need to pass jQuery object as argument?
Comment: What does this have to do with [Clojure](http://clojure.org/)? Do you mean "a closure"?
Comment: What happens if you're using `$` in other pieces of code to mean something that isn't _jQuery_?
Answer: You don't have to. You can name the function argument whatever you want it to be. It is just a common/best practice of people using jQuery since it is common to use $ as an alias to jQuery library object.
The reason why you should do it is because there are other libraries that use $ as an alias to their library objects. It is needed to avoid collisions with those libraries since function closure will ensure $ to be jQuery object inside the wrapper function.
Here's an example:
(function (myJqueryAlias) {
     console.log(myJqueryAlias('document') === jQuery('document'));
})(jQuery);

Comment: I know all about $. you should read my updated answer
Comment: Your `===` test will never pass - jQuery will create a brand new object for `$('document')` every time you invoke it that'll have a different reference each time.
Comment: It does not really matter that $ is already defined by jQuery unless you are 100% sure that $ will never be overwritten by other libraries or by your code.
Comment: @Juno  can I access to jQuery's `$` object within this closure? If I can it's mean that sens of passing jQuery object as parameter is _only avoiding collisions_ when accessing to `$`?
Comment: If you want to use $, you just have to name your parameter as $.
Answer: With this you archive that in this block you still have $ as jQuery and you can still write stuff like "$("selector")" instead of "jQuery("selector")".
And outside this block the variable $ is still what it should be (for example you use another JSLib that uses the $ too)
Comment: i.e. within closure I didn't have access to `$` variable? Or the only reason to explicitly pass `jQuery`  as `$` is to avoid collisions?
Comment: @MyTitle yes when outside of this function jQuery.noConflict() is called then u dont have access to $. See http://api.jquery.com/jQuery.noConflict/ for more informations


How to speed up VueJS SPA?

Question: I have a website written in Laravel and InertiaJS (VueJS).
It has more than 60 pages.
InertiaJS stores all pages and components in these three files:
/js/manifest.js
/js/vendor.js
/js/app.js
The problem is the size of these files (Specially app.js) are getting so huge! The app.js is about 5MB.
I removed useless plugins and libraries, Also i refactored my code and it's all clean.
When i was only using Laravel for web development, I could load each page javascript and css files in it's own page. So speed of the page was pretty good. But when i migrated to VueJS it loads app.js and styles.css at once! It also extracts all styles in one file which is not ideal.
Also i use CDN, gzip compression, SSR and they are not helping too much to have better performance.
I want extract all components and pages into different javascript/css files and load them in their own pages when needed.
How can i do that ?
Answer: Here's your app.js using code splitting. See if it'll reduce your load size:
import Vue from 'vue';

const App = () => import('./App.vue');
const Link = () => import('@inertiajs/inertia-vue/Link');
const plugin = () => import('@inertiajs/inertia-vue/plugin');
const BootstrapVue = () => import('bootstrap-vue/dist/bootstrap-vue.esm');
const IconsPlugin = () => import('bootstrap-vue/dist/bootstrap-vue-icons.esm');
const Ziggy = () => import('ziggy-js');
const InertiaProgress = () => import('@inertiajs/progress');

Vue.component('inertia-link', Link)

Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.use(plugin)

InertiaProgress.init()

Vue.mixin({
    methods: {
        route: (name, params, absolute) => Ziggy().then(ziggy => ziggy.route(name, params, absolute)),
    },
});

const app = document.getElementById('app')

if (app.dataset.page) {
    new Vue({
        render: h => h(App, {
            props: {
                initialPage: JSON.parse(app.dataset.page),
                resolveComponent: name => import(`./Pages/${name}.vue`).then(m => m.default),
            },
        })
    }).$mount(app)
} else {
    const app = new Vue({
        el: '#app'
    });
}

See this: Inertia doc
Comment: I really appreciate you. Inertia Docs Helped me with that.
Comment: Hi, i have the same problem here, When i follow inertia docs and do what documentation says, InertiaJs do not create javascript and style tags of extracted components in final output.
Comment: @MohammadZarifiyan is it a Laravel project? What do you mean by 'not creating js...'? Can you provide some codes?
Answer: Are you loading all the pages at once?
I think you can try loading components only if required. We can use lazy loading and reduce app.js. Ref: https://router.vuejs.org/guide/advanced/lazy-loading.html#with-webpack
        render: h => h(App, {
            props: {
                initialPage: JSON.parse(app.dataset.page),
                resolveComponent: name => require(`./Pages/${name}`).default,
            },
        })
    }).$mount(app)

This is my app.js file.
require('./bootstrap');

import {App, Link, plugin} from '@inertiajs/inertia-vue'
import Vue from 'vue'
import {BootstrapVue, IconsPlugin} from 'bootstrap-vue'
import route from 'ziggy-js';
import {Ziggy} from 'ziggy-js';
import {InertiaProgress} from '@inertiajs/progress'

Vue.component('inertia-link', Link)

Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.use(plugin)

InertiaProgress.init()

Vue.mixin({
    methods: {
        route: (name, params, absolute) => route(name, params, absolute, Ziggy),
    },
});

const app = document.getElementById('app')

if (app.dataset.page) {
    new Vue({
        render: h => h(App, {
            props: {
                initialPage: JSON.parse(app.dataset.page),
                resolveComponent: name => require(`./Pages/${name}`).default,
            },
        })
    }).$mount(app)
} else {
    const app = new Vue({
        el: '#app'
    });
}

Comment: I'm using Inertia JS and Laravel, What all people are talking in this forum are about Vue Router and other stuff. :(

Please read whole question again.
Comment: Can you share your app.js code? Why do you have manifest.js and vendor.js files in your js directory? What I'm familiar with is that this directory only contains your shared components, layout files, pages, app.js and bootstrap.js files.
Comment: @viking i understand you are using Inertia, what i means is are you loading dynamically without code splitting. That would be the issue i am tried to say. I uploaded the whole file. Vue router is the main place to load these components. That's why I am talking about vue router.
Comment: I believe what @PyaeSone says about code splitting should resolve your problem. I don't think this is an Inertia bug. Your app.js doesn't code-split, it loads all your pages.

How to speed up VueJS SPA?


Hibernate Search upgrade for JDK-17 and Jakarta Persistence APIs

Question: We are experimenting with JDK-17 migration. One of the steps was to migrate from javax.persistence to jakarta.persistence libraries.
Looks like Hibernate search is yet to upgrade to Jakarta Persistence. Could you please share if this is planned in future releases. or any alternatives.
Please be informed that we have tried with both  6.1.8.Final & 6.2.0.Alpha1 versions.
Thanks in advance
Answer: Hibernate Search 6.1+ does work with Jakarta Persistence and/or Hibernate ORM 6, but you have to switch to different Maven artifacts:

Artifacts suffixed with -orm6 for Hibernate ORM 6: https://docs.jboss.org/hibernate/search/6.1/reference/en-US/html_single/#other-integrations-orm6
Artifacts suffixed with -jakarta for Hibernate ORM 5's -jakarta artifacts: https://docs.jboss.org/hibernate/search/6.1/reference/en-US/html_single/#other-integrations-jakarta

See also https://hibernate.org/search/releases/#compatibility-matrix
Hibernate Search 7+ will use Hibernate ORM 6+ out of the box, in the main artifacts (no -orm6 suffix needed).


Why does selecting elements by the accessible name and checked state not work here?

Question: I'm trying to write a test where I select all the checked checkboxes using React Testing Library. I am able to use wrapper.getAllByRole('checkbox'); to get all of the checkboxes, but once I try to get the ones that are checked with wrapper.getAllByRole('checkbox', { checked: true }); then I get the error messaage:
TestingLibraryElementError: Unable to find an accessible element with the role "checkbox"

I saw that in the official docs, this is listed as a possibility so I'm not sure why it doesn't work here.
Even stranger, is that I can see that the checkbox elements are shown in the console:
TestingLibraryElementError: Unable to find an accessible element with the role "checkbox"

Here are the accessible roles:

checkbox:

      Name "":
      <button
        aria-checked="false"
        class="checkbox-module_checkbox__obRBR"
        data-state="unchecked"
        role="checkbox"
        type="button"
        value="folderType"
      />

      Name "":
      <button
        aria-checked="false"
        class="checkbox-module_checkbox__obRBR"
        data-state="unchecked"
        role="checkbox"
        type="button"
        value="fileType"
      />

      ...

What am I missing here?
Answer: It seems that queryAllByRole works; perhaps whatever getAllByRole was returning was the issue


Does $(n^p-1)/(n-1)=m^2$ have any positive integer solutions for $p\ge 2$ prime?

Question: I was working on my partial answer to this question, which led me to consider the diophantine equation
$$
\frac{n^k-1}{n-1}=m^2
$$
with $k>1$ odd. It's not too hard to prove that if $(n,k)$ is a solution, then if $k$ is a perfect square, $(n,p^2)$ is a solution for all $p\mid k$, and otherwise $(n,p)$ is a solution for $p\mid k$ the largest prime factor of $k$ with $\operatorname{ord}_p(k)$ odd.
Therefore, it is natural to ask whether there are any solutions with $k=p$ prime.
I have absolutely no idea to start. Perhaps note that
$$(m^2)=\prod_{i=1}^{p-1}\left(n-\zeta_p^i\right)\subseteq\mathbb{Z}[\zeta_p],$$
and that all the ideals in this product are pairwise coprime. Therefore, they must all be squares of ideals in $\mathbb{Z}[\zeta_p]$. Also, if $q\mid m$ is prime, then $q\equiv 1\pmod p$ and the decomposition of $(q)$ in $\mathbb{Z}[\zeta_p]$ is
$$
(q) = \prod_{i=1}^{p-1}\left(q,n-\zeta_p^i\right),
$$
whence $\left(q,n-\zeta_p\right)^2\mid \left(n-\zeta_p\right)$. I have no idea to continue. Perhaps if the class group of $\mathbb{Q}(\zeta_p)/\mathbb{Q}$ has odd order, we can use that $(n-\zeta_p)$ must be the square of a principal ideal?

Descending solutions: Suppose $(n,k)$ is a solution and $p^2\mid k$ for some prime $p$, then
$$
\frac{n^k-1}{n^{k/p^2}-1}\cdot \frac{n^{k/p^2}-1}{n-1} = m^2.
$$
Let $q\mid n^{k/{p^2}}-1$ be prime, then $\frac{n^k-1}{n^{k/p^2}-1}=\sum_{j=0}^{p^2}(n^{k/p^2})^j\equiv p^2\pmod q$. Hence, the only prime that can possibly divide both $\frac{n^k-1}{n^{k/p^2}-1}$ and $\frac{n^{k/p^2}-1}{n-1}$ is $p$.
However, if $p$ divides both, let $t:=\operatorname{ord}_p(n^{k/p^2}-1)$ and let $g$ be a primitive root mod $p^{t+3}$. Write $n^{k/p^2}\equiv g^a\pmod {p^{t+3}}$, then $\operatorname{ord}_p(a)=t-1$, whence $\operatorname{ord}_p(p^2a)=t+1$, so $\operatorname{ord}_p(n^k-1)=t+2$. We conclude that $\frac{n^k-1}{n^{k/p^2}-1}$ and $\frac{n^{k/p^2}-1}{n-1}$ are both perfect squares.
In particular, $(n,k/p^2)$ is a solution. This way, we can remove the $p^2$ factors from $n$ one by one, until we're either left with an exponent which is itself a square of a prime (if $k$ is a perfect square) or with a square-free exponent.
Assume we end up with a solution $(n,k)$ with $k$ square-free. Let $p\mid k$ be the smallest prime factor of $k$. Note that the product of $(n^k-1)/(n^{k/p}-1)$ and $(n^{k/p}-1)/(n-1)$ is a perfect square, and that $p$ is the only prime that can possibly divide both. However, $(p-1,k/p)=1$, so if $p\mid n^{k/p}-1$ then $p\mid n-1$ and $p\nmid (n^{k/p}-1)/(n-1)$. Therefore, $(n^{k/p}-1)/(n-1)$ is a perfect square, and $(n,k/p)$ a new solution. This is how we can remove the primes from $k$ one by one, until only the largest remains.
Comment: There's probably a discussion of this question in Richard Guy's book, Unsolved Problems In Number Theory.
Comment: $n=3,k=5$ is a solution. No idea whether there are more.
Comment: Here's a way we can maybe exclude primes $p\equiv 3\pmod 4$ for which  $\mathbb{Q}(\sqrt{-p})$ has odd class number. Over $\mathbb{Z}[\sqrt{-p}]$ we can factor $\Phi_p=f\cdot g$ as the product of two irreducible polynomials of degree $(p-1)/2$. Now, $(f(n))\cdot (g(n))$ is the square of an ideal and the two factors are coprime, so $(f(n))=I^2$ for some ideal $I$. Because the class number is odd, $I$ is principal, so $(f(n))=(a+b\sqrt{-p})^2$. Because the unit group of $\mathbb{Z}[\sqrt{-p}]$ is $\{\pm 1\}$, we find that $f(n) = \pm[a+b\sqrt{-p}]^2$. Solve for $a$ and $b$.
Comment: Of course the above needs $p>3$ for the unit group to be $\{\pm 1\}$
Comment: $n-1\equiv m\pmod 2$ or $n-1\equiv 0\pmod 2$
Answer: The only solutions to $\frac{x^k-1}{x-1}=y^2$ correspond to the identities
$$
\frac{3^5-1}{3-1}=11^2 \; \mbox{ and } \; \frac{7^4-1}{7-1}=20^2.
$$
This was proved by Ljunggren in 1943 (the proof is in Norwegian which makes it arguably less accessible than desired). I'm embarrassed to admit that I haven't actually looked at the proof, but would suppose that it uses $p$-adic techniques along the lines of Skolem's method.
Comment: Thanks for the reference! There is actually a Mathoverflow post which summarizes the proof: https://mathoverflow.net/questions/206645/on-a-result-attributed-to-w-ljunggren-and-t-nagell
Comment: Should the second identity be $\frac{7^4-1}{7-1}=20^2$?


Running Linux on a read only disk - possible?

Question: I'm wondering if it is possible to run a Linux server from a read only disk, specifically CentOS 5.4.
Our system has a number of Linux machines each with their own disk with it's OS installed.  Everything is read/write enabled at the moment.  We're booting from these disks but running all our software that we develop on some external disks shared over NFS.
What we want to be able to do is ensure that nothing is ever written to the internal disk with the OS on it, only to the external drive shared through NFS.  I'm thinking we can probably manage this by editing the /etc/fstab file and mounting the drive as read only.
So if we took an image of the internal disk then booted the system, ran our software (which would only touch the external disks), then shut down the system and took another image of the internal disk there wouldn't be a single byte different.
The OS itself is going to want to write its own log files etc so I can't see that mounting the drives as read only would result in a functioning operating system - or would it?
I can only think some kind of network boot would achieve this, but there is zero possibility of adding an extra machine to act as a DHCP and TFTP server for this.
Any help or ideas would be much appreciated! :)
Answer: Yes, it's possible to run a Linux server with read-only media. See Devil Linux; those servers run off a CD disc.
You can create a writable space for things like log files by using a RAM disk. Space will be very tight, though. I wouldn't recommend doing this except for very specialized circumstances.
In most cases you can hybridize the process; most of the server is read-only but there's a scratch space for log files with an internal drive or USB drive.
You can also do this with bootable Linux routers, as I've seen them made to boot from a floppy that's read-only.
Another drawback is updates. The thinking was that even if someone were to crack some flaw, they couldn't do much damage since they can't alter system files or anything like that, I guess. Periodically you update the master image or get the newest ISO image and use that to boot from as the update; with the Devil Linux server I had experimented with I had the ISO image to boot from then used a USB disk to pull the configuration-specific files for that server. Alternatively you can edit the files required for your particular setup and re-integrate them with the CD's /etc directory and re-burn the disc.
Anyway, yes, it can be done, but it's a maintenance hassle and something to only be considered in very specialized cases.
Answer: <code>"I'm wondering if it is possible to run a Linux server from a read only disk, specifically CentOS 5.4."
</code>
No, the server will need some place to write data.  Logs are a good example of this.
You can however setup partitions in such a way that the system is separate from the rest of your storage.
For example, I usually partition a desktop to have a /home/ partition for user data, a root partition / for the rest and then any additional drives I will partition on their own and add to fstab after install to mount them where they belong.
Answer: I guess it is possible - I suppose you should take a closer look at the Live CDs, and make a custom live cd.
Answer: Start your systems not from hard disk but from hardware write-protected Live USB flash drive. There's an utility in Fedora - livecd-iso-to-disk - which also works for Centos LiveCD. You can customize it easily using "overlay" feature and then turn on write protection.
Changes to system disk will be possible but will not survive reboot - they'll be only in memory.
Just mounting partitions read-only would not help much with security, as when system is compromised the first thing a cracker will do will be remounting it read-write. Only physical security will assure that no data on disk is changed.
But you'll never receive security updates for this systems, so you'll need to be very careful.


Is it possible to open Play Store from application with a predefined search?

Question: The following code opens Play store from my android application:
final String appPackageName = getPackageName();
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
                            .parse("market://details?id=" + appPackageName)));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(
                            Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id="
                                    + appPackageName)));
                }

Programmatically i want the user to see the search result for all the "File Explorers" available on the Play store as soon as it opens. When i fire the intent, what i see is Picture1 what i want is Picture2. Is it possible? Thanks in advance.

Answer: Try this:
startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse("market://search?q=File%20Explorers")));

"market://" is resolved to the google play store URL and the "search?q=File%20Explorers" will open the search for the given parameters. %20 is the encoding for a space.


how to solve $y''=-\frac{1}{2y^2}?$

Question: i've been learning special kind of second order non-linear ODE,of the form f(y,y') and f(t,y').I came across a question which I'm not able to reach to the solution.Can someone help me with the method...
Comment: @callculus $\frac{y''}{y^2}$ does not seem immediately the second derivative of anything.
Comment: Hint: Divide the equation by $y^2$ and integrate both sides twice.
Comment: Thus, $$2y''y'=-\frac1{y^2}y'$$ and both sides are exact derivatives. Can you continue?
Comment: @callculus The funny thing is your comment got upvoted. Twice...
Comment: @G.Sassatelli You´re right. My comment was overhasty.
Answer: Maple's solution entails solving a transcendental equation.
To start.  Note that the variable $x$ does not appear explicitly.  (The equation is autonomous).  So we can make a substitution like
$u=y'$ to change it to a first-order equation for $u$ as a function of $y$...
$$
u=y'
\\
\frac{du}{dy} = \frac{u'}{y'} = \frac{y''}{y'} = \frac{-1}{2uy^2}
\\
2uy^2\frac{du}{dy} = -1
$$
Then solve as usual...
$$
2u\;du = -\frac{dy}{y^2}
\\
u^2 = \frac{1}{y}+C
$$
Now substitute $u=y'$ back in to get first-order (but non-inear) differential equation for $y$
$$
(y')^2=\frac{1}{y}+C
$$
Here is where we end up with a transcendental equation.
One case for each of two square roots, let's do this one
$$
y'= \sqrt{\frac{1}{y}+C}
\\
\frac{dy}{\sqrt{\frac{1}{y}+C}} = dx
\\
1/2\,{\frac {y}{\sqrt {y \left( Cy+1 \right) }{C}^{3/2}}\sqrt {{\frac
{Cy+1}{y}}} \left( 2\,\sqrt {y \left( Cy+1 \right) }\sqrt {C}-\ln
 \left( 1/2\,{\frac {2\,Cy+2\,\sqrt {y \left( Cy+1 \right) }\sqrt {C}+
1}{\sqrt {C}}} \right)  \right) }
= x+C_2
$$
(I let Maple do the integral.)
And now merely solve for $y$...
Comment: Please replace every $$-\frac1y$$ by $$+\frac1y$$

how to solve $y''=-\frac{1}{2y^2}?$


temperament - its effect on a key

Question: Most of Western music is now played in 12et/edo, where a key change won't make an appreciable difference to how it sounds - providing voicings are the same.
Back in other temperamental days, let's take a piece written in, say, C major. If that was then transcribed to, say, Eb major, and replayed, would it actually sound any different, apart from being a m3 higher in pitch? Or, given the vagaries of instruments tuned to other than 12et, would it sound different?
Answer: It certainly would sound different. How different would depend on the particular temperament.
In the "mean-tone" temperaments that were widely used before J S Bach's time, and still used during his lifetime by some conservative organ builders, some keys were so out-of-tune as to be unusable. These temperaments were usually based on a cycle of 5ths from E flat up G sharp, and next lowest and highest fifths (i.e. A flat - E flat and G sharp - D sharp) were not usable, since Ab was a significantly different pitch from G sharp, etc.
Therefore, in your specific example, transposing a piece to E flat would probably sound horrible, since the A flats would actually sound as G sharps.
In the "well-temperaments" of Bach's time, all 12 major and minor keys were playable, but they certainly had their own distinctive sounds. If you study (and listen) to Bach's two and three part inventions, for example, you find that he makes deliberate use of the differences - and those pieces were written not only as teaching material for performers, but also for composers.
The same thing occurs in his major works.An example is the organ prelude and fugue in D Major BWV532, which starts with a passage of scales and arpeggios on a D chord, ending in a cadence on A. So far, all very nicely "in tune," but followed after a pause, by a lurch to F# major and its dominant C#7 - a "WTF" moment in unequal temperament, with the chords sounding as F#-Bb-C# and C#-F-G#-B! This is followed by another abrupt change, back to D major harmony.
This is a recording on an organ tuned to Valotti temperament where the tuning differences are fairly "mild" compared with some of the other baroque temperaments - but the effect is audible.

Contemporary writers noted that Bach sometimes used to "wind up" his favourite organ builder, Silbermann, who took a very conservative position on tuning systems, by deliberately using the out-of-tune chords when trying out a newly built instrument.
Modern digital organs (and other sound synthesis systems) often have the capability to switch between several historical temperaments. Experimenting with one will answer the question better than reading a wall of text!
Comment: **Modern digital organs (and other sound synthesis systems) often have the capability to switch between several historical temperaments. Experimenting with one will answer the question better than reading a wall of text!** Bolded in comment for truth. Apple Logic Pro X in particular has a *huge* range of temperaments and tunings that can be used with any of the equally huge number of virtual instruments included. The biggest catch is you have to have a Mac. And $200.
Comment: This covers organs mostly, and thank you for that. I'm wondering partly, though, if , say, a piece for strings, if written in C, played in C, would sound much different if written in Eb (for example), and played from those dots. What I'm getting at is a 4th or a 5th in any key is going to be the same, isn't it, in any similar tuning temperament. Not one instrument built around one good key, as I guess harpsichords, for instance, were tuned. I understand that a harpsichord tuned to C wouldn't sound good played in Eb,
Comment: @Tim I think you're mixing together a lot of separate things. A piece written purely for strings, or for any non fixed pitch instruments, isn't really in any temperament at all. The word temperament (at least in the sense you're using it) only really makes total sense with fixed pitch instruments like keyboards. An unfixed string instrument won't always play any pitch at the exact same frequency and will generally tend to something closer to just intonation. When you talk about a harpsichord tunes to the key of C it sounds like you're talking about a just intonation harpsichord, which would…
Comment: exceedingly rare. Unfixed pitch instruments and just intonation in general are untempered phenomena. If one wishes to make more than a few keys usable on a fixed pitch instrument, then one has to temper the instrument. That's where equal temperament and well temperament come in. There's (theoretically) no difference between keys on ET, but there will be differences in WT.
Comment: @PatMuchmore - yes, I'm probably mixing a lot of things. I'm also mixed up, otherwise the question wouldn't be asked. Why not put all this, and more down in a great answer?
Comment: @Tim I guess because Alephzero's answer is really good and I don't have much to add beyond trying to help with the misconception of your comment.
Comment: @Tim - have you heard any of Ben Johnston's string quartets? It's amazing how the relative tuning of the group makes the pitch center sag and blossom; it can be a real roller coaster.
Comment: @PatMuchmore - I'm looking for Alephzero's answer, and it eludes me.
Comment: @Tim -- Alephzero left the site a while back, but I think that this answer by the user formerly known as Alephzero (user19146) is the one to which PatMuchmore refers.
Comment: @Tim Yeah, my comment and the answer it's on are almost a full year old, so I don't remember for certain, but I think David must be right that I was talking about the answer these comments are attached to.
Comment: @PatMuchmore - seems like Alephzero took comments/questions/answers with him! Opportunity for your answer now!
Answer: It sounds different to me if people play in 12et or not, which makes different keys sound different.  Of course, to what extent depends on how far the tuning differs from equal temperament.
Comment: Sounds like you could be 'afflicted' with absolute pitch ! However, if you've never heard a piece before, the key becomes academic.That's not what I was trying to ask within the question.
Comment: Tim- I'm only afflicted with relative absolute pitch: I can produce a pretty good "A" if not disturbed, but not in the heat of the battle.  But yes, I do understand what you were getting at.  To be very specific, take Kirnberger III: it was a typical Baroque temperament, and it has three just (5/4) major thirds, three abysmal Pythagorean (81/64) major thirds, and the rest in between.  In normal C-centered Kirnberger, the major third between Eb and G is one of the Pythagorean ones.  This is a very audible difference.

temperament - its effect on a key


Use Functions from one Google Script in many different tables (google-sheets)

Question: I wrote the google-script. In that script I have a function that I need to use in 250+ different tables (google-sheets). Question is - How can I make it function accessible in each table?
Answer: To make a script or custom function available across other Google Sheets, publish it as a library.
Bruce Mcpherson has a nice post on how to do this: http://ramblings.mcpher.com/Home/excelquirks/gooscript/lib
Comment: by that way I can use my func in sheet only after creation new project in each table and import that library with my func and call in new func in new project from imported project? May be is there a solution to just write `=myLib.myFunc()` in cell?
Answer: Yes, it is possible.
Two options:

Create a Apps Script project that calls the 250+ spreadsheet, makes the operations and  updates each spreadsheet which the results.

On this you'll find a collection of tutorials to start with apps script.
https://developers.google.com/apps-script/articles/tutorials

Create a function that you can call from any cell of your spreadsheet just as you call any other default function like SUM()

On this documentation you'll find explained how to do this second option.
https://developers.google.com/apps-script/guides/sheets/functions#arguments
Answer: Ok, I fond the solution. In my case files that I need to change is placed in deferent folders and have similar name
<code>// function that i need to execute
function updatePrices(sheetId){
  // do some staff
  var activeSpreadsheet = SpreadsheetApp.openById(sheetId);
  var histPricesSheet = activeSpreadsheet.getSheetByName(someSheetName);
  ....
  var cell = histPricesSheet.getRange(range);
  cell.setValues(someData);
}

function walkFolders(folderId){
  // function that walk by folders and get ids of spradsheeds
  and call func that I need in each spradsheed that I need

  var fin_fold = DriveApp.getFolderById(folderId);
  var folders = fin_fold.getFolders();

  while (folders.hasNext()) {

    var folder = folders.next();
    var files = folder.searchFiles('title contains "карточка"');

    while (files.hasNext()){

      var file = files.next();

      updatePrices(file.getId());    // call my function to every spreadsheet
      Logger.log("обновлено");
    }
  }
}

walkFolders("folder ID wich contain folders with files to change");
</code>


Retorno com varios json com jquery .net

Question: Preciso retornar para o ajax um json, ou melhor vários json, sendo cidade,bairro,estado,pais, cada um sendo um json no mesmo método, porem como não e possível fazer vários retorno coloquei as lista dos obj acima em uma lista de lista.
        List < List<String> > final = new List < List<String> >();
        final.Add(cidade);
        final.Add(bairro);
        final.Add(estado);
        final.Add(pais);

logo abaixo retorno o json da lista final
        return Json(final, JsonRequestBehavior.AllowGet);

porem quando vou exibir os dados no ajax, quando acesso a posição dados[1] ou 2 ..., ele pega como uma lista inteira e não como um json, acho que ele retornou o json so as posições  0,1,2... e não o que tem dentro dela, como fazer para retornar esses dados como json

Comment: Tem como mostrar o java scrip que está usando para visualizar?
Answer: controller:
var result = new { cidade, bairro, estado, pais };
return Json (result, JsonRequestBehavior.AllowGet);

"result" é um objeto anônimo
javascript:

Retorno com varios json com jquery .net


Discord music bot fiding yt video

Question: Hi i would like to know how to make my bot play music based on YouTube search because the url copying and pasting pisses me off.The bot have youtube_dl and ffmpg. Here is updateted code its still doesn't working. Sorry for my bad english.
<code>    @client.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            print("Usunięto starą piosenke.")
    except PermissionError:
        print("Próbuję usunąć plik utworu, ale jest on odtwarzany ")
        await ctx.send(":no_entry_sign:  Muzyka już gra!")
        return

    await ctx.send(":mag_right: Szukanie i Pobieranie")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }

    yt = yt_search.build(url)
    search_result = yt.search("keyword", sMax=10, sType=["video"])
    print(search_result)

    with youtube_dl.YoutubeDL(options) as ytdl:
        if url[:4] == 'http':
            ytdl.download([url])
        else: # "yts" is youtube-search imported as
            link = json.loads(yts(url, max_results=1).to_json())['videos'][0]['url_suffix']
            link = 'https://www.youtube.com' + link
            ytdl.download([link])

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Zmnieniono nazwe: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print("Koniec!"))
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.17

    nname = name.rsplit("-", 2)
    await ctx.send(f" :notes: Teraz Leci: `{nname[0]} - {nname[1]}`")
    print("Puszczanie\n")
</code>
Answer: look up documentation on youtube-search. Here's an example:
<code>  with youtube_dl.YoutubeDL(options) as ytdl:
    if url[:4] == 'http':
      ytdl.download([url])
    else: # "yts" is youtube-search imported as
      link = json.loads(yts(url, max_results=1).to_json())['videos'][0]['url_suffix']
      link = 'https://www.youtube.com' + link
      ytdl.download([link])
</code>
Basically saying "if it starts with http then just use as a link. Else, use youtube-search to get a link for the first search result on YouTube." This probably isn't a good way to do it, maybe use a try/except to see if the search works as a link first, with the except retrying passing in the fetched link.
Comment: did you import json and youtube_search
Comment: yes i imported and its still doesnt working
Comment: when you type a command and a song name bot writes that he is looking for the song and then just nothing happens in terminal or on discord, there is no error
Comment: I edited the question it was too long for comment
Comment: make sure to match the variable names. for example, your youtube-dl options are called "ydl_options", while the with statement passes in "options".

Discord music bot fiding yt video


How to check if $\sin\left(\frac{\pi}{3}\right)+\cos\left(\frac{\pi}{4}\right)$ is algebraic

Question:
Prove that $\sin\left(\frac{\pi}{3}\right)+\cos\left(\frac{\pi}{4}\right)$ is algebraic.

Evaluating value of this, it is sum of two irrational numbers. How to find if it is algebraic?
Comment: So what is the problem? You do know the values of these trig functions?
Comment: Are you familiar with the result that the sum and the product of two algebraic numbers are both algebraic?
Comment: yes, I know that
Answer: Hint:
Let $$s:=\sqrt3+\sqrt2.$$
Then $$s^2=5+2\sqrt6$$ and $$(s^2-5)^2=24.$$
Answer: You can find a polynomial $p\in \mathbb{Q}[x]$ with that number as a root.
$\sin(\pi/3)=\frac{\sqrt{3}}{2}$
$\cos(\pi/4)=\frac{\sqrt{2}}{2}$
So the sum is $x=\frac{\sqrt{3}}{2}+\frac{\sqrt{2}}{2}$. To avoid denominators I'm going to consider $2x=\sqrt{3}+\sqrt{2}$. Then
$
2x-\sqrt{3}=\sqrt{2}\Rightarrow (2x-\sqrt{3})^2=2\Rightarrow 4x^2+3-4\sqrt{3}=2\Rightarrow 4x^2+1=4\sqrt{3}\Rightarrow 16x^4+8x^2+1=48
$
Hence, a polynomial with this root is
$p(x)=16x^4+8x^2-47$.
Answer: $$Sin(\pi /3)= \frac{\sqrt{3}}{2} = Root[4x^2-3==0] $$
$$ Cos(\pi /4)=\frac{\sqrt{2}}{2} = Root[2x^2==1] $$
So, both numbers are algebraic and sum of finte number of algebraic numbers is algebraic


Windows Server 2008 - Connecting to 127.0.0.1

Question: Im running Windows Server 2008 R2, we have an application that connects from (binds to) a public IP on the server to 127.0.0.1:8334 [connects to a service listening on 0.0.0.0:8334]
In Windows 2003, there was no issue with this. We can connect using TCP from 126.96.36.199 [eg] to 127.0.0.1:8334 just fine.
In Windows 2008, we find that TCP connections from public ip e.g. 184.108.40.206 to 127.0.0.1:8334 fail, even. but the service accepts connections from 127.0.0.1 to 127.0.0.1:8334, and 127.0.0.1 to 22.214.171.124:8334.
Tried turning Windows firewall off, configuring its logging etc (no useful log entries showed up), to no avail. Is this an issue with the new networking stack?
edits
18.104.22.168 is trying to connect to localhost [127.0.0.1] on the same machine
Hosts file is default Windows 2008 host file.
Loopback check info, interesting. Tried it out...didnt work. Crosschecked to verify that Id done everything correctly - I have.
Im wondering if there is a solution using NAT or some other way to forward ports - if I forward 127.0.0.1:port to 188.8.131.52:port, would that work? Given that the app listens on 0.0.0.0:port it would pick up connections on 184.108.40.206:port
The HOSTS file does contain localhost 127.0.0.1 - however, the hosts file is only used on hostname lookups. In this case, our application would not look up any hostname, since the 127.0.0.1 IP address is hardcoded into it (rather than localhost hostname). So the HOSTS file would not come into play here.
As for ports above 1024 [think you refer to the MaxUserPort issue perhaps?] I tested this out by trying a simple connect to port 445 - works from 127.0.0.1, doesnt work when I connect from source IP 18.104.22.168. 445 is a standard Windows service, so should work!
Currently not running NAT or RRAS on the machine...was wondering if there was a way to do the rerouting - Im guessing it wont work since the TCP/IP stack will reject the packet before it reaches the loopback interface to re-route.
Route print I had checked - seems fine, the public IPs routed first, then finally 127.0.0.0 netmask 255.255.255.0 and 127.0.0.1 netmask 255.255.255.255 both to loopback.
Edit
Seems I have found the answer as to the reason for the problem. I used eventvwr.msc, enabled Winsock logging, turned off other services, just tried this connection test. Got an error which in hexadecimal mapped to STATUS_INVALID_ADDRESS_COMPONENT when I googled it.
That got me to:
http://social.msdn.microsoft.com/Forums/en-US/wfp/thread/d7cb6138-3f67-4467-a068-8325f56739ba
Which confirmed that this is a change by design in WFP for Vista/7/Server 2008 [windows filtering platform].
[See response by Anupama Vasanth]
Looks like I will have to go the hard route and rewrite the code [hard because it means dealing with managers!]
Thank you for helping me locate/confirm the issue!
Comment: Are, in your description, 220.127.116.11 and 127.0.0.1 on the same machine? What do you have for them in hosts file?
Answer: Don't forget, in windows 2008, the firewall is turned on by default.  This potentially can block any & all traffic even on the loopback interface.  Additionally, if you bind to 0.0.0.0, you are accepting connections on ALL interfaces.  The firewall would still block this.  You could try turning off the firewall while testing... and then turn it back on.  I haven't had any issues connecting to various programs I have developed on 127.0.0.1.
Answer: Try connecting to 127.0.0.2 in Vista/win2k8 and above - sounds funny but it works.  Had positive results with this in the past
Answer: I most certain that it is connected with loopback check security feature though I cannot get in-depth detail how it is implemented, only how to overcome it:
http://chillicode.wordpress.com/tag/loopback-check/
And for "APPLIES TO" Windows 2008 see http://support.microsoft.com/kb/896861

Well, what is exactly is in your HOSTS file? I do not have W2008. Do you mean that there is no "127.0.0.1 localhost" there?
I also did read somewhere that default W2008 setup does not permit to communicate with ports greater than 1024.

You can submit feedback on MS Windows Server 2008 directly to MS team through

https://connect.microsoft.com/WindowsServerFeedback

and they will reply
If you tried to switch off "loopback check" through method of registry editing then it requires reboot. Another one - not.
NAT inside machine? 127.0.0.1 is not forwarded or routed, I believe so, it is internal, you can unplug network card, your 18.104.22.168 will disappear but 127.0.0.1 will continue to be there .
What is output of your (Run--> cmd --> route print)?
There is one more moment, I was thinking, though I do not know how to put it together.
127.0.0.1 is localhost (interface), it is single-label name and considered local. 220.127.116.11 is non-singlelabel name.
Possible issues with this is that such name might have been considered external

https://stackoverflow.com/questions/2638862/security-warning-when-opening-file-from-network-share/3435456#3435456

Can you try, separately:

Disabling (if it is enabled and enabling if it is disabled) IPv6 on network adapter?
Putting some single-label name for 18.104.22.168 into HOSTS file?

What is corresponding event description, EventID, etc. in eventvwr.msc for failure to communicate from 184.108.40.206 to 127.0.0.1:8334 ?

"445 is a standard Windows service"

Is it for SMB-direct over TCP/IP? for file sharing? CIFS?
Not so reliable... It is constantly being hacked by MS hotfixes.
 Read:
("NetBIOS browsing across subnets may fail after upgrading to Windows Server 2008")
 - http://blogs.technet.com/b/networking/archive/2008/07/25/netbios-browsing-across-subnets-may-fail-after-upgrading-to-windows-server-2008.aspx?wa=wsignin1.0

http://keznews.com/34562=NetBIOS_browsing_across_subnets_may_fail_after_upgrading_to_Windows_Server_2008

Then,

http://social.technet.microsoft.com/Forums/en-US/winserverfiles/thread/a0c533f5-100d-4a5f-91d3-bbcb5d47aaf0
("Windows Server 2008 does not use CIFS to connect to network shares")
tells:

"we have the same issue as described
  earlier with Vista SP2 machines trying
  to reach a Windows Server 2008 SP1 or
  SP2 file share. The file sharing
  service is protected by Windows
  Firewall with advanced security using
  a predefined rule for file sharing
  (SMB) reguesting a secure connection"