Observable array not displayed in knockout even though it rendered

Question: When entering an E-mail address, the user will have to select the E-mail
 domain from the pre-defined list (e.g., gmail.com; outlook.com; hotmail.com).
HTML:

            <input class='required' data-bind='value: userName' />
            <select data-bind="options: $root.availableEmailDomains(), value: domainName, optionsText: 'domainName', optionsValue: 'domainName'"></select>
            Delete

   Agregue otra direccion de email

VM:
billDeliveryEmails : [],
availableEmailDomains: ko.observableArray(['gmail.com','yahoo.com','hotmail.com','outlook.com','hotmail.es','yahoo.es'])

 addDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {

        bindingContext.$root.billDeliveryEmails.push({
            userName: "",
            domainName: this.viewModel.get('availableEmailDomains')[0]
        });

        event.preventDefault();
    },

    removeDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {

        bindingContext.$root.billDeliveryEmails.splice(0, 1)
        event.preventDefault();
    }

I get below output: even though options are rendered successfuly but they are not displayed, output
Answer: It looks like your select element is binding to availableEmailDomains but I don't see such an object defined in your viewmodel, so I'm going to assume you meant emailDeliveryDomains. If this is the case, you can just change the select element to the following:
<select data-bind="options: $root.emailDeliveryDomains()"></select>

I think you may be misunderstanding how the value, optionsText, and optionsValue bindings work (you may want to read the knockout documentation). value should be an observable to store the selected value from the dropdown. optionsText and optionsValue are used when the array passed to the options binding is an array of objects. For example, if you passed an array like [{ color: 'blue', id: 1 }, { color: 'red', id: 2}] to the options binding, it would make sense to also set optionsText: 'color' and optionsValue: 'id'.
In your example, emailDeliveryDomains is just an array of strings, so you don't need to set optionsValue or optionsText.


Reading an int from a text file into an array in C

Question: I've got a text file formatted like this:
100 0 10 1
101 6 10 1
102 8 4 1
103 12 20 1
104 19 15 1
105 30 5 1
106 35 10 1

I need to put these numbers into the arrays pID[], arrival[], bursts[], and priority[], respectively.  C is not my strongest language, so I'm having some trouble doing this.
Here's my current code:
void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]){
FILE *file;
int i = 0;
file = fopen("Process.txt", "r");

//File format is pID, arrival, bursts, and priority
if (file){
    while (!feof(file)){
        pID[i] = fscanf(file, "%d ", &i);
        arrival[i] = fscanf(file, "%d ", &i);
        bursts[i] = fscanf(file, "%d ", &i);
        priority[i] = fscanf(file, "%d ", &i);
    }
    fclose(file);
}

Thanks for any help!
Comment: [why-is-while-feof-file-always-wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). And "I'm having some trouble doing this" is not really **specific*. See [ask].
Comment: `fscanf` returns *the number of items successfully scanned*, not the scanned value. `if(fscanf(file, "%d", &pID[i]) != 1) exit(1);`
Comment: Sorry, the values that are put into the arrays are no where near what is from the file.  Thanks for the article. If !feof(file) is incorrect, what is the correct way to loop through each line of the file?
Comment: Please read the post
Comment: Note that for interactive inputs, a trailing blank in a format string is a disaster; the `scanf()` operation won't return until the user types a non-blank (tab, newline) character after the end of the relevant data.  That means they have to predict what you're going to request next — not good.
Answer: You are using feof and fscanf in the wrong way. I suggest you read one line from file at a time, checking it was read, and then scanning the values from the buffer, also checking that the array index is still ok, and the correct number of fields were scanned.
void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]) {
    FILE *file;
    int i = 0;
    char buffer[100];
    file = fopen("Process.txt", "r");
    if (file){
        while (i < n && fgets(buffer, sizeof buffer, file) != NULL) {
            if(sscanf(buffer, "%d%d%d%d", &pID[i], &arrival[i], &bursts[i], &priority[i]) != 4) {
                exit(1);                // or recovery strategy
            }
            i++;
        }
        fclose(file);
    }
}

Comment: Thank you so much! This solved my problem, everything is being read in how it should be.
Comment: So the sscanf line is checking to make sure there are four values in each line of the file, while also putting the respective values in the arrays?  Sorry I keep asking so many questions, I'm just trying to fully understand how this solved my problem.
Comment: Yes, that is correct. It is always a good idea to check whatever you can check: assume nothing for robust code, especially when the input source may not be within your control. Although note: this would simply ignore any other data in that text line if there were more than 4 numbers, but it *would* trap anything that wasn't a number.
Comment: For ditching `fscanf()` and embracing `fgets()` when data is per _line_ --> upvote.


For Azure Function App scaling, will all active nodes be triggered or just one of them?

Question: I am designing a solution that includes an Azure Function App function that will be triggered when a blob is created in an Azure Blob Storage container. The Function App will automatically scale out when needed (more than one instance will be available, pre-warmed). If there are two or more nodes active at a specific moment, and a new blob is created, will the function be triggered:
a. For each of the nodes
or
b. For only one of the available free instances (and just one)
Comment: The Function will scale For each of the nodes, Refer this github link on scaling function app for consumption and premium plan - https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/azure-functions/event-driven-scaling.md
Comment: In the Consumption and Premium plans, Azure Functions scales CPU and memory resources by adding more instances of the Functions host. The number of instances is determined on the number of events that trigger a function.

Each instance of the Functions host in the Consumption plan is limited, typically to 1.5 GB of memory and one CPU. An instance of the host is the entire function app, meaning all functions within a function app share resource within an instance and scale at the same time. Function apps that share the same Consumption plan scale independently
Comment: Only one function instance will process the blob if that is what you really want to know.
Comment: @PeterBons, yes, let's say I have three instances active, I want to make sure the function will not be triggered three times, alas, I don't want the same file to be processed three times. If it is as you explained, do you have any link to where this is mentioned?
Answer: Only one function instance will process the blob if that is what you really want to know

yes, let's say I have three instances active, I want to make sure the function will not be triggered three times, alas, I don't want the same file to be processed three times. If it is as you explained, do you have any link to where this is mentioned?

Well, see the docs:

The Azure Functions runtime ensures that no blob trigger function gets called more than once for the same new or updated blob. To determine if a given blob version has been processed, it maintains blob receipts.

If you are using the Event Grid to handle blob events things are different as the Event Grid service is responsible for sending events to a Event Grid triggered Azure Function. The function will always react to each event grid event once, but do mind that the Event Grid is designed using a at-least-once delivery mechanism:

Event Grid provides durable delivery. It tries to deliver each message at least once for each matching subscription immediately.

(source)
Comment: It will be triggered for just one function instance. The reason that it is not stated that specific in the docs is due to the fact that the infrastructure details are not something the consumer needs to think about , it is abstracted away.
Comment: "The Azure Functions runtime ensures that no blob trigger function gets called more than once for the same new or updated blob". I would interpret this as this mechanism guarantees than no more than one function consumes the blob event. My question is more about the instances of a function, and at the end for any trigger in general (i.e. an HTTP request, a message available for peeking in a service bus queue, etc.). Will the trigger be called for all the instances, or just for one of the available ones? The articles I found seem to show it is just for one instance, for any kind of trigger.
Answer: This article and this one explain how Azure uses an internal queueing for events and process each of them using an instance if available, or creating a new one if needed. So answer is, Function is triggered only once per triggering event for any kind of trigger (i.e. blob creation or update, HTTP request, service bus queue or topic message).
Since Azure will not process the same file using multiple instances, for that kind of requirement the fan in fan out pattern must be used.
Comment: The concurrency mentioned in the linked articles describe how concurrent function invocations are dealt with regarding scaling the number of messages received in a function invocation and how many invocations can run concurrently. That does not guarantee an exactly-once-delivery mechanism. That's why for blobs blob receipts are used for example.


Estou com problemas para imprimir valores de database

Question: estou tentando fazer imprimir o 'ok' na tela quando ele encontrar o valor '3' dentro de uma das keys do banco de dados.
<code>>>> with dbm.open('data1.db','r') as user:
    user['0'] = '1'
    user['1'] = '2'
    user['2'] = '3'
    for i in user:
        if '3' in user[str(i)]:
            print('ok')

Traceback (most recent call last):
  File "<pyshell#146>", line 3, in <module>
    if '3' in user[str(i)]:
  File "C:\Users\ThomasNote\AppData\Local\Programs\Python\Python36-32\lib\dbm\dumb.py", line 148, in __getitem__
    pos, siz = self._index[key]     # may raise KeyError
KeyError: b"b'0'"

with dbm.open('data1.db','r') as user:
    for i in user:
        print(i.decode(), user[i].decode())

>>> 0 1
>>> 1 2
>>> 2 3
</code>
Answer: Pelo tipo de erro parece que a lista user que está tentando atualizar não está inicializada nas chaves correspondentes.
Entretanto, partindo da premissa de que a lista user foi inicializada e atualizada corretamente, tente o seguinte loop.
<code>    for i in user:
     if (i=='3'):
      print('ok')
</code>
Comment: O problema é que deste jeito não aparece o 'ok' porque ele vai procurar entre os valores de 0 a 2(que são as chaves). Eu quero que o programa procure os valores que estão dentro das chaves
Comment: Acredito que não Thomas Caio.
 Veja o
[exemplo](https://goo.gl/jgtc1i)


Dynamic file directory for file fields

Question: I just learned about the creating fields and content types and had a quick question about the file field.  When you create a file field you can specify a relative path that the uploaded resource will be stored by entering a path in the "File Directory" text field, but what I am going to need is to have the value be different depending on the circumstances.  For example I might want to clump all of the files uploaded by a certain user so I might want the relative path to depend on the user's name.  Is there a way to specify this type of dynamic path?  Is the something people normally do?   Or would they just organize files based on type?
Answer: It's very easy if you have the Token module installed. On the file field edit page you'll see something like this:

The big table is a list of tokens that you can use in the path for the file. By default there are tokens available for current user, current page, current date and a couple of others.
For example you could have a path such as users/[current-user:name], in which the token would be substituted for the current user's name. You just need to click in the text box you want to add the token to and then click the links in the table, it will auto-fill for you.
Hope that helps
Answer: I think you may try filefield paths module which extends Token and gives you more interesting options like [node:nid].

Dynamic file directory for file fields


Operator ++ in an IF statement in C

Question: I have this:
...
int charry = 0;
if (l[charry++] == 'a'){
    whatever;
}
...

The question is: will charry be increased anyway or just if l[charry] == 'a' evaluates to true?
Thank you in advance.
Comment: Definitely compile-error. At least it was...
Comment: Try it and you'll know. It will take less time than posting it here.
Answer: char is a reserved key word. Program would not even compile.

EDIT:  Before comparison, both operand of == will be evaluated and hence any side effect to expressions will take place. Therefore charry will be modified.
Comment: To be pedantic: The side effect will *not* necessarily have taken place before the comparison. At that point it's certain to happen, but it may be delayed until the next [sequence point](http://stackoverflow.com/q/4176328/395760) (which would be after the comparison). So if you did something more complicated like `if (l[charry++] == 'a' && charry == 1)` you'd have undefined behavior.
Comment: So what? Still worth knowing :-)
Comment: My god..I just put that without thinking about it... Edited.
Comment: @delnan; I never said that side effect will take place "before/after". :)
Answer: It will absolutely be incremented by 1 after the if-statement. if you choose to name your variable something other than a reserved keyword.
int charry = 0;
if (l[charry++] == 'a'){
    whatever;
}
// charry is now 1

If charry is used again before the next sequence point, as user delnan explained in his comment, you would have undefined behaviour.
Comment: Yeah, yeah, you guys are so critical (and I appreciate it). It was a mistake, I am not using "char" as a name, haha.
Comment: "It will be incremented ... after the if-statement" is a bit imprecise: It will be incremented sometime between reading the old value of `charry` and the branch decision of the `if()`. At least as far as the language is concerned. The optimizer, of course, may move the increment pretty much anywhere else as long as the code behaves as if the increment happened within the parentheses of the `if()`.

Operator ++ in an IF statement in C


Determining current file's location in R to include file from same directory?

Question: I want to be able to source() a file which includes a different file in its same directory, but I don't want to have to set the working directory from the R-prompt before running this file:
> getwd()
[1] "/Users/myser"
> source("/Users/myuser/workspace/myproject/myfile.r")

Inside /Users/myuser/workspace/myproject, there would be myfile.r and my-utils.r.  myfile.r calls source('my-utils.r') from within it.
Other programming languages can determine the current file's path. Does R have something similar? Example:
cur_dir <- sys.get_current_file_path()
source(file.path(cur_dir, "my-utils.r"))

Answer: source("/Users/myuser/workspace/myproject/my-utils.r", chdir=TRUE)

When chdir option is set to true and the source file parameter is a full path, the directory of file will be used as the working directory while sourcing the file.
NOTE: cur_dir <- sys.get_current_file_path() doesn't make much sense because pathnames are not unique.
Comment: This is not a solution at all. The point is to avoid putting  "/Users/myuser/workspace/myproject" in the code.
Comment: The point of the OP is in the example followed "Does R have something similar? Example:"      The simple answer is: R can't do it.
Comment: The problem with this code/solution is that it ties the functionality of that call to `source` to it existing in that specific directory. It would be good to have a solution that did not depend on this, such as would be achievable by the approach which dolan was shooting for with his python inspired pseudo example. correct me if I'm missing something though.
Comment: beat my by 30 seconds... nice answer.
Comment: @Apprentice - my function name was probably poorly chosen.  What I meant was something like this Python code: os.path.realpath(\_\_file\_\_)
Comment: @Jfly, how do you expect to run /A/B/C.r from another location without somewhere telling R that it is located at /A/B?  You could use environment variables or write your own file searching function; but regardless, a directory name needs to be placed somewhere.  The point of the OP was how to execute with a different working directory not how to hide a constant.
Comment: @Jfly that wasn't the OP's point. It was to get something running using the directory of its source file. One idea he had was to extract it from within code. Yes, this technique is not available from R. And even in (interpreted) languages that provide such a technique, it doesn't always work because not all code comes from the filesystem (eg, it can come straight from memory).
Answer: I know it's very late, but for people of the future, I ran into this answer on getting the directory where the script being sourced is.
I think you should be able to do this without installing additional packages:
cur_dir = utils::getSrcDirectory(function(){})[1]
source(file.path(cur_dir, 'my-utils.R'))


Accessing route values in view Mvc.net

Question: I'm using default route of mvc2 like {controller}/{action}/{id}. I want to access that id field in my view. How can I do that without using TempData and ViewData?
If I have a url like http://server-name/home/edit/14 I need the value "14" in the view.
Answer: You can access route data using the ViewContext property:
<%= ViewContext.RouteData.Values["id"] %>

Accessing route values in view Mvc.net


Error adding bootstrap 5 toaster to angular 17 as standalone components

Question: I am trying to add a bootstrap toaster to my angular project. I am using angular 17 with standalone components.
I am trying to follow what was done in this github repository but my project is standalone.
Running ng serve is successful but when I am trying to access http://localhost:4200/ I get the following error
[vite] Internal server error: document is not defined
      at enableDismissTrigger (D:\dev\git-2.0\base-templates\angular\angular-bootstrap-5-base\node_modules\bootstrap\dist\js\bootstrap.esm.js:802:19)
      at eval (D:\dev\git-2.0\base-templates\angular\angular-bootstrap-5-base\node_modules\bootstrap\dist\js\bootstrap.esm.js:884:1)
      at async instantiateModule (file:///D:/dev/git-2.0/base-templates/angular/angular-bootstrap-5-base/node_modules/vite/dist/node/chunks/dep-G-px366b.js:54758:9) (x6)

https://stackblitz.com/~/github.com/Chrispie/code-problems on my issue-creating-bootstrap-5-toaster-with-angular-17-standalone branch:

I added my sample project where I have reproduced the error to my github repo.
Any idea as to what am I doing wrong here or what does it mean in this context?
For completeness sake I am outlining below what I have done.
I created a new angular project with scss and added the following 2 dependencies
npm i bootstrap
npm i @types/bootstrap --save-dev

A toast and a toaster component is added with a service and 2 models. The main app component has a few buttons to launch the toasts.
When running I am expecting it to look something like this
Comment: You should really place the code on https://stackblitz.com instead of github when asking questions
Comment: @GetOffMyLawn 100% correct. I added a link. Not 100% sure if my branch can be embedded in the link.
Answer: Seems like Server side rendering (SSR) with bootstrap does not work hand in hand. Not sure if there are a way to still use it with SSR.
But for now I disabled SSR by following the steps on this site:

Rm main.server.ts
Rm server.ts
Rm src/app/app.config.server.ts
Remove these keys from architect in angular.json
"server": "src/main.server.ts", "prerender": false, "ssr": { ... }
Remove these from tsconfig.app.json

files -> "src/main.server.ts"
types: [ "node" ] becomes "types": []

npm uninstall @angular/ssr express @angular/platform-server
npm uninstall -D @types/express @types/node

I uploaded the solution to another branch called issue-creating-bootstrap-5-toaster-with-angular-17-standalone-resolved if it might help anyone.


Short tailed/Long tailed distributions and their effects on p-value interpretation when assuming normality

Question: Can anyone offer better insight into the comparison of how p-values for hypothesis tests are affected when your distribution is short/long tailed but we assume it is normally distributed?  I'm specifically wondering about this with respect to the usual regression diagnostics (QQ-Plot to affecting t-test, F-test, etc)
I seem to recall a short-tailed distribution inflates p-values when assuming normality, so statistically significant p-values are still significant but we can possibly miss actually-significant results.  A long-tailed distribution is the opposite, deflating p-values and running a greater risk of claiming significance on false-positives.
Any greater insight or literature detailing this behavior would be appreciated!
Answer: Discussing this topic for regression will be difficult without more details.
Are you asking about simple linear regression (one predictor variable)?
Is the non-normality evident from looking at residuals, or is non-normality suspected for some other reason?
Here is a brief discussion, based on simulation in R, for two-sample Welch t tests, using normal, uniform (no tails), and exponential (heavy right tails) as examples. I hope some of the issues of interest to you will be addressed by looking at results for t tests.
Significance level. With any test, intended to be at the 5% level of significance, it is a good idea
to check whether the actual significance level is nearly 5%. So here are results
of three simulations in which sample sizes are $n_1=n_2=10$ and the two samples
come from exactly the same distribution. I use very small sample sizes because
the rubustness of the t test against nonnormal data tends to improve for larger $n.$
(All three populations have $\sigma \approx 1.)$
<code>## Null Hypothesis True:  Actual Signif Levels

set.seed(628)
pv = replicate(10^5, t.test(rnorm(10,0,1),rnorm(10,0,1))$p.val)
mean(pv <= .05)
[1] 0.04845

set.seed(629)
pv = replicate(10^5, t.test(runif(10,0,3.464),runif(10,0,3.464))$p.val)
mean(pv <= .05)
[1] 0.04993

set.seed(630)
pv = replicate(10^5, t.test(rexp(10,1),rexp(10,1))$p.val)
mean(pv <= .05)
[1] 0.03653
</code>
Results for normal and uniform data show significance levels that essentially
match 5% within simulation error. It is no surprise that uniform data performs
well because means of samples of size 10 from a uniform distribution are
hard to distinguish from normal.
Power. If we test a normal sample of size 10 from $\mathsf{Norm}(0,1)$ against
a sample from $\mathsf{Norm}(1,1),$ which is a shift of one unit, then the power
(probability of rejecting $H_0)$ is about $0.884 = 88.4\%.$ Power against a rightward shift of 1 unit for uniform data is about the same. Also for exponential data the power is about the same.
<code>## Null Hypothesis False: Power against shift to right of 1.5

set.seed(628)
pv = replicate(10^5, t.test(rnorm(10,0,1),rnorm(10,0,1)+1.5)$p.val)
mean(pv <= .05)
[1] 0.88406

set.seed(629)
pv = replicate(10^5, t.test(runif(10,0,3.464),runif(10,0,3.464)+1.5)$p.val)
mean(pv <= .05)
[1] 0.89382

set.seed(630)
pv = replicate(10^5, t.test(rexp(10,1),rexp(10,1)+1.5)$p.val)
mean(pv <= .05)
[1] 0.87095
</code>
Overall, rejection levels may be a little lower for exponential data because
the t statistic may not have exactly Student's t distribution. (I have used Welch
two-sample t tests, which do not assume equal variances, so in instances where
long right tails of exponential sample give unusually large sample variances
the Welch t test may perform better than the pooled test.)
Detecting non-normality. With sample sizes as small as 10, detecting non-normality can be difficult. Normal probability plots and Shapiro-Wilk tests of normality are shown below for small normal,
uniform, and exponential samples.

<code>set.seed(1234)
par(mfrow=c(1,3))
 x1 = rnorm(10)
  qqnorm(x1, main="Normal");  qqline(x1)
 x2 = runif(10,0,3.464)
  qqnorm(x2, main="Uniform"); qqline(x2)
 x3 = rexp(10,1)
  qqnorm(x3, main="Exponential"); qqline(x3)
par(mfrow=c(1,1))

shapiro.test(x1)$p.val; shapiro.test(x2)$p.val; shapiro.test(x3)$p.val
[1] 0.7294606
[1] 0.1470564
[1] 0.3675874
</code>
Possible availability of better test than t. As a practical matter it is worth mentioning that t tests are by far not the
best tests for uniform data: any sample with a value above 4.565 is just by
itself reason to reject $H_0.$ For exponential data a complete lack of observations below 1.5 in the second sample provides strong evidence for rejection. (The probability of that would be about $0.0000003.)$ The lesson here is that a good reason for
avoiding a t test may not be that it is a 'little off' for nonnormal data, but rather that a much better test may be available.
<code>(1 - pexp(1.5, 1))^10
[1] 3.059023e-07
</code>


Como fazer para trazer o Model por IDS e ordernar ao mesmo tempo

Question: estou com os ids retornados de uma query imensa para trazer os posts com um termo buscado... Ja esta funcionando trazer os posts atraves do Model pelos IDS selecionados mas ele traz sempre ordenado por ID e o que eu preciso eh ordenar por data... Na query imensa que fiz, ja trago os ID's ordenados corretamente mas quanto uso o modelo para buscar pelos IDS, ele desordena e traz ordenado pelo ID...
Exemplo do codigo:
<code>$terms = explode(' ', Input::get('search'));
$results =
DB::select(
    DB::raw($this->getSearchQuery($terms))
);

$postIds = [];
foreach ($results as $result) {
    array_push($postIds, $result->id);
}

$posts = Post::find($postIds);
</code>
O problema eh na ultima linha que ao inves de buscar os IDS na ordem que eu informo, ele busca na ordenado pelo ID...
Comment: Você tentou ordenar usando `Post::find($postIds)->orderBy('data');` ?
Comment: Sim! A resposta esta logo abaixo... Acabei implementando na mao... Vi no github do proprio laravel uma issue a respeito.
Answer: Digamos que você tenha uma lista de ids no formato array:
<code>$ids = [1, 2, 8, 15, 78];

$posts = Post::whereIn($ids)->orderBy('created_at', 'desc')->get();
</code>
Comment: Simples e eficiente(Abre apenas uma única conexão com o banco de dados).
Answer: Consegui ordenar da seguinte forma:
<code>$postIds = [];
foreach ($results as $result) {
    array_push($postIds, $result->id);
}

$posts = Post::find($postIds);

$sorted = array_flip($postIds);

foreach ($posts as $post) $sorted[$post->id] = $post;
$sorted = Collection::make(array_values($sorted));
</code>


Responsive jcarousel doesn't resize images

Question: Im using the jcarousel module and its responsive setting:
http://smartpeopletalkfast.co.uk/carousel/
Below you can see screenshots of how it works. When I resize the browser and the final image doenst fit it is then hidden.

This is working however the original jQuery plug in also resizes the remaining images so they take up the full available width:
http://sorgalla.com/jcarousel/examples/responsive/
How can I get my Drupal site to behave the same way? The only solution I can think of is pretty hacky. I could run javascript on page load and window resize which measured the images and the container, and then resized the images to take up the full width.
Answer: I think JCarousel still uses 0.2.x version of the JCarousel library and the example you're refering uses version 0.3.3 of the library which brings wider responsive support. Since 0.2.x and 0.3.x are not compatible as one can read here https://github.com/jsor/jcarousel, I think it will be difficult to achieve the features of the 0.3.x library in the drupal module. Look at the roadmap on https://www.drupal.org/project/jcarousel
Answer: Since there is not an official jcarousel release that uses v0.3.x you have limited options if you want to use jCarousel.
There is a jCarousel 7.x-3.x version being worked on that will use jCarousel 0.3.x but it is in development still and should only be used for testing purposes. With some good testing, I would imagine that you could use this version without much worry.
Personally, I would not use the development version or try to hack v0.3.x into the current release.  I ran into this issue a while back and ended up using OwlCarousel.  This module offers very similar functionality and seems a bit ahead of jCarousel as far as responsive settings go.  If you're not locked into using jCarousel, I'd give OwlCarousel a shot.


Find a conformal map onto the open disk

Question: I am trying to find a conformal map from $D = \{|z| <1\} \cap \{|z-1/2|>1/2\}$ to the open unit disk. I know that $D$ is the intersection of two "disks" so I want to use some sort of LFT to map $D$ onto a sector (which I believe will actually turn out to be a vertical strip). The problem is that usually I would use the LFT $f(z) = \frac{z-a}{z-b}$ where $a$ and $b$ are the points of intersection of the boundaries of the two disks. However, the boundaries of the unit disk and $|z-1/2| >1/2$ only intersect at one point (z=1) so I am not sure what to do.
Answer: Any Möbius transformation which maps the intersection point $z=1$ to $w=\infty$ and the real axis onto itself is a good start, because it maps the disc boundaries to vertical lines.
A possible choice is $T(z) = z/(z-1)$ which maps $1, 0, -1$ to $\infty, 0, 1/2$, respectively, and therefore the circle $\{ |z| = 1 \}$ to $\{ \operatorname{Re}(w) = 1/2 \}$ and the circle $\{ |z-1/2| = 1/2 \}$ to $\{ \operatorname{Re}(w) = 0 \}$, i.e. to the imaginary axis.
Now map one additional point to decide whether the image of your domain is the area between the vertical lines or the "outside."

Find a conformal map onto the open disk


VEGA LITE calculate filter to evaluate result on non-blank values

Question: I am facing some troubles in Vega Lite while trying to achieve the following:
I want to extract the minimum value from three measures, which works fine until one of the measures is blank - then it takes NULL as the minimum value.
I would like the calculation to ignore NULL values and only evaluate it on measures that are not blank. So basically, when it is [10, 5, NULL], it should return 5 as the result instead of NULL.
How could I achieve this? I have tried incorporating the "filter" function, but it did not work out.
This is the line of code where I would like to apply this condition:
<code>...{
      "calculate": "min(datum['min_actual'], datum['min_base'], datum['min_base_minus_1'])",
      "as": "low_value"
    }...
</code>
Thanks a lot for your help!
Answer: You could test each value with a ternary operation and if null, return a large number.
Something like:
<code>{
      "calculate": "min(isValid(datum['min_actual'])?datum['min_actual']:9e20, isValid(datum['min_base'])?datum['min_base']:9e20, isValid(datum['min_base_1'])?datum['min_base_1']:9e20)",
      "as": "low_value"
    }
</code>
Comment: helped as always!
thank you Davide!

your Vega knowledge is GOD level
Comment: Cool. I never heard of a ternary operation before.  Now I am smarter


In R, how can i use package"regular expression" or removing the unmatched files in two folders

Question: I have two folders. The first folder(post) has 7 files "abc.csv, bcc.csv, cdd.csv, dgg.csv, efg.csv, fgg.csv, gda.csv". The second folder(comment) has 4 files "abc_comment.csv, bcc_comment.csv, efg_comment.csv, fgg_comment.csv".
I want to read only the file that the first part in file name is same.
For example, abc.csv and abc_comment.csv are same in the first part but 3 files (cdd.csv, dgg.csv, fgg.csv) have no same comment.csv file. So, in second folder, file_lists are removed.
I have no idea for doing this and maybe I think that I need to use package"regex".
Below is my basic code, and how can I add the code?
    post_dir <- c:/post/
    comment_dir <- c:/comment/
    post <- list.files(post_dir)
    comment <- list.files(comment_dir)

Answer: You can do it easily without the knowledge of complex regex with stringr and R subsetting
library(tidyverse)

fake_post <- c('abc.csv',' bcc.csv', 'cdd.csv', 'dgg.csv', 'efg.csv', 'fgg.csv', 'gda.csv')

fake_comment <- c('abc_comment.csv', 'bcc_comment.csv', 'efg_comment.csv', 'fgg_comment.csv')

# Strip extension

fake_post2 <- fake_post %>% str_remove('.csv')

# Strip comment and extension
fake_comment2 <- fake_comment %>% str_remove('_comment.csv')

fake_post[fake_post2 %in% fake_comment2]
#> [1] "abc.csv" "efg.csv" "fgg.csv"

Created on 2020-01-06 by the reprex package (v0.3.0)
Comment: I want to read the file. so I think that if get rid of '_comment.csv' I cannot read the csv file using read.csv. could you recommend the other method?
Comment: You still have the file name, you can then do something like map(fake_post[fake_post2 %in% fake_comment2],read_csv)
Answer: Here is another solution.

Use for loop to change target pattern.
we get target file paths :)
Read files into R.
Assign the file names as object names.

post_dir <- c:/post/
comment_dir <- c:/comment/
post <- c('abc.csv',' bcc.csv', 'cdd.csv', 'dgg.csv', 'efg.csv', 'fgg.csv', 'gda.csv')

target<-gsub("\\.csv","",post)
#[1] "abc"  " bcc" "cdd"  "dgg"  "efg"  "fgg"  "gda"

for (i in target){
assign(i,read.csv(list.files(post_dir,pattern=i,full.names = T)))

name<-paste0(i,"_comment")
assign(name,read.csv(list.files(comment_dir,pattern=i,full.names = T)))

}


In Application of Taylor Polynomials section in Stewart Calculus 3rd, 7^(8/3) > 179?

Question: I am going over the very old edition of Stewart's "Calculus" 3rd edition, and found this innocent inequality approximation $7^{8/3} > 179$ in the section of Application of Taylor Polynomials (10.12). I don't think the particular material to be learned matter here. In fact, $7^{8/3} = 179.3059$. I am wondering if I am missing some scheme to approximation this type of calculation.
Comment: Doing this with Taylor series seems inconvenient (though perfectly possible).  Easy enough to check that $7^8>179^3$ of course.
Comment: Ah, that's kind of reasonable. The page innocuously puts the inequality as if it looks obvious. Is it obvious that $7^{8}$ should be somewhere around $180^{3}$ for any ways? I can only see it should be between $7^{8/4}$ and $8^{8/3}$. Between 49 and 256 is not tight enough to guess 179 with a few trials.
Comment: I wouldn't have thought that this was obvious, no.
Comment: Okay. Thank you.
Answer: The Taylor series aren't that bad. We use the binomial series
$$(8+t)^{\frac 83}=256\left(1+\frac{t}{8}\right)^{\frac83} = 256\left(1+\frac83\cdot\frac t8+\frac{8\cdot 5}{3^2\cdot 2}\cdot\frac{t^2}{64}+\frac{8\cdot 5\cdot 2}{3^3\cdot 6}\cdot\frac{t^3}{512}+\cdots\right)$$
Evaluating at $t=-1$, the four terms I've written out come to $256$, $-\frac{256}{3}=-85-\frac13$, $\frac{80}{9}=9-\frac19$, and $-\frac{20}{81}$. Adding them, I get $256-85+9-\frac13-\frac19-\frac{20}{81}=180-\frac{56}{81}>179$.
All right, we need an estimate for the tail as well. The fourth derivative is (for $-1\le t\le 0$)
$$256\cdot\frac{8\cdot 5\cdot 2\cdot -1}{3^4\cdot 8^4}\left(1+\frac t8\right)^{-\frac43}=\frac{-10}{2\cdot 81}\left(1+\frac t8\right)^{-\frac43} < \frac{1}{16}\cdot \frac43$$
That inequality is really about absolute values, estimating $81>80$ and $\left(\frac87\right)^{\frac43}<\left(\frac87\right)^2<\frac86$. The error in our third degree polynomial is $\frac{f^{(4)}(c)}{24}$ for some $c$, or less than $\frac1{12\cdot 24}=\frac1{288}$. Subtract that from $179+\frac{25}{81}$, and it's still greater than $179$. Proved.
No calculating aids were used here - just pencil and paper.
Comment: This is an alternating series, so the 5th term bounds the error.
Comment: No, it's not alternating. From the $x^3$ term on, the terms are all the same sign.
Comment: 'K.  You win....this time....


How to pass props using element in react-router v6?

Question: I'm trying to reuse my MainSection component for two different purposes (single story and all stories). To effect this, I want to pass in a property, home, in the Routes that go to those renderings of that component. Home is true or false, and I want to render the MainSection component based on that boolean. However, I home keeps being undefined when MainSection gets rendered. The link and route are updating the URL, but not rendering with the props I want. Am I doing something wrong?
Here are my routes:
function Routes(){
  return(
    <Switch>
      <Route path="/"  element={<MainSection home={true} />} />
      <Route path="/story" element={ <MainSection home={false} />} />
    </Switch>
  )
}

and here is the code for my MainSection component:
function MainSection({ home }){
  console.log(home)
  return(

      <BigPicture home={ home }/>
      <Quotes home={ home }/>

  )
}

The console log keeps returning undefined.
Thanks!
Answer: Since in the question title you state you are using react-router-dom version 6 I'll answer against that. V6 doesn't export a Switch component, it was replaced by a Routes component. Swap the Switch for the Routes component and rename your Routes component to something else to avoid the name collision.
function MainRoutes(){
  return(
    <Routes>
      <Route path="/" element={<MainSection home />} />
      <Route path="/story" element={<MainSection />} />
    </Routes>
  )
}

From here the home prop should either be treated as truthy/falsey. You can double-bang it to coerce it to a strict boolean value. Passing home through to children components should also work without issue.
function MainSection({ home }) {
  React.useEffect(() => {
    console.log(!!home);
  }, [home]);

  return(

      <BigPicture home={home} />
      <Quotes home={home} />

  )
}

Comment: @AzharUddinSheikh RRDv6 removed the route props. If you need to access the v6 versions of these objects you will use the React hooks, `useNavigate` for a `navigate` function which replaced the `history` object, `useParams` for `params` instead of `match.params`, and `useLocation` for `location`. I *highly* suggest reviewing the [migration guide](https://reactrouter.com/en/v6.3.0/upgrading/v5) for the changes from v5 to v6.
Comment: how to pass `default` props here?
Comment: @AzharUddinSheikh Can you clarify what you are asking to pass as props and where you want to pass them?
Comment: some `default` props like objects have `history` `match` and `location`
In the older version, we do something like this ` }`
but when I try this in latest version I unable to use `arrow` function


What is the benefit of Matthews correlation coefficient (MCC) over average of sensitivity and specificity for imbalanced data?

Question: Assume that we have a 2 class data where number of samples in each class are very different (data is imbalanced) and penalty of miss-classification is equal for the two classes. For assessing the performance of a binary classifier over this data,
I like to know what is the benefit(s) of Matthews correlation coefficient (MCC) over just averaging sensitivity (True positive rate) and specificity (True negative rate)?
Comment: You might find interesting the thorough discussion with worked example using Python published here: https://empiricalfinanceblog.home.blog/2020/01/18/assessing-the-performance-of-a-binary-classifier/
Answer: MCC is a correlation coefficient between target and predictions. It generally varies between -1 and +1. -1 when there is perfect disagreement between actuals and prediction, 1 when there is a perfect agreement between actuals and predictions. 0 when the prediction may as well be random with respect to the actuals. As it involves values of all the four quardants of a confusion matrix, it is considered as a balanced measure.
Let's consider a case where the number of cases for either positive or negative is too low and the classifier returns either of the TP or TN as 0, then averaging TPR and TNR will return a score without any direction.We cannot judge a model based on this score. MCC involves values of all the four quardants of a confusion matrix and being a balanced measure will return a value  with a direction (+ve and -ve)
There is a great explanation on MCC and accuracy measures in the below article
https://lettier.github.io/posts/2016-08-05-matthews-correlation-coefficient.html


Elegant creating of images in JS

Question: I would like to ask if there is a more elegant way to insert images to html with javascript without jQuery than:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>

Eventually I am gonna have there much more atributes and I want to avoid using  as much as possible to make it more transparent.
Answer: You can create elements in JavaScript by using document.createElement("tag"). For example, document.createElement("image"). So you don't need to construct a string like you're doing. For some elements, such as an image, you can also just do new Image(). Keep in mind when you create an element in such a manner, it not yet part of the DOM. You must add it using appendChild or some other means.
Also, I would refrain from using document.images[] as I'm not sure that's entirely cross-browser friendly. I believe the standard practice is document.getElementsByTagName("image"), which returns an array you can iterate through.
var whereToAppend = document.getElementsByTagName("body")[0];

for(var i = 0; i < 3; i++) {
     var name = i + "_img";
     var img = new Image();
     img.src = i + ".png";
     whereToAppend.appendChild(img);
}

Elegant creating of images in JS


Animação mover-se do sentido direito para a esquerda

Question: Tenho esta pequena animação em javascript, que faz o meu background mover-se contudo, isto tem vezes que se move da direita para a esquerda e tem outras vezes que se move da esquerda para a direita.
Como faria para mover-se sempre da direita para a esquerda.
Código:
<code>        $('#cores').animate({
 'background-position-x': cd.position
},{ duration: 6000, 'easing':'easeOutCubic'
</code>
Obrigado.
Comment: O que é o `cd.position`?
Comment: O cd.position é uma parte que recebe via socket do nodejs.
Answer: Tente definir dois lados, esquerda e direita como variável.
Depois procure fazer com que o background siga esta variável conforme a velocidade e efeito que você queira..
Se for o que eu entendi, você pode seguir esta lógica
Dê uma olhada neste site: All Animation , acho que lá deve ter o efeito que você quer! acho que dá pra ter uma boa noção.
Boa sorte!


Get profile2 fields based on user

Question: I am trying to retrieve some fields from my Profile 2 profile but am not sure how I should connect the table dr_field_data_field_resources to its relevant user.
In profile it is possible to add a field term_reference 'resources', then I want to be able to retrieve those values in an array based on a user I specify. I did see some other docs for profile2_load, but I using an example turorial. I am getting called to undefined function for profile2_load().
$userskillsresources = db_query("SELECT dr_users.name as 'username', dr_taxonomy_term_data.name  as 'userresourceterm'
    FROM dr_users
    JOIN dr_field_data_field_resources
    JOIN dr_profile ON dr_users.uid = dr_profile.uid
    JOIN dr_taxonomy_term_data ON dr_field_data_field_resources.field_resources_tid = dr_taxonomy_term_data.tid
    WHERE dr_users.uid = '10'")->fetchAssoc();

Answer: If you really do have Profile2 installed and enabled, then you shouldn't get getting undefined function errors.  Double check that it is enabled.
Otherwise, you are going about this in the wrong way.  You really don't need to do queries like this.  Leverage the API:
$account = user_load(10);
$profile = profile2_load_by_user($account);

If you have a single profile for the user, $profile will be a node object.  Otherwise, it will be an array of nodes.  Then you can do something like:
$resources = field_get_items('node', $profile, 'field_resources', $profile->language);

Also take a look at this article for a handy helper function or read more about the Field API.  If $resources are taxonomy terms, then take a look at taxonomy_term_load for loading the associated terms.
Comment: Hi, I am getting  Call to undefined function user_load() and it says for definite that profile2 is installed and enabled...
Comment: would it not work if I was logged in as admin?
Comment: If you are getting an undefined function for `user_load` then you have a serious problem elsewhere.  Off the top of my head I am not sure how I would go about debugging this, other than starting to disable anything custom I did to the site.
Comment: Hi, I didn't do anything custom to the site.
Comment: I am still getting this error. Any suggestions as to steps to take to debug it.
Comment: the answer to the error was that I had edit_profile module also install which I think was messing with things.

Get profile2 fields based on user


Every Time when I use the Number() function so i got an error

Question: I am trying to make a simple adding calculator on node.js and express.js that can add only two number but when I use the number function of JS that convert strings to a number so I got the error is:
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 4
    at ServerResponse.writeHead (_http_server.js:242:11)
    at ServerResponse._implicitHeader (_http_server.js:233:8)
    at ServerResponse.end (_http_outgoing.js:692:10)
    at ServerResponse.send

My CODE IS :
const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
    res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
    var a = Number(req.body.num1);
    var b = Number(req.body.num2);
    var result = a + b;
    res.send(result);
})
app.listen("3000", function(){
    console.log("The App is on port 3000")
})

So what should I do?
Answer: Apparently, if you pass number as first parameter to send method, it takes it as status code, and 4 is not valid HTTP status code and that's why the error.
Just change you code to send json in response and it will work:
res.send({sum:result})

Or else if you need number in response you can do like this also:
res.send(200,result)

Here 200 is success HTTP status code
Answer: according to the express's api doc.

res.send([body]) Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, or an
  Array.

So you set a Number to send() may be not work.


Erro em ListView com ArrayAdapter e View personalizada

Question: Estou querendo fazer uma listagem de produtos, onde cada linha contenha mais de uma informação por linha.
O problema é que o app lança exceção (acredito eu) e fecha quando clico no botão que preencheria a lista.
Fiz uma View personalizada pra cada item do ListView que é a produtos_item.xml
Minha IDE é o Android Studio. A Activity é a Inicial.java e a View onde está o ListView é principal.xml.
principal.xml (Activity)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Formar lista"
        android:onClick="FormarLista" />
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Principal__ListaProdutos"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

produtos_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:id="@+id/produtos_item__Nome"
        android:textColor="@android:color/background_dark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nome do produto"
        android:textStyle="bold"
        android:textSize="17dp" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false">
        <LinearLayout
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/clientes_itens_Quantidade"
                android:textSize="15dp" />
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" " />
            <TextView
                android:id="@+id/produtos_item__Quantidade"
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="150"
                android:textSize="15dp" />
        </LinearLayout>
        <LinearLayout
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/clientes_itens_Preco"
                android:textSize="15dp" />
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" R$ "
                android:textSize="15dp" />
            <TextView
                android:id="@+id/produtos_item__Valor"
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="5.50"
                android:textSize="15dp" />
        </LinearLayout>
        <LinearLayout
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/clientes_itens_Estoque"
                android:textSize="15dp" />
            <TextView
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" R$ "
                android:textSize="15dp" />
            <TextView
                android:id="@+id/produtos_item__Total"
                android:textColor="@android:color/background_dark"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="825.00"
                android:textSize="15dp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

ListAdapterList.java
public class ListAdapterList extends ArrayAdapter<Item> {

    private Context context;
    private ArrayList<Item> itens;
    private int layoutResourceId;

    public ListAdapterList(Context context, int layoutResourceId, ArrayList<Item> itens){
        super(context, layoutResourceId, itens);
        this.context = context;
        this.itens = itens;
        this.layoutResourceId = layoutResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Item item = this.itens.get(position);

        convertView = LayoutInflater.from(this.context).inflate(layoutResourceId, parent, false);
        ((TextView) convertView.findViewById(R.id.produtos_item__Nome)).setText(item.getNome());
        ((TextView) convertView.findViewById(R.id.produtos_item__Quantidade)).setText(item.getQuantidade());
        ((TextView) convertView.findViewById(R.id.produtos_item__Valor)).setText(String.valueOf(item.getValor()));
        ((TextView) convertView.findViewById(R.id.produtos_item__Total)).setText(String.valueOf(item.getValorEstoque()));

        return convertView;
    }
}

Item.java
public class Item {
    private String Nome;
    private double Valor;
    private int Quantidade;

    public Item(String nome, double valor, int quantidade) {
        Nome = nome;
        Valor = valor;
        Quantidade = quantidade;
    }
    public String getNome() { return Nome; }
    public double getValor() { return Valor; }
    public int getQuantidade() { return Quantidade; }
    public double getValorEstoque() { return Quantidade * Valor; }
}

Inicial.java
public class Inicial extends Activity{

    private ListView Lista;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.principal);
        Lista = (ListView)findViewById(R.id.Principal__ListaProdutos);
    }
    public void FormarLista(View v){
        ArrayList<Item> objects = new ArrayList<>();
        objects.add(new Item("Produto 1", 5.6, 18));
        objects.add(new Item("Produto 2", 16.9, 12));
        objects.add(new Item("Produto 3", 1.2, 200));

        ListAdapterList customAdapter = new ListAdapterList(this, R.layout.produtos_item, objects);
        Lista.setAdapter(customAdapter);
    }
}

Console de erros
E/ArrayAdapter: You must supply a resource ID for a TextView
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

Answer: Na linha
convertView = LayoutInflater.from(this.context).inflate(R.layout.principal, parent, false);

Você está inflando o XML referente ao layout chamado "principal", que parece corresponder a uma Activity. Isso está incorreto. Seu adapter tem que inflar as Views correspondentes aos items da lista, ou seja, tem que inflar o layout definido em produtos_item.xml .
Comment: Obrigado, realmente isso me passou. Mas ainda está com outro erro. Eu corrigi esse e o app ainda tá fechando.
Comment: @MarceloNascimento Que bom que ajudei um pouco. Abra uma nova pergunta com o novo erro e a nova situação para mantermos a organização e facilitar a busca por outros usuários.


Is the "makeup" of this year's womens' field at Wimbledon unusual?

Question: In this year's Wimbledon playoffs, the top two women's seeds (Serena Williams and Li Na) have been ousted in the first three rounds. Going into the round of 16, there are only six players seeded 1-16, four seeded 17-32, and six are unseeded.
That looks like a "low seeded" final four rounds to me. Is it common to have only three "top five" seeds and six unseeded contestants in the round before the quarter finals?
Answer: This kind of result in a grand slam event isn't that uncommon at all, really. One thing you've got to understand about the sport of tennis is that among the top 150-200 players in the world - they can all beat each other if one player isn't playing that well and the other is. The margin between winning and losing is really small and easily tilted in favor of one player given a break of serve or two. There are even matches where the losing player wins more total points than the winner does.
Also keep in mind that for major events (like Wimbledon) the singles draw begins with 128 players and so there are more rounds (and matches) for players to compete in, thus the chances of a seeded player losing goes up compared to say, the average tournament with just a draw of 32 or 64.
Answer: Going into the semifinals, the contestants were seeded Number 3 (Simona Helep), Number 6 (Petra Kvitova), Number 13 Eugenie Bouchard, and Number 23 (Lucie Safarova). That is, two from the top 8, one from the next 8, and one from the bottom 16. That is a reasonably normal result for the finals.
The "challengers" that won early-round matches against the likes of Serena Williams and Li Na were eliminated in the middle (fourth and fifth) rounds, as were several other unseeded players that had easy draws the fist three rounds. The "giant killers" turned out not to be giants in their own right, and fell to high seeded players who were not having bad days.


Which likelihood and prior corresponds to which loss and regularization?

Question: In Bayesian linear regression having the objective
$$\min_w \underbrace{\sum_{i=1}^N (w^Tx_i - y_i)^2}_{\text{log-likelihood}} + \underbrace{\lambda ~  w^Tw}_{\text{log prior distribution}}$$
can be seen this as the maximization of the log posterior distribution. The log posterior distribution then falls apart into two parts: A part corresponding to the log likelihood and a part corresponding to the log of the prior distribution.
In the above case we made the assumptions
(1) That the model is given by $y = w^Tx + \epsilon$ with $\epsilon$ being white noise, leading to the specific form of the log-likelihood (squared error).
(2) That the prior is given by a 0-centered Gaussian, leading to the specific form of the regularization term ($L_2$ regularization)
My Question is: Does anyone know anymore corresponding pairs like this (likelihood = loss function or prior = regularization)? Is there maybe some list of well known connections somewhere?
And more generally: Given an objective loss and regularization function, when can I find a fitting likelihood and prior distribution, s.t. the maximization of the posterior distribution corresponds to my objective.
Answer:
Another such pair is Gaussian data generating process (which gives the same loss function as the one given in the question) along with Laplace Distribution as prior for the parameters. It gives the L1 norm regularizer.
As far as I know, there is no formal way to discover such links (quite like the conjugate prior for a distribution).
Answer: The prior appearing in the loss function is a general idea not limited to linear regression. It is simple to understand. Assume you do some Bayesian inference with a prior $p(\theta)$ and a likelihood $l(x,\theta)$. The the posterior is:
$$P(\theta,x)\propto p(\theta)l(x,\theta)$$
Assume you want to find the mode (maximum) of the posterior (or equivalently its $\log$) as an estimator for $\theta$. You can just write:
$$\log(P(\theta,x))= \log (p(\theta))+\log(l(x,\theta))+c$$
That's how you get a two part loss function. This works for any kind of model, not only linear regression. Another classical example is using a Laplace prior and this is known as $L^1$ regularization. Gaussian prior is $L^2$ regularization.
With a Gaussian prior and Gaussian model (linear regression), the posterior is Gaussian and thus the mode happens to be the same as the mean. That's why this "mode estimator" is especially natural in Bayesian linear regression.


Existence of a non constant analytic function

Question: Assume $f:\mathbb{D} \to \mathbb{C}$ is non-constant analytic function. Which of the following are possible:

i. $|f(z)|=1\ \forall\ z\ s.t. 0 < |z|<\frac{1}{2}$

ii. $f(z)=0$ for infinitely many z such that $0 < |z|<\frac{1}{2}$

iii. $f(z)\in \mathbb{R}\  \forall\ z\ s.t. 0 < |z|<\frac{1}{2}$

iv. $|f(z)| < |z|\ \forall z\ s.t.0 < |z|<\frac{1}{2}$

ii. is false as $f^{-1}\{0\}$ is a set with limit point and hence by identity theorem $f$ is constant.
iii. is false as $f$ is open map and $f(0<|z|<\frac{1}{2})$ is not open.
What about i. and iv?
Thank you.
Comment: (iii) you don't know that's closed, you know it is not open.
Comment: Hint: for 1st one use Cauchy Riemann equations
Comment: I am sorry but I didn't really get your hint.
Answer: i. $|f|$ attains its maximum value of the disk of radius $\frac 1  2$ around $0$. By MMP $f$ is a constant $c$ on this disk. This implies that it is a  constant on $\mathbb D$ also. [Apply Identity Theorem to $f-c$].
1v. $f(z)=\frac z 2$ satisfies this inequality.
Comment: but how do I know that 1 is the maximum value. Why it can't be more than 1?
Comment: sorry I made an error in the last option. It's strict inequality.
Comment: @Naman That make little difference. Just divide by $2$.
Comment: yeah...that's fine...but I didnt follow i.
Comment: Do you know MMP (Maximum Modulus Principle)?  @Naman
Comment: understood....thank u
Answer: For first one:
If you consider $f = u + iv$ then first condition implies that $u^2 + v^2=1$ then by partial differentiation we have
$$
u_xu+v_xv = 0
$$
and
$$
u_yu+v_yv=0
$$
Now use Cauchy Riemann equations $u_x = v_y $ and $u_y = -v_x$ and get a contradiction.
Third one also very easy to do with the help of C-R equations. Observe that third condition implies that $v=0$ and consequently $v_x = v_y = 0$. Further by C-R equations we have $u_x = u_y =0$ which would imply that $u=0$ and ofcourse this is a contradiction.
Answer: Your A to (iii) is right but your reason is wrong. If $f$ is not constant on $E=\{z:0<|z|<1/2\}$ then its image is non-empty and open in $\Bbb C$ (as you said), but no non-empty subset of $\Bbb R$ is open in $\Bbb C.$
Another way, with Re$(f)=u$ and Im$(f)=v.$ If $v$ is $0$ on $E$ then  $u_x=u_x+iv_x=f'=-iu_y+v_y=-iu_y,$ so $f'$ is both real and imaginary so $f'=0$ on $E$. And $E$ is a connected open set. So $f$ is constant on $E$.
Comment: thanks...I made the changes.


NSRegularExpression error: Get into when false

Question: I have a problem with NSRegularExpression. I'm sure that is my mistake, but i can't figure it out. I have this code:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern: nextModelName
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];
[regex enumerateMatchesInString:objTmplName options:0 range:NSMakeRange(0, [objTmplName length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    NSLog(@"objTmplName:%@ nextModelName:%@",objTmplName,nextModelName);
  }];

And the output is:
2012-07-30 10:59:48.779 MyApp[8470:707] objTmplName:yaoygo nextModelName:\w*
2012-07-30 10:59:48.799 MyApp[8470:707] objTmplName:yaoygo nextModelName:yo*
2012-07-30 10:59:48.808 MyApp[8470:707] objTmplName:yaoygo nextModelName:yaoygo

Why it get into when objTmplName = yaoygo and nextModelName:yo* ?
What i want to do is when my objTmplName start with "yo..." it will be true, otherway this should be false. For example:
yooygo TRUE
yaygo FALSE
yayoyoyo FALSE

Answer:
2012-07-30 10:59:48.799 MyApp[8470:707] objTmplName:yaoygo nextModelName:yo*
Why it get into when objTmplName = yaoygo and nextModelName:yo* ?

yo* means:
y followed by any number of o (possibly none).
If you want to force at least one o, use:
yo+

After your edit to the question:
try and use the regex: ^yo.*
Comment: I'm update my question. This is not what i excatly what to do here.


Web application is seemingly not running when deployed in websphere

Question: I have a war file which I deployed and ran in tomcat. Then I deployed it in websphere from admin console. The status of the webapplication is seen as started along with the built-in web applications such as "ivtApp", "query", etc. Now from this link:
Heading
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.nd.doc%2Finfo%2Fae%2Fae%2Frins_portnumber.html
It looks like the port number for web application is 9080 for http. I tried to run the application using the link:
http://{localhost}:9080/spring3HibernateMaven/index
(I am using "{" because this website didn't allow typing localhost)
the context root being spring3HibernateMaven. And I get page not found error in the browser. So I thought there must be something wrong with my web application. Hence I tried to run their web application:
http://{localhost}:9080/ivtApp
Which gives the same error. Even
http://{localhost}:9080/
gives the same error. I assume it should show something for this url as is shown from tomcat.
So how can I run the/any web application in websphere? FYI, I downloaded the latest version of websphere from their website.
Thanks
Comment: Did you install the WAR as part of an EAR? Did you install the application using the admin console or using wsadmin? If you go to Applications > Application Types > WebSphere enterprise applications > your-app > Context Root For Web Modules, you should be able to see the context root that was used for your application.
Comment: Thanks for replying. I deployed the war by selecting the new application. I used the correct contextpath, as I copied the one from running tomcat webapp and using it for the websphere webapp.
Comment: You can not assume the port you are using is 9080. You are looking at a document for WAS 6.0 and even then the port is reconfigurable. You said you downloaded the latest version of WebSphere, which is version 8.5, several major versions later. You need to figure out for sure what port you are using. Do you have access to the administrative console?
Comment: Hello, thanks for your reply. I created a third profile AppSrv03 and the port for this is 80. I opened http://localhost/ without a problem. However, my deployed war file is still not being shown in the browser with url http://localhost/spring3hibernate. Still no page found :(.
Comment: I meant the the port for the webserver of the profile is 80.
Answer: ivtApp has context path "ivt", so you need to use host:9080/ivt
Btw, you can find context path setting in websphere\application control panel


Can't get favicon/shortcut icon to show up

Question: Despite trying multiple times various favicon location approaches:

at theme root
at files root
uploading the file through admin/appearance/settings
typing in a path of manually uploaded icon

always clearing cache afterwards, I cannot get my shortcut icon to show up.
I tried pasting into the browser's address bar the path of the ico file so to force an update, but I got a generic server error that there was no such file at this location. When I looked into the generated source code, I could not see neither my file nor the default drupal icon. So I'm completely lost.
I'm close to modifying the html.tpl.php by pasting the link tag manually or through drupal_add_html_head_link but I'm puzzled because it happened to me for the first time. Any clue what else I could double-check?
Comment: it should work, try running cron too and check with a different browser to see if it works
Answer: Just went through this Drupal favicon mess myself :) Hope this helps:

When I looked into the generated source code, I could not see neither my file nor the default drupal icon.

This is the first problem to solve – getting at least the default blue Drupal drop icon to show again. For this:

There is both a global "Shortcut icon settings: Use the default shortcut icon." setting at admin/appearance/settings and an equivalent one for each theme that can be enabled on that page. In all these forms, tick this setting and save the form. If neither this box is ticked nor a valid path entered into the "Path to custom icon" field of the form whose settings "win" the overwriting, Drupal will interpret this as "do not show any favicon".
Make sure Drupal's default favicon is readable by your webserver user: visiting http://example.com/misc/favicon.ico for your domain should show that icon. If it is not accessible to the web server, Drupal will detect that and not even render a shortcut icon header entry.
Cache clearing should not be necessary, but who knows. If still no favicon shows up, do a drush cc all and check again. Check the HTML source code, not what the browser shows, to prevent issues with the browser cache.

Now that the "blue drop" Drupal default favicon shows up again, let's configure your own one. The surefire way is this:

Navigate to the settings screen admin/appearance/settings/theme-name of your "most-sub-theme" applying to the page where you want your favicon to be in effect. So if you have a theme A, a sub-theme of A called B and a sub-theme of B called C, go to admin/appearance/settings/c.
Click "Shortcut icon settings: Browse" and upload a custom favicon. It will end up in the files root directory of your default site.
Load your site again, and it should show your favicon now, at least in the HTML source. If not, try a full cache clear, though that never helped in my case.

Explanations:

Choosing the most-sub-theme. This is necessary because the admin/appearance/settings form is just the global setting for all themes, and values entered here will be overwritten by each theme and sub-theme down the chain of themes. So the setting in the "most-sub-theme" will win. Plus, it seems there is no option to not enter a value into the "Shortcut icon settings": when you keep the "Path to custom icon" field empty, Drupal will not fall back to the theme higher up in the chain, but interpret it as "do not use any favicon".
Uploading, not typing in a path. There seems to be a Drupal bug with the "Shortcut icon settings" form: it will only accept typed-in values for the "Path to custom icon" field after uploading an icon before. You can then modify the value in that field and it will modify what favicon is used, but when you delete the value, save the form, enter a new value and save again, no favicon will show up even though the same value worked before.
Base path when typing in a filename. If you use the above trick to upload first, then modify the value in the "Path to custom icon" field, also remember that the base path for filenames entered here is the files directory of your default site. So, sites/example.com/files/ from web document root. You can be sure it's the right one by checking that your immediately before uploaded favicon arrived in this directory. (If the referenced file exists, Drupal will also accept without form validation errors if you type in a path starting at document root (like sites/all/themes/my_theme/favicon.png) – but I never could get favicons referenced this way to show up.)


statistical difference between four groups with age data

Question: I have four groups and in each group I have 12 cases.
<code>G1  G2  G3  G4
914 723 948 990
942 698 843 990
954 739 849 1020
932 775 918 990
930 788 961 1050
904 717 852 1050
878 751 864 1080
957 794 840 1110
878 770 852 1110
868 751 854 1110
889 734 920 1110
888 753 884 1140
</code>
the observations represent age in days.
How can I do statistic controlling of distribution of age between these 4 groups?

For example, how can I say whether G4 is older than the others?
Which post hoc test is needed for this type of data?
Solutions could be brought via excel, SPSS or R.
Answer: You can calculate mean and standard deviation for each group (easily done in each of your suggested software) and then use a Student's T-test to check if they vary significantly. This, too, can be done in Excel, SPSS and R.


cron create output file only if there is output

Question: I have a cronjob that calls a script. I want the output to be placed in a log file. The problem is that the log-file is created even if there is no output.
Since the job runs once an hour, and mostly has nothing to do. I am ending up with a lot of 0 byte files.
I could probably append to a single log file, but I wonder if there is a trick to use to prevent the log-file being created or to delete it if it is empty. (I don't really want to run a second cron-job to clean up after the first one)
A complication is the fact that the log filenames have a date/time appended to them. The line in crontab looks a bit like this:
<code>/your/script.sh config.txt > outfilepath_`date +\%Y-\%m-\%d_\%H\%M`.html
</code>
I guess that means I have to store the date in a variable first and then check if that file was created/empty. So if I take Stone's answer I end up with something like:
<code>logfile=outfilepath_`date +\%Y-\%m-\%d_\%H`; your/script.sh config.txt > $logfile; if [! -s $logfile]; then rm $logfile; fi
</code>
but I don't know if that's possible inside crontab
Comment: It is possible in crontab.:)
Answer: You can write something like this:
<code>/your/script > /your/log/file; if [ ! -s /your/log/file ]; then rm /your/log/file; fi
</code>
Comment: This is kind of what I want, but a bit like cleaning up after the mess has been made. There isn't a neat way to 'redirect-only-if-output'? (similar to the way an email is only sent if there is output).
The process is complicated by the fact that the logfile name has a date appended (see edit)


A,B and C can do a piece of

Question: A can do a piece of work in $10$ days, B in $20$ days and C in $30$ days. If A is assisted by B and C turn by turn in alternate days, in how many days the work might have been completed?
My Attempt:
In $1$ day, A can do $\frac {1}{10}$ work.
In $1$ day, B can do $\frac {1}{20}$ work.
In $1$ day, C can do $\frac {1}{30}$ work.
Now, how should I complete?
I know the question already has an answer, but I could not understand that. Can anyone give me a clear idea?
Comment: Fine, you have made a start. So now continue. On the first day what proportion of the total work is completed? What about the second day?
Answer: On the first day, $\frac{1}{10} + \frac{1}{20} = \frac{3}{20} = \frac{9}{60}$ work gets done. On the second day, $\frac{1}{10} + \frac{1}{30} = \frac{4}{30} = \frac{8}{60}$ more work gets done, making $\frac{17}{60}$ in total. Total work continues to increase alternatingly by $\frac{9}{60}$ and $\frac{8}{60}$, and on the third and following days we have $\frac{26}{60},~ \frac{34}{60},~ \frac{43}{60},~ \frac{51}{60},$ and $ \frac{60}{60}$ work done in total, respectively. The work is therefore completed after $7$ days.

A,B and C can do a piece of


What do results of Linux time wrapper tell me happened to this cp command?

Question: My view on this issue is from the developer side. I write the code that gets placed on a RHEL virtual machine running as one of many in an enterprise system. The filesystem being used is a remote, network attached storage device.
We had some high variability on simple commands during batch. So we set up a test to get more information, but now I don't know what we've found.
We ran the following  command every 30 minutes and logged the output. It's a copy of a 6 gb file.  What I see is elapsed time jump from 11 seconds to 190 seconds when the system is busy running lots of jobs and this test command gets low CPU time.
What I can see is that column "I" (filesystem inputs) gets populated when the CPU is low, but not when it's high. Column "w" (involuntary swaps) is also much higher.
My question is, what is happening to this job/command that forces it to run SO MUCH LONGER when the CPU time goes down? Does the swap in/out store all of that data on some other device that is much slower? Generally, what happens during a swap in/out?
Command being run:
<code>/usr/bin/time -a -o filename.txt cp file.txt fileCopy.txt
</code>

Date
Time
e
S
U
P
c
w
I
O

3/14/2022
5:19:02
64.9
16.23
1.03
26%
3005
29210
12000016
12000000

3/14/2022
5:49:02
12.7
11.63
0.79
97%
2069
76
0
12000000

3/14/2022
6:19:02
100.39
14.74
0.78
15%
1034
29925
12000136
12000000

3/14/2022
6:49:24
191.32
18.86
0.94
10%
3374
36164
12001024
12000000

3/14/2022
7:19:02
71.61
15.61
0.88
23%
1610
30316
12000296
12000000

3/14/2022
7:49:02
70.73
17.5
0.91
26%
1408
29540
12000072
12000000

3/14/2022
8:19:02
10.95
9.89
0.7
96%
1709
75
0
12000000

3/14/2022
8:49:02
11.01
10.22
0.73
99%
239
85
0
12000000

The column descriptions from the man page for /usr/bin/time
<code>e   Elapsed real time (in seconds).
S   Total number of CPU-seconds that the process spent in kernel mode.
U   Total number of CPU-seconds that the process spent in user mode.
P   Percentage of the CPU that this job got, computed as (%U + %S) / %E.
c   Number of times the process was context-switched involuntarily (because the time slice expired).
w   Number of waits: times that the program was context-switched voluntarily, for instance while waiting for an I/O operation to complete.
I   Number of filesystem inputs by the process.
O   Number of filesystem outputs by the process.
</code>
Answer: P in this context means the ratio of CPU time this job got over total time elapsed. Near 100% means almost all of the time it was on CPU, and so was CPU constrained for those runs. In contrast to the other runs where something else was the limiting factor. More system (aka kernel) time than system time, as is typical of I/O heavy tasks.
Given the workload was copy a 6 GB file, we can infer the 11 second runs averaged more than 0.5 GB writes per second. O column confirms the same number of writes each time, consistent with a simple copy one file process.
Input column has major swings, however. Slow runs have about equal reads as writes. But the fast runs don't do any reads! I assume the file is still cached in RAM from when it was last read. DRAM is much faster than even solid state storage. Which is a great speed boost, until under memory pressure the OS drops the cached data, and has to read from slow storage again.
So this is a 200 second task, which occasionally can take 12 seconds. Likely due to Linux page cache.

Finding root cause of a performance problem often requires a deeper understanding of the overall system, beyond any particular set of metrics.

The filesystem being used is a remote, network attached storage device.

Note your copy thing is over networked storage, so it could also be anything on the remote system or the network in between. Remote storage performance. Network (probably IP) speeds and utilization. Or it could be local to this VM, where the guest is competing for resources with everything else running on your infrastructure.
Always possible to go deeper into how things work. Does network storage (NFS?) matter at all, or do you also see this for local disk? 0.7 seconds of user CPU time is quite a bit of work actually, how much is accounting to manage many system calls? What does CPU busy actually mean when most of this is waiting for slow memory and very slow storage? Not easy questions to answer, however perhaps no need to dig too deeply once the thing is performing adequately.
Comment: "I assume the file is still cached in RAM from when it was last read." - This makes total sense when I really sit and look at the situation as a whole. It may also lead me to a way to fix this particular bump in the processing time.

It's a pig in a python situation where we are getting a massive 16gb file, encrypting/compressing it for use later, then decrypting/expanding it when needed. THEN sorting it.

The other relevant files are less than 800 MB, so I might be able to put those steps back-to-back and remove the need for so many operations.
Comment: How would you like to be credited when I take this up the chain?
Comment: Maybe the decryption and processing can happen in a pipe, if stream access is possible, but possibly not.  Or just throw memory and fast storage at the problem.    As to attribution, my name and a link to this, as typical for the CC BY-SA license for all Stack Exchange stuff  https://stackoverflow.com/help/licensing    Maybe you would not get the opportunity to adapt and share, but if say you ever write an engineering blog post about interpreting the humble time command, the license requires attribution.


File/function that is executed when I open node from view

Question: I have created view for displaying the nodes. I want to know which function/file is executed when I click on the node listed in the view table. I want to add some code to the file when the node information is loading. Can anyone suggest me the function/file where i'm supposed to do the changes?
Comment: Your question is too vague to answer. Drupal goes through a whole bootstrap process with a lot of code executing in order to process the request. You can hook into nodes loading via [hook_node_load](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_load/7). please never ever alter any existing code that is not your own. You need to always hook into code in your own module or overridden theme. Explain what you are trying to achieve in greater detail and perhaps someone can assist you.
Comment: Please don't ask duplicate questions.
Answer: You've two ways to afford the problem:
Site building way
If you're using a wiew of rendered nodes (usualy teasers) you can redefine the layout, tags, fields, etc. on admin/structure/types/manage/YOURCONTENTYPE/display/teaser
If you need more options try display suite and fences modules:
https://www.drupal.org/project/ds
https://www.drupal.org/project/fences
Developer way
Editing your view, on the "advanced" colum, "other section" you've the "templates" there the "Theme: Information" item.
There you've the name of the templates the view is using.
You can redefine then on your custom them.
EXTRA BALL: Common sense way
Probably a mix of two others are que best option


Mvvmcross support NotifyPropertyChanged event where event args contain the old value?

Question: There is a UIHealthBar which is binded to a viewmodel property that is changed from 5 to 10. I would like to animate it with filled color from a old value (5) to new value (10). How can I do it in mvvmcross with a better approach ?
Answer: This sounds like it could be done with a pair of viewmodel properties - perhaps a tuple that is always changed together - e.g.
public class MyViewModel : MvxViewModel
{
    public MyViewModel()
    {
        // subscribe for health updates here
    }

    public class HealthTuple
    {
        public double Old {get;set;}
        public double New {get;set;}
    }

    private HealthTuple _health;
    public HealthTuple Health
    {
       get { return _health; }
       set { _health = value; RaisePropertyChanged(() => Health); }
    }

    private void OnNewHealth(HealthMessage message)
    {
        Health = new HealthTuple() { Old = _health.New, New = message.Value };
    }
}

Your custom UIView - the UIHealthBar can then expose either a single property or two properties and you can bind these to the ViewModel's Health values. Drawing/animating the display is then 'normal UI kit work'
Comment: I see mvvmlight code that implement this directly on "void RaisePropertyChanged(string propertyName, T oldValue, T newValue, bool broadcast)"
Comment: you can use inpc to send a custom propertychangedmessage if you want to - but none of the standard windows controls know what to do with that extended message, nor do any of the standard android or ios controls that i've extended for mvx. If you think it's important to support this, then by all means implement it yourself - it's just a custom eventargs class. you are also welcome to open a feature request on github - but I don't personally expect many use cases to use this, so I don't personally expect this to be high priority
Comment: actually looking at https://github.com/ericschultz/GalaSoft.MvvmLight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/ObservableObject.cs I don't think mvvmlight actually sends the oldValue and newValue to the UI either
Comment: I am look at [https://github.com/ericschultz/GalaSoft.MvvmLight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/ViewModelBase.cs](https://github.com/ericschultz/GalaSoft.MvvmLight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/ViewModelBase.cs), I think it can be used instead of touching the mvvmcross base.


theming field collection in node add form

Question: I have themed node/add form of a special content type using the following instruction:
https://www.drupal.org/node/1092122
and I have changed this form to a table.
Now I'm struggling with a field collection with unlimited number of item.
As I have hidden the default form of displaying node/add form when I click on 'add another item' of the field collection, nothing happens.
What I want is to show the next form of the field collection as the next row of the table ready for the user to fill it out.
Any help would be appreciated.
thanks in Advanced.
Answer: You'll need to hook into the field collection entity on insert, and add a callback function to trigger the new row to appear via ajax in your table.
Check out field_collection.api.php in the field collection module for a full list of field collection api calls/methods.
Also, you may find the responses to this previous post as a good indicator of the direction to take: Perform actions on field collection insert or update
Comment: the problem is in the previous step of inserting. I don't have a form to fill and submit. I just want to show the form of new field collection entity as a table.


SQL Error: ORA-00918: column ambiguously defined

Question: Please help me find out what I'm doing wrong here:
Error starting at line : 1 in command -
CREATE VIEW VW_ROUTE AS
  SELECT ROUTE_NAME
       , FARE
       , DESTINATION
       , ROUTE_ID
       , STOP_NAME
       , TERMINUS
       , NUMBER_OF_STOPS
  FROM STOPS S
    LEFT JOIN ROUTE R
        ON S.ROUTE_ID = R.ROUTE_ID
 WHERE NUMBER_OF_STOPS > ('1')

Error at Command Line : 5 Column : 10
Error report -
SQL Error: ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:

Comment: Post the table schemas that you are joining. I assume you reference a column that exists in two tables and you need to use a table reference (alias).
Answer: You have the same column name in both table. Add aliases.
CREATE VIEW VW_ROUTE AS
SELECT ROUTE_NAME
       , FARE
       , DESTINATION
       , S.ROUTE_ID          -- ROUTE_ID exists in table STOPS/ROUTE
       , STOP_NAME
       , TERMINUS
       , NUMBER_OF_STOPS
FROM STOPS S
LEFT JOIN ROUTE R
  ON S.ROUTE_ID = R.ROUTE_ID
WHERE NUMBER_OF_STOPS > ('1');

The good practice is to use aliases in all occurences to avoid ambiguity.
Comment: +eleventy-million for the statement "use aliases in all occurrences to avoid ambiguity"!


Exercises to get beter at rhythm (piano)

Question: I am 26 years old and am learning the piano on my own. I haven't started to learn sheet music yet. The way I practice is by looking at videos of other people teaching how to play piano songs.
At first, I found it difficult to play with both hands, however gradually over time, this is becoming easier.
My current problem is that I notice my rhythm / rests isn't good, the songs I learn from video, I find it difficult to play in rhythm. I can't think myself of a technique I can use, but I assume it would involve counting in my head, while I'm playing.
And also I find it sometimes hard to find out how long to keep a note pressed, since in the videos it isn't really clear sometimes, I usually start counting how long they press them, to get an idea.
What can I do to get better at rhythm and also is this way of learning Piano bad? I do plan to get lessons at end of this year, but I thought I practice on my own for now.
Comment: Have you tried using a metronome?
Comment: No, I haven't used a metronome yet.
Comment: That might help
Comment: What kind of videos? How are they "teaching"? I usually discourage learning from video tutorials (about *any* subject), as they often are too generic and unreliable, and for performing arts that's even worst, as teaching those subjects should be normally *tailored* on the students. Then, keeping track of the duration of notes can be tricky: unlike other instruments, piano has not a constant sustain, and sometimes it's not possible to hear when a note actually ends; start by focusing more on the actual rhythm ("when the note should be played"), play along with the video and then on your own.
Comment: Just to be sure: when you say "I usually start counting how long they press them", what do you use as a reference for your counting? Also, as already said in an answer, if you want to count while playing, count out loud. Counting in your head is **not** the same thing, especially if you're a beginner.
Comment: @musicamante videos like: https://www.youtube.com/watch?v=ZR8Zd3F4mC0
Comment: @OS while it might seem an easy piece, that is not. While technically and conceptually it is not "that hard", consider that even professional musicians spend days or even weeks to "get it right" (obviously, they do that for many reasons, most of which are to do things that are almost undistinguishable from "normal people", but that's another story). Considering that you're already planning to get lessons in the near future, I'd suggest you to avoid losing time with that kind of things, and focus more on other basic principle (including timing, which is maybe the most important aspect music).
Answer:
I assume it would involve counting in my head, while I'm playing.

Count out loud while playing. Make sure you count beats correctly for the meter. Basically, if the meter is common time 4/4, count "1 2 3 4" on the quarter note beats. If counting shorter rhythms like eight notes count `"1 and 2 and 3 and 4 and ". The beat gets the number count. Look up some videos or articles about meter and counting.
A metronome is good too.

I find it sometimes hard to find out how long to keep a note pressed, since in the videos it isn't really clear...

Those video are probably various piano rolls or scrolling graphics, right? Colorful sparkles, bubbles popping, etc. etc.
Those aren't music notation, it's eye candy. I know a lot of people use them to learn music, but you are pointing out one of the problems, rhythm isn't given precisely.
Lot's of people are intimidated by staff notation. Admittedly it does take a lot of training to read well. But in regard to rhythm particularly proper staff notation works well. Barlines, note grouping, visual spacing, etc. make a lot of rhythms fairly easy to read.
You can use material like this...

Czerny, Exercises for Beginners
Peterson, Jazz Exercises

That will help with counting aloud and reading notation generally.
Then you can either go back to the piano videos with better coordination. Or, if you get comfortable with notation, you can start reading sheet music for songs.
Comment: "Count *out loud* while playing." Yes, absolutely. People (even some musicians) don't realize how *hard* is to be able to accurately keep track of time only in your head. The usual response is "but I'm doing in my head, that's the same".
Answer: Answering your last question first. It can be bad. As a beginner, you won't have much idea of the quality of lessons, and when you come unstuck, there's no-one to ask at that moment, as there will be with a real live teacher.
As far as rhythm is concerned, the first port of call is usually a metronome - particularly one which doesn't just click, but can ping on the first beat of each bar. A visual helps too, so if it flashes as well, what a bonus!
A lot of us find the metronome very boring to play to, and a way round this is to use drum tracks. Drum machines aren't dear now, and you could probably pick up a pre-loved electronic keyboard with drums on for a drink or two.
Counting internally is essential for any muso, so utilising body movements is encouraged. Nod head, tap foot, shrug shoulders, anything which will help to keep all of you in time. Being able to keep a steady rhythm is also important, and a trick here is to listen to some music, get the beat going, turn down the volume, and hear how well you have kept the beat when you turn it up again.
Answer: Disclaimer: I'm neither a qualified piano teacher nor to good of a player. I'm just someone who had a few years of classical piano lessons and also struggled with building a sense of rhythm.
Here are two things that helped me improve:
The first thing to try is to play with a metronome. But don't force yourself to play everything with the metronome. Only turn it on for exercises or pieces that are simple enough that you don't have to think what or how to play. Ideally pick a sufficiently shot repeating pattern, like immitating a kick-snare drum pattern with a bass note in the left hand and a chord in the right (keep the chord progression as simple as necessary). This way you can make sure to focus on your rhythm and your rhythm only. Also, don't worry about making mistakes. Just try to keep rhythm.
While the metronome works for many people, it only got me so far. When I tried jamming with some friends in a rock/jazz context, I realized that I still had considerable trouble keeping a straight rhythm. Around the same time I had bought a midi 4x4 pad controller and I tried to learn a bit of finger drumming. As it turns out, practicing finger drumming really helped rectify my unevenness in piano playing. I can only recommend it, especially if you're planning to play in a band.


Variance of a row-vector?

Question: I have calculated the following vector
$$\begin{bmatrix} \frac{-1}{\sigma^2} \sum_{i=1}^n (X_i - \xi), \frac{n}{2\sigma^2} - \frac{1}{2\sigma^4} \sum_{i=1}^n (X_i - \xi)^2 \end{bmatrix}$$
Each $X_i$ is iid normal with mean $\xi$ and variance $\sigma^2$.
I now want the variance of this vector. I have the solution at hand, but don't quite understand the calculations. Do we create a matrix where we take variance on the diagonals, and covariances off the diagonals? If so, how do I calculate covariances of this tricky-looking thing?
Comment: Is the second component supposed to be $\dfrac{n}{2\sigma^2}$ or $\dfrac{n}{2}\sigma^2$?
Answer: In principle a random vector $\overrightarrow{Y}=\left(Y_{1},\dots,Y_{n}\right)^{T}:\Omega\to\mathbb{R}^{n}$
has no variance but has a covariance matrix $\Sigma=\left(\Sigma_{i.j}\right)$
with entries: $$\Sigma_{i.j}=\text{Cov}\left(Y_{i},Y_{j}\right)$$
If $U,V$ are random variables and $a,b,c,d$ are constants then: $$\text{Cov}(aU+c,bV+d)=ab\text{Cov}(U,V)$$
Also we have: $$\text{Cov}(U,U)=\text{Var}(U)$$
In your case it is quite handsome to substitute: $$U_i:=\frac{X_i-\xi}{\sigma}$$ which has standard normal distribution, so has mean $0$ and variance $1$.
These facts can simplify your calculations considerably.

Variance of a row-vector?