Is it possible to group services in sails using subfolders?

Question: Is it possible to group services files into subfolders under services in sails.js? This speaks about grouping controllers. How do I do the same for services?
Answer: You could try something like this

services/

FooBar/

foo.js
bar.js

FooBarService.js

Your FooBarService.js should just require everything inside FooBar/
/**
 * FooBarService
 */

module.exports = {
    foo: require('FooBar/foo.js'),
    bar: require('FooBar/bar.js')
};

Or if you want to make it more sails-y, use include-all. It is include in all sails projects, and is used everywhere in sails
/**
 * FooBarService
 */

module.exports = require('include-all')({
    dirname: __dirname + '/FooBar',
    filter: /.+\.js$/
});


How do archaic instruments affect contemporary music?

Question: Many once-common instruments are now rare or obsolete. For example, some transposing instruments have fewer variants than they used to – the B♭ soprano clarinet has largely supplanted the A and C clarinets. Other instruments, like the grand piano, overshadow earlier members of their family like the fortepiano, clavichord, and harpsichord. How does this affect contemporary performance?
Specifically, do older works fall out of favor because of archaic instrumentation? Do performers adapt and arrange the works to suit contemporary instruments? Do older works keep archaic instruments in use, among professionals at least? I suspect that the answer is that "it depends." If so I would like to know the major historical trends and broad classes are among professional musicians. What disappears, what sticks around, and what adapts?
Comment: I disagree strongly that the A clarinet is obsolete. It is very standard for professional clarinetists to have both a Bb and an A for orchestral and solo playing. If you want obsolete, talk about Bass Trumpets, Hurdy-Gurdy, Lutes, and Ophicleides.
Comment: Hi, folks! If you have suggestions for how to narrow the question, that would help!
Comment: I'm not sure of the premise, Bradd. The A clarinet is out of favour in popular music and wind bands, to be sure, but wind band instruments have always tended to lie in the flat keys - the A clarinet is still useful in orchestral work. As for early instruments, that movement has only been picking up pace since the days of Dolmetsch and Landowska. I think we actually play more of the older composers than was the case at the end of the 19th century, and more often on original instruments. This seems to apply: "The past is never dead. It's not even past." New and old seem to coexist these days.
Answer: Older works keep older instruments in use among professionals and amateurs. You may not have any visibility of the early music community, but there are quite a lot of us and we're out there playing recorders, viols, baroque flutes and oboes, baroque violins, harpsichords, clavichords, hurdy gurdies, musette du cour, rauschpfifes, racketts, shawms, sackbuts, cornets and the list goes on and on.
During the 20th century a revival happened in early music, and the idea of historically informed performance gained a lot of traction. But to play music as it was originally meant to sound means you need instruments which can produce those sounds, so a lot of very clever people have spent a long time trying to make instruments which can do that, while other very clever people have tried to figure out what the performance technique was for these instruments based on written sources. Regrettably without a time machine we can't hear the original performances of Vivaldi or Handel to know what they sounded like to the composers, but we can come up with things we like that have some evidential justification.
That said, old music is also often played on new instruments, often very badly. Pick a random recording of Bach's keyboard music for an example - you're probably not going to get one of the good ones. Sometimes it can work to use a modern instrument's capabilities to enhance a performance of music that was written before anything capable of that was ever built, but more often you unfortunately end up with someone who only really knows how to play music written in the 19th century trampling all over some Bach and making it all mushy.
It can work though, and there are recordings out there of people who've managed to pull it off, sometimes using completely different instrument families to the original but still capturing something very wonderful in the performance. Musicianship and understanding are most definitely required.
Oh also, go to a gathering of folk musicians and ask them if the hurdy gurdy is obsolete. I dare you. Especially in Hungary.
Answer: With transposing instruments (as the clarinet given as example) switching to a different instrument is more difficult, since you either have to rely on the musician to transpose mentally or need a new edition of his or her part. On the other hand using a C clarinet gives a sound a full tone higher without any further modification. I know no clarinetist not having B♭ and A instrument, and in classical literature there are pieces, where one has to swap even between the movements, so I can't confirm that the A clarinet faces extinction.
I consider the answer to have two parts: amateurs use what instrument they have at hand easily crossing instrument families by replacing violin by flute etc, so there is no impact at all. This is especially true for exotic stuff like crumhorns, which are increasingly difficult to obtain as mass products, so substitution by recorder ensemble is very likely.
For professionals it depends on flow of current taste and whether for recording or  performance. Currently ("historically informed") for recordings the trend is towards authentic period instruments, for performances practicality restrictions (more tuning necessary for gut strings and harpsichord) influence the decision. Whether this will change is a topic of speculation in my opinion.
Comment: "B♭ soprano clarinet has largely supplanted the A and C clarinets" means that A and C have become obsolete because B♭ is dominant. Does it make sense now?
Answer: Archaic instruments are not only employed today for old music, as the others here have already pointed out.  There is also a small but flourishing scene of composing new works for old instruments, including harpsichord, recorder, and viola da gamba.
Here's a short example- a polymetric piece composed for medieval double harp, not really playable on any modern instrument I know of:
Answer: Not only is there the early music community that keeps old instruments alive, but there have been some instances where these instruments have crept into contemporary music. So, to flesh out Scott Wallace's answer, here are a few examples.
Kagel has a piece called Musik für Renaissance-Instrumente. There are a few compositions for the gamba family, quite a substantial modern repertoire for the recorder (mainly by Dutch and Japanese composers) and some notable works for harpsichord, e.g. by Ligeti, Xenakis, and not least Cage's and Hiller's collaboration HPSCHD.


Proxy pattern - why to implement interface from real object class?

Question: I do not understand why do I have to implement the interface in Proxy Pattern target object to represent. I think at it as the common use of an interface, which is implemented by proxy class, which will provide to get real object class info and show them to the client...but I see that all real object class examples implements the interface.....why?
Answer: The goal of the Proxy Pattern is to have an object (the Proxy) that can stand in for another one (the Real object). To achieve this, both objects (the Proxy and the Real object) must implement a common interface: the one used by the Client. That way, the Client will only have to manipulate the interface, no matter if it is implemented directly by the Real object, or indirectly by the Proxy forwarding to the Real object.
There's another, very close, pattern called the Adapter pattern, which doesn't require the Real object to implement this interface. This is because the goal is different: the Adapter aims to allow the Client to manipulate indirectly a Real object that does not implement the interface.


How to programmatically add Ant library dependencies for mail task

Question: I've been tasked with creating automated notifications for our Ant build scripts. This is so that when someone pushes out a deployment, our team can automatically receive an email about it.
The obvious choice was to use Ant's mail task, which comes predefined with Ant:
<target name="notify" description="notify team">
    <mail subject="latest deployment">
        <from address="firstname.lastname@example.com" />
        <to address="firstname.lastname@example.com" />
        <message>A new build has been pushed out to prod</message>
    </mail>
</target>

However this results in the following runtime exception:
java.lang.ClassNotFoundException: javax.mail.internet.MimeMessage

This is because Ant's mail task depends on JavaMail and JavaBeans Activation Framework, libraries which are apparently not included with its distribution. Why Ant would define a task that depended on a library but not include that library is unclear to me.
This issue has already been discussed on this post: ant mail task using mail and activation jar in external location. Based on the answers there seem to be two solutions.
The first is to manually put these library dependencies on the ant classpath. This can be done using the -lib command line argument, or in eclipse one can use Window > Preferences > Ant > Runtime > Global Entries, and then add mail.jar and activation.jar (I'm pretty sure this amounts to the same thing as -lib, correct me if I'm wrong). But this solution is undesirable for our team because it would mean every one of us would have to manually carry out these steps. I'm looking for a way to simply commit my notification code, and it should work on another eclipse install after svn update.
The other solution in the linked post mentions a way to do the above programmatically, by calling Ant from itself:
<exec executable="ant">
    <arg value="-lib"/>
    <arg value="PATH_TO_MY_LIB"/>
    <arg value="target"/>
</exec>

The problem with this is that the Ant command line tool is apparently only included with the full install, not the eclipse distribution. So again there's no way to make it work without some manual action by anyone wanting to use the mail task.
Is there any way I can automate this without adding another annoying step to project setup? I really don't understand why this is so hard to achieve - it seems like if the mail task wasn't predefined by Ant this would be easier. Hopefully I'm missing something.
Comment: Have you considered using a CI for this kind of tasks? They comes with mails and much improved reporting. My votes is for http://jenkins-ci.org/
Answer: Mail is one of the optional tasks in ANT. To install these additional libraries ANT 1.7 added a fetch.xml script, invoked as follows:
ant -f $ANT_HOME/fetch.xml -Ddest=user -Dm2.url=http://repo1.maven.org/maven2

On windows you could try:
ant -f %ANT_HOME%/fetch.xml -Ddest=user -Dm2.url=http://repo1.maven.org/maven2

For a full explanation, see the ANT Manual documentation.

Update
The following ANT file has an install-jars target that can be used to install the missing ANT jars used by the mail task.
<project name="demo" default="notify">

    <target name="install-jars" description="Install ANT optional jars">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/mail.jar"       src="http://search.maven.org/remotecontent?filepath=javax/mail/mail/1.4.4/mail-1.4.4.jar"/>
        <get dest="${user.home}/.ant/lib/activation.jar" src="http://search.maven.org/remotecontent?filepath=javax/activation/activation/1.1/activation-1.1.jar"/>
    </target>

    <target name="notify" description="notify team">
        <mail subject="latest deployment">
            <from address="email@example.com" />
            <to address="firstname.lastname@example.com" />
            <message>A new build has been pushed out to prod</message>
        </mail>
    </target>

</project>

I discovered that the ANT mail task task loads it's dependent classes from the ANT system classpath. This means the build has to be run in two steps:
$ ant install-jars
$ ant

Most ANT tasks allow you to specify a classpath reference. The Mail task does not. Trying to research this issue lead me to the following mailing list thread:

http://ant.1045680.n5.nabble.com/Mail-task-with-mail-jar-amp-activation-jar-out-of-lib-folder-td3347501.html

The solution is convoluted and not worth the effort. I'd recommend living with the inconvenience... (The install-jars target only needs to be run once)
Comment: @oers I thought of doing a check on the existence of the classes (rather than files), but it doesn't get away from having to run ANT twice.... That was why I gave up :-( The root cause here is an old ANT task that doesn't support a classpathref attribute. Hacking the ANT classloader seems so clunky by comparison, and that option is also denied to us (using standard ANT)
Comment: And how might this be done programmatically through the build file, so that after doing an svn checkout of the changes (and jars) in eclipse it would work without any manual setup?
Comment: After seeing how insurmountable it is to truly automate this, my team and I decided to give up and swallow the pill of manually setting up Ant per eclipse install. Your install target came close, +1 for that and the link - it's just unfortunate Ant needs to restart but it seems there's truly no way around that without wading into the classloader mess.
Comment: @PaulBellora just an additional idea, you could check if the files exists and only run install-jars, if they do not. [check if file exists](http://stackoverflow.com/questions/520546/ant-task-to-check-if-a-file-exists). This will integrate those steps transparently in your workflow.
Answer: With the example from this mail thread I got a working solution that sends email when the tests fail.
You need to download ant-classloadertask.jar,
and mail.jar from javamail and place them in test.libs.dir.
<property name="test.libs.dir" location="${basedir}/lib/unit-test"/>
<property name="test.results.dir" location="${basedir}/test-results/"/>

<path id="project.classpath.tests">
    <pathelement location="${build}"/>
    <path refid="project.lib.path"/>
</path>

<target name="unit-tests" depends="">
    <mkdir dir="${test.results.dir}"/>
    <junit fork="false" showoutput="yes" includeantruntime="false"
        errorproperty="test.error" failureproperty="test.error"
        haltonerror="false" haltonfailure="false">
        <classpath refid="project.classpath.tests"/>
        <formatter type="plain" usefile="true" />
        <batchtest fork="no" todir="${test.results.dir}">
            <fileset dir="${build}/test/">
                <include name="package/dir/path/to/tests/TestFile.java"/>
            </fileset>
        </batchtest>
    </junit>
    <antcall target="sendMail"/>
</target>

<path id="mail.path">
    <pathelement location="${test.libs.dir}/mail.jar"/>
</path>

<taskdef name="classloadertask"
    classname="org.apache.tools.ant.taskdefs.ClassloaderTask"
    classpath="${test.libs.dir}/ant-classloadertask.jar"/>
    <classloadertask classpathRef="mail.path" loader="thread"/>

<target name="sendMail" if="test.error">
    <mail mailhost="smtp.gmail.com"
        mailport="587"
        user=""
        password=""
        ssl="yes"
        failonerror="true"
        from=""
        tolist=""
        subject="Unit tests have failed"/>
</target>

Answer: With the taskdef command, you can dynamically load new tasks and specify a classpath from where they are loaded. I use this successfully for loading new tasks from an external library which is not on the ant class path. Whether it also works when the task already exists, I don't know.
I would probably start with trying to re-define the mail task with a new name:
<taskdef name="mymail" classname="class.of.mail.task" classpath="mail.jar;activation.jar">

Perhaps you need to include the original ant class path in the class path here so that the class of the mail task can be found.
If this doesn't work, perhaps you can take the source code of the mail task, rename the class, bundle it together with the classes from mail.jar and activation.jar into your own jar and load this task from the JAR. This should work just as it works with any task not shipped with ant.
Comment: [This seems to be possible](http://ant.1045680.n5.nabble.com/Mail-task-with-mail-jar-amp-activation-jar-out-of-lib-folder-td3347501.html), but requires an additonal ant task due to class loading issues.
Comment: I tried this, doesn't work. Still get the ClassNotFoundException because the mail task is loading it's dependent classes from the system classpath. Looks like @oers discovered the same mail thread I did!
Comment: @oers Could you please give some more details why this doesn't work?
Comment: Sry I may have been to hasty. I misread your answer as something that I tried. This approach could work.
Answer: You can put these jars as external jars to the classpath of the ant run config (this is my ftp example):

and save this run config to the project(Tab: Common--> Shared File, I usually take something like resources/eclipse for that) and commit it to svn.

it will be available for all developers who check this project out from svn
you have to deliver the jars in that project, too. So that they will always be available
Everybody can run it easily from the external tools menu

Of course you could write your own mail task, to take care of that.
Comment: +1 This is an interesting suggestion - ultimately we decided just to tolerate the manual Ant setup per install.
Answer: With Ant 1.8.2 and ant-classloadertask.jar solution mentioned above (by bro) I needed to change loader attribute of classloadertask from:
loader="thread"

into:
loader="project"

otherwise classes in activation.jar and mail.jar were not found by the classloader.


Find and move files to appropriate directories using shell script

Question: I have below setup and I want to find and move files.
I have files /home/backup/abc/123.wav and  /home/backup/xyz/456.wav.
Same directories exist at /usr/src/abc  and /usr/src/xyz which does not have any files.
I want to find .wav files from home_dir and move them to particular dest_dir.
So 123.wav should move to /usr/src/abc and 456.wav should move to /usr/src/xyz.
I am using below command for that.
home_dir=/home/backup/
dest_dir=/usr/src/
cd $home_dir && find . -iname "*.wav" -exec mv {} $dest_dir \;

But all the .wav files(123.wav and 456.wav) moved to /usr/src and not to its respective directories(/usr/src/abc  and /usr/src/xyz).
Is it possible to achieve what I want ?
Please suggest.
Answer: Use cp --parents option with find to create parent directories of each file being copied:
home_dir=/home/backup/
dest_dir=/usr/src/
cd "$home_dir"

find . -iname "*.wav" -exec cp --parents {} "$dest_dir" \; -delete

Comment: I want to move the files.When I use
find . -iname "*.wav" -exec cp --parents {} "$dest_dir" \;
.wav files copy as 123 and 456 not as 123.wav and 456.wav.
Comment: After my suggested `cp` command you can use `find . -iname "*.wav" -delete` to delete all files from source directory.
Comment: .wav files are generate randomly so if I use delete command after copy command, is there any chances to delete any file that will not be copied ?
Comment: You can do both in same `find` also: `find . -iname "*.wav" -exec cp --parents {} "$dest_dir" \; -delete`
Answer: This would be a lot easier if mv had a --parents option, but unfortunately it doesn't.  It's best to use mv instead of cp because cp will copy all the data unnecessarily if the source and destination directories are on the same filesystem.  if you've got Bash 4 (which supports globstar) you could do it like this:
home_dir=/home/backup/
dest_dir=/usr/src/

shopt -s globstar nullglob dotglob

for src_wav in "$home_dir"/**/*.wav ; do
    rel_wav=${src_wav#$home_dir/}
    dst_wav=$dest_dir/$rel_wav
    dst_parent=${dst_wav%/*}
    [[ -d $dst_parent ]] || mkdir -p -- "$dst_parent"
    mv -- "$src_wav" "$dst_wav"
done

Comment: I will try this too.Thanks.


how to change browserSync Port

Question: My application is running on port 8000. I have changed the borowserSync port to 8000 from browser-sync/default-config.js. And it looks something like this
<code>// Change the default project
ui: {
    port: 8000
},

ui: {
    port: 8000,
    weinre: {
        port: 8000
    }
},
</code>
but when I ran gulp watch command it spins the server on port 8001.
my terminal looks like this after I ran gulp watch command
<code>[23:40:54] Starting 'browserSync'...
[23:40:54] Finished 'browserSync' after 23 ms
[23:40:54] Starting 'sass'...
[BS] Access URLs:
------------------------------------
Local: http://localhost:8001
External: http://192.168.1.6:8001
------------------------------------
UI: http://localhost:8002
UI External: http://192.168.1.6:8002
</code>
Does anyone know who to change the port in browserSync.
Answer: This kind of shifting by 1 normally happens when there is something else running on the port. Do you have another instance that is already occupying port 8000?
I notice that you have port 8000 mentioned twice in your config file and you have two of the same node for ui
My config for gulp looks like this for example
<code>browserSync.instance = browserSync.init({
  startPath: '/',
  ui: {
    port: 3001
  },
  server: server, //server variable set elsewhere
  port: 3000,
  browser: browser, //set elsewhere
});
</code>
So your config should look more like
<code>{
  port: 8000,//Or whatever port you want for your application
  ui: {
    port: 8001 //Or whatever port you want for browsersync ui
  }
}
</code>
Comment: Yes you're right. My development server is running on port 8000. As soon as i stopped it. Browser sync started taking port 8000 but my application stopped working. Is there a way to keep both running on 8000 simultaneously.
Comment: @vsoni, You can never have more than one application on any given port. That is a fundamental when it comes to ports. You can just run the ui on a different port then access with localhost:8001 for example. PS please accept the (updated answer) if it solves your issue :)

how to change browserSync Port


How to add twitter metatags dynamically in Next.js 13

Question: I am using Next.js 13 and using the generateMetaData function for dynamic metadata works for openGraph, but how to do it for Twitter meta tags?
export async function generateMetadata( {params, searchParams}: Props, parent?: ResolvingMetadata): Promise<Metadata> {
  return {
    openGraph: {
      type: "website",
      url: '',
      title: '',
      description: '',
      image: '',
    }
  }
}

For instance, the HTML output needs to be:
  <meta property="twitter:card" content="summary_large_image" />
  <meta property="twitter:url" content={url} />
  <meta property="twitter:title" content={ogTitle} />
  <meta property="twitter:description" content={ogDescription} />
  <meta property="twitter:image" content={ogImage} />

Answer: You need to do something very similar for twitter:
  twitter: {
    card: "summary_large_image",
    title: "Your title",
    description: "Your description",
    creator: "@author_name",
    images: ["you_url_here"],
  },

Don't forget that the recommended dimensions are 1200x630px.
More info here: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#twitter
Also if you end up having issues with the title / description being rendered but not the image, you might want to use this way to specify the information for the image:
  twitter: {
    card: "summary_large_image",
    title: "Your title",
    description: "Your description",
    creator: "@author_here",
    images: [
      {
        url: "you_url_here",
        blurDataURL: "you_blured_url_here",
        width: 1200,
        height: 630,
        alt: "Your alt text",
      },
    ],
  },

Comment: This is not working for me with Next 13
Comment: hey, what if that image is not 1200 * 630. Does just putting that width there just make it work? For a larger image for example
Answer: Make Sure you are using this function in the page.js file of the page that you like to share , or write it in app.jsx if you are sharing your whole website and want media to be rendered , I have added tag generation for whatsapp as well.
To make sure if your metatags are working fine , you can view source of your page and then check if the tags / OG tags are there or not . To view source of your page press ( Ctrl + U ) on the page that you are going to share , or you can use this validatior for twitter to see if you have a valid card ,twitter validator , just paste your page url and see in logs if there is green text or red. green text means you are probably doing things the right way.

export async function generateMetadata({ params }) {
  let post = await fetch(
    `https://@yourapiendpoint`,
    { cache: "no-store" } // so that we dont see stale data
  ).then((res) => res.json());

  const twitterCard = "summary";

  return {
    openGraph: {
      title: post?.data?.title,
      description: post?.data?.description,
      url: `post/${post?.data?.postId}`,
      siteName: "your site name",
      images: [{ url: post?.data?.url, width: 1200, height: 630 }], //make sure its a valid image url
    },
    twitter: {
      card: twitterCard,
      title: post?.data?.title,
      description: post?.data?.description,
      images: [{ url: post?.data?.url, width: 1200, height: 630 }],
    },
    whatsApp: {
      title: post?.data?.title,
      description: post?.data?.description
        ?.replace(/<[^>]*>/g, "")
        ?.replace(/ /gi, " "),
      thumbnailUrl: post?.data?.url,
      thumbnailWidth: 800,
      thumbnailHeight: 800,
    },
  };
}


One-point safety by defending team

Question: I learned about the conversion safety today, where an NCAA team attempting an extra point can get a one-point safety if the kick is blocked but the defending team takes the ball into the endzone and gets tackled.
I couldn't figure out if this is the case, but I was wondering if the defending team could score one point in the same way. Suppose the kicking team attempts the extra point, which is blocked and grabbed by the defense, and they run it back - but the player with the ball fumbles it close to the endzone, and a player from the kicking team recovers it but his momentum carries him into the endzone, where he is tackled. I realize this is a very implausible situation, but would this be a way that a team could theoretically finish with a score of 1?
Comment: Good question.  There is some discussion of this in the comments to [this answer](http://sports.stackexchange.com/a/3209/1723).
Comment: Just to add a short answer to this question, yes, this is a way for a team to finish with one point.
Answer: Yes, it is possible for a team to end the game with a score of 1 in the NCAA and in the NFL.
This could happen in the exact scenario that you mentioned in your question.  On an extra point attempt, Team A (which already has 6 points for a touchdown) fumbles the ball (or has kick blocked).  Team B recovers.*  Team B has a chance to take the ball to the other end of the field.  So Team B runs down the field, but fumbles before he gets to the end zone.  Team A recovers, but gets tackled in the end zone, resulting in a 1 point safety for Team B.
I don't think this has ever happened, but I don't see why it couldn't.

* Before the 2015 NFL rule change, the ball would have been dead at this point, but now in the NFL the defense can take possession during a conversion attempt and try to score.
Comment: As of the 2015 season, the NFL rules have changed. The ball is no longer dead on change of possession during a conversion attempt, so a one-point safety for the kicking team is now possible.
Comment: I wonder... In the NFL, if on a two-point conversion attempt, the quarterback gets chased (or possessed by evil) and runs backwards all the way to the other end, where he gets sacked in the end zone, would this be a 1 point safety for the defense?  Is there any scenario where the refs would let this happen without blowing a whistle on the way down the field?
Comment: It's hard to imagine a one-point safety on the other end; the ordinary one-point safety example is so rare already: https://www.youtube.com/watch?v=jp4TeP4rw0s&t=7s
Comment: @MichaelMyers I finally updated my answer. Thanks!
Comment: @MichaelMyers: Before the rule change, what would have happened in the scenario mentioned by Ben Miller's comment, if there were no change of possession?  Would there be any league-tiebreaker scenarios where a team might do better in playoff standings if they win by 3 or 6 in overtime than if they win by 1 in regulation?  Would it be unsportsmanlike for a team which had received a 1-point lead because of a touchdown to give up the lead to tie the game in hopes of a 3 or 6-point win in overtime?
Answer: 6-1 score
Scenario.
Extra point blocked and ran back towards the kickers endzone,runner fumbles ball at the offenses 1 yard line kicking team picks up ball and runs into there own endzone and gets tackled... wahlah 1 point!
Comment: This happened in the 80s in college football.   I was a kid watching the game but for sure happened.   I was enthralled because I watched a ton of football and never saw a 1 on the board.
Answer: There is no way for a team to score just 1 point in American Football (final score 1-0).
If an extra point it blocked and returned for a score it will result in 2 points for the returning team.  This is also true if the kick is blocked and does not cross the line of scrimmage, the ball can be advanced by the kicking team for 2 points.
If it is a Field Goal attempt and the kick is blocked than the defending team can return it for a touchdown (6 points).
Note: If a field goal is attempted and partially block and the ball travels past the line of scrimmage it is treated like a punt and can only be recovered by the kicking team if the defending team touches the ball first.  However, I do not believe that the kicking team can advance the ball once it is touched by the defending team.
EDIT: There is still no way for a team to end up with a final score of 1, however there is another way for a team to end up scoring 1 point other than the usual extra point.
HERE
Is a video of this occurring.  The team can score 1 point after an extra point is blocked, caught outside of the end zone, returned backwards into the end zone, and downed.  This results in 1 point for the kicking team.  As it has to occur after a touchdown the team would therefore score a minimum total of 7 points for the game.
Answer: The one point safety on the Defense suggested in the previous response may only occur during an Extra Point try by the offense, it's result is the same as a successful extra point by the offense.
Basically what has to happen is a defensive player commits a safety in the end zone. It's more common in college football as PAT attempts can be returned for 2 points. It happened as recently as the 2013 Fiesta Bowl.
However, this does not allow for the 1-0 score you're seeking. The offense has already scored a touchdown so they have at least 6 points. The play in question ends in 7 total points for the offense.
This is incredibly rare in the NFL (hasn't happened since the '40s) because there is no incentive for the defense to try anything strange in the NFL, they just fall on the football and the play is over.
There is no method for the defending team to score a single point. And there is no way to only score a single point in american football
Comment: 1-0 score is impossible, but a team can finish with only one point in the way described by Ben Miller. Also, as of 2018, PAT's can now be returned for safeties in the NFL.
Answer: An NFL score can end up say 6 to 1 (but not 1 to 0). If the offense scores a touchdown (6 points) then kicks the extra point (a "try") and that kick is blocked, in the NFL (and I think at all levels of NCAA football and high school),  the defense can try to pick up the blocked kick and return it for a score (technically called a defensive 2-point conversion). But if the defense fumbles that blocked return way downfield say at the one yardline (right before reaching the opposite endzone to score) and the ball us recovered again by the kicking team, but way back now at their own 1 yard line. Then the original kicking team (offense) tries to run the ball back again,  but they somehow get tackled in their own endzone (ie a safety). That would be a 1-point safety for the defense. If the game ended that way,  the final score would be 6 to 1. Note, the only way a 1-point safety can happen is on a try (extra point or 2-point conversion), thus a 1 to 0 final score is impossible,  it must be at least 6 to 1. Very rare, but the strange defensive safety has happened before (more common now is the 2 point defensive conversion because of the tougher extra point tries and relaxed return rules. An NFL game was decided a couple-three years back on such a conversion play).

One-point safety by defending team


How can we use IR sensor in MIT App Inventor

Question: We can use in MIT App Inventor 2 these sensors:

Can we use another sensor e.g. IR Sensor or Step Sensor?
And if we can, how can we do it?
Which component should we use to access other sensors?
Comment: You may want to edit your question to be more clear about what you are asking.  For instance, I could completely answer your question with a simple, "Yes you can", however, I rather suspect your question is HOW.  If so, then ask that.
Comment: Oh, Thanks, I'm editing now. (I'm sorry, i weak in English)
Answer: There is no IR component available in MIT App Inventor, but you can create your own App Inventor Extension.
More information about how to create an extension see here,
however that will be more advanced and will require some Java skills...
As an example, see my Barometer Sensor Extension.


how do I update a value in my table when I press a confirm button

Question: I have a code that brings data idnumber from a database and puts it into a select box.
If I select an idnumber from the select box and press a confirm button how can I write the code to update a column called "confirm" in the database from No to Yes?
The code below is the one for the select box
<select>
    <?php
        $mysqli = new mysqli("localhost","root","","volunteer");
        /* check connection */

        if (mysqli_connect_errno()){
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
            $query = "SELECT * FROM registrations";
            $result1 = mysqli_query($mysqli,$query);

            while($rows = mysqli_fetch_assoc($result1)){
                echo "<option>" . $rows['idnumber'] . "</option>" ;
            }
    ?>
</select>
<form action="confirm.php" method="post">
    <button type="submit" name="confirm-btn">Confirm</button>
</form>

Comment: Please post the content of "confirm.php"
Comment: Where are you stuck? This is the type of thing you can see examples of in many many tutorials. Note though that no value for the select will be submitted to the server until you give it a name, and also the select needs to be within the form. Again, study HTML forms tutorials more closely, to learn the basics
Comment: The PHP manual has a section on [Dealing with Forms](https://www.php.net/manual/en/tutorial.forms.php). Give your `` a `name` attribute so you can access it. And most of all, place it _inside_ your ``
Answer:
Put your select input under form tag
Give name to select box :
Click on confirm button.
Write code in : confirm.php

if (!empty($_POST['registrations'])) {
if (!empty($_POST['registrations'])) {
$sql = "UPDATE TABLE_NAME SET COLUMN_NAME=".$_POST['registrations']."  where YOUR_CONDITION";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

Answer: Form Input:
<form action="confirm.php" method="post">
<select name="idnumber">
    <?php
        $mysqli = new mysqli("localhost","root","","volunteer");
        /* check connection */

        if (mysqli_connect_errno()){
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
            $query = "SELECT * FROM registrations";
            $result1 = mysqli_query($mysqli,$query);

            while($rows = mysqli_fetch_assoc($result1)){
                echo "<option value=". $rows['idnumber'] .">" . $rows['idnumber'] . "</option>" ;
            }
    ?>
</select>
    <button type="submit" name="confirm-btn">Confirm</button>
</form>

Write code in : confirm.php
$mysqli = new mysqli("localhost","root","","volunteer");
            /* check connection */

        if (mysqli_connect_errno()){
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }

$sql = "UPDATE TABLE_NAME SET COLUMN_NAME=".$_POST['idnumber']."  where YOUR_CONDITION";

if ($conn->query($sql) === TRUE) {
    echo "Updated successfully";
} else {
    echo "Updating record: " . $conn->error;
}


How to register app from private repo in Spring Cloud dataflow 2.6.1

Question: I'm using SCDF 2.6.1 in Openshift 3, and I'm facing error while registering the app, error log like below :
java.lang.NullPointerException: null
at org.springframework.cloud.dataflow.configuration.metadata.container.DefaultContainerImageMetadataResolver.getRegistryRequest(DefaultContainerImageMetadataResolver.java:162)
at org.springframework.cloud.dataflow.configuration.metadata.container.DefaultContainerImageMetadataResolver.getImageLabels(DefaultContainerImageMetadataResolver.java:110)
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.resolvePortNamesFromContainerImage(BootApplicationConfigurationMetadataResolver.java:215)
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.listPortNames(BootApplicationConfigurationMetadataResolver.java:163)
at org.springframework.cloud.dataflow.server.controller.AppRegistryController.getInfo(AppRegistryController.java:193)
at org.springframework.cloud.dataflow.server.controller.AppRegistryController.info(AppRegistryController.java:162)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I checked the line of code in DefaultContainerImageMetadataResolver.java:162
// Convert the image name into a well-formed ContainerImage
ContainerImage containerImage = this.containerImageParser.parse(imageName);

// Find a registry configuration that matches the image's registry host
RegistryConfiguration registryConf = this.registryConfigurationMap.get(containerImage.getRegistryHost());

// Retrieve a registry authorizer that supports the configured authorization type.
RegistryAuthorizer registryAuthorizer = this.registryAuthorizerMap.get(registryConf.getAuthorizationType());

I'm pretty sure the error is because registryConf is null as result from
RegistryConfiguration registryConf = this.registryConfigurationMap.get(containerImage.getRegistryHost());
How to put my private repo URI in registryConfigurationMap ?
I have tried to put imagePullSecret in the deployment.yml which is registered with the private repo, but I think it doesn't work because in the startup log, I still see :
2020-09-03 04:55:24.111  INFO 1 --- [           main] urationMetadataResolverAutoConfiguration :
Final Registry Configurations: {registry-1.docker.io=RegistryConfiguration{registryHost='registry-1.docker.io', user='null', secret='****'', authorizationType=dockeroauth2, manifestMediaType='application/vnd.docker.distribution.manifest.v2+json', disableSslVerification='false',
extra={registryAuthUri=https://auth.docker.io/token?service=registry.docker.io&scope=repository:{repository}:pull&offline_token=1&client_id=shell }}}

Answer: The only place where SCDF server downloads the container image layer is when it looks for app metadata.
Currently, this is configured to use the docker registry host (as this is where all the out-of-the-box applications are hosted).
If you want to override, you can modify these property values at the time of server startup and proceed.
Remember the fact that this configuration is only needed to download the app metadata layer of the image - not to download the entire container image at the SCDF server side.


Why is my highest coefficient not significant but lower ones are? (Poisson regression)

Question: I'm looking to see if income level affects the number of pets a person has, controlling for number of children. I have run a GLM (Poisson family) model, and found that if a person is categorised as 'Low' income, their number of expected pets decreases by 21.3%. I also found that for every child a person has, their number of expected pets increases by 4.03%.
However, the 21.3% decrease is not significant, and the 4.03% increase is significant. I'm wondering if this is incorrect/whether I have done something wrong? I am aware I may be confused about how statistical significance works, so just want to check whether the below makes sense!
The R outputs for estimates and p-values look like this:
                             Estimate   Pr(>|z|)
Level_of_IncomeLow:         -0.239043   0.0830 .
Num_of_children              0.039527   7.54e-10 ***

My calculations:
Exponent of -0.239043: 0.787381
1-0.787381=0.212619
= 21.3% decrease

Exponent of 0.039527: 1.040319
= 4.03% increase

Essentially, is it okay that the larger effect is not statistically significant, but the smaller effect is? It just feels wrong!
Comment: You can't compare the size of coefficients that are in different units. There's no basis on which to call one coefficient  "larger" or "smaller" when you're comparing incommensurable units.
Comment: Significance of a test depends on the ratio of the coefficient to its standard error (which you should also report in your analyses). The standard error is determined (i) the sample size, (ii) the variance of the residuals of the model, and (iii) the variation in the independent variables. Components (i) and (ii) affect the tests for both coefficients. However, it's possible that for (iii) there is more "relative" variation in the number of children in your sample than the level of income.
Comment: This means that it is easier to "detect" an effect. There could still be an income effect but the sample size is too low to detect it.
Comment: The fact that it depends on a ratio is extremely important. For example, if you rescale the variable, it affects both the numerator and denominator, and doesn't alter the significance. This makes significance a measure that doesn't depend on the units of measurement.
Comment: Thank you for all the helpful answers! I will also add standard error into my report
Comment: it is easier, even with the eye, to see significantly if groups align to a line than it is to see if two groups are from the same population. I'd also try a comment on the subject matter; that poor families are more likely to have more children, which means that the two effects could be confounding each other, which would impact the latter test more.
Comment: Statistical significance describes how certain you are about the existence of an effect. It tells you nothing about the size of the effect.
Answer: low (vs. high) has a restricted range (i.e., only 2 values).  Number of children presumably has a much wider range.  The narrower the range of an $X$ variable, the less power there is to test it.  That's a general principle.  Specific to this example, it sounds like the underlying variable (income) was subjected to a median split, or something similar.  If so, you should be aware that categorizing a continuous variable has long been considered poor statistical practice.
Answer: Significance is not purely about the magnitude of an effect. For instance, if the parameter/effect is $1$ light-year or $9.46×10^{12}$ km, then it is different figures but the same distance.
(You might argue that this example is bad because I changed the units, but how are you gonna make sure that the units match when you compare 'pets per unit of income' with 'pets per number of kids'. When you change the currency then you change the effect size.)
Significance is an expression of the magnitude of an observed effect size in terms of how likely or unlikely it is to have an at least as strong deviation from the value predicted by some null hypothesis, given that the null hypothesis is true.
When this probability is low then you might consider the effect as an anomaly from the point of view of the null hypothesis. If you detect an effect with a small magnitude to be an anomaly, but an effect with a large magnitude is not, then it means that the experiment has different sensitivity for the two effects.

is it okay that the larger effect is not statistically significant, but the smaller effect is? It just feels wrong!

It depends on the relative effect size. Relative to the error of the estimate and this might be different for the two coefficients.
Below you see an example where the estimated intercept of 1.724 is different from 0 but it is not more significant than the estimated slope of 0.095 being different from 0.
The slope is a smaller effect size if you compare the plain figures like 0.095 < 1.724. But the slope has a much smaller variation from sample to sample, and such a small effect is significant.


Getting error while creating the NodePort service in EKS cluster

Question: I am trying to create Nodeport service in my EKS cluster however I am getting error as for: "network/minikube/orderers/services.yaml": map: map[name:endpoint] does not contain declared merge key: port. Can anybody help me to fix the issue.
My service.yaml file
apiVersion: v1
kind: Service
metadata:
  name: orderer0-service
  labels: {
    component: orderer0,
    type: orderer
  }
spec:
  type: NodePort
  ports:
    - name: endpoint
    - port: 7050
      targetPort: 7050
      nodePort: 30050
  selector:
    component: orderer0
    type: orderer

Answer: ports: is representing list of ports, where by - you are separating the ports, (name, port, targetPort, nodePort) these four are combinedly representing one service port values, and you mistakenly included another list in (- port: 7050), your yaml should be like below,
  ports:
    - name: endpoint
      port: 7050
      targetPort: 7050
      nodePort: 30050

YAML:
apiVersion: v1
kind: Service
metadata:
  name: orderer0-service
  labels: {
    component: orderer0,
    type: orderer
  }
spec:
  type: NodePort
  ports:
    - name: endpoint
      port: 7050
      targetPort: 7050
      nodePort: 30050
  selector:
    component: orderer0
    type: orderer

Answer: The yaml has a problem.You don't need the - infront of port.It should be like below
apiVersion: v1
kind: Service
metadata:
  name: orderer0-service
  labels: {
    component: orderer0,
    type: orderer
  }
spec:
  type: NodePort
  ports:
    - name: endpoint
      port: 7050
      targetPort: 7050
      nodePort: 30050
  selector:
    component: orderer0
    type: orderer


apache2 Path rewrite to Get Parameter - Make Slashes work

Question: The following is my current .htaccess file. If I open https://example.com/test and it doesn't end with one of the endings specified in line 2, it will open https://example.com/index.php?url=test
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !\.(css|js|png|jpg|php|svg|gif|webm|webp|eot|ttf|woff|woff2)
RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA]

However, if I try to open https://example.com/something/test, it just opens ?url=something instead of ?url=something/test. How can I achieve this? I have absolutely no knowledge about regex stuff
Answer: The regex ^([^/]+)/? only captures the first path segment, ie. [^/]+ matches 1 or more non-slash characters. If you wish to match the entire URL-path then use (.+) (to match 1 or more any characters). However, you can be more restrictive if you only want to match say 1 or 2 path segments?

and it doesn't end with one of the endings specified in line 2

That condition doesn't specifically check that the URL "ends" with one of those extensions, it checks that one of those extensions are contained within the filesystem path that the URL maps to. You need an end-of-string anchor $ at the end of the regex. And to specifically check the URL, you should check against the REQUEST_URI server variable.
So, this becomes:
RewriteEngine on
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|php|svg|gif|webm|webp|eot|ttf|woff|woff2)$
RewriteRule (.+) index.php?url=$1 [L,QSA]

Comment: That htaccess file works. Thank you very much.


TCPDF Textfield issues with default value

Question: I'm trying to create a PDF file with a form. I'm using php and tcpdf.
The text fields need to be precisely positioned to fit the image in the background.
Some of the text fields have default values (via the 'v' attribute).
The issue is that when I click the text field to edit the contents, the text moves a few pixels to the side (probably because of the border around the active input field). When the input loses focus, the text does not return to the original position.
I've tried to visualize the problem with these screenshots:
(note the text position relative to the line below)

My form default settings:
$pdf->setFormDefaultProp(array('lineWidth'=>1, 'borderStyle'=>'solid',
'fillColor'=>array(), 'strokeColor'=>array(255, 128, 128)));

This is the code for the field:
$pdf->TextField('test', 47, 6, [], ['v' => 'test(12)'], 8, 13);

What I have tried so far:

setting the lineWidth to 0, but while the border is no longer visible, the text still moves.
setting the borderStyle to 'none', same result.
setting the strokeColor to [], same result.

What I would like to do:

set a padding to the default value (or otherwise influence its positioning)

or

remove the border from the active form field (not just make it invisible)

I noticed the same behavior on the TCPDF example here: https://tcpdf.org/examples/example_014/
If you click into the address field, the text moves up and to the left.
Answer: While I couldn't solve the problem with PHP, I managed to find a viable workaround (at least for our project):
If I insert the default values via Javascript, the effect doesn't occur.
$js = "
var fields = {'field1':'test', 'field2':'test2'};
for (var fieldName in fields) {
    if (!fields.hasOwnProperty(fieldName)) continue;
    var field = getField(fieldName);
    if (field && field.value === '') {
        field.value = fields[fieldName];
    }
}
";
$this->pdf->IncludeJS($js);

This has the drawback, that if the user empties a field, the default value will be filled in again on next opening the file. This is no use case for our project, so it works for us, but keep it in mind!
So it's by no means perfect, but it helped us move on with our project. And maybe someone searching for this problem finds this helpful :)
If anyone finds an actual solution, I'd still be grateful!
Answer: I think you want to distinguish the first time a user opens the (blank) form, from when they re-open it after they saved it with the field emptied.
In the textfield, set the value (or default value) to 10 blanks. In your javascript, first check for 10 blanks, and if there, insert your default values.  If the field has anything but 10 blanks, don't insert defaults.  The user is unlikely to use exactly 10 blanks to clear a field.
But if that isn't robust enough, use another textfield that the user would never edit (like a version number).  Start with it empty, and insert the version number (or whatever) only after you have checked the field, and inserted your set of defaults.


Proving set theory is true if an argument has been given

Question: I am having troubles finding a proof for a set.
$$A^C \cup (B-C)^C = ((A \cap B) - C)^C$$
I have tried drawing a diagram to represent both and help to find a proof for it but in all honesty I cannot figure it out and need some help understanding the problem.
Comment: The title of the question is obscure and it seems to have no relation to the text of the question.
Answer: Using the definition of the set difference and the DeMorgan law we have
$$A^C \cup (B-C)^C =A^C\cup \left(B\cap C^C\right)^C=A^C\cup B^C\cup \left(C^C\right)^C=A^C\cup B^C\cup C.$$
and
$$\left((A \cap B) - C\right)^C=\left(A\cap B\cap C^C\right)^C=A^C\cup B^C\cup C.$$
By this the equivalence has been proven.
Answer: Your title is a bit peculiar. You understand that the problem here is NOT to "prove set theory is true", don't you?
The most Basic way to prove "$X= Y$", for X and Y sets, is to prove both "$X\subset Y$" and "$Y\subset X$".  And to prove "$X\subset Y$", start "if $x\in X$" and use the definitions of X and Y to conclude "then $x \in Y$".
Here, $X= A^C\cup(B- C)^C$ so saying "x\in X" means that either $x\in A^C$ or $x\in (B- C)^C$.
If $x\in A^C$ then x is NOT in A so NOT in $A\cap B$ so NOT in $(A\cap B- C$ so that $x\in (A\cap B- C)^C$.
<code>If $x\in (B- C)^C$ then x is NOT in B- C so x is NOT in B or x is in C.
</code>
If x is not in B, then it is not in $A\cap B$ so is not in $A\cap B- C$ so is in $(A\cap B- C)^C$.
If x is in C, then it is not in $A\cap B- C$ so is in $(A\cap B- C)^c$.
That proves that $A^C\cup (B- C)^C\subset (A\cap B- C)^C$.  Now try proving the other way yourself.
(By the way, it is not a good idea to use "C" to mean both a set and "complement".  If you are using "C" as a set, use the lower case, "c", to indicate the complement.)
Answer: Let $X$ be the universal set containing $A,B$ and $C$. Then,
$A^C \cup (B-C)^C=(X-A) \cup (X-(B-C))$
$=X-(A \cap (B-C))$ ....(By De-Morgan's Law).
$=X-(A \cap (B \cap C^C))$
$=X-((A \cap B) \cap C^C)$......(By Associativity).
$=X-((A \cap B)-C)$
$=((A \cap B)-C)^C.$


calculate homology of mapping cone

Question: Here is the problem statement I am concerned of:

For a space $A$ let $CA = A\times [0,1]/A\times \{1\}$ be the cone and if $f:X\to Y$ let $C_f = (Y\coprod CX)/\sim$ where we identify $(x,0)\sim f(x)$.

Let $f:S^2\to S^2$ be a map of degree $3$. Compute the groups $H_i(C_f,\mathbb Z)$ for all $i\ge 0$.
Let $g:S^2\to S^2$ be a contractible map. Compute the groups $H_i(C_g,\mathbb Z)$ for all $i\ge 0$.

Here are my questions:
a) I provided my solution for the first part as below, but I am missing one last step: what is $H_2(C_f)$? Can I also get a sanity check on my solution?
b) In the second part, I am not familiar with the terminology "contractible map". I looked it up in different sources and had no luck. Presumably, it has something to do with contractible spaces. Can anyone clarify this?
Thanks in advance!

So $C_f$ is the mapping cone of $f$. Given the mapping cone $C_f$, we divide it into $A$ and $B$, where $A$ is an open neighborhood of the tip $*$ of the cone, and $B = C_f\setminus\{*\}$. Now we use the Mayer-Vietoris sequence. Note that

$A$ deform retracts to the tip $*$, so the homology is trivial,
$B$ deform retracts to the bottom, i.e., $B\simeq S^2$, and
$A\cap B$ is a cylinder with the section equivalent to the domain, so it is equivalent to $S^2$.

On each degree the sequence gives
$$
\cdots \to H_k(S^2)\to 0\oplus H_k(S^2)\to H_k(C_f)\to \cdots
$$
so whenever $k>3$ we have $H_k(C_f) = 0$. For $k =0$ obviously $H_0(C_f) =0$. For $k = 2,3$, we have
$$
0\to H_3(C_f)\to \mathbb Z\xrightarrow{\cdot 3} \mathbb Z \to H_2(C_f)\to 0
$$
where the middle map is multiplication by $3$ since this is the induced mapping by $f$, which has degree $3$. By exactness at the first $\mathbb Z$ we have $H_3(C_f)= 0$ since $H_3(C_f)\to \mathbb Z$ is injective. I am not entirely sure what $H_2(C_f)$ should be in this case though.
Comment: I would assume that "contractible map" is non-standard terminology for "nullhomotopic map."
Answer: Everything you've written is correct. Your final exact sequence simplifies to
$$
0 \to \mathbb Z \xrightarrow{\cdot 3} \mathbb Z \to H_2(C_f) \to 0,
$$
so by exactness
$$
H_2(C_f) \cong \operatorname{coker}(\mathbb Z \xrightarrow{\cdot 3} \mathbb Z) = \mathbb Z / im(\cdot 3) = \mathbb Z/3\mathbb Z,
$$
where the middle equality is just the definition of cokernel.
For $H_1$, we have
$$
0 \to H_1(C_f) \xrightarrow f \mathbb Z \xrightarrow g \mathbb Z \xrightarrow h \mathbb Z \to 0
$$
with $h$ surjective hence $\pm id$, so by exactness at the middle $\mathbb Z$ we have $\operatorname{im} g = \ker h = 0$ so $g$ is the $0$ map. Thus $\operatorname{im} f = \ker g = \mathbb Z$, making $f$ an isomorphism.
Comment: Not quite; I've analyzed that sequence in an edit. Basically, the first $\mathbb Z \to \mathbb Z$ is indeed trivial, but this means the kernel is the entire group.
Comment: Yes. What might be helpful to remember is the sequence $0 \to \ker f \to A \to B \to \operatorname{coker} f \to 0$. If $f$ is injective, then $\ker f = 0$ and you get that $B/A$ is the cokernel. And if $f$ is surjective, $\operatorname{coker} f = 0$ and you get...I guess the first isomorphism theorem?
Comment: thank you, can you elaborate on what $H_1(C_f)$ would be (I missed that in the beginning)? I suppose it is given by $0\to H_1(C_f)\to \mathbb Z\to \mathbb Z\to \mathbb Z\to 0$, and since the last $\mathbb Z$ is the cokernel then the first $\mathbb Z\to \mathbb Z$ map is trivial, hence the kernel is $H_1(C_f) = 0$?
Comment: thank you: for some reason my homological algebra memory failed me and assumed the cokernel is always this quotient; is the cokernel of $f:A\to B$ given by $B/A$ only when we have a short exact sequence then?

calculate homology of mapping cone


composing a piece for pipe organ

Question: Basically I was asked to write a piece for pipe organ until tomorrow morning. I've played a pipe organ before, so I sort of know how it works, but I don't have an organ I can play on before tomorrow.
I've composed pieces for piano and string quartets before, but I have never composed anything for organ so far.
Are there any important things I need to know? Any tips?
Comment: How many manuals, pedals, octaves?
Comment: you have the possibility to choose different sounds for each manual and pedal, you can change the registration during the piece. And you can easily assume that if you compose something for the choir, it will probably work really well with organ too :) (but voice crossing each other won't be that noticeable)
Answer: Know the ranges of the manuals and pedals.
Don't feel you HAVE to specify the mechanics.  If you write a section 'f' then a section 'p', the player will automatically set up suitable registrations on a couple of manuals and change between them.  And yes, there IS a swell pedal, but you will often play a complete service without using it.
As this has to be done by tomorrow, may we assume this is a transcription rather than a big composing project?   Consider giving the organist the piano part.  He's very accustomed to translating it into organ terms on-the-fly.

composing a piece for pipe organ


Determine where a user has selected a song in the MPMediaPickerController

Question: Once a user has selected a song in the picker, is there a way to determine where the user had selected the song, i.e. In the songs or playlist tab, or if the song was selected as a part of a single album or a list containing all albums of a particular artist.
Just wondering if at all this was possible with the MPMediaPickerController instead of creating a new navigator from scratch.
Thanks!
Comment: you got any solution?
Answer: The simple answer is no, and creating a new navigator is not as difficult as you might imagine.


Multiple links to the same page but with different information on it

Question: I have a table which is created 'on the fly' from a database using the following code:

      <?php echo $row_buyerdetails['time_stamp']; ?>
      <?php echo $row_buyerdetails['title']; ?>
      <?php echo $row_buyerdetails['first_name']; ?>
      <?php echo $row_buyerdetails['surname']; ?>
      <?php echo $row_buyerdetails['email_address']; ?>
      <?php echo $row_buyerdetails['phone_number']; ?>
      <?php echo $row_buyerdetails['house']; ?>
      <?php echo $row_buyerdetails['street']; ?>
      <?php echo $row_buyerdetails['town']; ?>
      <?php echo $row_buyerdetails['city']; ?>
      <?php echo $row_buyerdetails['postcode']; ?>
      **LINK IN HERE**

    <?php } while ($row_buyerdetails = mysql_fetch_assoc($result)); ?>

The code produces a table with the buyers basic details in it as shown below:

In the cells with the text "LINK IN HERE" I want a link to a page called buyerdetails.php which will show all the information about that person. How do I create the link so that it passes an identifying value to the page buyersdetails.php so that page knows which users details to look up in the database and display them?
Comment: Please read this - [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)
Answer: Assuming each buyer detail has a unique identifier (we'll use an integer id for this example), something like this should suffice

    <a href="buyerdetails.php?id=<?= (int) $row_buyerdetails['id'] ?>">More Details

On buyerdetails.php, you can then retrieve the value via $_GET['id'].
Comment: sorry I couldnt accept your answer, I went with first come, first serve im afraid :)
Comment: @Giovanni If you really want to honour the first answer, check the timestamps next time. I'm a good 8 seconds prior to Gaby ;)
Comment: @Giovanni If you hover the answer time, you get a full timestamp. Mine - `22:54:39Z`, Gaby's - `22:54:47Z`. Don't go changing your vote though, doesn't bother me when the answers are that close together
Answer: Pass it as a url parameter..
<a href="buyersdetails.php?buyerid=<?php echo $row_buyerdetails['id'];?>">LINK HERE

and in that page use $buyerid = $_GET['buyerid']; and use it in your query
Answer: Easy example is that you create link with GET parameter - like buyersdetails?id=X
X = ID of clicked user.
and than at buyerdetails.php add some SQL statement which gets all data from database with id = X


Complex inequalities and constants

Question: Let $f(z)$ be an analytic function. Show that if $|f(z)| > 1 + |e^z|$ then $f(z)$ is constant.
I have no idea what to do, I've subbed $z= x+iy$
and got $|f(z)|>1+e^x$
 but lost here.
Comment: $f$ is analytic in where ?
Comment: @S.Panja-1729 Presume that $f$ is entire.
Comment: It is necessary to mention that $f$ is entire OR $f$ is analytic in $\mathbb C$
Answer: Hint: Clearly $f$ has no zeros. Then
$$\left|\frac{1 + e^z}{f(z)}\right| < 1$$
for all $z \in \mathbb{C}$. What can you conclude now?

Alternatively, if you prefer even stronger theorems, note that $f(\mathbb{C})$ is missing two points.
Comment: All too easy.  +1 for the concise and solid hint!
Comment: @Cayde [Little Picard](https://en.wikipedia.org/wiki/Picard_theorem) shows that the image of a non-constant entire function is either $\mathbb{C}$ or $\mathbb{C}$ minus a single point. The image of $f$ is missing infinitely many points, namely anything in the unit disk.
Comment: Sorry friend, I have not seen anything like that before. I see how you got to that but I don't know what to conclude after a bit of fiddling with that. Though I also know it must be greater than 0.
Comment: @@ Cayde) Do you know Liouville's theorem ? Picard's little theorem ??
Comment: Oh, actually, yes. I'll need to revise it though. I'll respond soon, and thanks!
Comment: Alright so, can I say this? Let $g(z) = $ the function above which is less than 1. It is bounded and entire so by theorem, it is constant. Would this be sufficient?
Comment: @Cayde Yes, but you should specifically cite the theorem you use (in this case, Liouville).
Comment: Oh alright, thanks. I am curious about your stronger theorems method, how does that go?
Comment: That Picard's little theorem..which states ' An entire function which omits at least two values is necessarily constant'. In this case f omits $0$ and $1$.
Comment: Thanks, I wrote down the theorems for future reference. Y'all are life savers. Oh 1 final thing, if $g(z)$ is constant, does it imply, $f(z)$ is as well?

Complex inequalities and constants


Practice for skill maintenance with busy life

Question: When I was younger I learned piano to grade 6 level, and I also picked up some bass guitar along the way. I enjoy playing music and composing from time to time. But life is busy (PhD thesis/work/etc.) and I find it hard to convince myself I have time to practice.
What are some strategies I could use to keep up my skills despite a busy schedule? Things I'm currently most concerned about:

Sight reading
Accuracy and consistency in piano technique, inc. touch
Accuracy and speed in bass guitar technique

Edit: I'm asking about specific practice techniques people have used. That is, practical advice. Motivation to practice should be assumed as given.
Comment: There seems to be a misunderstanding - I intended for this question to be exactly about musical practice. That is, about practice techniques. I intended for the motivation behind practice to be taken as assumed, and hoped to receive suggestions about actual techniques for practicing musical instruments.
I'm well aware that practice is the only way to be good at playing an instrument. I'm simply hoping to hear about practical strategies people have used to achieve that while maintaining a life full of other things.
Comment: I'm not sure this is really on topic. It's a motivation question, not a music question. You could use exactly the same question on any topic. If you want to do it just fit it in. If you don't then your skills will deteriorate, as you have suggested.
Comment: Real practice takes time, always.  Any sort of strategy for managing practice with a busy life is about time management, not about practice techniques.
Comment: I'm voting to close this question as off-topic because it's not about musical practice and theory per se.
Comment: Maybe the question is problematic because there is no single technique that will be better or worse at preventing atrophy. Whatever one chooses to practice will atrophy less, and whatever one doesn't practice will atrophy more quickly. Perhaps the question intends to ask about how to prioritize practice. But then, the answer depends on specific musical goals that aren't included. Which parts of your playing do you want to not atrophy (eg, sight reading, fast technique, etc.)? Would this sort of info make the question more on topic?
Comment: @jdjazz that is a good point. In a specific sense, I have noticed my sight reading getting worse (though it's never been great), but I'm also concerned about accuracy and consistency of touch with my piano technique, and speed and accuracy with bass guitar. I am more concerned in a general sense, but I take your point about the breadth of the question. I'll try to re-cast it a little.
Comment: I think the sort of answer hartacus seeks is something like "practice scale patterns and major triads." But I wonder if some specific musical goals (or genres) are needed to narrow the focus. It seems like the question is currently asking, "how do I practice piano with 30 min a day," which is perhaps too broad given this site's goals. A useful way to rephrase might be: "what are the two most important techniques for practicing X and Y with limited time?" where X and Y represent specific techniques or aspects of music practice.
Comment: To me the question is really "what is the most efficient way to practice?" and it's a question all musicians should visit and revisit regardless of  how much or little time is available.
Answer: This will likely not apply to such instruments as guitars or the piano, but if possible carry instruments with you, so you can practice e.g. in a stairwell on the way in to work

Otherwise, carve out specific time say 30 minutes when you get home or some other predictable time for practice. Another option would be to reserve time (a commitment!) in a musical practice room, should such be available nearby. (This might also provide quiet time to work at other things or to let your mind wander as necessary...)
Comment: I like the idea of booking a practice room! There are some near where I work and I'd completely forgotten about them. Thanks for the reminder! If you do this yourself, do you set a specific thing to practice on during your booking?
Comment: Usually only contextual things I'm having trouble with, like high notes on the end-blown flutes. But I mostly use stairwells or 70s brutalist structures (the concrete has good acoustics) for practice.
Answer: I use to have this problem as well. I have a really busy schedule and practicing guitar had become really really hard. so what I did was,
I decided to spend at least 30 minutes of time every day.
So now the question would be when?
I pick up my guitar right after I wake up. Usually, I wake up around 6.30 AM and practice for 30 mins and then get ready for work.
And when I return back from work every day, I try to pick up my guitar back again if possible. Sometimes I skip at evening but that's fine.
I just make sure that I pick up my guitar at least once a day.
So that's my two cents for you.
Answer: Build a library of sight reading material. You have to find the right level for yourself. Some examples that worked for me are:

Czerny, 100 Progressive Recreations
Schubert, Dances for Solo Piano (Dover edition)
Mozart, L. Nannerl Notebook; Notebook for Wolfgang
Mozart, WA. London Sketchbook
Bach, Anna Magdalena Notebook
Beyer, Elementary Instruction Book
A hymnal notated on the grand staff
Answer: Some ideas that I feel have helped me:

I squeeze in small amounts of practice during breaks or other down time during the day.
I rarely practice any one thing more than a few minutes.  I find diminishing returns beyond that, and figure on any given task I'm probably better off with frequent short practice than less frequent long practice.  I could be wrong.
I try to keep my practice area organized and ready to use: bass plugged in, with strap, on a stand, electronics all on one switch, any reading material on a stand, etc.  With an hour long practice session it wouldn't matter so much, but I don't want to waste even one minute of a ten-minute session setting up.
I keep lists of lots of small (5-10 minute) tasks.  I use the phone app AnkiDroid to track them.  I like that it will remind me periodically (at wider intervals depending on how the previous practice went), but it's not really intended for this and there may be better ways.
I also have lists of practice tasks that don't require an instrument.  This lets me take advantage of time in the shower, on the bus, etc.  In my case that's been mainly ear training, repertoire memorization, and fretboard memorization (e.g., visualizing the locations of every ii-V-I in every key using some voicing).  But with some creativity I bet it's possible to come up with some good reading exercises that don't require an instrument.  I think when I was younger I overestimated the importance of physical relative to mental components of musical skills.
For occasional conference travel I have the same list of mental exercises or other hotel-room-friendly activities (composing would be good), but I also sometimes take a midi keyboard (tiny 25-key CME XKey) or small bass (a used Ashbory that fits under an airplane seat).
Sometimes the only dedicated time I have is at the end of the day when I'm tired and (I know that's not what this was about, but...) unmotivated.  I try to have in mind one short (<10-minute) task that I am absolutely committed to doing every day even if I feel like crap.  I tell myself that if that's all  I feel like, that's OK.  But usually once I get over the initial hump I'm good for longer.
I try to remember that this is in the end just a hobby for me that's supposed to be fun, and that if I need to take some time off that's not the end of the world.
That said, during my own PhD program I mostly dropped the ball on music and wish I could have found some regular low-key commitments to force me to keep it going.  (Sorry, motivation again.)

Good luck!  I'm no expert, just another amateur with too much else going on, so take this all with a grain of salt.


Ajuda com innerHTML no Javascript

Question: estou tentando adicionar uma variavel que contem um elemento html no meu arquivo html, estou tentando usar o innerHTML += minhavar, o problema é que, eu tenho dois elementos para serem adicionados, um iframe e um paragrafo, quando adiciono iframe vai de boa, mas o paragrafo não adiciona.
function inserir() {
  let nomeVideo = document.querySelector('#nome-video').value;
  let linkVideo = document.querySelector('#link-video').value;
  let itemVideo = `

${nomeVideo}

`;

  document.querySelector('#conteudo-videos').innerHTML += itemVideo;
}

Oque eu posso estar fazendo errado ?? lembrando que estou começando agora no javascript, então perdoem a noobise.
Comment: Tinha esquecido de fechar o iframe
Answer: Primeiramente, tome cuidado com os Template Literals, o suporte dos Browsers ainda é pequeno.
Então no lugar do Template Literals irei utilizar o Handlebars, apenas para melhorar a compatibilidade do seu codigo.
Mas o problema, era que você está esquecendo de fechar o seu iframe.

var templateVideo = document.querySelector('#template-video');
var inserirVideo = document.querySelector('#inserir-video');
var nomeVideo = document.querySelector('#nome-video');
var linkVideo = document.querySelector('#link-video');
var conteudoVideo = document.querySelector('#conteudo-videos');

var template = Handlebars.compile(templateVideo.innerHTML);
var parser = new DOMParser();

function inserir() {
  var modelo = {
    linkVideo: linkVideo.value,
    nomeVideo: nomeVideo.value
  };
  var htmlVideo = template(modelo);
  var itemVideo = parser.parseFromString(htmlVideo, "text/html").firstChild
  conteudoVideo.appendChild(itemVideo);
}

inserirVideo.addEventListener("click", inserir);

<fieldset>
  <legend>Inserir Video</legend>

    Nome:
    <input id="nome-video" type="text" />

    Link:
    <input id="link-video" type="text" />

  <input id="inserir-video" type="button" value="Inserir" />
</fieldset>

Comment: Dessa eu não sabia @TobiasMesquita, muito obrigado por ajudar
Answer: Vi que o erro no seu código é a falta do fechamento da tag iframe.
Fiz um teste aqui e deu certo, segue:

function inserir() {
            let nomeVideo = "Teste Template String"
            let linkVideo = "https://www.youtube.com/embed/mKcZVZNDQPE"
            let itemVideo =
                `

${nomeVideo}

                `;

            document.querySelector('#conteudo-videos').innerHTML += itemVideo;
        }

        inserir()

Com relação ao comentário sobre a compatibilidade da template String, realmente. O IE nem o Opera implementaram ainda.
Entretanto, se a compatibilidade for um ponto crucial para seu problema, sugiro dar uma olhada no Transpiler BabelJS.
O que ele faz é fazer um "Downgrade" do seu código escrito em ES6+ (mais novas funcionalidade) para o javascript ES5-, código que todos os browsers entedem.

Ajuda com innerHTML no Javascript


Block Inserts Compatibility

Question: I'm fixing a guitar and the owner lost his Floyd Rose saddle inserts. The guitar has a Floyd Rose Special system. Are the Floyd Rose Schaller saddle inserts compatible with Floyd Rose special? Or should i search specific saddle inserts for Floyd Rose special?
Thank you!
Answer: An entire saddle set for the Floyd Rose Special is about the same cost as a decent set of strings (search at https://floydrose.com). I'd just replace the whole set and keep it genuine.

Block Inserts Compatibility


Align identical data in two columns while preserving values in the 3rd in excel

Question: I have a large amount of data spread throughout 3 columns on a worksheet in excel. I want to match identical values in columns A & B while keeping values associated with column B inline with their respective B components. Here is an example:
What I have-
    A   B   C
1   a   g   '
2   b   h   *
3   c   a   ?
4   d   e   $
5   e   b   /
6   f   j   )
7   g   c   #
8   h   d   @
9   i
10  j

What I am looking to achieve:
    A   B   C
1   a   a   ?
2   b   b   /
3   c   c   #
4   d   d   @
5   e   e   $
6   f
7   g   g   '
8   h   h   *
9   i
10  j   j   )

I found this code, but it doesn't also carry over the 3rd column values.
Sub Macro1()
    Dim rng1 As Range
    Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))
    rng1.Offset(0, 1).Columns.Insert
    With rng1.Offset(0, 1)
        .FormulaR1C1 = _
        "=IF(ISNA(MATCH(RC[-1],C[1],0)),"""",INDEX(C[1],MATCH(RC[-1],C[1],0)))"
        .Value = .Value
    End With
End Sub

Any help would be greatly appreciated!
Thanks
Answer: You will have to store the values in memory (a variant array seems appropriate), then clear the values and work through A1:A10 looking for matches to the first rank of the array.
Sub aaMacro1()
    Dim i As Long, j As Long, lr As Long, vVALs As Variant
    With ActiveSheet
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        vVALs = Range("B1:C" & lr)
        Range("B1:C" & lr).ClearContents
        For i = 1 To lr
            For j = 1 To UBound(vVALs, 1)
                If vVALs(j, 1) = .Cells(i, 1).Value Then
                    .Cells(i, 2).Resize(1, 2) = Application.Index(vVALs, j)
                    Exit For
                End If
            Next j
        Next i
    End With
End Sub

It would probably be best if you tested that on a copy of your data as it does remove the values from B1:C10 before returning them.


Potential Equation with Polar coordinates...

Question: The problem:

Consider Laplace's equation $$\nabla^2u=\frac{1}{r}(ru_r)_r + \frac{1}{r^2}u_{\theta\theta}=0$$
  on the annulus ${(r,\theta)}: r \in (\frac{1}{2},2),\theta \in[0,2\pi]$. Find all separable solutions $u(r,\theta)=\phi(r)\xi(\theta)$

Here is my work for this problem:

$$u(r,\theta)=\phi(r)\xi(\theta)$$
  $$u_r=\phi'(r)\xi(\theta), u_{\theta\theta}=\phi(r)\xi''(\theta)$$
  $$\implies \frac{1}{r}(r\phi'(r)\xi(\theta))+\frac{1}{r^2}\phi(r)\xi''(\theta)=0$$
  $$\implies \frac{1}{r}(r\phi''(r)\xi(\theta) +\phi'(r))\xi(\theta) = -\frac{1}{r^2}\phi(r)\xi''(\theta)$$
  $$\implies r(\frac{r\phi''(r) +\phi'(r)}{\phi(r)})=-\frac{\xi''(\theta)}{\xi(\theta)}=\mu^2$$
  where $\mu^2 \geq 0$ so $\xi$ will be a periodic function. We now have the equations:
  $$(1):r^2\phi''(r) +r\phi'(r) - \mu^2\phi(r)=0,$$
  $$(2):\xi''(\theta)+\mu^2\xi(\theta)=0.$$
  Solving for (2), we obtain for $\mu >0$:
  $$\xi(\theta)=a_1cos(\mu\theta)+a_2sin(\mu\theta).$$
  If $\mu=0$, we have
  $$\xi(\theta)=a_1+a_2\theta.$$
  Solving for (1), we obtain for $\mu >0$
  $$\phi(r)=b_1r^{\mu}+b_2r^{-\mu}$$
  If $\mu=0$, we obtain
  $$\phi(r)=b_1log(r)+b_2$$

The only boundary condition is that r is bounded by zero (as we cannot have negative radius). Otherwise, we are given nothing but intervals. So to the overall question: where do I go from here to find the separable solutions? I know the answer is right around the corner I just cannot get around the corner :(
Answer: You have a few small typos, but they seem insignificant.
As the function $\xi(\theta)$ has to be $2\pi$-periodic we obtain the following:

If $\mu=0$ we must have $a_2=0$ in your solution, so that $\xi(\theta)=a_1$. Multiplying this with the corresponding $\phi$ gives solutions of the form $A_0 \log r+B_0$.
If $\mu>0$, in order to make $\xi$ $2\pi$-periodic we must have that $\mu=n$ is a (positive) integer. The corresponding solutions are of the form $(A_n r^n+B_nr^{-n})(C_n \cos n \theta+D_n \sin n \theta)$.
Comment: Thank you. Everything is cleared up now :)


Issue with Playwright running multiple workers and executing hooks multiple times

Question: I'm experiencing an unexpected behavior with Playwright when running tests with multiple workers. According to the Playwright documentation, the beforeAll hook should be executed ONCE PER WORKER. However, I'm observing that the hook is being executed multiple times, resulting in duplicated log messages.
I have a simple test setup with the following structure:
test.beforeAll( async({browser}) => {
    console.log("should be before all tests")
});

test.beforeEach( async()=>{
    console.log('should be before Each test')
})

test.afterAll(async() => {
    console.log('should be after all tests')
});

test('test case',async () => {
});

test('test case 2',async () => {
});

Expected behavior per worker should be: one console.log before, two console.logs (once per test) and one console.log after.
Received behavior:
Running 8 tests using 4 workers
[chromium] › loginAndNavigate.spec.ts:65:5 › test case 2
should be before all tests
should be before Each test
should be after all tests
[chromium] › loginAndNavigate.spec.ts:60:5 › test case 1
should be before all tests
should be before Each test
should be after all tests
[firefox] › loginAndNavigate.spec.ts:60:5 › test case 1
should be before all tests
should be before Each test
should be after all tests
[firefox] › loginAndNavigate.spec.ts:65:5 › test case 2
should be before all tests
should be before Each test
should be after all tests
[webkit] › loginAndNavigate.spec.ts:60:5 › test case 1
should be before all tests
should be before Each test
should be after all tests
[webkit] › loginAndNavigate.spec.ts:65:5 › test case 2
should be before all tests
should be before Each test
should be after all tests
[Mobile Safari] › loginAndNavigate.spec.ts:60:5 › test case 1
should be before all tests
should be before Each test
should be after all tests
[Mobile Safari] › loginAndNavigate.spec.ts:65:5 › test case 2
should be before all tests
should be before Each test
should be after all tests

As you can see, each message is being printed multiple times.
Any insights or suggestions on what might be causing this issue would be greatly appreciated.
I've already checked my Playwright configuration(where the number of workers is set to 4). I'm using the latest version of Playwright
Comment: I'm facing this exact scenario. I would assume at least in a test suite consisting of multiple tests in 1 file that a beforeAll would only be performed once. The 2 workarounds I can think of is separating the tests into their own tests file so that it still processes in parallel but that would require a global setup and teardown. Or do serial mode for this 1 test file. If there are other test files, then it'll still be parallel depending on number of workers.
Answer: I beleive this is expected behavour. As you have set number of workers to 4, beforeAll will potentially run up to 4 times per browser. The beforeAll hook is also done before each new browser.
To demonstrate, in the run below, I have changed to max 2 workers and are running 4 tests in 2 different browsers:
Running 8 tests using 2 workers

  ✓  1 [chrome web] › multipleworkers.spec.ts:19:5 › test case 3 @1 (1ms)
  ✓  2 [chrome web] › multipleworkers.spec.ts:15:5 › test case @1 (1ms)
should be before all tests
should be before all tests
should be before Each test
should be before Each test
  ✓  3 [chrome web] › multipleworkers.spec.ts:17:5 › test case 2 @1 (0ms)
  ✓  4 [chrome web] › multipleworkers.spec.ts:21:5 › test case 4 @1 (0ms)
should be before Each test
should be after all tests
should be before Each test
should be after all tests
  ✓  5 [firefox web] › multipleworkers.spec.ts:19:5 › test case 3 @1 (1ms)
  ✓  6 [firefox web] › multipleworkers.spec.ts:15:5 › test case @1 (1ms)
should be before all tests
should be before Each test
  ✓  7 [firefox web] › multipleworkers.spec.ts:17:5 › test case 2 @1 (0ms)
should be before all tests
should be before Each test
  ✓  8 [firefox web] › multipleworkers.spec.ts:21:5 › test case 4 @1 (0ms)
should be before Each test
should be after all tests
should be before Each test
should be after all tests

Here, beforeAll are run 4 times; 2 workers and 2 different browsers while beforeEach are run 8 times.
Answer: Serial Mode
You may run tests in serial mode , if you need to run beforeAll just once:
// Annotate entire file as serial.
test.describe.configure({ mode: 'serial' });

test.beforeAll( async({browser}) => {
    console.log("should be before all tests")
});

test.beforeEach( async()=>{
    console.log('should be before Each test')
})

test.afterAll(async() => {
    console.log('should be after all tests')
});

test('test case',async () => {
});

test('test case 2',async () => {
});

https://playwright.dev/docs/test-parallel#serial-mode


Normal subgroups of $A_5$ must contain a 3-cycle.

Question: I am trying to prove the simplicity of $A_5$ by showing that every non-trivial normal subgroup $H$ contains a 3-cycle, and therefore is all of $A_5$ since the 3-cycles all belong to one conjugacy class and all the 3-cycles generate $A_5$. Now if $H$ contains a 3-cycle already then the proof is done. Otherwise $H$ contains only products of two transpositions or 5-cycles. How can I cook up some general calculation that no matter what I'll always get a 3-cycle from these types of elements?
I've asked a related question here.
Answer: If $H$ contains a 5-cycle then it contains all 5-cycles, since all subgroups of order 5 are conjugate. Show that the product of two well-chosen 5-cycles gives a 3-cycle.
If $H$ contains a permutation that is a product of two disjoint 2-cycles, then $H$ contains all such permutations (all are conjugate). Again, pick two and take their product.
Comment: This doesn't really affect the validity of the argument, but it is not true that all $5$-cycles are conjugate in $A_5$. But all subgroups of order $5$ are conjugate, so any normal subgroup containing a $5$-cycle contains all $5$-cycles.
Comment: When you say that a subgroup is conjugate you mean it is normal?
Comment: And how do we know all subgroups of order 5 are conjugate? And why must a normal subgroup contain all 5-cycles?
Comment: @Morgan Rodgers Thanks for that. I'll just put this one on the back burner for now as I haven't been introduced to Sylow subgroups yet.
Answer: A very nice proof is the following, due to Galois. Let $N$ be a normal subgroup, and suppose that it is nontrivial. Pick an element $\sigma$ with the maximum number of fixed points that is not the identity. If it is not a three cycle, its cycle decomposition is of the form $\sigma =(123\cdots)\cdots$ or $\sigma =(12)(34)\cdots$. If you think about it for a while, you should be able to conjugate $\sigma$ appropriately so it fixes more elements, which contradicts our choice of $\sigma$.


When $\text{ord}_n(p)/m = \text{ord}_{n/m}(p)=1$

Question: $\newcommand\ord{\text{ord}}$
For integers $n,m,p$, suppose $m$ and $n$ share the same prime divisors with $m$ dividing $n$, and suppose $\text{gcd}(p,n)=1$.
I want to show that $\ord_n(p)/m=\ord_{n/m}(p)$, where $\ord_x(p)$ denotes the order of $p$ in the multiplicative group of integers modulo $x$.
It's only my guess that this is true, and I'm wondering how to prove it.
Edit: As `reuns' showed a counter-example in the comments for $\ord_{n/m}(p)>1$, I now only consider the question for $\ord_{n/m}(p)=1$.
But even the case $\ord_{n/m}(p)=1$ is difficult for me.
Then $p = qn/m+1$ for a quotient $q$ from division by $n/m$.
If $\ord_n(p)=1$ then $p=q'n+1$ for another quotient $q'$ (from division by n) in which case $q'=q/m$.
Hence unless $q$ is divisible by $m$ we know $\ord_n(p)>1$.
Henceforth we will actually assume $\text{gcd}(m,q)=1$.
Now we'd like to show $m$ is the smallest $t$ for which $(qn/m+1)^t\equiv1(\bmod n)$.
Using binomial expansion we write
$$
\begin{align}
(qn/m + 1)^t &= \sum_{k=0}^t \binom{t}{k}(qn/m)^k \\
&= 1 + tqn/m + \frac{t(t-1)}{2!}(qn/m)^2 + \dots + \frac{t(t-1)}{2!}(qn/m)^{t-2} + t(qn/m)^{t-1} + (qn/m)^t
\end{align}
$$
I'd like to assert that if the sum of all terms other than $1$ is divisible by $n$, it must be that each term other than $1$ is divisible by $n$. Is this true?
Supposing that to be the case, if $n$ is to divide $tqn/m$ we must have $tq=\text{lcm}(q,m)=qm/\text{gcd}(q,m) = qm$ implying $t\geq m$.
Now to show all terms other than the first two are also divisible by $n$ when $t=m$, I only know to further restrict criteria with $m^s=n$ for $s\geq2$.
Then $(n/m)^k/n = m^{ks-k-s}$ and $ks-k-s\geq0$ for $k\geq2$, in which case all terms beyond the first two are indeed divisible by $n$, implying $\ord_n(p)=m$.
For what other criteria can this equation be shown to hold?
In particular, how about for $n$ not a power of $m$? How about for $p$ an odd prime? (Still supposing $\text{gcd}(m,q)=1$.)
Comment: Look up a proof of lifting the exponent lemma. I believe that is what you need here.
Comment: Your question is unclear because it seems what you want to show is wrong.
Comment: @reuns Where is the proof wrong? I'm asking for what other criteria it can also be proven.
Comment: $p=7,n=8,m=2, ord_n(p)=ord_{n/m}(p)=2$
Comment: @reuns I see, thanks. I've edited the question to assume $\text{ord}_{n/m}(p)=1$.
Comment: Which doesn't help (try $p=17$)
Comment: @reuns That violates the assumption $m$ doesn't divide $q$, which I've edited to make more explicit.
Answer: $\newcommand\ord{\operatorname{ord}}\newcommand\lcm{\operatorname{lcm}}$
Consider integers $n,m,p$ with $m^2|n$.
Suppose we have $p=q(n/m)+1$ for some integer quotient $q$ such that $\ord_{n/m}(p)=1$.
Then $\ord_n(p)=m/\gcd(q,m)$.
We must show that the smallest integer $t$ for which $(qn/m+1)^t\equiv1(\bmod n)$ is $m$.
Using binomial expansion we write
$$
    \begin{align}
        (qn/m+1)^t &= \sum_{k=0}^t \binom{t}{k}(qn/m)^k \\
        = 1 &+ t(qn/m) + \frac{t(t-1)}{2!}(qn/m)^2 + \dots \\
         &+ \frac{t(t-1)}{2!}(qn/m)^{t-2} + t(qn/m)^{t-1} + (qn/m)^t
    \end{align}
$$
We must find the smallest $t$ for which $n$ divides all terms for $k\geq1$.
With $r:= n/m^2$ we may represent the $k$'th term as
$$
    \begin{equation}
        n\binom{t}{k}q^k\frac{n^{k-1}}{m^k}
        = n\binom{t}{k}q^kr^{k-1}\frac{m^{2(k-1)}}{m^k}
        = n\binom{t}{k}q^kr^{k-1}m^{2k-2-k}
    \end{equation}
$$
Since $2k-2-k\geq0$ for $k\geq2$ we have it that $n$ divides all terms for $k\geq2$.
Therefore $n$ divides the sum of all terms for $k\geq1$ if and only if $n$ divides the term $t(qn/m)$.
The smallest $tq$ for which $tq/m$ is an integer (and thus $n$ divides $t(qn/m)$) is $\lcm(q,m)$.
Thus $\lcm(q,m)=qm/\gcd(q,m)$ is the smallest such $tq$ and it follows that $\ord_n(p)=t=m/\gcd(q,m)$.


what does the "ctx" really doing discord.py

Question: Im programming a discord bot in Python
and every tutorial on Youtube telling me that i have to use the 'ctx' when im making a command,
but none of those Youtubers explaining what this is doing, so pls can someone answer me?
Answer: As explained in the docs:

A command must always have at least one parameter, ctx, which is the Context as the first one.

Now, what is Context? Again, the docs:

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.


How to translate strings available in JS library?

Question: I'm showing some images on my site where those are displayed using jquery.magnific-popup.min.js library. I'm not able to translate a string in that library. i.e.

"%curr% of %total%"

It is not searchable even in the translate interface. How can I translate it?
Comment: Drupal doesn't know about strings in 3rd party javascript code (it's client side, and not Drupal), so it won't be able to list them as available translations. I imagine you'll need to implement something yourself with whatever method the library in question provides for localisation. After you've got that bit done you can probably find a way to introduce the new strings to Drupal's translation interface, but I would've thought you'll need to write the integration part first
Answer: See the plugin's translation documentation for a list of strings and their option names.
Pass these strings through Drupal.t() when attaching your popup.
Answer: Do not waste your time with the interface translation, you may find strings started with "" in jquery.magnific-popup.min.js file, just locate there with your editor, and change them. Just before make a backup of the javascript file for sure.
Then clear your site's cache /admin/config/development/performance and reload your page.
Hope it can help, that's worked for me.
Comment: Thanks for this answer but it is not recommended to make changes in original files like these, isn't it?


Apache server-status not showing "Server Load"

Question:
Apache's server-status page displays information from mod_status.
It is not displaying Server load:

But as you'll notice, the Apache.org/server-status status page does show Server load:

On previous servers I have used it always displays.
Why is this? How can Server load be enabled?
Answer: Server Load is only displayed on the <code>/server-status</code> page for Apache v2.4. You will need to upgrade to see it


Getting Type Expected Error in VB

Question: Please see attached code
<code>topThird = RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(Nothing, GetType((System.Math), "Round", New Object() {Operators.DivideObject(totalTitles, CType(3, Integer))}, Nothing, Nothing, Nothing))
</code>
I am getting an error in VS 2008 that says "Type Expected". I am at a loss and cannot figure out what I need to add. I can see from the error something is not correct but I am not sure what. BTW option strict is ON
I can post the whole function if it is needed, please post a comment if this will help
Answer: I think there is an error with brakets: you have 8 opening brakets and only 7 closing... maybe there is a superfluous one near GetType.

Getting Type Expected Error in VB


Deserialize multiple objects from filestream in C#

Question: I can't deserialize multiple JSON objects from a FileStream; I get a SerializationException.
I can do it with one object but not with multiple.
I'm trying with this from a .txt file :

csharks imi 1991
csharks romeo 1989
csharks peti 1989
csharks berti 1991
csharks bala 1993

JSON:
  [
   {
     "Name": "imi",
     "TeamName": "csharks"
   },
   {
     "Name": "romeo",
     "TeamName": "csharks"
   },
   {
     "Name": "peti",
     "TeamName": "csharks"
   },
   {
     "Name": "berti",
     "TeamName": "csharks"
   },
   {
     "Name": "bala",
     "TeamName": "csharks"
   }
 ]

C# code:
public class Program
{
    private static List<TeamMember> teamMembers = new List<TeamMember>();
    private static List<TeamMember> teamMembersDeserialized = new List<TeamMember>();

    public static void Main(string[] args)
    {
        string teamFile = @"C:\Users\Precision\Downloads\Serializacio\csharks.txt";
        string teamFileJson = @"C:\Users\Precision\Downloads\Serializacio\csharksJSON.json";
        string teamFileJson2 = @"C:\Users\Precision\Downloads\Serializacio\csharksJSON2.json";
        using (FileStream fs = new FileStream(teamFile, FileMode.Open, FileAccess.Read))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                List<string> memberData = new List<string>();
                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    memberData = line.Split(' ').ToList();

                    TeamMember member = new TeamMember(memberData[0], memberData[1], int.Parse(memberData[2]));
                    teamMembers.Add(member);
                }

            }
        }
        using (FileStream fs = new FileStream(teamFileJson, FileMode.OpenOrCreate, FileAccess.Write))
        {
            foreach (TeamMember member in teamMembers)
            {
                Console.WriteLine(member.ToString());
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(member.GetType());
                jsonSerializer.WriteObject(fs, member);

            }
        }

        using (FileStream fs2 = File.OpenRead(teamFileJson2))
        {
            foreach (TeamMember member in teamMembers)
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(member.GetType());
                {
                    TeamMember memberNew = jsonSerializer.ReadObject(fs2) as TeamMember;
                    teamMembersDeserialized.Add(memberNew);
                }
            }
        }

        foreach (TeamMember member in teamMembersDeserialized)
        {
            Console.WriteLine(member.ToString());
        }

        Console.ReadKey();
    }
}

Comment: I'm confused the file is not json? where are teamMembers coming from?
Comment: That doesn't look like valid json ?
Comment: Sorry! Updated!
Comment: Does this work (where json is the whole file from '[' to ']'): var my_array = JsonConvert.DeserializeObject>(json)? (Ref https://www.newtonsoft.com/json/help/html/DeserializeObject.htm)
Comment: I have made it work! Thx guys! DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List)); readMembers = jsonSerializer.ReadObject(fs2) as List;
Answer: The following example parses your JSON. I'm using the Newtonsoft.Json namespave. Please let me know if you need any additional help.
void Main()
{
    var json = @"[
        {
            'Name': 'imi',
            'TeamName': 'csharks'
        },
        {
            'Name': 'romeo',
            'TeamName': 'csharks'
        },
        {
            'Name': 'peti',
            'TeamName': 'csharks'
        },
        {
            'Name': 'berti',
            'TeamName': 'csharks'
        },
        {
            'Name': 'bala',
            'TeamName': 'csharks'
        }]";

    var teams = JsonConvert.DeserializeObject<List<Team>>(json);

    teams.ForEach(x => Console.WriteLine($"Name: {x.Name}, Team: {x.TeamName}"));
}

public class Team
{
    public String Name { get; set; }
    public String TeamName { get; set; }
}

This gives the following output:
Name: imi, Team: csharks
Name: romeo, Team: csharks
Name: peti, Team: csharks
Name: berti, Team: csharks
Name: bala, Team: csharks

To read this JSON from a file, you can do the following:
var filename = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
    "test.json");

var json = File.ReadAllText(filename);