Is the tempo supposed to be denoted in the same units as the bottom number of the time signature?

Question: I've seen tempo sometimes denoted like "♩ = 120 BPM" instead of using something like "Adagio". In cases like this where it has a number, the actual size of the note seems irrelevant since I could just say then "dotted-half-note = 30 BPM" and it would mean the same thing.
So let's suppose I'm in 3/4 time signature, which means my measure is made up of quarter notes in a pattern of 1-1-1. Is it customary to use the same size note as in the bottom of the time signature? In this case, it would then be "♩ = 120 BPM". Or can I just put any size I want as long as it means the same thing, e.g. "dotted-half-note = 30 BPM"?
Comment: You could also give the length of a beat in time as s, ms or ns. However that wouldn't help much. What you feel, or what you might dance to, is, in your example: 123 123 etc., not 3 3 etc. So it's more a specification of feel, rather than tempo alone.
Answer: Generally, the bottom note (of simple time such as 3/2, 2/4, 3/4,  2/2, or 4/4), the bottom note is used to represent the beat. Compound time may be a bit more complex (but the composer ought to indicate what's wanted); times like 6/4 or 6/8 or 12/8 may indicate grouping by triplets. Sometimes the actual notes are used  as in "quarter note = 120."
However, some care needs to be taken with dancers or music intended for dancing. Often dances are indicated in "measures per minute" rather than "beats per minute." In waltzes vs foxtrots, there is a difference. As some older sheet music was written in 2/4 but with an eighth-note beat, measures per minute would equalize 4/4 with 2/4 (rags, tangos, foxtrots, cha-chas...). There's always some "performance culture" that must be considered in figuring out tempi. (Not to mention the speed changes needed to compensate for venues with long reverb times, but that's not notated except for computer.)
Comment: I second the advice to consider the "performance culture". If the score you're writing is in a well-established tradition, you can probably look at other scores and figure out what makes the most sense that way. Otherwise it's a good idea to ask relevant performers. They can figure out lots of things, but you want to make their lives as easy as possible, so you want to put whatever is clearest to them/easiest to count.
Answer: A metronome mark doesn't always match the bottom of a time signature, but neither should it be whatever you want.
A metronome mark is most properly a number of beats per minute. So the note value used for a metronome mark should be the value taken by a beat, not an arbitrary note value. Normally the bottom of a time signature indicates the beat directly, as in 3/4, or 2/2.
However, when the top of the time signature is divisible by 3, it often indicates compound time, especially when the bottom number is 8 (note that 3/4 would not normally indicate compound time, 12/4 might indicate it, and 6/8 does indicate it). For most compound time, a dotted quarter note gets the beat, which should be reflected as such in any metronome mark. Including a metronome mark with a note value along with an unusual time signature is one way to clarify how the time signature is to be interpreted.
Other cases where the metronome mark would not match the bottom number would be time signatures that are slightly changed forms of other time signature. For example, many cases of 7/8 time are meant to be played as 4/4 with a dropped 8th note. The tempo is best indicated with a quarter note value even if traditional metronomes could never play those clicks. Partly to be clear about the intention of the music and today also because there are digital metronome and apps that can click on quarter notes in 7/8 time.
Answer: BPM stands for Beats Per Minute, so the note used in the tempo indication should have the duration of one beat.
In a simple time signature like 2/4, 3/4, or 4/4, you should use a crotchet note (quarter note), because this is the duration of one beat.
But in a compound time signature such as 6/8, or 9/8, or 12/8, a quaver (eight note) is the duration of a pulse (which has less emphasis than a beat), a dotted crotchet (dotted quarter note) has the duration of a beat, and so this is what should be used in the tempo indication.
In a 'larger' compound time signature such as 6/4 or 9/4 (again compound time signatures), the beat duration is a dotted minim (dotted half note).

Irregular time signatures are a bit more difficult because the duration of a beat is not constant.
[where S = strong beat, M = medium beat, w = weak (pulse)]
5/8 has the beat structure of SwwMw (but could also be SwMww)
7/8 has SwwMwMw (usually)
and 8/8 is SwwMwwMw
These irregular time signature should probably be denoted with dotted crotchets because this is the duration of a strong beat.  (The second option of 5/8 should use a crotchet).
But, it would also be reasonable to instead uses a quaver in the tempo indication and write a PPM (Pulses Per Minute) instead of BPM.
Comment: Dave Brubeck's Unsquare  Dance - SwSwSww.
Comment: @Tim Hmm strange piece, sounds like `SwSwSMw` to me, which is a type of 7/4.
Comment: That song is really groovy!
Answer: The most usual case is to give the tempo in the units of the bottom of the time signature. For fast tempi it might be given in multiples of that, and for very slow tempi it might be given in a subdivision.
For example in 4/4:

quarter=120 works well
quarter=200 might be better expressed as half=100
quarter=50 might look better as eighth=100

The tempo of a Viennese waltz could be given as quarter=180 or dotted-half=60. Both are common.
It's up to the composer to choose something they think will help the performer.


Run scheduled task with other domain user

Question: I have a .bat that copies files from source to destination. The source is the local joined server, the destination is a non-joined computer on the network. I need to run this .bat with task scheduler. What user can have privileges on the destination folder? On task scheduler I can only set local or domain users.
The syntax of the bat is like the following:
robocopy "C:\temp\test.txt" "\\192.168.0.1\c$\temp"

Answer: Since this question has a lot of hits from search engines I though it will useful to add another method that works well (mentioned in this reply to a similar question):
You can add the credentials to a user profile in Windows using the Credential Manager found in the Windows control panel.

Login under the user that will be running a Scheduled Task
Open Credential Manager
Click "Add A Windows Credential"
Populate the "internet or network address" field with the server
name
Populate the "User Name" (include domain where required, i.e.
MyDomain\MyUser)
Populate the "Password"
Click OK

Your scheduled task will now automatically use the credentials saved in the Credential Manager for the specified host.
Note that if user password changes you would need to update that in the Credentials Manager.
And a picture that worth a thousand words:
Answer: Because the destination machine is not joined, it is impossible to actually have your task running on your source host as a user from the destination host. The only way it might work is via pass-through authentication.
That is, create a user with the same username and password on both source and destination hosts.  Then configure your task to run as that local user from the source host.  Because the credentials are the same in both locations, Windows may be able to pass-through the authentication request to the destination host and just work because the credentials are the same.
I've never done this in the context of a scheduled task, but it works fairly reliably for interactive type stuff.  You may run into some network UAC limitations depending on the OS versions though.
Answer: Net Use should work for this:
Map a drive letter with net use, then use robocopy to copy to the drive letter. Wrap it all up in a bat script, then schedule the bat script.
net use x: \\servername\sharename /user:username password
For username, put LocalMachineName\username
At the end of your bat script, remove the drive mapping:
net use x: /DELETE
Answer: Why not try using "runas" in the batch file and for the username make sure you use MACHINENAME\username where MACHINENAME is the name of the non-domain joined computer.
The other problem I see is your syntax for robocopy is wrong. If you are only copying one file you might only need to use copy. If you want to use robocopy, please see the correct syntax below.
Then schedule the batch file to run on the domain joined computer.
runas /user:MACHINENAME\username robocopy "C:\temp\ \\192.168.0.1\c$\temp test.txt"

robocopy transfer file and not folder
https://stackoverflow.com/questions/1030739/how-can-i-copy-network-files-using-robocopy


Buffer N values per second RxJava, Project Reactor

Question: I have a stream with some values:
Flux<Integer> stream = getStream();
And I was trying to implement N items per second functionality
stream.bufferTimeout(MAX_SIZE_TWO, _1_SECOND).subscribe(val => {
  System.out.println(val);
});

I am trying to find operator that close to my expected result.
Expected result:
time: 15:00:00, stream_next_value: 1, output: {1}
time: 15:00:00, stream_next_value: 2, output: {2}
time: 15:00:00, stream_next_value: 3, no output => buffer
time: 15:00:00, stream_next_value: 4, no output => buffer
time: 15:00:00, stream_next_value: 5, no output => buffer
time: 15:00:01, stream_no_next_value, output: {3,4}
time: 15:00:01, stream_next_value: 6, no output => buffer
time: 15:00:02, stream_no_next_value, output: {5,6}

But looks like overloaded versions of buffer operator does not support this behavior.
How to achieve expected behavior using buffer operator ?
Comment: Trying to help here but I miss some information.
Could you explain what is the nature and the frequency of your stream ?
Ideally, could you put a minimal, reproductible example  for the input stream (`interval` operator for example) with what result you expect ?
Answer: May be you can do this:
Flowable<Long> stream = Flowable.generate(() -> 0L, (next, emitter) -> {
        emitter.onNext(next);
        return next + 1;
});

// Flowable<Long> stream = Flowable.interval(100, MILLISECONDS);
//                                 .onBackpressureDrop(); // to make it works otherwise get a MissingBackPressureException

stream.buffer(2)
      .zipWith(Flowable.interval(1, SECONDS), (first, second) -> first)
      .flatMap(Flowable::fromIterable)
      .subscribe(s -> LOGGER.info("received: " + s),
                 Throwable::printStackTrace);

Beware of stream must honor backpressure otherwise you have to add a onBackpressureXXX() operator (for instance, that would be the case if stream would be an interval() (see commented code)).
You get this kind of output:
14:39:59.538 | INFO  | RxComputationThreadPool-1 | received: 0
14:39:59.540 | INFO  | RxComputationThreadPool-1 | received: 1
14:40:00.527 | INFO  | RxComputationThreadPool-1 | received: 2
14:40:00.528 | INFO  | RxComputationThreadPool-1 | received: 3
14:40:01.528 | INFO  | RxComputationThreadPool-1 | received: 4
14:40:01.528 | INFO  | RxComputationThreadPool-1 | received: 5
14:40:02.528 | INFO  | RxComputationThreadPool-1 | received: 6
14:40:02.528 | INFO  | RxComputationThreadPool-1 | received: 7
14:40:03.528 | INFO  | RxComputationThreadPool-1 | received: 8
14:40:03.528 | INFO  | RxComputationThreadPool-1 | received: 9


ASP.NET Core 2 EmailSender exception with Sendgrid

Question: I'm trying to implement SendGrid in Angular project template with ASP.NET Core.
I'm using this example: Account confirmation and password recovery in ASP.NET Core
Unfortunately I always get this error (status: 500):

System.InvalidOperationException: Unable to resolve service for type 'MyWebApp.Extensions.EmailSender' while attempting to activate 'MyWebApp.Controllers.AuthenticationController'

Here is the Controller:
[HttpPost]
public async Task<IActionResult> Register([FromBody]RegistrationViewModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var userIdentity = _mapper.Map<AppUser>(model);
    var result = await _userManager.CreateAsync(userIdentity, model.Password);

    if (!result.Succeeded)
        return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState));

    //Enable account confirmation
    var code = await _userManager.GenerateEmailConfirmationTokenAsync(userIdentity);
    var callbackUrl = Url.EmailConfirmationLink(userIdentity.Id, code, Request.Scheme);
    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

    //await _appDbContext.SaveChangesAsync();

    return new OkObjectResult("Account created");
}

And the EmailSender:
public class EmailSender : IEmailSender
{
    public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        Options = optionsAccessor.Value;
    }

    public AuthMessageSenderOptions Options { get; } //set only via Secret Manager

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(Options.SendGridKey, subject, message, email);
    }

    public Task Execute(string apiKey, string subject, string message, string email)
    {
        var client = new SendGridClient(apiKey);
        var msg = new SendGridMessage()
        {
            From = new EmailAddress(<email-address>, <name>),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        msg.AddTo(new EmailAddress(email));
        return client.SendEmailAsync(msg);
    }
}

I tried to write the apiKey directly in the code, but same result.
I've already successfully added a user in the database, but without SendGrid.
Answer: Make sure that the service and its abstraction is registered with the service collection so that the service provider is aware of how to resolve them
Startup.ConfigureServices
services.AddSingleton<IEmailSender, EmailSender>();

services.Configure<AuthMessageSenderOptions>(Configuration);

Comment: They were already registered. I've forgot to show it in the question. Is the sequence important? They are added after `services.AddMvc()`
Comment: @GSeriousB if you review the documentation you linked to in your question you will see where they registered them after.
Comment: I moved the code at the end, but same error. Probably the problem is somewhere else. I'll find it out. Thanks for Help!


Is it acceptable to design a method with a parameter of type System.Enum?

Question: Consider the following method,
public void Add(Enum key, object value);

Since Enum is a "special class", I didn't realize you could use the type in this way, but it compiles.  Now, the .NET Framework Design Guidelines don't have anything to say about this construction, so I'm curious what everyone else thinks about this.
Here is what this method is doing internally:
public void Add(Enum key, object value)
{
   this.dict.Add(key.ToString(), value)
}

Did you expect the parameter to be converted to a string or cast to an int?
Consider the following use-case,
public enum Names
{
   John,
   Joe,
   Jill,
}

Add(Names.John, 10);
Add(Names.Joe, 11);

Is using enum in this way an acceptable alternative to using string constants (given that the domain is the set of all strings which are also valid enum identifiers)?
Last question: Does anyone know of any other real world scenarios that required passing the abstract Enum base class as parameter?
Comment: I've received a fine answer, but I just want to clarify some things for anyone else that reads this.  This question was not about normal scenarios for enumerations, but about the circumstances that require the use of the System.Enum base class as a method parameter where it functions as the base class of all enumerated types -- that is, perhaps I should have phrased the question as "Are there any good reasons for treating enumerations polymorphically?".
Answer: Yes, using Enum as a parameter type is completely valid.
Comment: I'm surprised this comment received so many points because it has no detail.
Comment: It was the first answer that directly answered your question.
Answer: It's absolutely valid to use an enum value as a parameter.

Is using enum in this way an acceptable alternative to using string constants(...)?

Yes, in fact this is one of the main uses of enums.
Using a general Enum value is a little less obvious, since you generally want to know what values you can expect. A common use of enum values is to use it in a switch statement, and it helps to know what values can be expected. The name of an enum value is not generally that important, it's what it represents.
Comment: If you "Go to definition" in Visual Studio on the Enum type, you'll be presented with the definition of the "public abstract class Enum" which contains the static methods and instance methods like ToObject.
Answer: A recent example of using the Enum class was to extend it to get the DescriptionAttribute of a specified Enum value: link.
Comment: That's a very clever use. Hopefully that works with the InternalsVisibleTo attribute in a way the integrates with Intellisense.
Answer: Yes it is completely valid.  But make sure that the enum's visibility is equal to the method's visibility.
In other words: If your method is public, make the enum public.  Otherwise you'd be unable to invoke the method.
The String's Equals method uses an enum as the optional second parameter for comparison options:
String s = "Hello";
s.Equals("hello", StringComparison.OrdinalIgnoreCase);

EDIT:
After rereading your question I understand what you are asking.  I personally don't see the benefit of passing an Enum element to only convert it to a string.
I guess you are trying to accommodate several different derived enum types?  Would it be better to either store the enum into the dictionary, or limit the parameter to a specific derived instance?
You aren't solving the problem of key uniqueness if you are allowing any derived enum to be passed into the method.
Comment: It would be able to work as a constraint if you created a derived enum that contained all valid strings.  But I think it would be better to use the dictionary in your example to enforce string uniqueness.
Comment: I suppose this limitation arises at run-time as an exception?  The second part of your answer is not relevant to my question -- of course you can pass types derived from System.Enum to methods (in this case StringComparison) and it is a good idea to do so.
Comment: I think your last point is a valid one -- it's a shame that Enum doesn't work as a constraint on a generic method.
Answer: If you design a factory pattern to generate classes for different Products with different uses and of course a common base. But all of this products has Enums that describes their actions or States.
You could have a method to generate those products in the base class
like
public class ProductsFactory
{
public static BaseProduct Create( string ProductName, Enum State)
{
....
  return new ProductX;
}
}
public class SailBoat: BaseProduct
{
public enum BoatState
{
Sailing,
Docked,
}
}

public class Airplain: BaseProduct
{
public enum AirplainState
{
Flying,
Landing,
TakingOff
}
}

void main
{
ProductFactory.Create("SailBoat", SailBoat.BoatState.Sailing);
ProductFactory.Create("Airplain", Airplain.AirplainState.Flying);
}


SQL RegEx Create Split: Include SET

Question: I'm writing a regex pattern to split MySQL CREATE statements into column definition arrays. So far, it works great for everything aside from SET columns.  Here's the process:
$lines = explode("\n", $create_sql);

foreach ($lines as $line) {
    $line = str_replace('NOT NULL', 'NOT_NULL', $line);

    $pattern = '/`(.*)`[\s]*([^\s]*)[\s]*(NOT_NULL|NULL)[\s]*(.*),/';

    $search = preg_match($pattern, $line, $matches);

    if ($search !== false && count($matches) === 5) {
        $columns[$matches[1]] = array(
            'type' => $matches[2],
            'null' => $matches[3] === 'NULL',
            'extra' => $matches[4],
        );
    }
}

This process works great on a column with a definition like this:
`id`          INT(11)               NOT NULL         AUTO_INCREMENT,

...but fails on SET columns. How can I best accommodate for the extra quotes and parentheses in this line?
`platform`    SET('iOS', 'Android') NULL             DEFAULT NULL,

To summarize, I need to integrate a pattern to match SET('one', 'two', n) in a string.
Answer: First just let slightly modify your pattern expression, first for readability (\s* instead of [\s]*), then to ensure working even with lowercase statements :
$pattern = '/`(.*)`\s*([^\s]*)\s*(NOT_NULL|NULL)\s*(.*),/i';

Then, to answer your question, prepare the pattern depending on a SET is present or not in the line:
$sub_pattern = stripos($line, ' SET(') ?
  'SET\([^\)]*\)\s*[^\s]*'
  : '[^\s]*';
$pattern = '/`(.*)`\s*(' . $sub_pattern . ')\s*(NOT_NULL|NULL)\s*(.*),/i';

Note that, however, this code is not secured against syntax errors in the source lines.
Comment: @jterry It's what I spontaneously considered before posting my answer, and the intuitive way for that is to merely include the two cases as an alternative in the pattern: `'/`(.*)`\s*(SET\([^\)]*\)\s*[^\s]*|[^\s]*)\s*(NOT_NULL|NULL)\s*(.*),/i'`. But it needs to be finely analyzed to be sure there are no unexpected side effects. It's why I preferred to suggest a more secure way.
Comment: Thanks @cFreed. Great idea to look for the exception with PHP; is there any way you can see to do the if/then `$sub_pattern` check directly in the regex?
Answer: // Input: $sql
$match = '(
             ([^(),]+?|       # no parens, or contains ():
              [^(),]+?
            \(  [^)]+?  \)  # (123), (enum...), etc
              [^(),]*?
           )  \s*(,\s*|$)           # separator or terminator
         )';

preg_match('/(CREATE\s+TABLE.*?\()(.*)(\)[^()]*(;|$))/si', $sql, $m);
list($x, $pre, $list, $post, $z) = $m;
$list = trim($list);
$list = preg_replace('/\s+/', ' ', $list);
$list = preg_replace("/$match/sx", "$1
    ", $list);
$list = trim($list);

// Output:
echo "

$pre
    $list
$post\n
\n";

Notes:

Certain quoted strings will fail to parse correctly.
I think all cases of parentheses work ok.
You will still need to parse each element in $list[], which should be one per column.

SQL RegEx Create Split: Include SET


how to hide a string in an BMP image (Steganography)?

Question: I have to do steganography program using MIPS mars simulator. but i'm having a problem on how do i encode the image and how do i put my message(string) in the image .Also the image has to be in a BMP format and coded in 24 bits (8 bits for red , 8 bits for blue and 8 bits for green).
So if anyone can help me by showing me the code or telling me how to do it .I will be grateful.
update: this is what i managed to do. the problem now is how to transform the string into binary and encode it in the image
.data
fin:    .asciiz "1.BMP"
fout:   .asciiz "1_out.BMP"
addr: .space 250000
input: .space 20
str1:  .asciiz "entrez une chaine de caracteres  :"
    .text

main:
str:
    #lire la chaine
    la $a0, str1
    li $v0, 4
    syscall
    #enregistrer la chaine
    li $v0, 8
    la $a0, input
    li $a1, 20

    move $t0, $a0
    syscall

img:
# ouverture du fichier
li   $v0, 13
la   $a0, fin
li   $a1, 0
li   $a2, 0
syscall
move $s6, $v0

# lire le fichier
li   $v0, 14
move $a0, $s6
la   $a1, addr
li   $a2, 230454
syscall

# fermeture du fichier
li   $v0, 16
move $a0, $s6
syscall

#print le fichier
li   $v0, 13
la   $a0, fout
li   $a1, 1
li   $a2, 0
syscall
move $s6, $v0

# lire le fichier
li   $v0, 15
move $a0, $s6
la   $a1, addr
li   $a2, 230454
syscall

 # fermeture du fichier
li   $v0, 16
move $a0, $s6
syscall

#fin de programme
li $v0, 10
syscall

Comment: I imagine there are tutorials out there for writing a basic steganography process, I'd take one of those work through converting it to your language of choice. I'm afraid this question is probably too broad for StackOverflow, you may want to give it a try first and then post if you have any specific problems.
Comment: i couldn't find a tutorial for it on Mips so if you can link me one it would be amazing
Comment: @kkhater And you likely won't--the point is the algorithm; translating it to ASM is the easy part. Personally I think you should just figure it out and do your own work--that's kind of the point.
Answer: The .BMP file format is not incredibly complicated (fortunately).
Considering that you're operating on such a low level, I would recommend (if security isn't a huge issue) that you mask the last bit of each pixel to your data. Simply jump past the data headers directly into the image data and begin changing the least significant bit of each RGB color to the next bit of your embedded message. Be advised that there is some padding that occurs in BMP format, so it would be best to keep a counter of how many bytes you've already masked in the current row so you don't affect the padding 0's. This method requires an 8/1 ratio of data sizes.
Additionally, you could use a Shift Logical Right loop in MIPS to determine the target bit to embed in your image. Mask each loop iteration with the number 1 and $bitToEmbed, $yourMessageByte, 1 to determine the bit to embed and move to the next byte after 8 iterations (8 bits per byte).
A single masking operation may look like (Actual register names must be substituted, of course):
and $bitToEmbed, $yourMessageByte, 1  #Get Target Bit to embed
and $RGBByte, $RGBByte, 254           #Mask the RGB Byte with 11111110
or $RGBByte, $bitToEmbed, $RGBByte    #Embed your target bit.

Add some iteration to go over a single whole Message Byte:
#Jump Past Header...
#Create all temporary versions of your image and message...
#Begin data processing:
ITERBYTE:
    and $bitToEmbed, $yourMessageByte, 1  #Get Target Bit to embed
    and $RGBByte, $RGBByte, 254           #Mask the RGB Byte with 11111110
    or $RGBByte, $bitToEmbed, $RGBByte    #Embed your target bit.
    srl $yourMessageByte, $yourMessageByte, 1 #Bitshift right by one...
    addi $counter, $counter, 1            #Increment counter
    bne $counter, $BitsInByte, ITERBYTE   #continue loop if we have not read the whole byte

The security of this method relies on the fact that most people cannot tell the difference between slightly different shades of the same color. (Could you tell me if this text is #000000 or #000001)?
Please note, however, that there are methods to detect this level of stenography, as it is not highly sophisticated. Generally it involves computers scanning for the average noise of images or comparing existing images to their modified counterparts. However, if you simply need something that is not human detectable (or readable), then this is a great solution.
Comment: Hopefully you'll be there for his tests, too.
Comment: can you please explain it more simply


Install postgresql on fedora 16 for use with Rails3

Question: I'm trying to install posgresql on F16 to work with my rails installation.  Using this guide
http://wiki.postgresql.org/wiki/YUM_Installation#Initialize
But when I run service postgresql initdb I get this error

Unknown operation initdb
Answer: Fedora 16 has migrated to systemd from traditional init.d layout, so you should run su - postgres -c "PGDATA=/var/lib/pgsql/data initdb" directly, see Fedora wiki
Answer: Reading the link you provide it says
For PostgreSQL version 9.0 and above, the <name> is postgresql-9.0...

and later is says
service <name> initdb

so I'm guessing you want
service postgresql-9.0 initdb

Answer: You can now use sudo postgresql-setup initdb.


Optical Flow in python

Question: Can someone show me an example of how to use cv.calcOpticalFlowPyrLK in python? I've looked over the internet and can't quite figure it out.
Answer: This webpage from the OpenCV-Python Documentation can help understanding the Optical Flow algorithm with source code. The source code can also be found in the OpenCV installation folder : C:\opencv\samples\python2\lk-track.py.
EDIT
This also can help.(Explanation+SC+Demo)

Optical Flow in python


Positive definite matrix with positive entries

Question: I have a question about linear algebra.
My question is:
Is any real symmetric matrix $A$ with non-negative entries such that $\det(A)>0$ positive definite?
Thank you.
Comment: "positive entries" or "non-negative entries"?  It does not really matter, as there are counterexamples.  What have you tried?
Comment: I meant that all entries $a_{i,j}\geq 0$.
If $A$ is of size 2, then it is true.
Answer: The answer is no. For example,
$$
A = \pmatrix{1&2&2\\2&1&2\\2&2&1}
$$
is symmetric with positive entries and $\det(A) = 5 > 0$, but it has negative eigenvalue $-1$ with multiplicity $2$.


Redirect a http request to a specific IP and port in a Docker Container

Question: I am using a Docker container with an image based on python:2.7-alpine.
I would like to have all the requests to ec2.us-west-2.amazonaws.com to be redirected to 127.0.0.1:3000.
How can I achieve that?
I am running a dummy AWS API endpoint locally in the container and I would like that all the requests to AWS EC2 go to my dummy endpoint on port 3000. Unfortunately, I cannot override the API endpoint, that is the reason because I am after a solution that may include IP tables and some hacks in the hosts file.
Comment: Plenty of web servers or reverse proxies can handle this, lighttpd, nginx, haproxy, to name a german couple.
Comment: ok are you able to show me an example of docker file using iptables? @GerardH.Pille
Comment: No, I meant to say that I would not use iptables to solve your problem.
Comment: Ok, can you show me how you would solve this problem in a Docker file?
Answer: To let nginx act as a reverse proxy for your Docker container, you'd add the following to its config
server {
  server_name ec2.us-west-2.amazonaws.com;

  location / {
    proxy_pass_header Authorization;
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;
    client_max_body_size 0;
    proxy_read_timeout 36000s;
    proxy_redirect off;
  }
}

If you'd like to know what you're doing, have a look at https://www.techandme.se/set-up-nginx-reverse-proxy/


How do I check the value of $y$ for which the quadratic equation becomes linear?

Question:
Let$$y= \frac{x^2 + 34x - 71}{ x^2 + 2x - 7}$$  where $x \in \mathbb R$.
  Find the range of the given equation.

By cross-multiplying and rearranging the terms, we will get:
$$(1-y)x^2 + (34-2y)x+ (7y-71) = 0 $$
Now, we will put $D\geq 0$ ($x \in \mathbb R$) and then solve the in-equation using wavy curve method to get
$$y \in (-\infty,5] \cup [9,\infty)$$
Now, even though the quadratic equation doesn't remain quadratic for $y=1$ as the coefficient of $x^2$ becomes zero, we get $y=1$ in the range from the same equation.
So, should I make the assumption that $y$ will not be in the range? But we will get $x=2$ when we put $y=1$ in the given rational equation which proves that y=1 is valid.
How should I go about the value $1$ for $y$?
Comment: Yes you can. I think your solution is true.
Answer: Your analysis is fully correct, what it shows is that for any $y$ there are two solutions for $x$ if the determinant is positive ($y<5$ and $y>9$), no (real) solution for a negative determinant ($5<y<9$), and 1 solution for the boundary cases $y=5$ and $y=9$.
Only at $y=1$ there is something funny going on, because suddenly there is only 1 solution again which is for $x=2$. What you should do here is make a graph of the function $y(x)$ on the interval say $x \in [-10,10]$ and look at the behavior of the curves. Then rotate the graph by 90 degrees and you see how the function $x(y)$ would look like, specially near $y=1$. You will find that there is actually more than one curve, one that behaves nicely near $y=1$ and one that diverges at $y=1$. The latter corresponds with $x = \pm \infty$ and can not be found as a solution to the quadratic equation.
You could also try to determine the function $x(y)$. If you do this correctly, you will find two solutions:
$$
x_\pm(y) = \frac{-y+17 \pm 2 \sqrt{2} \sqrt{(y-5)(y-9)}}{y-1}
$$
and see that at $y=1$ the solutions are suspicious. If you insert $y=1$ in the solutions you get $x_+(1) = \frac{32}{0}$ which diverges as you would expect. But for the other one you get $x_-(1)=\frac{0}{0}$, which is indeterminate.
If you would do a careful analysis, you would find that for values close to $y=1$, the function does no diverge at all but you get for $y \rightarrow 1$ that $x_-(y) \rightarrow 2$.


Prove that $\frac{a}{b+2c+3d}+\frac{b}{c+2d+3a}+\frac{c}{d+2a+3b}+\frac{d}{a+2b+3c} \geq \frac{2}{3}.$

Question:
Let $a,b,c,d$ be positive real numbers. Prove that $$\dfrac{a}{b+2c+3d}+\dfrac{b}{c+2d+3a}+\dfrac{c}{d+2a+3b}+\dfrac{d}{a+2b+3c} \geq \dfrac{2}{3}.$$

I was thinking of trying $a \geq b \geq c$ since the inequality is cyclic. I am not sure how to use this, though, or if this would help simplify the inequality. It also doesn't look like I can really use AM-GM or Cauchy-Schwarz.
Comment: possibly work: multiply both numerator and denominator by $a,b,c,d$ for each term, then use this inequality: $\sum\limits_{i=1}^n \frac {a_i^2}{b_i} \geq \frac{(\sum\limits_{i=1}^n a_i)^2}{\sum\limits_{i=1}^n b_i}$
Answer: We need only note that
\begin{align*}
& \ \frac{a}{b+2c+3d}+\frac{b}{c+2d+3a}+\frac{c}{d+2a+3b}+\frac{d}{a+2b+3c} \\
=& \ \frac{a^2}{ab+2ac+3ad}+\frac{b^2}{bc+2bd+3ab}+\frac{c^2}{cd+2ac+3bc}+\frac{d^2}{ad+2bd+3cd} \\
\ge& \ \frac{(a+b+c+d)^2}{4(ab+ac+ad+bc+bd+cd)}\\
=&\ \frac{a^2+b^2+c^2+d^2+2(ab+ac+ad+bc+bd+cd)}{4(ab+ac+ad+bc+bd+cd)}\\
\ge& \ \frac{\frac{2}{3}(ab+ac+ad+bc+bd+cd)+2(ab+ac+ad+bc+bd+cd)}{4(ab+ac+ad+bc+bd+cd)}\\
=&\ \frac{2}{3}.
\end{align*}
EDIT:
\begin{align*}
(a+b+c+d)^2 &= \bigg(\frac{a}{\sqrt{ab+2ac+3ad}}\sqrt{ab+2ac+3ad} \\
&\qquad+\frac{b}{\sqrt{bc+2bd+3ab}}\sqrt{bc+2bd+3ab}\\
&\qquad+\frac{c}{\sqrt{cd+2ac+3bc}}\sqrt{cd+2ac+3bc}\\
&\qquad +\frac{d}{\sqrt{ad+2bd+3cd}}\sqrt{ad+2bd+3cd}\bigg)^2\\
&\le \bigg(\frac{a^2}{ab+2ac+3ad}+\frac{b^2}{bc+2bd+3ab}+\frac{c^2}{cd+2ac+3bc}\\
&\qquad +\frac{d^2}{ad+2bd+3cd}\bigg)\Big[ 4(ab+ac+ad+bc+bd+cd)\Big].
\end{align*}
That is,
\begin{align*}
&\ \frac{a^2}{ab+2ac+3ad}+\frac{b^2}{bc+2bd+3ab}+\frac{c^2}{cd+2ac+3bc}+\frac{d^2}{ad+2bd+3cd} \\
\ge& \ \frac{(a+b+c+d)^2}{4(ab+ac+ad+bc+bd+cd)}.
\end{align*}
Moreover,
\begin{align*}
(a+b+c+d)^2 &= a^2+b^2+c^2+d^2 +2(ab+ac+ad+bc+bd+cd)\\
&=\frac{1}{3}\Big[\big(a^2+b^2\big) + \big(a^2+c^2\big) + \big(a^2+d^2\big) + \big(b^2+c^2\big)+\big(b^2+d^2)\big)\\
&\qquad+\big(c^2+d^2\big) \Big] +2(ab+ac+ad+bc+bd+cd)\\
&\ge \frac{2}{3}(ab+ac+ad+bc+bd+cd)+2(ab+ac+ad+bc+bd+cd)\\
&=\frac{8}{3}(ab+ac+ad+bc+bd+cd).
\end{align*}
Comment: How is $\frac{a^2}{ab+2ac+3ad}+\frac{b^2}{bc+2bd+3ab}+\frac{c^2}{cd+2ac+3bc}+\dfrac{d^2}{ad+2bd+3cd} \ge \frac{(a+b+c+d)^2}{4(ab+ac+ad+bc+bd+cd)}$
Comment: @user19405892, by Cauchy-Schwartz Inequality.
Comment: @SubhadeepDey I don't see how. What are the $x_i's$ and $y_i's$?
Comment: If I answer your question then, the comments zone will fall short. Should I Post the solution of your query  in the answer zone? If you say, I can do so.
Comment: @user19405892, ok, Gordon has posted that in his answer, see this.
Comment: @SubhadeepDey Why is $a^2+b^2+c^2+d^2 \geq \dfrac{2}{3}(ab+ac+ad+bc+bc+bd+cd)$?
Comment: @user19405892,

$3\sum_{cyclic} a^2 - 2\sum_{cyclic} ab=\sum_{cyclic}(a-b)^2\ge 0 $
Answer: By C-S $\sum\limits_{cyc}\frac{a}{b+2c+3d}\geq\frac{(a+b+c+d)^2}{\sum\limits_{cyc}(4ab+2ac)}\geq\frac{2}{3}$, where the last inequality it's
$\sum\limits_{sym}(a-b)^2\geq0$. Done!
Comment: I don't get $\sum\limits_{cyc}\frac{a}{b+2c+3d}\geq\frac{(a+b+c+d)^2}{\sum\limits_{cyc}(4ab+2ac)}$.
Comment: This is essentially the same solution as Gordon's.
Comment: @MichaelRozenberg Why is the last inequality $\sum\limits_{sym}(a-b)^2\geq0$?
Comment: @user19405892 because $\frac{(a+b+c+d)^2}{\sum\limits_{cyc}(4ab+2ac)}\geq\frac{3}{2}\Leftrightarrow$ $3(a+b+c+d)^2\geq8(ab+ac+ad+bc+bd+cd)\Leftrightarrow$ $3(a^2+b^2+c^2+d^2)-2(ab+ac+ad+bc+bd+cd)\geq0\Leftrightarrow\sum\limits_{sym}(a-b)^2\geq0$.


Ajustar orientação horizontal e vertical no Bootstrap

Question: Minha página na horizontal está da maneira que eu quero:

Mas se deixar o celular vertical ela está ficando assim:

Como fazer para que na vertical fique da seguinte forma?

Segue meu código:

Answer: Não precisa mecher no css, só remover a classe col-xs-4 que é referente aos "Extra Small Devices", e assim as divs ficam em linhas e não em colunas nos dispositivos de largura menor que 768px. Vai aí o código editado:

Comment: @AngeloScali Sim, você pode alterar o tamanho das colunas da grade de acordo com a largura do dispositivo. A tabela de valores das larguras e respectivos prefixos você vê aqui: http://getbootstrap.com/css/#grid-options
Comment: tive uma dúvida vendo seu código.
O uso duas classes col (sm e md), ajuda a responsividade em telas de diferentes tamanhos?
Até então, eu só usava uma classe.

Agradeço se puder esclarecer essa minha dúvida.
Abs
Answer: Coloque float:left nas duas últimas divs.
Comment: Coloquei e não adiantou Rafael..
Comment: não mudou nada?
Comment: Não, não mudou nada..
Comment: Consegui resolver usando media queries, segue oque fiz:

@media (min-width: 500px)
{
    .opcoesHome .row .col-md-4
    {
        width: 33.33333333%;
        float: left;
    }
}


When using git-svn, is there a way to make a commit that 'git svn dcommit' will ignore pushing to its remote?

Question: I want to know if there is a way to tell git-svn to ignore a commit in history, and never push it to the remote server.
Comment: If you could, then you wouldn't be able to push any successive commits either, because every git commit depends on its parent commits. What kind of information do you want in the repository which you don't want anyone else to see?
Comment: It's just a set of source files that I would like to have tracked locally that don't get pushed to the remote server. Right now I just copy/paste a backup of these files in the case I need to run "git clean" or anything like that, but "I program, therefore, I am"... lazy haha. I basically want to be able to set my working copy back to any state I need without losing this fileset in question
Comment: If you add those files to your exclude, there's some way for git clean to ignore them, I think. As long as you do not run with -x, they should be fine. You could also place them on a branch and just always rebase it onto master
Comment: Ah, I didn't realize that git commands actually honor the .gitignore. For some reason I had the notion that .gitignore just told git not to track those files.
Answer: Turns out I could do what I needed by properly configuring my .gitignore file. After more searching, I couldn't find a way to keep specific commits from pushing to the server. And in retrospect, even if you could I can't think of a use case that wouldn't turn your local repository history into spaghetti eventually.


Existence of biregular bipartite graph with constraints

Question: Context: This problem came up in the design of circuitboards.
Consider a bipartite graph $G$, colored $\color{red}{\text{red}}$ and $\color{blue}{\text{blue}}$. It's a biregular graph, which means that the valency (=degree) of each blue vertex is the same as every other blue vertex, and likewise for the reds.
In my particular example, there are $\color{red}{32}$ red vertices and $\color{blue}{24}$ blue vertices. The valency of the reds are $6$, and the valency of the blues as $8$. Note that $32 \times 6 = 24 \times 8$.

The question is:

Is there a biregular graph with the above parameters that satisfies the minimum (geodesic) distance between every pair of distinct red vertices is $2$?
If not, how many blue vertices need to be added to guarantee the existence of such a solution?

I'll worry about actually finding the solution once I determine whether or not it exists.
My progress:
The adjacency matrix $\mathbf A$, considered as a block matrix, is of the form:
$$\mathbf A = \begin{bmatrix} \color{red}{\mathbf{0}_{32^2}} & \color{purple}{
\mathbf M_{32 \times 24}} \\ \color{purple}{
\mathbf M^\intercal_{24 \times 32}} & \color{blue}{\mathbf{0}_{24^2}} \end{bmatrix}$$
The degree constraint means that $\color{purple}{\mathbf M}$ will have each row sum equal to $6$, and each column sum equal to $8$.
The matrix $\mathbf A^2$ the number of walks of length $2$ between any two vertices:
$$\mathbf A^2 =\begin{bmatrix} \color{red}{\mathbf{MM^\intercal}_{32^2}} & \color{purple}{\mathbf 0_{32\times24}} \\ \color{purple}{\mathbf 0_{24\times32}} & \color{blue}{\mathbf{M^\intercal M}_{24^2}} \end{bmatrix}$$
Because I'm interested only in the red-to-red paths, only $\mathbf {\color{red}{MM^\intercal}}$ is of interest. If a solution exists, there exists an $\mathbf{\color{red}{MM^\intercal}}$ with every off-diagonal entry $>0$.
Answer: We can do this.
In fact, we can do this with only $\color{blue}{20}$ blue vertices (red degrees being reduced to $5$). So we have $4$ extra blue vertices whose adjacencies can be determined arbitrarily at the end (as long as they all have different neighbors, and therefore increase the degree of every red vertex by exactly $1$).
In fact, we can do something harder still: find such a bipartite graph with $\color{red}{16}$ red vertices and $\color{blue}{20}$ blue vertices in which every red vertex has degree $5$, every blue vertex has degree $4$, and any two red vertices have exactly one blue vertex in common.
This is just a $(16,4,1)$ block design. (Look up block designs for solutions to such problems more generally!) Here is one possible solution. (Each red vertex is a letter between A and P; each block of $4$ letters below represents the adjacency list of a blue vertex. In this solution, every row of blue vertices covers each red vertex once. One way to get such a solution is to look at the points and lines in an affine plane over $\mathbb F_4$.)
ABCD    EFGH    IJKL    MNOP
AEIM    BFJN    CGKO    DHLP
AFKP    BELO    CHIN    DGJM
AGLN    BHKM    CEJP    DFIO
AHJO    BGIP    CFLM    DEKN

To go from this to the original problem with $\color{red}{32}$ red vertices, just replace each red vertex by two copies with the same adjacent blue vertices. This doubles the blue degree (from $4$ to $8$). The $16$-vertex solution becomes:
AaBbCcDd    EeFfGgHh    IiJjKkLl    MmNnOoPp
AaEeIiMm    BbFfJjNn    CcGgKkOo    DdHhLlPp
AaFfKkPp    BbEeLlOo    CcHhIiNn    DdGgJjMm
AaGgLlNn    BbHhKkMm    CcEeJjPp    DdFfIiOo
AaHhJjOo    BbGgIiPp    CcFfLlMm    DdEeKkNn

Here is this solution in unhelpful picture format, just for fun.

To go from this to a solution with $\color{blue}{24}$ blue vertices, we could just double the first row (that is, add $4$ more blue vertices with the same adjacencies as the blue vertices in the first row of the solution above). This has the effect of increasing every red degree by exactly $1$. Of course, there are many other ways to do this.
Comment: The original $16 \times 20$ graph is very symmetric; since it's an affine-plane construction, given any two triples $(r_1, r_2, r_3)$ and $(r_1', r_2', r_3')$ of red vertices, if neither triple is on the adjacency list of a blue vertex, then there's a graph automorphism sending one triple to the other. The $32 \times 24$ graph should still have some symmetries that preserve the blocks $\{A,B,C,D\}$, $\{a,b,c,d\}$, $\{E,F,G,H\}$, and so on.
Comment: Neat! Is there a way to extend this method to create a symmetric graph? Symmetric being, for example, that the upper-left $16 \times 12$ block submatrix of $M$ is eqaul to the lower-right $16\times 12$ block submatrix of $M$
Answer: There isn't a biregular graph with the above parameters that satisfies the minimum (geodesic) distance between every pair of distinct red vertices is 2.
Proof. Suppose such biregular graph exists. Then at least 4 blue "transit" vertices must exist for every red vertice to be connected with other by the path of length 2. So, the number of blue vertices must be at least $(32\times 4)/2=64$.
Consequently, the answer to the second question is probably 40. If we fix the valency of the blues as 8, then valency of the reds must be 16.
Comment: I believe you're over-counting.


Has music notation become more prescriptive?

Question: Another question asks about the Meaning of 1/1 and 1/2 beneath pedaling marking near some sustain pedal markings.  It looks like they are used to specify a particular amount of pedal to use while playing the piece.  Is there a trend in music notation to be increasingly prescriptive in an attempt to cause the performer to create the exact sound imagined by the composer?

pre·scrip·tive
1.
  of or relating to the imposition or enforcement of a rule or method.
  "these guidelines are not intended to be prescriptive"
  synonyms: dictatorial, narrow, rigid, authoritarian, arbitrary, repressive, dogmatic

Source: definition of prescriptive in Oxford dictionary (American English) (US)
Comment: There are many side-trends, counter-trends and tributaries in music.  Just as some composers strive to be more prescriptive, others strive to be more interpretive.  For example, graphic scores often leave almost everything to the performer's whim.  http://en.wikipedia.org/wiki/Graphic_notation https://www.google.com/search?q=graphic+notation#=100&espv=2&source=lnms&tbm=isch&sa=X&ei=oLWSU5qwKY3uoASk-4D4BA&ved=0CAgQ_AUoAQ&biw=1294&bih=674
Answer: What a great question! From an early historical standpoint, I can think of several cases where this has happened. I'd be interested in more answers, and especially later historical examples.
In the Middle Ages and Renaissance, accidentals were often not notated, with the composer relying on the performer's knowledge of musica ficta to provide the correct pitches. Ornaments were also not typically notated, and were left to the performer's taste; there are treatises from the time (e.g. Silvestro Ganassi's Opera intitulata Fontegara) on how to tastefully improvise ornaments and other elaborations (called divisions).
Starting in the Baroque era, there was an increasing trend to write out at least partly ornamented lines (though much was still left to taste). However, articulations and dynamics, while occasionally indicated when important, were often left unmarked. On the other hand, there was also the creation of basso continuo, which took a relatively non-prescriptive, improvisatory approach to accompaniment.
Beethoven was one of the first composers to specify precise tempos in terms of metronome beats (e.g. =120), rather than a general feeling (e.g. Allegro, Andante...).
Edit: I think Jazz probably provides a good modern counter-example, where there is an incredibly non-prescriptive notation. You might be given a lead sheet with chord symbols, and expected to decorate the melody line, substitute chords, and improvise various fills and counter-melodies on the fly.
Comment: I am not sure why this answer has gotten so many up-votes.  It does not answer the question *at all*.  It mostly relates historical practice of *not* writing things down - the exact opposite of what the OP initially asked. There is little information here - no mention of Boulez, Berio, Ravel, Ferneyhough, expansion of the orchestra / harmonic language, futurism, Varese, Xenakis, Schwantner, Rouse, or any other contemporary composers.  I am just wondering here...are people actually reading before they up-vote?
Comment: Just wondering if the OP has seen any Boulez...
Comment: (+1) There are some outliers though.  Not so extreme as jazz or renaissance music, but for example _Canto Ostinato_ by S. ten Holt is quite anti-prescriptive. (Anti used on purpose. Ten Holt opposed prescriptivity in music (to some degree) according to the preface in my copy.)
Comment: +1 Caleb: just want to mention that precise notation is taught in most universities for composition as to lock down the intent, no surprises for either the performer or the composer. At the same time, composition professors are very aware of stochastic or aleatory practices and are very willing to assist in notating the best way to 'cut it loose'.
Comment: I wrote it, and I'm as baffled by the upvotes as you! I admitted as much in my first paragraph, that I wanted more relevant and later examples.
Comment: In Jazz, if you don't fit into the ensemble, the drummer will throw a stick at you. Not all prescription is in the paper sheets. :)
Comment: True, but OP specifically asked about *notation*. Edited my wording to match that intent.
Answer: Music notation is presciptive. Generally speaking, if you see a note on the middle staff line of a treble clef, and there is no key signature, you're expected to play a B, and not something else, like a B# or A. So the pitches and time values are quite clearly prescribed. The remaining squabble, then, is whether other things are to be prescribed, like dynamics, tempo, strictness of tempo, and such. But these aspects of notation are no more or less prescriptive than pinning down whether a note is B or C; they just concern themselves with different aspects: those of style.
If the bulk of the content of some music consists of its style (so that it is barely recognizable if not played in a certain way), then its notation needs to capture those elements.
For instance, the notation for playing some particular "indie rock" song might include the exact guitar stomp-boxes to use and in what order, and their precise settings, with less of an emphasis on whether the right notes are played.
Comment: My perception of the "squabble" was which elements are reserved to the performer as elements of interpretation, vs elements of the composition.  In particular, depth of pedaling on a piano seemed to me to be beyond the purview of the composer.
Answer: In the context of sequenced (electronic) music the answer is clearly yes -- if you consider the computer files that define the music to be the score, then they are fully prescriptive in a way that exceeds what is possible with standard notation.  For many electronic artists the line between composition and performance is pretty much erased.
Comment: (+1) This is a great point! (At least until you get into the realm of realtime algorithmic composition...)
Answer: While Beethoven has been mentioned as a milestone for "prescriptive scores", but Bach is actually already quite prescriptive as well.  As an example, take the prelude from Partitia III for unaccompanied violin.  The manuscript on the third to seventh line uses beaming in a very concise manner to specify the string changes to be employed for the passage (starting with a two-string pattern, and later using a three string pattern) consequently determining the positions and fingerings as well as the basic bowing technique.
It is interesting that this score can be played on lute or guitar in a quite analogous manner, again putting the voicing information in the beaming to good use even though the fingering turns out quite different due to the different string tuning.  It works comparatively badly on single-manual keyboards and so-so on dual manuals.
At any rate, the manuscript is giving quite more information than the pitches and durations to play.
Bach is known to spell out a lot of ornaments instead of leaving them to the discretion of the player.


javascript not running onBlur

Question: The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here.  Just trying to test a simply validation.

   DOB

   <input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">

Comment: Try this.. your function is missing start time , so you need to specify that and then try to validate on that. This piece of code is for validating the date string for valid format.

javascript not running onBlur


Monitoring field changes in custom content type

Question: I have custom content type with "price" field.
I would like to log the information about when the price has been changed (by administrator). All I need is date and old/new value of that field (for each entity of my custom content type).
But how to monitor such changes? Can I use any hook for it?
Comment: @Pierre.Vriens Sorry, I eventually used another ready-made module for auditing fields and forgot to give you feedback. But I checked your answer and it works too, so I accepted it :)
Answer: Step 1 - Detecting changes
You can make this work using the Rules module:

Rules Event: Before saving content.
Rules Condition (1st): "Entity has field", whereas you should specify these values:

"node" (saved content) for the "data selector" of entity.
the machine name of your price field.

Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different. For this you add an additional Rules Condition which is a Data comparison. And the actual data to be compared are:

original value of the field, which you should be able to find/select by first using as data selector the node-unchanged:...(unchanged content), followed by selecting the field name of your field from the additional list that is shown after you selected that node-unchanged:...(unchanged content).
updated value of the field, which you should be able to find/select by first using as data selector the node:...(saved content), followed by selecting the field name of your field from the additional list that is shown after you selected that node:...(saved content).

Step 2 - Logging changes
By using the Message module, you can create your custom logging of changes detected by the Rules module. For way more details on this, refer to the answer to "What is a good flexible way to send auto system emails to users?".


Why does the consensus number matter in multithreading?

Question: So the consensus number for a fetch-and-add operation is 2
I'm having a hard time grasping what that means and how it affects multithread programming? I would love some practical examples on how that would affect compared to a compareandswap for example ... Thank you very much.
Answer: Fetch-and-add gives you the ability to read and modify and location in memory atomically. Consensus means that protocol (fetch-and-add in this case) can give consensus for n different threads.
What does that mean?
Our goal is to use a protocol, where e.g. one thread determines a value and that value gets adopted by all other threads. You can google some of those protocols. In multithreading, it is important that we can modify memory atomically and that threads sometimes decide on one value.
It is important to note that consensus protocols are wait-free, that means that all threads make progress even when one dies (for some reason). Therefore it is important, when using multithreading, to be aware of an objects consensus number. A consensus number of e.g. an atomic register (1) tells us that we will never be able to implement an object using only atomic registers that can give consensus for 2 threads. That's why we use constructs such as fetch-and-add in multithreading.
Example
Scheduling in an OS is usually done with FIFO queues. FIFO queues have consensus two so it is safe to use them for multithreading.


Dica de livro para quem parou no tempo

Question: Olá,
Programei até meados de 2012, parei nessa época e pretendo voltar meus estudos, mas muita coisa mudou. Minha principal área foi a web, utilizava php 5.3 , html 4 , css 2 e javascript com jQuery.
Chegou bastante tecnologia nova, minha principal loja para comprar livros era a linuxmall que infelizmente fechou.
Pretendo continuar na área web, mas dessa vez quero aproximar um pouco das ferramentas microsoft.
Já iniciei meus estudos em cakephp e em c#.
Abordagem atual:
Lendo a biblioteca oficial do cakephp e procurando melhorar quando possível em javascript. Acredito que o php que conheço seja o suficiente por enquanto.
Comecei a seguir esse tutorial mas parece que a organização em camadas que ele utiliza já esta desatualizada (BLL, DAL, GUI), conheço o MVC...
Bom se puderem recomendar alguma literatura que irá acelerar meus estudos em web e c# desktop ou melhor ainda voltado para web eu agradeceria, pois devido a quantidade de informação estou tendo muita procrastinação ao buscar as informações. Diria que estou meio impactado com tantas novidades desde quando parei na área.
Obrigado!
Comment: Olá Leatar, bem vindo ao [pt.so]. Você pode encontrar algumas dessas informações nas próprias descrições das tags, clique sobre elas para dar uma olhada.
Comment: A pergunta vai acabar sendo fechada por ser baseada em opiniões, mas vou deixar minha contribuição pra você antes: https://www.youtube.com/watch?v=VbA_JZJtKaY
Answer: Como o Maicon disse, a pergunta vai acabar por ser fechada por ser baseada em opiniões, porém também vou deixar algumas coisas que podem vir a ser úteis para ti.

Se o Inglês não for problema para ti recomendo-te os seguintes canais do YouTube:

DevTips - Web Development focado em Front-end.
PHPAcademy - Web Development focado em Back-end.
Derek Banas - App Development porém se não me engano ensina um pouco de C#
Brackeys - Game Development também ensina C#.

Se quiseres ler livros recomendo visitares este site onde encontras bastantes livros de programação atualizados.

Caso o Inglês seja um problema eu não te posso ajudar muito, o que te posso indicar é procurares alguns livros ou canais no YouTube pois realmente eu conheço muito poucos e maior parte deles já não existem ou estão desatualizados.
Comment: Obrigado pelas informações, não entendo muito as regras do stackoverflow... Se tiver outras dicas mesmo em inglês eu agradeço.
Comment: @Leatar Esqueci-me de referir que a existência de uma [wiki](http://pt.stackoverflow.com/tags/php/info) para a tag php, dá uma olhada e vê se encontras algo que te ajude também.

Dica de livro para quem parou no tempo


Is the theory of real closed fields expanded by restricted analytic functions decidable?

Question: Is the theory of real closed fields expanded by restricted analytic functions decidable?  I have been doing a lot of reading on the subject, but I can't quite find a straight answer on this one.  The theory seems to enjoy many good properties, o-minimality, completeness, quantifier elimination.  But I can't seem to find anything about it being decidable or undecidable.  I think it needs to be recursively axiomatized in order for it to be decidable, but I am not quite sure.  Does that mean that real closed fields augmented with a specified list of restricted analytic functions is decidable?
Comment: Isn't the language uncountable here? If so than you can't encode formulas by numbers, so there is no notion of decidability.
Comment: Concerning the recursive axiomatisability: there is no intrinsic reason why you can't take a non-recursive axiomatisation of a theory and somehow use it to prove that the theory is decidable. However, if you did that, you would have that the theory is recursively axiomatisable as an immediate corollary.
Answer: As Levon Haykazyan pointed out in a comment, since there are uncountably many analytic functions, the language is uncountable. In order to discuss whether a theory is decidable, the appropriate definitions require that the language in question be presented computably: that is, the function and relation symbols are given by natural numbers, and the arity function (telling how many arguments a symbol takes) must be a computable function. Since this presentation requires us to associate symbols with natural numbers, it doesn't make sense for uncountable languages.


Managing services started on boot (rc0.d, rc1.d, etc)

Question: What is the best way of managing which services start when?
service --status-all lists all services, but does a poor job of the service status (most are "unknown") and does not provide any method of disabling/enabling services.
I read that modifying/deleting the symlinks in the rc*.d folders is not advised, because they can be recreated when their package is upgraded.
Answer: service --status-all is for Upstart. If you are using traditional SysV init script, take a look at sysv-rc-conf or install rcconf.
Comment: Does rcconf work for both upstart and sysv? or do I need two tools to manage all the services, because on Ubuntu 10.04 services seem to be a mix of the two.
Comment: I haven't got a Ubuntu in front of me to test, but `rcconf` seems is only for SysV.


Induction Validity

Question: Is it valid in an induction to prove a base case for$ n=3$then prove for $n=4$ and use the fact that the transition from $n=3$ to $ 4$ was possible to then prove it is possible for $n=k$ and $ n=k+1?$
For example, If I have the problem to prove that every permutation in $S_n$ is the product of a transposition of the form $(J,J+1)$ where $1\leq J \lt n.$ Can I do this....
Base case, $n=2$ works (show work) $n=3$ works (show work) inductively assume n=k works and say because the transition from $n=3$ to $ n=4$ worked then $n=k$ to $n=k+1$ will work?
Comment: Short answer is no but you may be able to modify the $3\implies 4$ case to the $k\implies k+1$ case.
Comment: No, absolutely not, this wouldn't be a correct proof.
Comment: Thanks everyone. I didn't think so. Felt off.
Answer: Not valid. This would fail for example if we have 1,1,2,3,5,8,... and the statement was the nth number is odd. Then n=3 is odd, n=4 is odd, but the rest of the numbers are not odd.

Induction Validity


How to set a query timeout for apache ignite cache?

Question: I am working on TIBCO BusinessWorks 5.3. So we normally provide query timeout in the SQL Direct/JDBC Query activity. But for Ignite cache that timeout does no seem to work.
This is installed on a Linux server. I tried to add the setTimeout property in the config xml under cacheConfiguration property node.
I have tried with 2 different configurations
1.
<bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
<property name="cacheConfiguration">
 <list>
   <bean class="org.apache.ignite.configuration.CacheConfiguration">

     <property name="setTimeout" value="60" />
   </bean>
</list>
</property>

2.
<bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
<property name="cacheConfiguration">
 <list>
   <bean class="org.apache.ignite.configuration.CacheConfiguration">

   </bean>
  <bean class="org.apache.ignite.cache.query.SqlFieldsQuery">
    <property name="setTimeout" value="60" />
  </bean>
</list>
</property>

Error message is thrown as below-
    org.springframework.beans.NotWritablePropertyException: Invalid
    property setTimeout of bean class
    [org.apache.ignite.configuration.CacheConfiguration]: Bean property
    setTimeout is not writable or has an invalid setter method.

Answer: Currently you may use SqlQuery/SqlFieldsQuery API to set individual timeouts for queries: https://apacheignite-sql.readme.io/docs/query-cancellation
It's a known issue that there is no option to configure default timeout for a query, here is link for your reference (there is a PR that was active month ago): https://issues.apache.org/jira/browse/IGNITE-7285
JDBC query timeout is implemented, but not yet documented/released: https://issues.apache.org/jira/browse/IGNITE-5438


Powershell error - Unexpected token error

Question: I am getting an error while executing the below. Is the below method to concatenate $env:userprofile with path correct?
<code>$env:userprofile\Documents\DNS\GetDnsRecord.ps1 | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Append $env:userprofile\Documents\DNS\DnsRecord.csv

</code>
Error:
<code> + $env:userprofile\Documents\DNS\GetDnsRecord.ps1 | ConvertTo-Csv -NoTy ...
 +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token '\Documents\DNS\GetDnsRecord.ps1' in expression or statement.

</code>
Thanks for the help
John
Comment: Concatenating paths like that only works in argument-mode - prepend the entire thing with the call operator `&` and it'll work: `& $env:userprofile\Documents\DNS\GetDnsRecord.ps1 | ...`
Answer: You might want to read a bit about Join-Path: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/join-path?view=powershell-7
<code>Join-Path $env:userprofile '\Documents\DNS\GetDnsRecord.ps1'
</code>


Zeros in a sequence

Question: Define the sequence $x_n$ by $x_1=0$ and
$$
x_n=x_{\lfloor n / 2\rfloor}+(-1)^{n(n+1) / 2}
$$
for $n \geq 2$. Find the number of $n \leq 2023$ such that $x_n=0$.
My approach was the following:
To find the number of values of $n \leq 2023$ for which $x_n = 0$, we can observe some patterns in the sequence and use it to our advantage.
Let's start by calculating the first few terms of the sequence:
$x_1 = 0$
$x_2 = x_1 + (-1)^{2(2+1)/2} = 0 + (-1)^3 = -1$
$x_3 = x_1 + (-1)^{3(3+1)/2} = 0 + (-1)^6 = 1$
$x_4 = x_2 + (-1)^{4(4+1)/2} = -1 + (-1)^{10} = -1 - 1 = -2$
$x_5 = x_2 + (-1)^{5(5+1)/2} = -1 + (-1)^{15} = -1 + 1 = 0$
$x_6 = x_3 + (-1)^{6(6+1)/2} = 1 + (-1)^{21} = 1 - 1 = 0$
$x_7 = x_3 + (-1)^{7(7+1)/2} = 1 + (-1)^{28} = 1 + 1 = 2$
$x_8 = x_4 + (-1)^{8(8+1)/2} = -2 + (-1)^{36} = -2 + 1 = -1$
From the above calculations, we can observe some patterns:

$x_1 = 0$
$x_2 = -1$
$x_3 = 1$
$x_4 = -2$
$x_5 = x_6 = 0$
$x_7 = 2$
$x_8 = -1$

We can see that the sequence repeats itself in a pattern of length 6: $0, -1, 1, -2, 0, 0$. After these initial terms, the sequence becomes periodic.
Now, to find the number of values of $n \leq 2023$ for which $x_n = 0$, we can break it down as follows:

The values of $x_1, x_2, x_3, x_4, x_5, x_6$ are fixed, and they are not equal to 0.
For $n \geq 7$, the sequence becomes periodic with a period of 6. Therefore, for any $n$ such that $n \geq 7$, $x_n = x_{n \mod 6 + 7}$.

Now, let's calculate the values of $x_n$ for $n = 7, 8, 9, 10, 11, 12$:
$x_7 = x_1 + (-1)^{7(7+1)/2} = 0 + (-1)^{28} = 0 + 1 = 1$
$x_8 = x_2 + (-1)^{8(8+1)/2} = -1 + (-1)^{36} = -1 + 1 = 0$
$x_9 = x_3 + (-1)^{9(9+1)/2} = 1 + (-1)^{45} = 1 - 1 = 0$
$x_{10} = x_4 + (-1)^{10(10+1)/2} = -2 + (-1)^{55} = -2 - 1 = -3$
$x_{11} = x_5 + (-1)^{11(11+1)/2} = 0 + (-1)^{66} = 0 + 1 = 1$
$x_{12} = x_6 + (-1)^{12(12+1)/2} = 0 + (-1)^{78} = 0 + 1 = 1$
Now we see that $x_8, x_9, x_{11}, x_{12}$ are equal to 0.
So, every 6th value of $n$ starting from $n = 7$ will have $x_n = 0$, i.e., $n = 7, 13, 19, 25, \ldots$.
To find the number of such values of $n$ less than or equal to 2023, we can calculate the largest value of $n$ in this sequence that is less than or equal to 2023:
$$
7 + 6k \leq 2023
$$
Solving for $k$:
$$
6k \leq 2016
$$
$$
k \leq 336
$$
So, there are 336 values of $k$ that satisfy this inequality. Therefore, there are 336 values of $n$ such that $x_n = 0$ and $n \leq 2023$.
Comment: What is the source of this problem?  Puzzles involving the current year often appear in competitions.
Comment: I see: $x_5=x_2+(-1)^{15}=-1-1=-2$.  And then $x_{10}=x_5+(-1)^{55}=-3$.  For example.
Comment: It is not periodic.  Indeed for $2^{2m-1} \le n \lt 2^{2m}$ you find $a_n$ is always odd and for  $2^{2m} \le n \lt 2^{2m+1}$ you find $a_n$ is always even.   For example, this means there can be no zeros from $a_{512}$ through to $a_{1023}$ since they are all odd.
Comment: @Henry Thanks for your comment. Do you have any ideas on how to solve this problem? I would appreciate a more detailed approach to know how this problem could be solved.
Comment: You could simply brute-force it.  Telling us the source of the problem might suggest the desired method.
Comment: @Henry I think the source doesn't play a big role here since this was proposed by one of my professors during the lecture. He mentioned there exists an elegant solution so simply brute-forcing would not be a suitable approach.
Answer: Let us pick some random number $n$ and see how to compute $x_n$ in this specific case. The computer gave me:
sage: import random; n = random.choice([1000..2023])
sage: n
1399

OK, we take $n=1399$ and write it in base two.
sage: n.digits(base=2)
[1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1]

This representation is "reversed", well $n$ is seven mod eight. So:
$$
n = 10101110111_{\text{base two}}\ .
$$
Now we inspect $n$ and the corresponding term. I will write $x(n)$ instead of $x_n$, since the music should not be minimalized in a sub index.
We have $x(n)$ defined in terms of $x(m)$ with $m={[n/2]}$, and $m$ is obtained from $n$ by deleting the last binary digit. What about the contribution of $(-1)$ to the power $n(n+1)/2$? Well, we separate into cases.
For $n$ with last digits:

$00_{\text{base two}}$ we have $n=0$ mod four, so $n(n+1)/2$ is even,
$(-1)^{n(n+1)/2}=+1$,
$01_{\text{base two}}$ we have $n=1$ mod four, so $n(n+1)/2$ is odd,
$(-1)^{n(n+1)/2}=-1$,
$10_{\text{base two}}$ we have $n=2$ mod four, so $n(n+1)/2$ is odd,
$(-1)^{n(n+1)/2}=-1$,
$11_{\text{base two}}$ we have $n=3$ mod four, so $n(n+1)/2$ is even,
$(-1)^{n(n+1)/2}=+1$.

It may be useful to define $s$ to be the above function of "two binary digits", so $s(00)=s(11)=+1$, $s(01)=s(10)=-1$. So $s$ is $+1$ for two equal digits, its contribution in the recursive computation of $x_n$ is $+1$ for two equal consecutive digits, and $-1$ for ... non equal consecutive digits.
So:
$$
\begin{aligned}
&x(1399)\\
&=x\left(10101110111_{\text{base two}}\right)\\
&=x\left(1010111011_{\text{base two}}\right) + s(11)\\
&=x\left(101011101_{\text{base two}}\right) + s(11) + s(11)\\
&=x\left(10101110_{\text{base two}}\right) + s(01) + s(11) + s(11)\\
&=x\left(1010111_{\text{base two}}\right) + s(10) + s(01) + s(11) + s(11)\\
&=x\left(101011_{\text{base two}}\right) + s(11) + s(10) + s(01) + s(11) + s(11)\\
&=x\left(10101_{\text{base two}}\right) + s(11) + s(11) + s(10) + s(01) + s(11) + s(11)\\
&=x\left(1010_{\text{base two}}\right) + s(01) + s(11) + s(11) + s(10) + s(01) + s(11) + s(11)\\
&=x\left(101_{\text{base two}}\right) + s(10) + s(01) + s(11) + s(11) + s(10) + s(01) + s(11) + s(11)\\
&=x\left(10_{\text{base two}}\right) + s(01) + s(10) + s(01) + s(11) + s(11) + s(10) + s(01) + s(11) + s(11)\\
&=
\underbrace{x\left(1_{\text{base two}}\right)}_{=0} + s(10) + s(01) + s(10) + s(01) + s(11) + s(11) + s(10) + s(01) + s(11) + s(11)\ ,
\end{aligned}
$$
So in essence, we write $n$
in base two, consider the result as a "word" in alphabet $0,1$,
and count the number of

consecutive two letters which are equal,
consecutive two letters which are not equal,
in this representation, take the difference of the counts, and check if it is zero.

Before we start solving the problem, let us check the receipt found for the first some numbers:
$$
\begin{aligned}
x(1) &= 0\ ,\\[2mm]
x(2) &= x(10) = s(10) = 0-1=-1\ ,\\
x(3) &= x(11) = s(11) = 1-0=1\ ,\\[2mm]
x(4) &= x(100) = s(10)+s(00) = 1-1=0\ ,\\
x(5) &= x(101) = s(10)+s(01) = 0-2=-2\ ,\\
x(6) &= x(110) = s(11) + s(10) =1-1=0\ ,\\
x(7) &= x(111) = s(11) + s(11) =2-0=2\ ,\\[2mm]
x(8) &= x(1000) = s(10) + s(00) + s(00)  =2-1=1\ ,\\
x(9) &= x(1001) = s(10) + s(00) + s(01)  =1-2=-1\ ,\\
x(10) &= x(1010) = s(10) + s(01) + s(10)  =0-3=-3\ ,\\
x(11) &= x(1011) = s(10) + s(01) + s(11)  =1-2=-1\ ,\\
x(12) &= x(1100) = s(11) + s(10) + s(00)  =2-1=1\ ,\\
x(13) &= x(1101) = s(11) + s(10) + s(01)  =1-2=-1\ ,\\
x(14) &= x(1110) = s(11) + s(11) + s(10)  =2-1=1\ ,\\
x(15) &= x(1111) = s(11) + s(11) + s(11)  =3-0=3\ ,\\[2mm]
x(16) &= x(10000) = s(10) + s(00) + s(00) + s(00)  =3-1=2\ ,\\
x(17) &= x(10001) = s(10) + s(00) + s(00) + s(01)  =2-2=0\ ,\\
x(18) &= x(10010) = s(10) + s(00) + s(01) + s(10)  =1-3=-2\ ,\\
x(19) &= x(10011) = s(10) + s(00) + s(01) + s(11)  =2-2=0\ ,\\
x(20) &= x(10100) = s(10) + s(01) + s(10) + s(00)  =1-3=-2\ ,\\
x(21) &= x(10101) = s(10) + s(01) + s(10) + s(01)  =0-4=-4\ ,
\end{aligned}
$$
and so on. We can draw some conclusions.
If the number of the $s$-terms is odd, we cannot get the difference result zero.
So there are no $n$ values with $x(n)=0$ for $n$ in the ranges:

$n$ between $2=2^1$ and $3=2^2-1$,
$n$ between $8=2^3$ and $15=2^4-1$,
$n$ between $32=2^5$ and $63=2^6-1$,
$n$ between $128=2^7$ and $255=2^8-1$,
$n$ between $512=2^9$ and $1023=2^{10}-1$,
$n$ between $2048=2^{11}$ and $4095=2^{12}-1$,
and so on.

Now we are ready to start. I will call simply a pair a "subword" of length two in the (word of the) binary representation of a number.
We count the $n$'s with equal pairs of the shape $AA$, and of the shape $AB$, $A\ne B$. Such an $n$ has an even number of pairs. Thus an odd number of digits, call it $d$. The first digit is one. We follow the word from the next place, the "second place" to the "last place" in its writing. We mark with a star the positions in the word where the second letter in the pair coincides with the first one. The other are not marked, so there is a blank - and if we want to still mark somehow the place, there will be a small dot. The first position remains unmarked. In case of $x(n)=0$ we have an equal number of blanks and stars. We count these words. Looking at only the positions of the stars we obtain a subset of the index set $(d-1),\dots,3,2,1,0$. Conversely, if such a subset is given, we can complete $n$ in a unique manner, so that the stars associated to $n$ are in the given position.
Example:
Consider the numbers $n$ between $256=2^8$ and $511=2^9-1$. Each of them needs $d=$nine digits. The first digit is $a_8=$one. So $n$ is written like:
$$
\overline{1a_7a_6a_5a_4a_3a_2a_1a_0}_{\text{base two}}=2^8+a_7\cdot 2^7+\dots+a_1\cdot 2+a_0\ .$$
Fix some subset with four elements in the index set $\{7,6,5,4,3,2,1,0\}$.
For instance $7,4,3,1$. Then $7$ is a star place, so $a_7=a_8=1$. And $6$ is not a star place, so $a_6\ne a_7=1$, so $a_6=0$. And $a_5\ne a_6$, so $a_5=1$. And $4$ is on a star place, so $a_4=a_5=1$. Then $3$ is also on a star place, so $a_3=a_4=1$. And $a_2\ne a_3$, so $a_2=0$. And $1$ is on a star place, so $a_1=a_2=0$. Finally $a_0\ne a_1$, so $a_0=1$.
In a picture:
110111001
 *  ** *

How many such "good" numbers are thus in the range from $256$ to $511$? Exactly $\binom84=\frac{8\cdot7\cdot6\cdot5}{4\cdot3\cdot2\cdot1}=7\cdot 2\cdot 5=70$.

Which are explicitly the "good" numbers with $d=5$ digits? We search for star patterns on the relevant last four places. Blanks are dots. Here they are:
..** 10111 = 23
.*.* 10011 = 19
*..* 11011 = 27
.**. 10001 = 17
*.*. 11001 = 25
**.. 11101 = 29

How many such good numbers are between one and $2048$? Exactly:
$$
\underbrace{\binom00}_{1} +
\underbrace{\binom21}_{4,6} +
\underbrace{\binom42}_{17,19,23,25,27,29} +
\underbrace{\binom63}_{68,\dots,122} +
\underbrace{\binom84}_{261,\dots,501} +
\underbrace{\binom{10}5}_{1034,\dots,2026}
\ .
$$

For some reasons, the problems wants us to stop at $2023$, so we miss  exactly one "good" number, the greatest one. This greatest one is obtained by insisting to start with "ones" (as digits)
1|11111|?????|
  *****

so the five stars are consumed, we need only blanks/dots after, and the number is
1|11111|01010| = 1 11111 11111 - 10101 = 2047 - (16+4+1) = 2026 .
  ***** .....

(The numbers $2024$ and $2025$ also have the pattern $1\ 11111\ ?????$
but introduce in the last five digits further equal pairs. So we miss only the $2026$ when we stop at $2023$.)

So the answer to the problem is:
$$
\bbox[yellow]{\qquad
\binom 00 +
\binom 21 +
\binom 42 +
\binom 63 +
\binom 84 +
\binom {10}5  - 1
\\
=
1+2+6+20+70+252-1
=
350\ .\qquad}
$$

Zeros in a sequence


Applying a function a non-integer amount of times

Question: Taking the principal log of a real or complex number an infinite number of times converges one of two particular values in the complex plane.  These values are $-W(-1)^*$ given a seed value with $\Im(z) \ge 0$, and $-W(-1)$ otherwise (with $W$ being the principal branch of the Lambert W function.)
While converging these values appear to "spiral" around this number in a way reminiscent of certain systems of differential equations.

However, function application is a discrete operation, so relating the two might be a bit of a fool's errand.  I'm aware that it is possible to extend the differentiation operator in this manner.  But that may be specific to differentiation, and it might not be possible with general function application.
So, is there a method for a general function?  What about the specific function log?  Is there a class of functions for which this works?
Comment: A sign error in your two fixed points. The one in the plot is $\approx 0.31+1.33i$ but $W(-1)\approx -0.31+1.33i$.
Comment: Ah, that's true.  Fixed.
Answer: The simplest case of fractional iteration is when $\,f(x) := c\cdot x\,$ with fixed point $0$, convergence is linear and the converging factor $\,0<c<1.\,$ Then the fractional iteration $\,f^{(t)}(x) = c^t\cdot x.\,$ Complications arise if $c$ does not satisfy the bounds. That is, the exponentiation $\,c^t\,$ is multivalend. The general case reduces to the simplest case using conjugation of composition with the convergence factor still the first derivative at the fixed point. Similarly for quadratic or higher orders of convergence.
In the example of $\,f(x):=\log(x),\,$
$\,f(w + x) \approx w + c\,x\,$ where $\,w\approx 0.318+1.337i\,$ and the convergence factor $\, c := f'(w)\,$ is
 $\approx 0.168-0.707i.\,$ Now we want an expansion for $g(x)$ so that
 $$\log(w+g(x)) = w+g(c\cdot x)$$ where the conjugating function
 $g(x)$ has a power series expansion
$$g(x) \approx  x + (-0.151 -0.296i)x^2 +(-0.036+0.098i)x^3 + (-.025-0.017i)x^4 + O(x^5).$$
Comment: How do you arrive at the convergence factor?
Answer: It's called fractional iteration. There are papers on it and some research, among other things in the domain of fractals, but it's not a widely known subject. There are quite some restrictions on what properties the functions needs to have. The simplest case is to consider behaviour of a function between two stationary points (intersect the $f(x)$ and $x$ curves). On every such a bump, between two stationary points (assuming the function there is also monotonic), fractional iteration is well defined, as you have nicely behaved flow from one stationary point to the other. Of course, this operation has to satisfy rules, such as $f^{1/2}(f^{1/2}(x))=f(x)$ and so on. I don't know enough about the topic to state it with certainty, but I think there is no generally accepted rule for computing it for an arbitrary function, especially not in closed form (I once tried to compute it numerically for a few noninteger "powers", with mixed results). I do know that the question may be rewritten in terms of Schröder's equation, which looks more like a normal equation than asking "what happens if we apply a function noninteger number of times".
This is also somewhat related to the concept of fractional differentiation.


How to compare two PySpark columns with Pytest, without using dataframes?

Question: A have a situation where I need to compare the columns before I create the dataframe for a test suit, something like that:
import pytest
import pyspark.sql.functions as F

def first_test():
    c1 = F.col("First Column").alias("1st Column")
    c2 = F.col("Second Column").alias("2nd Column")
    c3 = F.col("Second Column").alias("2nd Column")

    print(c1)
    print(c2)
    print(c3)

    assert c1 != c2
    assert c2 == c3

Once I run pytest with -s and -vv options I see the following:
Column<'`First Column` AS `1st Column'>
Column<'`Second Column` AS `2nd Column`'>
Column<'`Second Column` AS `2nd Column`'>

self = Column<'(`First Column` AS `1st Column` = `Second Column` AS `2nd Column`)'>

    def __nonzero__(self) -> None:
        raise ValueError(
>           "Cannot convert column into bool: please use '&' for 'and', '|' for 'or', "
            "'~' for 'not' when building DataFrame boolean expressions."
        )
E       ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.

The same error if I comment the first assertion (c1==c2) and keep only the second (c2==c3).
How can I assert that 2 columns are the same in this simple case scenario?
Answer: Since Python is an incomplete language it's not possible to do it properly, the best solution I found was to use str() to convert the column as string and compare both strings, I also used to compare the data type.


How do I access field variables directly in Drupal 7 without having to drill down into a node array?

Question: I have a view reference field and have some php code in the view where it grabs the taxonomy ID of the page its currently on. Currently I am grabbing the TID via
menu_get_object()->field_device_type_vocabulary[und][0][tid];

I know you can access the fields directly without having to do that, but forgot how that was done.
Comment: BTW, you have a subtle error in that line of code.  The `[und]` should be quoted, eg `['und']`.  PHP will consider it a string automagically, but will throw a warning.
Comment: Clive's answer also fixes the following errors in reference to the same question but expanded:

http://drupal.stackexchange.com/questions/75624/what-other-way-can-you-reference-a-variable-without-getting-the-following-error?noredirect=1#comment83708_75624
Answer: There are two main methods:

Procedural, using field_get_items(), e.g.
$node = menu_get_object();
if ($items = field_get_items('node', $node, 'field_device_type_vocabulary')) {
  $tid = $items[0]['tid'];
}

Objected oriented, using an EntityMetadataWrapper, e.g.
$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();

Comment: seems like menu_get_object() has to be called regardless. i thought there was a variable something to field_field_name[value] or something of that sort.


How to convert Class Component into Functional Component

Question: i am working only on class component but now i am trying function component. but i am not know much about the function component.
but after converting my class into function my code is not working well
Error:(in my functional component code) if i am click next button then it not show me 2nd question but after clicking again then it show me 2nd question.
then after im clicking the back button then it show me next question instead of previous question
But my Class component code is work properly.but after converted in functional component is not work correct. Means my converted functional component code is not correct.
Please help me in the converting class component into functional component.Or tell me what is incorrect in my converted functional component code.
...
...
Orignal Class Component
import React, { Fragment, Component } from "react";

import classnames from "classnames";
import isEmpty from "../is-empty";
import questionsArray from "../questions.json";

export default class PlayQuiz extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: questionsArray,
      currentQuestion: {},
      nextQuestion: {},
      previousQuestion: {},
      answer: "",
      numberOfQuestions: 0,
      numberOfAnsweredQuestions: 0,
      currentQuestionIndex: 0,
      score: 0,
      correctAnswers: 0,
      wrongAnswers: 0,
      nextButtonDisabled: false,
      previousButtonDisabled: true,
    };
  }

  componentDidMount() {
    const {
      questions,
      currentQuestion,
      nextQuestion,
      previousQuestion,
    } = this.state;
    this.displayQuestions(
      questions,
      currentQuestion,
      nextQuestion,
      previousQuestion
    );
  }

  displayQuestions = (
    questions = this.state.questions,
    currentQuestion,
    nextQuestion,
    previousQuestion
  ) => {
    let { currentQuestionIndex } = this.state;
    if (!isEmpty(this.state.questions)) {
      questions = this.state.questions;
      currentQuestion = questions[currentQuestionIndex];
      nextQuestion = questions[currentQuestionIndex + 1];
      previousQuestion = questions[currentQuestionIndex - 1];
      const answer = currentQuestion.answer;
      this.setState(
        {
          currentQuestion: currentQuestion,
          nextQuestion,
          previousQuestion,
          numberOfQuestions: questions.length,
          answer,
        },
        () => {
          this.showOptions();
          this.handleDisableButton();
        }
      );
    }
  };

  handleOptionClick = (e) => {
    e.preventDefault();
    if (e.target.innerHTML.toLowerCase() === this.state.answer.toLowerCase()) {
      console.log("correct");
      this.correctAnswer();
    } else {
      console.log("incorrect");
      this.wrongAnswer();
    }
  };

  correctAnswer = () => {
    this.setState(
      (prevState) => ({
        score: prevState.score + 1,
        correctAnswers: prevState.correctAnswers + 1,
        currentQuestionIndex: prevState.currentQuestionIndex + 1,
        numberOfAnsweredQuestions: prevState.numberOfAnsweredQuestions + 1,
      }),
      () => {
        if (this.state.nextQuestion === undefined) {
          this.endGame();
        } else {
          this.displayQuestions(
            this.state.questions,
            this.state.currentQuestion,
            this.state.nextQuestion,
            this.state.previousQuestion
          );
        }
      }
    );
  };

  wrongAnswer = () => {
    this.setState(
      (prevState) => ({
        wrongAnswers: prevState.wrongAnswer + 1,
        currentQuestionIndex: prevState.currentQuestionIndex + 1,
        numberOfAnsweredQuestions: prevState.numberOfAnsweredQuestions + 1,
      }),
      () => {
        if (this.state.nextQuestion === undefined) {
          this.endGame();
        } else {
          this.displayQuestions(
            this.state.questions,
            this.state.currentQuestion,
            this.state.nextQuestion,
            this.state.previousQuestion
          );
        }
      }
    );
  };

  showOptions = () => {
    const options = Array.from(document.querySelectorAll(".option"));

    options.forEach((option) => {
      option.style.visibility = "visible";
    });
  };

  handleNextButtonClick = () => {
    if (this.state.nextQuestion !== undefined) {
      this.setState(
        (prevState) => ({
          currentQuestionIndex: prevState.currentQuestionIndex + 1,
        }),
        () => {
          this.displayQuestions(
            this.state.question,
            this.state.currentQuestion,
            this.state.nextQuestion,
            this.state.previousQuestion
          );
        }
      );
    }
  };

  handlePreviousButtonClick = () => {
    if (this.state.previousQuestion !== undefined) {
      this.setState(
        (prevState) => ({
          currentQuestionIndex: prevState.currentQuestionIndex - 1,
        }),
        () => {
          this.displayQuestions(
            this.state.question,
            this.state.currentQuestion,
            this.state.nextQuestion,
            this.state.previousQuestion
          );
        }
      );
    }
  };

  handleQuitButtonClick = () => {
    if (window.confirm("Are you sure want to quite Quiz")) {
      //  this.props.history.push("/");
    }
  };
  handleButtonClick = (e) => {
    e.preventDefault();

    switch (e.target.id) {
      case "next-button":
        this.handleNextButtonClick(e);
        break;

      case "previous-button":
        this.handlePreviousButtonClick(e);
        break;

      case "quit-button":
        this.handleQuitButtonClick(e);
        break;

      default:
        break;
    }
  };

  handleDisableButton = () => {
    if (
      this.state.previousQuestion === undefined ||
      this.state.currentQuestionIndex === 0
    ) {
      this.setState({
        previousButtonDisabled: true,
      });
    } else {
      this.setState({
        previousButtonDisabled: false,
      });
    }

    if (
      this.state.nextQuestion === undefined ||
      this.state.currentQuestionIndex + 1 === this.state.numberOfQuestions
    ) {
      this.setState({
        nextButtonDisabled: true,
      });
    } else {
      this.setState({
        nextButtonDisabled: false,
      });
    }
  };
  endGame = () => {
    alert("Game has ended.");
    const { state } = this;
    const playerStats = {
      score: state.score,
      numberOfQuestions: state.numberOfQuestions,
      numberOfAnsweredQuestions: state.correctAnswers + state.wrongAnswers,
      correctAnswers: state.correctAnswers,
      wrongAnswers: state.wrongAnswers,
    };
    console.log(playerStats);
    setTimeout(() => {
      this.props.history.push("/play/QuizSummary", playerStats);
    }, 1000);
  };

  render() {
    const {
      currentQuestion,
      currentQuestionIndex,
      numberOfQuestions,
    } = this.state;
    return (
      <Fragment>

Quiz Mode

            {currentQuestionIndex + 1}.{currentQuestion.question}

              {currentQuestion.opt1}

              {currentQuestion.opt2}

              {currentQuestion.opt3}

              {currentQuestion.opt4}

            <button
              className={classnames("", {
                disabled: this.state.nextButtonDisabled,
              })}
              id="previous-button"
              onClick={this.handleButtonClick}
            >
              Previous
            </button>
            <button
              className={classnames("", {
                disabled: this.state.nextButtonDisabled,
              })}
              id="next-button"
              onClick={this.handleButtonClick}
            >
              Next
            </button>
            <button id="quit-button" onClick={this.handleButtonClick}>
              Quit
            </button>

      </Fragment>
    );
  }
}

My Converted Functional Component
import React, { Fragment, useEffect, useState } from "react";
import { withRouter } from "react-router-dom";

import classnames from "classnames";
import isEmpty from "../is-empty";
import questionsArray from "../questions.json";

const PlayQuiz = ({withRouter}) => {
  const [questions, setQuestions] = useState(questionsArray);
  const [currentQuestion, setCurrentQuestion] = useState({
    content: "",
    question: "",
    opt1: "",
    opt2: "",
    opt3: "",
    opt4: "",
    answer: "",
  });
  const [nextQuestion, setNextQuestion] = useState({
    content: "",
    question: "",
    opt1: "",
    opt2: "",
    opt3: "",
    opt4: "",
    answer: "",
  });
  const [previousQuestion, setPreviousQuestion] = useState({
    content: "",
    question: "",
    opt1: "",
    opt2: "",
    opt3: "",
    opt4: "",
    answer: "",
  });
  const [numberOfQuestions, setNumberOfQuestions] = useState(0);
  const [numberOfAnsweredQuestions, setNumberOfAnsweredQuestions] = useState(0);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [score, setScore] = useState(0);
  const [correctAnswers, setCorrectAnswers] = useState(0);
  const [wrongAnswers, setWrongAnswers] = useState(0);
  const [nextButtonDisabled, toggleNextButtonDisabled] = useState(false);
  const [previousButtonDisabled, togglePreviousButtonDisabled] = useState(true);

  useEffect(() => {
    console.log("useEffect");
    displayQuestion(questions, currentQuestion, nextQuestion, previousQuestion);
  }, []);

  const displayQuestion = (
    questions,
    currentQuestion,
    nextQuestion,
    previousQuestion
  ) => {
    if (!isEmpty(questions)) {
      // questions = questions;
      console.log("current Question Index:" + currentQuestionIndex);
      console.log("display");
      currentQuestion = questions[currentQuestionIndex];
      nextQuestion = questions[currentQuestionIndex + 1];
      previousQuestion = questions[currentQuestionIndex - 1];
      setCurrentQuestion(currentQuestion);
      setNextQuestion(nextQuestion);
      setPreviousQuestion(previousQuestion);
      setNumberOfQuestions(questions.length);
      // showOption();
      handleDisableButton();
    }
  };

  const handleOptionClick = (e) => {
    e.preventDefault();
    if (
      e.target.innerHTML.toLowerCase() === currentQuestion.answer.toLowerCase()
    ) {
      console.log("correct");
      correctAnswer();
    } else {
      console.log("incorrect");
      wrongAnswer();
    }
  };

  const correctAnswer = () => {
    setScore(score + 1);
    setCorrectAnswers(correctAnswers + 1);
    setCurrentQuestionIndex(currentQuestionIndex + 1);
    setNumberOfAnsweredQuestions(numberOfAnsweredQuestions + 1);

    if (nextQuestion === undefined) {
      endQuiz();
    } else {
      displayQuestion(
        questions,
        currentQuestion,
        nextQuestion,
        previousQuestion
      );
    }
  };

  const wrongAnswer = () => {
    setWrongAnswers(wrongAnswers + 1);
    setCurrentQuestionIndex(currentQuestionIndex + 1);
    setNumberOfAnsweredQuestions(numberOfAnsweredQuestions + 1);

    if (nextQuestion === undefined) {
      endQuiz();
    } else {
      displayQuestion(
        questions,
        currentQuestion,
        nextQuestion,
        previousQuestion
      );
    }
  };

  const handleNextButtonClick = (e) => {
    e.preventDefault();

    if (nextQuestion !== undefined) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
      displayQuestion(
        questions,
        currentQuestion,
        nextQuestion,
        previousQuestion
      );
    }
  };

  const handlePreviousButtonClick = (e) => {
    e.preventDefault();

    if (previousQuestion !== undefined) {
      setCurrentQuestionIndex(currentQuestionIndex - 1);
      displayQuestion(
        questions,
        currentQuestion,
        nextQuestion,
        previousQuestion
      );
    }
  };

  const handleQuitButtonClick = () => {
    if (window.confirm("Are you sure want to quite Quiz")) {
      //  this.props.history.push("/");
    }
  };
  const handleButtonClick = (e) => {
    e.preventDefault();

    switch (e.target.id) {
      case "next-button":
        handleNextButtonClick(e);
        break;

      case "previous-button":
        handlePreviousButtonClick(e);
        break;

      case "quit-button":
        handleQuitButtonClick(e);
        break;

      default:
        break;
    }
  };

  const handleDisableButton = () => {
    if (previousQuestion === undefined || currentQuestionIndex === 0) {
      togglePreviousButtonDisabled(true);
    } else {
      togglePreviousButtonDisabled(false);
    }

    if (
      nextQuestion === undefined ||
      currentQuestionIndex + 1 === numberOfQuestions
    ) {
      toggleNextButtonDisabled(true);
    } else {
      toggleNextButtonDisabled(false);
    }
  };
  const endQuiz = () => {
    alert("Quiz has ended.");
    const playerStats = {
      score: score,
      numberOfQuestions: numberOfQuestions,
      numberOfAnsweredQuestions: numberOfAnsweredQuestions,
      correctAnswers: correctAnswers,
      wrongAnswers: wrongAnswers,
    };
    console.log(playerStats);
    console.log(questionsData.questions);
    console.log(questionsArray);

    history.push("/give-exam/QuizSummary", playerStats);
  };

  return (
    <Fragment>

Quiz Mode

          {currentQuestionIndex + 1}.{currentQuestion.question}

 handleOptionClick(e)} className="option">
            {currentQuestion.opt1}

 handleOptionClick(e)} className="option">
            {currentQuestion.opt2}

 handleOptionClick(e)} className="option">
            {currentQuestion.opt3}

 handleOptionClick(e)} className="option">
            {currentQuestion.opt4}

          <button
            className={classnames("", { disabled: previousButtonDisabled })}
            id="previous-button"
            onClick={(e) => handleButtonClick(e)}
          >
            Previous
          </button>
          <button
            className={classnames("", { disabled: nextButtonDisabled })}
            id="next-button"
            onClick={(e) => handleButtonClick(e)}
          >
            Next
          </button>
          <button id="quit-button" onClick={(e) => handleButtonClick(e)}>
            Quit
          </button>

    </Fragment>
  );
};

export default withRouter(PlayQuiz);

questionArray.json
[
  {
    "question": "What temperature does water boil at?",
    "opt1": "50 degrees Celcius",
    "opt2": "25 degrees Celcius",
    "opt3": "100 degrees Celcius",
    "opt4": "150 degrees Celcius",
    "answer": "100 degrees Celcius"
  },

  {
    "question": "Who wrote Julius Caesar, Macbeth and Hamlet?",
    "opt1": "Wole Soyinka",
    "opt2": "William Shakespeare",
    "opt3": "Ngozi Chimamanda Adichie",
    "opt4": "Dan Brown",
    "answer": "William Shakespeare"
  },

  {
    "question": "What did the crocodile swallow in Peter Pan?",
    "opt1": "A Book",
    "opt2": "A Computer",
    "opt3": "A pair of shoes",
    "opt4": "Alarm Clock",
    "answer": "Alarm Clock"
  },

  {
    "question": "Which is the only mammal that can't jump?",
    "opt1": "Dog",
    "opt2": "Elephant",
    "opt3": "Goat",
    "opt4": "Lion",
    "answer": "Elephant"
  },

  {
    "question": "Who lived at 221B, Baker Street, London?",
    "opt1": "Tony Stark",
    "opt2": "Morgan Freeman",
    "opt3": "Sherlock Holmes",
    "opt4": "Samuel L. Jackson",
    "answer": "Sherlock Holmes"
  },
]

isEmpty.js
const isEmpty = (value) =>
  value === undefined ||
  value === null ||
  (typeof value === "object" && Object.keys(value).length === 0) ||
  (typeof value === "string" && value.trim().length === 0);

export default isEmpty;

Answer: You can wrap your class component in a Higher Order Component and turn it into a Functional Component.
import React from 'react';
import { useHook } from '../hooks/useHook';

export const withFunctionalComponent = (Component) => {
  return (props) => {
    const hookValue = useHook();

    return <Component value={hookValue} {...props} />;
  };
};

And use it like so:
import React from 'react';
import { withFunctionalComponent } from './withFunctionalComponent';

class ClassComponent extends React.Component {
  render() {
    return
Hello, {this.props.value}
;
  }
}

export default withFunctionalComponent (ClassComponent)


The mean and variance of the inverse of a normal distribution

Question: I would want to ask if I have a random variable $A \sim N(b,c)$ then what is the distribution of the inverse of $A$?
Answer: As stated in wikipedia and this math.stackexchange question, $1 / A$ has a bimodal distribution.
However, the mean and the variance and higher order moments of $1 / A$ are not defined (as shown here for the mean).
Comment: (+1) Wikipedia asserts bimodality only for the case $b=0$ and $c=1$.  Clearly the value of $c$ will not affect this characteristic, but in principle $b$ can.  Nevertheless, $1/A$ will always be bimodal, because it has a density of $0$ at $0$ and both the positive and negative parts are unimodal (as becomes obvious when you consider the distribution of their logarithms).
Comment: Surely you mean bimodal and not binomial