Prove $\frac{11n^3 + 25n}{6}$ is an integer

Question: Prove by induction that for every integer n, $\frac{11n^3 + 25n}{6}$ is an integer (i cant post the actual given expression since it might cause academic offence). I have only worked with proofs with natural numbers so induction was quite linear. For integers how do i go about showing that it is an integer. I tried cases where n = 1, 2, 3, -1, -2, -3 and it is all true but i dont know how to start it. Any insight would be appreciated. Thank you for your time.
Comment: can you show that it's true for $-1$ and if it's true for $-n$ then it's true for $-(n+1)$?
Comment: Unfortunately, the details of a proof will depend intimately on the concrete expression. We can give some general pointers, but it will mostly be things you have probably heard before.
Comment: It may be easiest to phrase the induction based not on the actual *value* of the integer, but rather on the *absolute value* of the integer.  Show that if $|x|=k$ then $f(x)$ is an integer.  Then use this to show that if $|x|=k+1$ that $f(x)$ is an integer.  So $f(0)$ being an integer simultaneously implies $f(1)$ and $f(-1)$ are both integers.  These being integers implies $f(2)$ and $f(-2)$ are both integers, etc...  Again though, more specific advice depends on the actual expression.
Comment: Addition, subtraction and multiplication of integers are always integers. For division you need to prove divisibility. You can use:  $P(0) \wedge [\forall n>0 (P(n)\implies P(n+1) \wedge P(-n)\implies P(-n-1))]$
Comment: @Arthur I added the expression
Comment: @JMoravitz i added the expression
Comment: I recommend [this answer](https://math.stackexchange.com/questions/19485/dominoes-and-induction-or-how-does-induction-work/19488#19488) for any induction question
Comment: For that particular expression you can write $$\frac{11(n+1)^3 + 25(n+1)}{6}=\frac{11n^3 + 25n}{6}+6+11\frac{n(n+1)}{2}.$$
Comment: Induction can "go down" just as easily as "go up".  If $P(k) \implies P(k\pm 1)$ and $P(c)$ is true for any $c \in \mathbb Z$ then $P(n)$ is true for *all* $n \in \mathbb Z$.  (Because induction goes up, it is true for all $n \ge c$ and because induction goes down it is true for all $n \le c$).
Comment: Since it equals $(n-n^3)/6 + 4n+2n^3$ it suffices to prove $(n-n^3)/6$ is an integer and this is a FAQ, e.g. see the linked dupes.
Comment: No induction is needed. It suffices to prove that $11n^3 + 25n \equiv 0 \bmod 6$, that is, $11n^3 + 25n \equiv 0 \bmod 2$ and $11n^3 + 25n \equiv 0 \bmod 3$. Both cases are very easy to prove directly.
Answer: For your particular expression, $$f(n)=\frac{11n^3+25n}{6}.$$
We have the property that $f(-n)=-f(n)$, hence if $f(n)$ is an integer, $f(-n)=-f(n)$ must also be an integer.
Hence, you can focus on proving that for natural number $n$, $f(n)$ is an integer.
For base case, do it for $P(0)$.
Induction step: show that $P(n) \implies P(n+1)$
If you insist: show that $P(n) \implies P(n-1)$ as well. For this particular problem, once you find a relationship between $f(n+1)$ and $f(n)$, both directions should be similar.
I would actually recommend understanding the expression using modulo $6$ arithmetic besides induction.
Answer: Rewrite:
$$A=11n^3+25n=12n(n^2)-n(n-1)(n-2)$$
$A_1=(n-1) n (n+1)=6 k$
Because it is the product of three consecutive numbers.So A is always divisible by 6,so $A/6$ is integer. To show that by induction put $n+1 $ you get:
$A_1=n(n+1)(n+2)$
which is again a product of three consecutive numbers and is a multiple of 6, that is $A/6$ is integer for both n and n+1 so it is integer for every n.
Answer: Start anywhere.
If $n = 59$ then $\frac {11n^3 +25n}6 = \frac {11*59^3 + 25*59}6 = \frac {2260644}6 =376774$.
Now prove by induction that we can "go up". If $\frac {11n^2 + 25n}6$ is an integer then  prove $\frac {11(n+1)^2+ 25*(n+1)}6$ is an integer.
So $\frac {11(n+1)^3 + 25(n+1)}6 = \frac {11(n^3 + 3n^2 + 3n + 1) + 25n + 25}6=$
$\frac {11n^3 + 25n + (33n^2 + 33n + 36)}6= \frac {11n^3+25n}6 + \frac {11n^2 + 11n + 12}2=$
$\frac {11n^3 +15n}6 + 11\frac {n(n+1)}2 + 6$.
Now $\frac {11n^3 + 15n}6$ is an integer. Ad as either $n$ or $n+1$ is even $11\frac {n(n+1)}2$ is an integer and $6$ is an integer.  SO the sum is an integer.
So you have proven if $n =59$ or $n$ is an integer that can be reached from $59$ by adding $1$ any number of times then $\frac {11n^3 + 25n}6$ is an integer.
Now prove by induction that we can "do down.   If $\frac {11n^2 + 25n}6$ is an integer then  prove $\frac {11(n-1)^2+ 25*(n-1)}6$ is an integer.
So $\frac {11(n-1)^3 + 25(n-1)}6 = \frac {11(n^3 - 3n^2 + 3n - 1) + 25n - 25}6=$
$\frac {11n^3 + 25n + (-33n^2 + 33n - 36)}6= \frac {11n^3+25n}6 + \frac {-11n^2 + 11n - 12}2=$
$\frac {11n^3 +15n}6 -11\frac {n(n-1)}2 - 6$.
Now $\frac {11n^3 + 25n}6$ is an integer. And as either $n$ or $n-1$ is even $11\frac {n(n-1)}2$ is an integer and $6$ is an integer.  SO the sum is an integer.
Wo we have proven if $n=59$, or if $n$ can be reached from $59$ by repeatedly adding $1$, or if $n$ can be reached from $59$ by repeatedly subtracting $1$, we have proven our result.
And that covers every integer.
....
We could simplify it.
Start with Base case $n=0$, have the induction step go "both ways" and prove for if true for $n$ then is true for $n\pm 1$.
That's do it.
====
or note: $\frac {n^3 + 25n}6$ is an integer if and only if $\frac {(-n)^3 + 25(-n)}6 = -\frac {n^3 + 25n}6$ is an integer.
So we don't have to prove for all $n$.  Just all natural $n$.
Comment: do you have to prove that $\frac{11n(n + 1)}{2}$ or can you just claim its an integer?
Comment: You have to prove it.  (And I did.....).
Comment: "And as either n or n+1 is even...."


What value will I get if not call setValueForKey first?

Question: I set up 3 UITextField in my viewController.
@property(nonatomic,retain) UITextField *line1;
@property(nonatomic,retain) UITextField *line2;
@property(nonatomic,retain) UITextField *line3;

And I try to get the value for key:
for (int i = 1; i <= 3; i++)
{
    NSString *fieldName = [NSString stringWithFormat:@"line%d",i ];
    UITextField *theField = [self valueForKey:fieldName];
    NSLog(@"TEXTFIELD : %@",theField);
}

And I got all UITextFields.
2015-03-03 10:32:32.776 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00e1c5c0; frame = (50 120; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00e1ae40>>
2015-03-03 10:32:32.777 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00f1b920; frame = (50 160; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00f1bb80>>
2015-03-03 10:32:32.777 KVCTEST[26691:1586602] TEXTFIELD : <UITextField: 0x7f9a00f1d330; frame = (50 200; 220 30); text = ''; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9a00f1d590>>

But if I changed the instance variable name to e.g. LINE1, LINE2, LINE3, exception will raise.
So is the key-value-coding will associate with the name of the ivar by default? And I don't have to setValueForKey first?
Comment: Your answer is under `Default Search Pattern for valueForKey:` in the [docs](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/SearchImplementation.html#//apple_ref/doc/uid/20000955)
Answer: Your answer to this can be found in the Apple documentation regarding KVC.

A key is a string that identifies a specific property of an object.
  Typically, a key corresponds to the name of an accessor method or
  instance variable in the receiving object. Keys must use ASCII
  encoding, begin with a lowercase letter, and may not contain
  whitespace.


Simple Form Query

Question: I'm using .Net 4.5.2 and MongoDB. What I want to make is just a simple query, which gets user list from table with given user FirstName , LastName etc. I wrote;
<code>   var Users = DataAccess.DbLoad<User>().Where(UserInfo =>
        ((FirstName == null || FirstName == "") || UserInfo.FirstName == FirstName) &&
        ((LastName == null || LastName == "") || UserInfo.LastName == LastName)
        ).ToList();
</code>
But if I write any surname and click for search, it doesn't bring any record but when I check db, I see it's there.
First Name Search Fiedl: null
Last Name Search Field: Lüle
Table: FirstName: "Ahmet", LastName: "Lüle"
How can I solve this? What is the problem?
Comment: you have to show your table data and search text in your question.Maybe your first name is not matching
Comment: "But if I write any surname and click for search, it doesn't bring any record but when I check db, I see it's there." I wrote.
Comment: "Maybe your first name is not matching " that's why I am asking you to show the data
Answer: Just remove the && condition if you want to search in both fields As follow:-
<code>  var Users = DataAccess.DbLoad<User>();
If(FirstName != null){
users=users.Where(u => u.FirstName.ToLower().Equals(FirstName.ToLower()))
}
 If(LastName != null){
users=users.Where(u => u.LastName .ToLower().Equals(LastName .ToLower()))
}
</code>
Comment: When I do this, it brings all data from table. It doesn't look for FirstName or LastName.

Simple Form Query


image.jpg instead of true.html in save dialog box

Question: I don't know how to add image in my snippet code but hope the question will bi clear anyway.
Want to save i.e. download imgb on disk.
Save As dialog appears but:

default name and format is true.html - I want it to be image.jpg or similar.
there is no any existing image in the list so I can't click and replace it with the new one.
if I write image.jpg inside Save As dialog the final result is not an image but a black rectangle.

Any help?

$('button').on('click', function(){
  let dl = document.createElement("a");
  dl.href = document.getElementById('imgb');
  dl.download = true;
  document.body.appendChild(dl);
  dl.click();
});

<button>CLICK</button>
Answer: I think this will work:
 $('button').on('click', function(){
      let dl = document.createElement("a");
      dl.href = document.getElementById('imgb').getAttribute("src");
      dl.download = true;
      document.body.appendChild(dl);
      dl.click();
    });

html:

    <button>CLICK</button>

Your element hat the class of imgb and not id, and you can access the href by using getAtribute
Comment: document.getElementById('imgb').getAttribute("src") try with src


How can I configure mail for Drupal 7 on an Ubuntu Raring EC2 node?

Question: I have installed apache2, php5, mysql5, php5-mysql and other supporting packages on an EC2 server, and when I started to install drupal7, it pulled in several packages including mail support, and presented me with a screen:
Package configuration
┌────────────────────────┤ Postfix Configuration ├────────────────────────┐
  │                                                                         │
  │ Please select the mail server configuration type that best meets your
  │ needs.
  │
  │  No configuration:
  │   Should be chosen to leave the current configuration unchanged.
  │  Internet site:
  │   Mail is sent and received directly using SMTP.
  │  Internet with smarthost:
  │   Mail is received directly using SMTP or by running a utility such
  │   as fetchmail. Outgoing mail is sent using a smarthost.
  │  Satellite system:
  │   All mail is sent to another machine, called a 'smarthost', for
  │ delivery.
  │  Local only:
  │
  │
  │                                                                         │
  └─────────────────────────────────────────────────────────────────────────┘
What is/are the preferred way(s) to get mail working adequately for Drupal on an EC2 server running Ubuntu Raring? I searched and didn't find a recommendation.
--EDIT (clarification)--
The paste above is from Ubuntu Raring's aptitude program, which is requesting to know how to configure Postfix (and, perhaps, other programs pulled in). I am not asking how to configure Drupal once I have a working local SMTP server. I am asking how to configure postfix, pulled in by aptitude on an attempt to install drupal7, so that I have a working local SMTP server. This is for an EC2 instance, and I don't know what is appropriate in EC2.
Answer: If you haven't got a smart host to relay mail through then you will have to choose "internet site" this will let you send mail from Drupal, Drupal will then just SMTP connect to the local mail server to send mail.
Comment: Please see the clarification above; I am trying to configure Postfix to presumably **get** a local mail server.
Comment: @JonathanHayward Please re read my answer I know what your after its quite clear. When you choose "internet site" as suggested in my answer you will have a fully functional local mail server that Drupal can send email through.


Drush from GitHub stopped working

Question: I have a Github clone of drush that has been working since it moved there.  I did a git pull this morning, and am now getting errors:

$ drush
Warning: require(/home/mpd/drush/vendor/autoload.php): failed to open
  stream: No such file or directory in
  /home/mpd/drush/includes/bootstrap.inc on line 1007
Fatal error: require(): Failed opening required
  '/home/mpd/drush/vendor/autoload.php' (include_path='.:') in
  /home/mpd/drush/includes/bootstrap.inc on line 1007

How can I fix this?
Comment: possible duplicate of [Undefined error: 0 OR Unable to load autoload.php. Drush now requires Composer](http://drupal.stackexchange.com/questions/105828/undefined-error-0-or-unable-to-load-autoload-php-drush-now-requires-composer)
Comment: Don't agree with the dup.  It's a totally different error.  I posted this question a day to two after the composer change and asked Greg to write a canonical response to it to prevent lots of similar questions.
Answer: Drush now uses composer for managing external libraries.  You can read about this in the GitHub issue.
If you don't have composer installed, you can follow the instructions on its project page.  Under Linux or OSX, you can do
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer

which will install it globally.
Once you have done this, you can
$ cd /path/to/your/git/clone/of/drush
$ composer install

This will download all of the external depencencies, and drush should start working.
See the drush project page for details.
Comment: This should totally be in the README.md (composer install)!! Very helpful!

Drush from GitHub stopped working


Anagram consecutive letters probability

Question: Say I have a word like resemblance with 11 letters and 3 e letters.
I know there are 11!/3!=6652800 anagrams for the word. (Not real words obviously.)
My question is what is the probability within those permutations that all three e letters are next to one another? Thanks.
Comment: Edit: I'm not specifically asking for a solution but formulas to use.
Answer: Hint: treat the three adjacent "e"s as a single letter so that you effectively have 9 letters. This will allow you to count the number of words such that the three "e"s are together, and you can then divide by $11!/3!$ to obtain the probability.
Comment: Hey, thanks. So would I do 3! divided by 11!/3!? Since e's can be ordered in 3! ways

Anagram consecutive letters probability


Android open AlertDialog from another activity

Question: I have read conflicting reports on here and other sites that say it is/is not possible to show an alert dialog from another activity. What I'm trying to do it this:
public class Options extends Activity {

    /** Include classes */
    SharedPreferences sharedPrefs;
    Preferences prefs;
    Location loc;
    LocationSQL locSQL;
    NetworkConnection netConnect;

    /** Declare buttons */
    Button bLocation;
    Button bRefresh;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.options);

        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(Options.this);

        /** Set the location for the user */
        setLocationPref();

        /** Refresh selection */
        bRefresh = (Button) findViewById(R.id.bRefresh);
        bRefresh.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        loc = new Location(getApplicationContext());
            try{

                loc.locationSelection();
            }catch (Exception e){
                Log.d("ERROR", "Catch " + e);
            }
            }
        });

        /** Location selection */
        bLocation = (Button) findViewById(R.id.bLocation);
        bLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            }
        });
    }
}

I then want to do some processing and if needs be call a AlertDialog box. But I get the error below. I understand that I'm using a context that has been destroyed if I'm correct? But I can't think how to solve this?
public class Location {

    private static final String Context = null;
    NetworkConnection nc;
    SharedPreferences getSharedPrefs;
    SharedPreferences putSharedPrefs;
    NetworkConnection netConnect;
    Options opts;
    Context context;

    public Location (Context arg)
    {
        context = arg;
    }

    public void locationSelection(){

        message();

    }

    public void message(){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("Your Title");
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

}

Catch android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
Many thanks for your help :-)
Answer: Instead of passing getApplicationContext() to your Location constructor try passing YourClass.this (so here, Options.this).
Also, what is this line of code?
private static final String Context = null;

Comment: thanks yea that seems to have helped, thought I had tried that :/ that line of code was a copy and paste error, it shouldn't have been there, thanks for the help!


OpenSearch range query not working correctly on dates?

Question: I have created an index using the OpenSearch.Client library and I perform queries on it, again using OpenSearch.Client.
I have noticed that some range queries do not work as expected on date fields.
I try to index and send all dates in UTC, just to be sure, but it doesn't help.
For example, this is a query I send (taken from the logs and tested via OpenSearch Dashboards):
POST documents/_search
{
  "query": {
    "bool": {
        "adjust_pure_negative": true,
        "boost": 1.0,
        "must": [
            {
                "bool": {
                    "adjust_pure_negative": true,
                    "boost": 1.0,
                    "must": [
                        {
                            "range": {
                                "copies.creationDate": {
                                    "boost": 1.0,
                                    "from": "2023-09-06T21:00:00Z",
                                    "include_lower": true,
                                    "include_upper": true,
                                    "to": "2023-09-29T20:59:00Z"
                                }
                            }
                        }
                    ]
                }
            }
        ]
    }
  }
}

...and here is one of the hits I get back in return, having the date field set at 2023-09-05T07:59:53.0770000Z:

What is going on here?
Both values seem to be in UTC (that's what I think the Z means), and the from in the query has a bigger value than the search result!
Increasing the query from value even more does eliminate the result, but I am not sure why it doesn't work as expected. Is there some timezone logic built into OpenSearch that screws things up?
This drives me insane.
Answer: I see that copies is an array of objects. Could it be that the array in your response includes also dates satisfying the range query, other than the one in your screenshot? If that is the case, you should look for nested queries.
Comment: Ah... I am so blind. Indeed, there are more than one copy in this case, some of which have a bigger creation date.


json_encode on a PHP array returns a string

Question: I've searched through the site and can't see a question quite like mine so I hope this isn't a copy.
So I've got a PHP script which is supposed to return a JSON array to my AJAX, and I want to use the array to generate a URL.
However, even though I'm pretty sure I've got an array on the PHP end, when I json_encode I'm getting a simple string out on the other end.
PHP Code:
    $n = 10;
    $all_titles = array();

    while($row = mysqli_fetch_array($result)) {
        $title = trim($row['Job Title']);
        if(array_key_exists($title, $all_titles)) {
            ++$all_titles[$title];
        } else {
            $all_titles[$title] = 1;
        }
    }

    arsort($all_titles);
    $top_titles = array_slice($all_titles, 0, $n);
    $title_list = array();

    foreach (array_values($top_titles) as $key => $val) {
        array_push($title_list, array_keys($top_titles)[$key]);
    }
    echo json_encode($title_list);

These array operations seem to be working so far, based on other tests I've done, so I'm pretty sure that $title_list is an array.
Here is my JS:
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        alert("Generated URL: " + URL_gen(xmlhttp.responseText));
      }
    }

And finally where the problem arises:
function URL_gen(list) {
    var url = list[2];
    return url;
}

I have varied the number in list[#] (list[0], list[1], etc.) and each one is a character, meaning list (which is passed in from onreadystatechange as the responsetext from the PHP function above) is a string, not a JSON array.
Any suggestions?
Comment: JSON is by *definition* a string.  It's a string format used to transport data.  Its format is a (strict) subset of JavaScript's array/object notation.  There is no such thing as a "JSON array".  You either have a "JavaScript array" or a "JSON string".
Answer: That's what it does. Returns a string. You need to parse it on the client side.
alert("Generated URL: " + URL_gen(JSON.parse(xmlhttp.responseText)));

Comment: Oh jeez. I'm so dumb, I was reading only through the json_encode documentation and I didn't look at what had to be done on the other end.
Thank you thank you thank you!


Sorting a string array in C

Question: <code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i,j;
    char temp[10];

    char **A;

    A=(char**)malloc(10*sizeof(char*));

    for(i=0;i<10;i++)
        A[i]=(char*)malloc(100*sizeof(char));

    printf("Enter the words you would like to sort :\n");
    for(i=0;i<10;i++)
        gets( *A );

    for(i=0; i < 10 ; i++)
    {

        {
            if(strcmp(A[i],A[i+1]) > 0)
            {
                strcpy(temp,A[i]);
                strcpy(A[i],A[i+1]);
                strcpy(A[i+1],temp);
            }
        }
    }

    for (i = 0; i < 10; i++)
        printf("%s\n", A[i]);

    return 0;
}
</code>
I am trying to write a C program that sorts a given list of 10 strings in alphabetical order. The program takes all of the strings but then it freezes and doesn't sort them. Can anyone tell me where I am going wrong? Thank you in advance.
Comment: `gets( *A )`, do you mean `gets( A[i] )`?
Comment: `if(strcmp(A[i],A[i+1]) > 0)` :  `a[i+1]` out of bounds when `i` is 9.
Comment: Yea I have changed it but when I compile the program i'm still getting the same error.
Answer: Your gets(*A) overwrites previous input. You should use gets(A[i]) instead.
Also you should use c builtin sorting fun for it: qsort(A,sizeof(char*),10,strcmp); instead of manual bubbling.
If you want it to do manualy, instead of copying strings you should simply swap pointers to them.
<code>for (int i=0; i<9; i++)
{
    for (int j=i+1; j<10; j++)
        if (strcmp(A[i],A[j])>0)
        {
            char* t=A[i];
            A[i]=A[j];
            A[j]=t;
        }
}
</code>
Comment: You could sort pointers to strings using strcmp comparator function.
Comment: I didn't want to revert to the built in sorting function. Instead I want to try doing it manually.
Comment: How would I implement qsort in this condition?
Comment: And to print them out I used for (i = 0; i < 10; i++) printf("%s\n",A[i]); , but I didn't get the sorted list back.

Sorting a string array in C


Retrieve the first result for each field on sql table

Question: I have a sql table like this:

code
label

1
row

1
row2

2
row3

2
row4

2
row5

I want to retrieve the first description for each 'code'
For ex:

code
label

1
row

2
row3

How can be the SQL query?
Comment: First - according to what?
Comment: with where CODE=xyz
Comment: How do you define which one is first, second, etc? Remember that in relational databases, tables do nor have inherent ordering.
Answer: There is an ability to enumerated rows within each code with order by label.
/*
WITH MYTABLE (code, label) AS
(
VALUES
  (1, 'row')
, (1, 'row2')
, (2, 'row3')
, (2, 'row4')
, (2, 'row5')
)
*/
SELECT CODE, LABEL
FROM
(
  SELECT ROW_NUMBER () OVER (PARTITION BY CODE ORDER BY LABEL) AS RN_
, T.*
FROM MYTABLE T
)
WHERE RN_ = 1

CODE
LABEL

1
row

2
row3


Relacionamento de duas tabelas MVC C#

Question: Como posso fazer uma consulta Lambda, tenho duas tabelas Permissão e Funcionário,
aonde ao informa o email do Funcionário, ele me traga as permissões do Funcionário, através do email que informei. Em SQL fica assim:
Select Funcionario.Email, Permissao.Nome'Nome permissao'
from Funcionario, Permissao
where Funcionario.PermissaoId = Permissao.PermissaoId

Uso Entity Framework, eu tenho esse método, e preciso retorna o nome da permissão do funcionário.
public override string[] GetRolesForUser(string username) {
    FuncionarioRepositorio _funcionarioRepositorio = new FuncionarioRepositorio();
    string sRoles = _funcionarioRepositorio.BuscarTodos().Where(c => c.Email == username).FirstOrDefault().ToString();
    string[] retorno = { sRoles }; return retorno;
}

Comment: acho que sua pergunta precisa de mais detalhes para ser respondida, você está usando o que para fazer a consulta? Entity Framework? Poderia mostrar o código (csharp incluido) de uma consulta que você faz atualmente?
Comment: Desculpa não ter esclarecido mais, uso sim o Entity Framework, eu tenho esse método, e preciso retorna o nome da permissão do funcionário.

`public override string[] GetRolesForUser(string username)
{
            FuncionarioRepositorio _funcionarioRepositorio = new FuncionarioRepositorio();

            string sRoles = _funcionarioRepositorio.BuscarTodos().Where(c => c.Email == username).FirstOrDefault().ToString();

            string[] retorno = { sRoles };
            return retorno;
      }`
Comment: Não sei se eu entendi direito. Esse método retorna o que deseja, mas está retornando dados a mais, é isso?
Comment: Poste também o método `_funcionarioRepositorio.BuscarTodos()`.
Comment: http://pt.stackoverflow.com/questions/51536/quando-usar-entity-framework-com-repository-pattern/80696#80696
Answer: Assumindo que você utiliza o Entity Framework e que você tenha as seguintes classes:
public class Permissao
{
    [Key]
    public int PermissaoId { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Funcionario> Funcionarios { get; set; }
}

public class Funcionario
{
    public int Id { get; set; }

    public string Email { get; set; }

    public int PermissaoId { get; set; }

    [ForeignKey("PermissaoId")]
    public Permissao Permissao { get; set; }
}

public class Repositorio : DbContext
{
    public DbSet<Permissao> Permissoes { get; set; }

    public DbSet<Funcionario> Funcionarios { get; set; }
}

Você pode fazer a query da seguinte maneira:
using (var db = new Repositorio())
{
    Funcionario funcionario = db.Funcionarios
        .Include(p => p.Permissao)
        .Where(c => c.Email == "email@example.com")
        .FirstOrDefault();

    Console.WriteLine(funcionario.Permissao.Name); // nome da permissão
}

Utilizei a versão Core do EF neste exemplo, o princípio permanece o mesmo para o Entity Framework 6.x.
Neste link tem outros exemplos e uma breve documentação de como carregar entidades relacionadas:
https://msdn.microsoft.com/en-us/data/jj574232.aspx
Notas:
a. É necessário oque você tenha um repositório com as duas entidades (DbSet).
b. Talvez seja necessário/mais adequado mapear o relacionamento das entidades através no método DbContext.OnModelCreating. Exemplo de como mapear entidades: http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx
c. A Query pode ficar significamente grande com a quantidade de campos das tabelas, então você pode incluir .Select ao final da expressão de busca se achar necessário.
Comment: EF7 não existe mais. Agora é o Entity Framework Core. Senti falta de um `public virtual ICollection Usuarios { get; set; }` em `Permissao`.

Relacionamento de duas tabelas MVC C#


SQL: Summarize Date Data by blocks of Time

Question: I have a data set of information that logs events as they happen; and I would like to be able to summarize that data over different time periods during the day.
My RAW data is simply time stamped with the system time of the event.
I have an SQL query that can calculate how many events happen in an hour period.
Example or RAW data over three days,
Time_Period             Count
------------------------------
29/07/13 08:00:00       2
29/07/13 09:00:00       19
29/07/13 10:00:00       21
29/07/13 11:00:00       30
29/07/13 12:00:00       21
29/07/13 13:00:00       24
29/07/13 14:00:00       18
29/07/13 15:00:00       35
29/07/13 16:00:00       17
29/07/13 17:00:00       3
30/07/13 09:00:00       20
30/07/13 10:00:00       47
30/07/13 11:00:00       22
30/07/13 12:00:00       19
30/07/13 13:00:00       26
30/07/13 14:00:00       30
30/07/13 15:00:00       20
30/07/13 16:00:00       26
30/07/13 17:00:00       10
30/07/13 18:00:00       1
31/07/13 08:00:00       1
31/07/13 09:00:00       23
31/07/13 10:00:00       28
31/07/13 11:00:00       18
31/07/13 12:00:00       25
31/07/13 13:00:00       17
31/07/13 14:00:00       17
31/07/13 15:00:00       36
31/07/13 16:00:00       22
31/07/13 17:00:00       8
31/07/13 20:00:00       1

However what I would like to achieve is to get this data and get it summarized ignoring the Date part of the field (Not time, like everyone else wants)
I would have a result that looks like this. (For the 3 days above)
Time_Period   Sum_Count
-----------------------
08:00:00        23
09:00:00        89
10:00:00        71
11:00:00        67
12:00:00        72
13:00:00        71
14:00:00        55
15:00:00        97
16:00:00        49
17:00:00        12
18:00:00        1

I could do it in code and dump the answer back to a temporary table; however doing it correctly in SQL to begin with would make it easier to call from different systems.
Answer: SELECT
    HourMinuteSecond=CONVERT(TIME,YOURDATE),
    GroupCount=COUNT(*)
FROM
   YOURTABLE
GROUP BY CONVERT(TIME,YOURDATE)

Answer: As simple as :
select count(*),
convert(sysname,DATEPART(HOUR,Time_Period ))+':'+
convert(sysname,DATEPART(minute,Time_Period ))+':'+
convert(sysname,datepart(second,Time_Period ))
from YourTable
group by
convert(sysname,DATEPART(HOUR,Time_Period ))+':'+
convert(sysname,DATEPART(minute,Time_Period ))+':'+
convert(sysname,datepart(second,Time_Period ))

If you use SQL2012, you can build strong typed time using TIMEFROMPARTS function. If you use earlier versions, justify strings in example above and add ORDER BY clause


Problemas com três forms e picture box

Question: Oi, o meu cenário é o seguinte:
- Formulário de configuração (nome, e-mail e uma foto)
- Formulário ABC - que possui um formulário que é aberto ao clicar num Button do formulário ABC
- Formulário BCA - que possui um formulário que é aberto ao clicar num Button do formulário BCA
O formulário ABC ou o formulário BCA serão chamados com base da escolha feita no formulário de Configuração, através de radio buttons.
Nesse formulário de configuração também é feita a escolha de uma imagem jpg/png que o usuário vai procurar no próprio pc. Depois de todos os dados preenchidos e foto escolhida nesse formulário de configuração, o usuário clicará num botão "Iniciar", onde com base da escolha do ratio button ABC ou BCA vai abrir seus respectivos formulários. E também, a imagem será salva numa pasta com o nome de logo.jpg.
No formulário ABC ou formulário BCA também há uma picture box onde será carregado a imagem salva na pasta X (C:\X\Img\logo.jpg). Aí que entra o meu problema. Ambos formulário ABC ou BCA tem um botão que leva em outro formulário, onde também será carregado a mesma picture box... Porém dispara um erro, pois diz que a imagem já está carregada.
Observação: Pra 'finalizar' o form de configuração eu uso this.Visible = false;
E também para os formulários ABC e BCA. Creio que é por isso que dá esse erro, pois a imagem já está com um espaço alocado na memória..
Vocês poderiam me ajudar?
private void pictureBox_logo_Click(object sender, EventArgs e)
{
 OpenFileDialog file = new OpenFileDialog();
 file.Filter = "PNG|* .png|BMP|*.bmp|JPG|*.jpg;*.jpeg";
 if (file.ShowDialog() == DialogResult.OK)
{
 pictureBox_logo.ImageLocation = file.FileName
}
 pictureBox_logo.Image.Save(@"C\tools\img\logo.jpg");

}

E no outro form (que será aberto com a escolha do radio button ABC ou BCA)
public partial class frmPrincipal : Form
 {
    public frmPrincipal()
    {
        InitializeComponent();

        picturebox_principal.Load(@"C:\tools\img\logo.jpg");
     }
}

Comment: Sem o código onde o erro ocorre fica difícil, poste o código.
Comment: Pronto editei... Espero que dê pra entender...
No que eu havia escrito dá pra entender um pouco melhor o meu cenário... A imagem é carregada num formulário, quando tento abrir outro formulário através de um botão e carregar a mesma imagem, dispara um erro falando que a imagem já está em uso
Answer: Utilizando o código disponibilizado não há em nenhum momento a atribuição da imagem para o componente PictureBox, logo ao executar a linha que tem o .Save() ocorre erro de referência nula.
Segue código modificado:
using (OpenFileDialog openDialog = new OpenFileDialog())
{
     openDialog.Filter = "PNG|* .png|BMP|*.bmp|JPG|*.jpg;*.jpeg";
     if (openDialog.ShowDialog() == DialogResult.OK)
         pictureBox1.Image = Image.FromFile(openDialog.FileName);

     pictureBox1.Image.Save(@"C:\tools\img\ip.png");
}

O carregamento da imagem no outro PictureBox será feito da mesma forma:
public Form2()
{
      InitializeComponent();
      pictureBox2.Load(@"C:\tools\img\ip.png");
}

Problemas com três forms e picture box


Createfile in path given by user only if the file doesn't exist

Question: I'm trying to create a file only if the files doesn't exist in the path located and that the directory i guess path exists too and if the file already exist I don't let the user continue so the app closes. I tried doing this but it seems that when I give the location it tells me the file exists when it doesnt.
<code>this.path = @output;
      this.path2File = @output + "\\" + type + "tobearchived.txt";

if (!Directory.Exists(path) && !File.Exists(path2File))
      {
        File.Create(path2File);
      }
      else
      {
        Console.WriteLine("Error: File Already Exists. Press any key to exit.");
        Console.ReadKey();
        Environment.Exit(0);
      }
    }
</code>
Answer: Your IF condition seems faulty, try following;
<code>  if (Directory.Exists(path) && File.Exists(path2File))
  {
    Console.WriteLine("Error: File Already Exists. Press any key to exit.");
    Console.ReadKey();
    Environment.Exit(0);
  }
  else
  {
   File.Create(path2File);
  }
</code>
Edit: The problem in your code is, Let's say that directory exists but file doesn't. Then '!Directory.Exists(path)' is 'false' and it will skip checking for 'File.Exists(path2File)' because of AND condition.
Therefore, control will directly go to 'else' part of your code.
Answer: I tried this and worked fine for me.
<code> FileInfo Finfo;
 public bool StartLog(string path)
 {
      Finfo = new FileInfo(path);
      if (Finfo.Exists)
      {
          Finfo.Delete();
          FileWriter = Finfo.AppendText();
      }
      else
      {
          FileStream fs = Finfo.Create();
          fs.Close();
          FileWriter = Finfo.AppendText();
      }
 }
</code>


how to fetch/load model.json and weight.bin from two different URL?

Question: I was going through Save and load models- Tensorflow documentation page to load/save and run models into browser. CDN version of tensorflow.js is 1.1.2
Syntax to use for example
const model = await tf.loadLayersModel('http://model-server.domain/download/model.json');

The documentation says:

This loads a model from an http endpoint. After loading the json file the function will make requests for corresponding .bin files that the json file references.

But the system i am working doesn't allow two different file to have the same URL path, as each file is saved with an individual id.
So my question is, how can I load/save the model.json and the weight.bin (https method) from two different URL addresses?
Btw if tf.loadFrozenModel (modelUrl, weightsManifestUrl, requestOption?) could be used,then please let me know how to use it? Because, it did not work for me.
Answer: If you want to load the model and the weights from 2 different locations, according to the doc, the following can be used:
const model = await tf.loadLayersModel('http://model-server.domain/download/model.json', {weightPathPrefix: weigthsUrl});

Comment: hi.   i did something like: const myModel = await tf.loadLayersModel(  [link]("https://instance_name.com/nav_to.do?uri=sys_attachment.do?sys_id=735a52a0dbd5330093d88a1848961988") ,  [link](
 "https://instance_name.com/nav_to.do?uri=sys_attachment.do?sys_id=316a166cdb95330093d88a1848961960"));  but it was not working. can you kindly provide a code snippet. BTW, the link that you have provided doesn't mentions about this method. where exactly can i find it, please pin point?
Comment: No doubt that it didn't work because you didn't follow the syntax, I gave in the answer. The link I gave talks about an optional object parameter. One of the key of that object is `weightPathPrefix`. Please do follow the answer and do report an error only if it is not working !
Comment: hey ,sorry for my  lack of knowledge :(..     I next did       const model = await tf.loadLayersModel([link]('https://id=735a52a0dbd5330093d88a1848961988'),
  {weightPathPrefix: [link]('https://id=316a166cdb95330093d88a1848961960'),
  method: 'GET', headers: {'Authorization': 'Basic YWCraW46MTIzNA=',
                          'Accept':'application/json',
                         'Content-Type':'application/json'}
  }
                     );
model.summary();
 which again didnt work for me :/ i was doing it on the doc page that you referred.Am i again doing anything wrong ,please help?


Best estimate of a count from a single observation

Question: A company produces tickets that are individually numbered. The first ticket is numbered 1, the second ticket is numbered 2, etc...
You get a ticket numbered n. Knowing nothing else, we wish to estimate N, the total number of tickets produced. What is the best estimate of N? n would appear like a candidate although it would definitely be a biased estimate as it represents the lower bound. Maybe 2n? Maybe half-way between the lower and upper bounds (that would be ∞)? Does the question even make sense?
Answer: This sound a lot like the German-Tank-Problem: https://en.wikipedia.org/wiki/German_tank_problem
The minimum variance unbiased estimator is (see also https://web.archive.org/web/20140223104835/http://www.rsscse-edu.org.uk/tsj/wp-content/uploads/2011/03/johnson.pdf for more explanation):
$m(1 + k^{-1}) - 1$ with
$m$: Highest Oberved Number
$k$: Observations, in your case 1.
Answer: I don't believe one ticket is enough information. You might get something silly, like n=1.
If you could get more tickets, then you could apply the central limit theorem.
Google "Random Number Between", and here https://www.calculator.net/average-calculator.html is an average calculator.
I myself let there be 100 tickets, and got five randomly chosen groups of four numbers each, without replacement. The average of the averages of the five groups was 41. Two more groups, rose the average of the averages to 45.
As I get more random groups, the probability distribution of what my average-average may be becomes a normal distribution, centered at N/2*, and so I'd more and more often would get a number close to 50 as the average-of-averages, as I evaluate the averages of more random groups.
***(this is because all numbers from 0 to N are equally likely. If this were human height's being evaluated from 0 to 7 feet, then it would centered at the average adult's height of 5.5 feet, not the midway point of 3.5 feet, since even though 0 to 7 are all possible, adults are more likely to exist than kids.)
This would let you estimate N, if you had more, preferably much more, than 1 ticket.
With just one ticket, all assumptions of what N could be are equally likely.
Unless you know they made like, at least 1,000 tickets and no more than 10,000. If your random number n was below 1,000, that implies N is nearer to 1000 than it is to 10,000, since if N was close to 10,000 you would've been way, way more likely to have gotten a number bigger than 1000.


Solutions to a system of equations

Question: I know that Bezout's theorem says that if you take two plane curves, then their maximal number of intersection points is the product of their degrees. However, assume that I have two irreducible polynomials in say 6 variables and I plug in values for 4 of them. I'm left with two plane curves. What can be said about their number of intersections?
I assume the original two polynomials are irreducible. I know that there are cases like
$$u+f(x,y),\;\; v+f(x,y),$$
where I can plug in zero for $u,v$ and then I end up with just one curve. Therefore, is it possible to say something like ''for most values of the other 3 variables'' the number of intersection points is the product of the degrees?
Answer: Yes, what you want to say is true.
Let's stick to projective space and homogeneous equations to keep things tidy. (There's a process called "homogenisation" that allows us to pass from inhomogeneous polynomials in $n$ variables to homogeneous polynomials in $n+1$ variables of the same degree which then define hypersurfaces in projective space $\mathbf{P}^n.$ So we can answer the projective version first, and then go back to the original version.)
Suppose your two original polynomials homogenise to give $F$ and $G$. Then they define two hypersurfaces $\{F=0\}$ and $\{G=0\}$ in projective space $\mathbf P^6$. Since $F$ and $G$ are irreducible and distinct, these two hypersurfaces intersect in a subset $X$ of dimension 4 and degree $(\operatorname{deg} F \cdot \operatorname{deg} G)$.
Now "plugging in values" for 4 variables in your setting corresponds, in the projective setting, to intersecting with a linear subspace $L$ of codimension 4, in other words a plane.
Then the statement you want is that for "almost all" choices of the plane $L$, the intersection $X \cap L$ will consist of  $(\operatorname{deg} F \cdot \operatorname{deg} G)$ points in $\mathbf P^6$. Of course, there are some choices of $L$ for which this will fail --- it could be that $\{F=0\} \cap \{G=0\}$ contains a line, for example, in which case any plane $L$ containing that line will intersect in an infinite set of points. But those "bad" $L$ are a smaller-dimensional set of the set of all possible choices of $L$.
Of course you asked about inhomogeneous polynomials, so let's go back to the affine picture. For a slightly smaller set of choices of $L$ than in the previous paragraph, none of the points of $X \cap L$ will be "points at infinity" in $\mathbf P^6$, so your original equations have exactly  $(\operatorname{deg} F \cdot \operatorname{deg} G)$ common solutions.

Solutions to a system of equations


How can injections from a "bigger" space to a "smaller" one exist?

Question: I have this question about injective functions that I can't answer. Take the top half of the sphere $S^2$ and the disc $D^2$ and  as an example. The "vertical" projection from the former to the latter is an injection.
It seems counterintuitive to me that such an injection can exist, when the area of the upper hemisphere is greater than that of the disc, i.e. the upper hemisphere consists of more points than the disc. Which property of the space $R^3$ that can answer this question am I missing here?
Answer: Injection do not preserve area. In particular, $$A: \mathbb{R}^2 \to \mathbb{R}^2: (x,y) \mapsto (2x, 2y)$$ is a bijection, but clearly doesn't preserve area.
In a set theoretical point of view, the upper hemisphere and disc contain an equal amount of points (i.e. the same amount as $\mathbb{R}$ does). The proper 'counting intuition' rules do not carry over wholesale here.
Another example is the fact that there exists an injection from $\mathbb{Q}$ into $\mathbb{N}$, while intuitively you'd estimate $\mathbb{Q}$ to be much larger.
Comment: Could you please elaborate more on the comment that those surfaces contain the same amount of points?
Comment: By definition, two sets have the same amount of points if a bijection exists between them. Since you gave a bijection, by definition they have the same amount of points.
Comment: The problem here is that the *measure* is not preserved - the image of a surface element of the hemisphere with area 1 won't have area 1. However, this is a more complicated concept than the number of points in a set.


How to merge two different pages on one page

Question: I am using profile 2 module to manage users profile related information.
so far I am having two tabs

My Accounts
Customize the tabs takes me to two different URLs i.e
(mydomain.com/users/user-name/edit/Customize)(mydomain.com/users/user-name/edit/MyAccounts)

My question is,
can I make this into one tab and make these two different pages to display in one single page?
Thanks alot
Answer: Hide the tab on the user account page.
<code>function MY_MODULE_menu_alter(&$items) {
  $items['user/%user_category/edit/profile']['access callback'] = FALSE;
}
</code>
Then, merge the profile2 form with the user account form itself :
<code>/**
 * Implements hook_form_FORM_ID_alter() for the user edit form.
 */
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  if (($type = profile2_get_types('profile')) && $type->userCategory) {
    if (empty($form_state['profiles'])) {
      $profile = profile2_load_by_user($form['#user'], 'profile');
      if (empty($profile)) {
        $profile = profile_create(array('type' => 'profile', 'uid' => $form['#user']->uid));
      }
      $form_state['profiles'][$profile->type] = $profile;
    }
    profile2_attach_form($form, $form_state);
  }
}
</code>
From http://www.jide.fr/english/add-profile2-form-directly-on-the-user-edit-form
Comment: @user1414193 great. Then choose the correct answer by clicking the tick icon below the vote up/down buttons.


Remove zero values from array

Question: I have an array with zero values, and I wish to copy this array to other array but without the zero values. How can I do this if determining the array size is not possible because I do not know how many zeros are there. Please note that I can not use List or ArrayList because of reasons.
// frame is the original array

final int[] sorted = new int[??];

for (int i = 0; i < frame.length; i++) {
    if (frame[i] != 0) {
        sorted[i] = frame[i];
    }
}

Comment: In complexity theory there really is no O(2n). O(2n) actually IS O(n).  Both 2n and n are considered LINEAR time, hope this is also helpful :-)
Comment: Most likely this is homework, and the professor is looking for the OP to learn algorithmically what is necessary which is why List and ArrayList cannot be used. Are there any other constraints to this problem???
Comment: Nice one... Actually no. I get this array from external device that connected to the phone. I get this array 9 time per second and I need to sort it without zeros. The reason I cannot use ArrayList because it to slow to cast Array to ArrayList and it causes lag to the app. If I had faster processor (Testing on S2) maybe I could use ArrayList.
Comment: And thanks for the answer. Actually I hoped It can be done in O(n), but O(2n) it fine also.
Comment: You right, but the array in size is about 120,000. Each second instead of 9 iteration I make 18, twice on same array, try to tell my android processor that O(n)=O(2n). This little difference make it hard on it. Thanks Again!
Comment: I would argue, if your professor is saying that O(n) != O(2n), perhaps he should not be teaching computer science :-)
Comment: @trumpetlicks processor, not professor.
Comment: If there is no reason to make a copy (i.e. if you can just strip the 0-elements from the original and use it along with the known number of non-zero values computed during stripping), I would assume that would be had to beat for optimal footprint and performance. [**See it live**](http://ideone.com/E2bC3y). Given you have 120,000 of these to process each time, a true single-pass algorithm sacrificing the original array body would seem attractive if you're really doing this on 120K elements 9x/sec.
Answer: Yo can do this if it must use array:
int j = 0;

for (int i = 0; i < frame.length; i++) {
    if (frame[i]!=0) {
        j++
    }
}

final int[] sorted = new int[j];
j = 0;
for (int i = 0; i < frame.length; i++) {
    if (frame[i]!=0) {
        sorted[j] = frame[i];
        j++;
    }
}

Comment: Sorry, but if frame has zero(s) the code will end with out of range error: "sorted[i] = frame[i]" will fail when i is big enough.
Comment: @DmitryBychenko right. missed completely.. edited :) thanks for pointing out
Answer: The only way I know how to do this with your given constraints would be to COUNT FIRST, Process NEXT:
unsigned int nonZeroCount = 0;

// Count the amount of non-zero values
for (int i = 0; i < frame.length; i++){
    if (frame[i]!=0)
        nonZeroCount++;
}

// Create the NEW Array
final int[] sorted = new int[nonZeroCount];

// NEXT add them to your new array, Need to have 2 separate counters, 1 for your initial array,
// Another for where you are placing it within your new array
unsigned int anotherCount = 0;
for (int i = 0; i < frame.length; i++){
    if (frame[i]!=0){
        sorted[anotherCount ] = frame[i];
        anotherCount++;
    }
}

Answer: Try the following:
String validNumbers = "";

for (int i = 0; i < frames.length; i++) {
 if (frames[i] != 0)
   validNumbers += (i > 0 ? ";": "")+frames[i];
}

String sorted[] = validNumbers.split(";");

This way, You'll have an array of String with the numbers that are different of 0;
Comment: This might actually be the slowest of all of the answers.  Inside of a string, Im not completely sure how it does it's memory allocations, but at worst it will do a memory allocation (often considered one of the heaviest taxing burdens in a program) for each non-zero element you add!!!  I wont down-vote, because it is technically correct, but it also uses more memory (n-1) semicolons.
Comment: Glad you ran the JUnit tests :-)  Again since java's String implementation is essentially hidden from us, the only way to KNOW is to test timing.  I knew that it would use more memory.  I think that Java's String implementation does a form or pre-allocation, and so long as your continual concatenation doesn't go past it, than time wise it will be the same as my version's single allocation.  Always heavily depends on implementation :-)  Good work!
Comment: Also, this does not actually answer the OPs question, as it is specific to arrays, and most likely for a class, that he has no ability to change the use model.
Comment: You're right about the memory allocation, but not about being the slowest way. A simple JUnit test showed that the time to execute your algorithm was the same to execute mine.
But yours gain in memory usage, mine was 7x more memory usage in comparison with yours =)
Answer: I do not know much zeros there is.
So why don't you fond out?
int counter = 0;
for (int i = 0; i < frame.length; i++) {
    if (frame[i]==0){
        counter++;
    }
}

Answer: You could make a new array with the same size like the one you test. After that you iterate over the array and for each non zero value you found, you add it, while increasing a counter that will represent the number of non zero elements found. After this you can use it to create a new array where to copy your values or simple use the counter as a upper bound when iterating the new array.
Answer: int noneZeroCount= 0;

for (int i = 0; i < frame.length; i++) {
    if (frame[i]!=0) {
        noneZeroCount++;
    }
}

final int[] sorted = new int[noneZeroCount];

// You got size of non zero elements in array now run copy loop

Remove zero values from array


Using PySpark in Python: WindowsError: [Error 5] Access is denied

Question: I'm trying to run PySpark unit tests using PyBuilder under Windows 10
<code>pyb_ clean install
</code>
All the necessary libraries are included into PYTHONPATH and they are available.
But when running I get the following error:
<code>..\..\src\unittest\python\client_tests.py:11: in <module>
    from ut_setting import spark
..\..\src\unittest\python\ut_setting.py:75: in <module>
    spark = SparkSession.builder.master("local[4]").getOrCreate()
..\python\pyspark\sql\session.py:169: in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
..\python\pyspark\context.py:307: in getOrCreate
    SparkContext(conf=conf or SparkConf())
..\python\pyspark\context.py:115: in __init__
    SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
..\python\pyspark\context.py:256: in _ensure_initialized
    SparkContext._gateway = gateway or launch_gateway(conf)
..\python\pyspark\java_gateway.py:82: in launch_gateway
    proc = Popen(['spark-submit.cmd', "-f"])
D:\Python27\Lib\subprocess.py:672: in __init__
    errread, errwrite)
D:\Python27\Lib\subprocess.py:882: in _execute_child
    startupinfo)
E   WindowsError: [Error 5] Access is denied
</code>
I've also tried to use different approaches: running using admin permissions, moving to another drive and etc.
If I do the same on Linux, it works fine without any tuning.
Do you have any thoughts?
Thanks!
Comment: The `CreateProcess` call in `subprocess.Popen` is failing. Verify that the `ComSpec` environment variable is set properly to `"%SystemRoot%\System32\cmd.exe"`. And confirm that you have access to "spark-submit.cmd", wherever that's located in `PATH` when `Popen` fails.
Answer: Thank you guys!
I've managed to solve the issue.
The main reason was that I've tried to set admin permissions to the single processes, while I need to set the permissions to the whole pyspark directory.
Right click on the directory -> Properties -> Security tab
I've set "Full control" for "Everyone" and enabled inheritance.
Comment: Giving everyone full control is extremely permissive. It should suffice to give "Administrators" full control and "Users" read and execute access. "Everyone" includes anonymous logons over SMB.
Answer: Try this:

Right click the Start button and click "Command Line (Admin)" (or "PowerShell (Admin)")
Run the installation command.
...
PROFIT!
Comment: The question states that Stephan already tried "running using admin permissions".


Problemas com classe PDO não encontrada

Question: Estou estudando um livro no qual tenho que efetuar algumas queryes através de um design pattern TableDataGateway porem estou recebendo a seguinte mensagem de erro:

Fatal error:  Uncaught Error: Class 'classes\tgd\PDO' not found in C:\xampp
  \htdocs\livro_php_poo_12_persistencia\classes\tgd\Connect.php:12
  Stack trace:
0 C:\xampp\htdocs\livro_php_poo_12_persistencia
  \exemplo_table_data_gateway2.php(24): classes\tgd\Connect->__construct()
1 {main}
  thrown in C:\xampp\htdocs\livro_php_poo_12_persistencia\classes
  \tgd\Connect.php on line 12

index
produto
    <?php
namespace classes\tgd;
class Produto {
    private static $conn;
    private $data;

    public static function setConnection(PDO $conn){

        self::$conn = $conn;
        ProdutoGateway::setConnection(self::$conn);

    }
    function __get($prop) {
        return $this->data[$prop];
    }
//...
}

TableDataGateway

namespace classes\tgd;

class ProdutoGateway {

    private static $conn;

    public function setConnection(PDO $conn){
        self::$conn = $conn;
    }
    //fazendo buscar por id
    public function find($id,$class = 'stdClass'){
        $sql = "SELECT * FROM produto WHERE id=:id";
        print "$sql
\n";
        $result = self::$conn->prepare($sql);
        $result->bindValue(":id",$id,PDO::PARAM_INT);
        $result->execute();
        return $result->fetchObject($class);
    }

    //...
}

conexão
<?php
namespace classes\tgd;

class Connect {
    private static $conn;
    const CONN = array('HOST'=>'xxx','USER'=>'xxx','PASS'=>xxx,'DATA'=>'xxx');

    public function __construct(){
        self::$conn = new \PDO("mysql:host=".self::CONN['HOST'].";"
        . "dbname=".self::CONN['DATA'],self::CONN['USER'],self::CONN['PASS']);
        $conn = self::$conn;
        $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        return Produto::setConnection($conn);
    }
}

Comment: Você está utilizando uma classe global dentro de um *namespace*, então precisa de uma barra invertida. Nos métodos que recebem o PDO como parâmetro, coloque `\PDO` ao invés de `PDO`.
Comment: Adriano, o problema estava no parâmetro dos métodos, não na instância. Para simplificar, retire essa barra invertida que colocou e coloque `use PDO` em **todos** os arquivos que fazendo referência à classe, incluindo *TableDataGateway* e *produto*.
Comment: Pela mensagem de erro citada, acredito fielmente que esse era o erro. Tem como atualizar a pergunta com o novo código? Aliás, a mensagem de erro permaneceu a mesma?
Comment: Atualizar a pergunta implica em editá-la. Se mudou o erro, coloque o código e a mensagem de erro na pergunta.
Comment: eu ja fiz isso amigo nao deu certo
Comment: pronto atualizado
Comment: funcionou obrigado.
Answer: Quando você referencia uma classe dentro de um namespace sem identificá-la com a instrução use, o PHP entenderá que esta classe também pertencerá ao namespace. Isto é, ao fazer:
<?php

namespace classes\tgd;

class Foo {
    public function method(PDO $pdo) {}
}

O PHP entenderá que a classe PDO pertence ao namespace classes\tgd. Para resolver isso, sempre que você utilizar a classe dentro de um namespace, você precisa identificar sua origem. Como a PDO pertence ao contexto global, basta colocar:
use PDO;

Ficando algo semelhante a:
<?php

namespace classes\tgd;

use PDO;

class Foo {
    public function method(PDO $pdo) {}
}

Comment: Perfeito, é que eu acabei de entrar neste mundo de `namespaces e design patterns`

Problemas com classe PDO não encontrada


Confusion Matrix produces different results in Keras model tf==2.3.0

Question: With Keras Sequential Model Prediction,
To get Class Labels
we can do
yhat_classes1 = Keras_model.predict_classes(predictors)[:, 0] #this shows deprecated warning in tf==2.3.0

WARNING:tensorflow:From <ipython-input-54-226ad21ffae4>:1: Sequential.predict_classes (from tensorflow.python.keras.engine.sequential) is deprecated and will be removed after 2021-01-01.
Instructions for updating:
Please use instead:* `np.argmax(model.predict(x), axis=-1)`,   if your model does multi-class classification   (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype("int32")`,   if your model does binary classification   (e.g. if it uses a `sigmoid` last-layer activation).

so
yhat_classes2 = np.argmax(Keras_model.predict(predictors), axis=-1)

With the first class labels if i create confusion matrix, i get
matrix = confusion_matrix(actual_y, yhat_classes1)
 [[108579   8674]
 [  1205  24086]]

But with the second class labels with the confusion matrix, i get 0 for True Positive and False Positive
matrix = confusion_matrix(actual_y, yhat_classes2)
 [[117253      0]
 [ 25291      0]]

May I know whats my issue here?
Comment: how many neurons does your final layer have?
Comment: Keras_model.add(Dense(1, activation='sigmoid', kernel_initializer=init_mode))
Answer: The confusion matrix returns 2 rows/columns, which leads me to believe that you have two classes. The warning specifically says that you should use this line for binary classification, which is what you're doing:
(model.predict(x) > 0.5).astype("int32")

Please use instead:* np.argmax(model.predict(x), axis=-1),   if your model does multi-class classification   (e.g. if it uses a softmax last-layer activation).* (model.predict(x) > 0.5).astype("int32"),   if your model does binary classification   (e.g. if it uses a sigmoid last-layer activation).

The error is that you used np.argmax(model.predict(X), axis=-1) on a 1D output and so this always returns the same column (because there's only one, so the maximum value will be in that column). That explains that all your predicted values are in the same column in your confusion matrix.
Comment: yes, it is binary classification, only two classes, so returns the highest class
Comment: i'm not sure i understand what you're trying to say
Comment: Just explained that you believe two classes
Comment: Tried this (model.predict(x) > 0.5).astype("int32"), this produces the correct result as yhat_classes1
Comment: The Warning message carried away


how to read substrings from specific patterns

Question: I have an input string like _FIR_abcdef_gh_SEC_ijk1234_LAS_tun_1234
Assume i need make sub string of abcdef_gh , ijk1234 and tun_1234.
_FIR_ ,_SEC_ and _LAS_ are the keys here.
I have tried with sub string options but couldn't figure out a solution.
Answer: Do you like this?
public class Substring {
public static void main(String[] args) {
    String fullString = "_FIR_abcdef_gh_SEC_ijk1234_LAS_tun_1234";

    int start1 = fullString.indexOf("_FIR_");
    int start2 = fullString.indexOf("_SEC_");
    int start3 = fullString.indexOf("_LAS_");

    String first = fullString.substring(start1+5, start2);
    String second = fullString.substring(start2+5, start3);
    String third = fullString.substring(start3+5, fullString.length());

    System.out.println(first);
    System.out.println(second);
    System.out.println(third);
}

}
Console:
abcdef_gh
ijk1234
tun_1234
Comment: Thanks stefan like this I need.
Comment: I'm glad I could help.


How to customise order cart customer information pane

Question: During checkout, I can add fields to billing or delivery information, but how can I add fields to customer information, or create another customized pane for them?
Example:
Student Information:
Name: Skill interest: Phone: Email: etc.....
Answer: You can achieve this using Ubercart Webform Integration module.
This module integrates two other modules: webform and ubercart. It allows you sell products directly from your webforms. It is particularly suited to be used as part of a registration system.
Using this module you can create additional field in check page.
Comment: Thank for your reply Smalution. I had installed this module and enable it. I read how to get it started. Unfortunately, I still not sure where to start. I go check either ubercart or webform nothing change. Need advice.
Comment: there is a option in webform configuration to integrate with uber cart form.
Comment: I can see Product, Product grid, Product list and Hidden is already checked, but it does not appear in the Form components.
Comment: Seem like not working...is there any other alt solution?


Combining probabilities for multiple individuals

Question: Take the example question, 'How many individuals will be in state A'.
Let's say I have 5 individuals each with a probability of entering state A.  Those probabilities could be 0.33, 0.87, 0.55, 0.64, 0.17.  Each probability is independent of the other.
What is the probability that the number of individuals in state A will be 3?  Or perhaps the similar question of 'at least 3'?
Answer: Modeling the system
I'll use "state 1" to refer to state A in your example, and "state 0" to mean not in state A.
The states of $n$ individuals can be modeled as a random vector $X = [X_1, \dots, X_n]$. Each $X_i$ is a Bernoulli variable that independently takes the value 1 with probability $p_i$ or 0 with probability $1-p_i$.
We can describe any given configuration of the system with a binary vector $x = [x_1, \dots, x_n]$ specifying the state of every individual (0 or 1). Because the states of individuals are independent, the probability of a given configuration is:
$$Pr(X=x) = \prod_{i=1}^n Pr(X_i = x_i)$$
How many individuals in state 1?
Let $K$ be a random variable representing the number of individuals in state 1:
$$K = \sum_{i=1}^n X_i$$
The probability that $K$ takes a particular value $k$ is the sum of the probabilities of every system configuration where exactly $k$ individuals are in state 1. Let $C_k$ denote the set of all such configurations--that is, the set of all length-$n$ binary vectors with exactly $k$ ones. Then:
$$Pr(K=k) = \sum_{x \in C_k} Pr(X=x)$$
This is the Poisson binomial distribution, which models a sum of independent (but not identically distributed) Bernoulli variables. The way I've written it is different from the Wikipedia article, but they're equivalent.
Computational issues
There are $\binom{n}{k} = \frac{n!}{k! (n-k)!}$ configurations with exactly $k$ individuals in state 1. This number quickly grows astronomically large. So, computing $Pr(K)$ by explicitly summing over these configurations is infeasible except for small problems. There are various approaches for computing $Pr(K)$ more efficiently; see the Wikipedia article for references.


Prove this theorem related with specification tests

Question: I'm not a mathematician and I need to prove what this theorem says. I think is easy and I know how it works, but definitively I'm not too much rigorous to make a demonstration. Can anybody help me?
I enounce it:
If the test statistic has a continuous distribution, then under H0 : θ = θ0, the p-value has a Uniform[0, 1] distribution. Therefore, if we reject H0 when the p-value is less than α, the probability of a type I error is α.

Therefore, when H0 is true, the p-value is like a random draw from a
Uniform[0, 1].
On the other hand, if H0 is not true, the distribution of the p-value will
tend to concentrate closer to 0.
A large p-value can occur for two reasons:

H0 is true, or
H0 is false, but the test has low power

Do not confuse the p-value with P(H0 | data). The p-value is not the
probability that the null hypothesis is true.

Thank you so much!
Answer: Your theorem basically follows from the result in theoretical statistics that, for a continuous random variable X with cumulative distribution function F, F(X) has a uniform distribution. That's because your p-value is $1-F_s(S)$, where $S$ is the test statistic and $F_s$ is the distribution of $S$ under the null hypothesis.
The proof goes as follows:
Assume $X$ has cdf $F$. Then
$$ Prob(F(X) \leq t) = Prob(X \leq F^{-1}(t))=F(F^{-1}(t))=t$$
And that's the definition of a uniform: $Prob(U \leq t) = t$, for $t \in [0.1]$.
Why does it matter that $X$ be continuous? If $X$ has discrete point masses of probability, then $F$ may not have an inverse for every possible value of $t$ in the unit interval.
A well-behaved, continuous random variable will have a strictly monotone cdf over its domain, and the inverse will be well defined.
I'm not so sure about the statement that the distribution of the p-value tends towards 0 always and everywhere when the null is false. Consider a contingency table with overly regular cell counts. The chi-square value will be very small and the p-value close to one.
I admit that's an artificial example, and works partly because the chi-squared test is one-sided.
I would qualify your point about the reasons for large p-values by adding "the test was not designed to detect the alternative that actually occurred." In effect, that's the problem with the chi-squared test on a contingency table - it's not designed to detect "rigged" data with overly even cell distributions.
Comment: What means "overly regular cell counts"? Isn't it called unbiased test if the distribution of its p-value tend to 0 whenever the null hypothesis is false?
Comment: Overly regular cells would be cells with equal counts or nearly equal counts. This constitutes a departure from multinomial data with equal probabilities, since in practice, one typically gets a lot of variation from cell to cell. A p-value is calculated with reference both to the null and alternate hypotheses. So if the alternate is one-sided, the test is incapable of detecting an alternative from the wrong side.


What does it mean that multiplication and division have the same precedence?

Question: I have read and heard in many places that multiplication and division are of equal precedence. So what is the value of:
$$
80 \div 10 \times 2
$$
Is it
$$(80 \div 10) \times 2 = 16$$
or
$$
80 \div (10 \times 2) = 4
$$
? The answer here seems to be that by convention we operate from left-to-right, so the first solution is correct. But I would have thought we should get the same answer either way if multiplication and division are of equal precedence. Isn't the whole point of operator precedence to resolve expressions that would otherwise have more than one solution?
For example, people also say that addition and subtraction are the same level of precedence, but no such ambiguity exists there:
$$
80 + 10 - 2 = (80 + 10) - 2 = 80 + (10 - 2) = 88
$$
So what is meant when people say that multiplication and division have the same precedence?
Comment: Well $(80-10)+2 \ne 80-(10+2)$.
Comment: Division and subtraction aren't associative so you can't rearrange the order.  "Precidence" is about distribution.
Comment: Actually addition subtraction has the exact same ambiguity.  Is 10-8+2 equal to (10-8)+2=4 or is it 10-(8+2)=0?
Comment: @fleablood, but precedence is always taught by using parentheses to show the intended order. Just look at the example in the second paragraph [here](https://en.wikipedia.org/wiki/Order_of_operations). That doesn't have to do with associativity?
Answer: When there is equal precedence, the standard thing to do is to work from left to right. Hence
$$80/10\times 2 = (80/10)\times2=16. $$
It should be noted that this is not completely universal, i.e. some programming languages don't do it this way, as far as I know. Anyway, it doesn't really matter that much because no one actually writes $80/10\times2$, instead they write $(80/10)\times2$ to remove any ambiguity.
Comment: No one **should** actually write $80/10 \times 2$, especially if they mean $80/(10 \times 2)$.  If you read MSE enough, you'll find out that lots of people would actually write that, and even worse things.
Comment: You should probably use `$\div$` $\div$ rather than $/$ for this.
Comment: While it is certainly true that nobody writes $80/10\times2$, people *do* write things like $80/3x$ or $1/2\pi$, and sometimes context makes it clear that what is meant is $80/(3x)$ and $1/(2\pi)$, respectively.  (Such expressions are even found in textbooks.)
Comment: So then what is meant by "equal" precedence?
Comment: It means that they come at the same level in the hierarchy of operations, and in case of ambiguity (i.e. multiple operations at the same level) go from left to right.
Comment: Note that the left-to-right rule this is not always valid. A perfect example is exponentiation, which defaults to right-to-left. 2^3^2 = 512, not 64, because 2^3^2 = 2^(3^2).
Comment: @mweiss I'm 4 years late to this party, but this is a timeless issue. In the case of implied multiplication like 1/2π, PEMDAS is not enough. For over 100 years (if not longer), the accepted convention in math and scientific circles (and better calculators) has been that implied multiplication goes first, before explicit multiplication or division. (Between the E and M of PEMDAS.) There's a great video (not mine) about it, related to a recent viral trend. I probably don't have the score to post a link, so search youtube for "The Problem with PEMDAS: Why Calculators Disagree".
Answer: I'm fine with Eff's answer because I don't think my question was particularly clear. But I'd like to offer what I hope is a clearer question and answer.
When learning about order of operations, examples of mathematical ambiguity like the following often come up:

What is $2 + 4 \times 6$?

The teacher then demonstrates to the pupil that by performing this computation in a different order of operations, we get two different answers. So we use order of operations to indicate that the real answer is $2 + (4 \times 6) = 26$, not $(2 + 4) \times 6 = 36$. In other words, order of operations removes the ambiguity of which operation to perform first.
When I heard that two operations have "equal" precedence, my interpretation of that was that it does not matter which order you perform your operations. But mathematically, this cannot be true since:
$$
(80 \div 10) \times 2 \neq 80 \div (10 \times2)
$$
While $\div$ and $\times$ have equal precedence.
Clearly, something else is meant by "equal". Implicit in Eff's answer is that by "equal" we mean that the ambiguity cannot be resolved by simple precedence. The ambiguity is resolved by a new left-to-right rule.
To answer my own question, "What does it mean that multiplication and division have the same precedence?" I say: it means that you cannot perform multiplication or division first as a rule and in fact you will get different answers depending on context. The real rule is that you perform operators with equal precedence in a left-to-right computation.
Comment: This kind of thing is precisely why all mathematics educators ought to learn programming. **Every** proper programming language reference will not only specify precedence groups, but also the associativity (left-to-right or right-to-left) within each group. Only people who appreciate precision fully can really teach mathematics well. (For example see the [C++ operator precedence rules](http://en.cppreference.com/w/cpp/language/operator_precedence).)
Answer: To say the multiplication and division have equal precedence is to say that, in an unparenthesized expression, they are both to be performed before operations of lower precedence, such as addition and subtraction, and that they are both to be performed after operations of higher precedence, such as exponentiation.  Equality of precedence further implies that in an unparenthesized expression containing both multiplication and division, neither operation takes priority over the other.  This leaves an ambiguity that must be resolved by some other rule—a left-to-right rule in this case.
One thing that precedence does not imply is that order of operations of equal precedence is irrelevant.  To see this, you don't even need to look at an expression containing both multiplication and division.  You can consider an expression containing only divisions, such as $10\div2\div5$.  Clearly precedence rules can't tell you which division is to be performed first since, well, the precedence of division equals the precedence of division.  In this case you need a rule that tells you how to associate the factors in the expression.  As stated before, the rule use here is the left-to-right rule: $(10\div2)\div5=1$ is meant, and not $10\div(5\div2)=4$.  One could say that associativity of division (and of a mixture of multiplications and divisions) defaults to left-to-right in the absence of parentheses.
A final thought: as discussed above, precedence rules resolve some, but not all ambiguities.  I would not say that resolving ambiguity is the ``point'' of precedence rules (or of default associativity rules).  The most straightforward way to resolve ambiguity would be to require parentheses everywhere, and to declare expressions such as $1+2\times3$ and $10\div2\div5$ to be undefined.  Rather, the point of precedence and default associativity rules is to make expressions more human-readable by allowing parentheses to be omitted in certain situations.
Answer: For this discussion, operations have 2 properties of interest:

Precedence
Associativity

Both, yes, are used to disambiguate expressions.  (Note, e.g., that prefix and postfix expressions never need to rely on precedence, and never need parenthesis to force evaluation.)
Precedence applies when 2 operators are adjacent; the operator with the higher precedence is evaluated first.  $2 + 3 \times 5$ is always 17.  In such examples, associativity plays no role.  (When I say always, I mean, in math.  Every programming language I know will do it this way, but that doesn't make them authoritative.  Not all calculators yield this answer, though (infix) scientific calculators should.)
When 2 operators with the same precedence are adjacent, then associativity applies.  The four basic arithmetic operators associate left-to-right.  So, $8 - 3 - 2$ is always 3.
There are other operations which associate right-to-left.  Exponentiation.  $2^{3^2}$, which might be written as 2 ^ 3 ^ 2 in some languages, is always $2^9 = 512$.  We use parenthesis to force evaluation otherwise:  $\left(2^3\right)^2 = 8^2 = 64$.
While we're here, for clarity, 'cause I've seen too many CS professors get this wrong, associativity does not apply when evaluating, e.g., $ 3 \times 7 + 64 \div 16$  It does not matter (in arithmetic) whether the multiplication is performed first, or the division, just so they are both performed before the addition is applied (per the precedence rules).  Languages like C, Python and Java have no rules about which is evaluated first, either.
Someone commented above that math teachers should learn programming.  Languages are not authoritative; it is up to them to implement the rules of math correctly (or, not).  For example, while writing this, the Tex engine balked at $2^3^2$, insisted I put braces in to clarify, though math is quite clear on the subject.  OTOH, Python3 evaluates 2**3**2 just fine.
I would say it is important for programmers to be good at math, and know a bit about language theory.  Side-effects are not a concern in arithmetic, but must be considered in programming.
Answer: It means, if you use $\clubsuit$ to represent "either $\times$ or $\div$" then
$$a \; \clubsuit \; b  \; \clubsuit  \; c  \; \clubsuit  \; d  \; \clubsuit  \; \cdots$$
means you compute the answer in this order

$\; a \; \clubsuit \; b$
$(a \; \clubsuit \; b) \; \clubsuit \; c$
$((a \; \clubsuit \; b) \; \clubsuit \; c) \; \clubsuit \; d$
etc.
Answer: I don't see the answer I'm looking for and this circulates as a viral meme every year, so I'm going to take a stab at answering it. Someone else pointed out that the "ambiguity" also holds true for addition and subtraction. There is no ambiguity, PEMDAS is just a horrible way to teach order of operations. I teach my students GEMA (grouping, exponents, multiplication, addition) to increase understanding of the connections between multiplication and division as well as addition and subtraction and to remove any sense of ambiguity for problems like these. It also removes any need to memorize a random rule that you should work from left to right.
Subtraction can ALWAYS be written as addition by a negative number. So 10-8+2 can be rewritten as 10 + - 8 + 2. To do 10 - (8 +2) is mathematically incorrect because now you are distributing that negative to both the 8 and the 2 (i.e. 10 + - 8 + - 2), which is not what the notation 10 - 8 + 2 means. Another way of looking at it is to notice he plus sign in front of the 2. That tells us we're adding 2. If you do 10 - (8 + 2), you're subtracting 2 instead.
Division and multiplication work the same way. Dividing by a number can ALWAYS be written as multiplication by its reciprocal. So 80 / 10 × 2 can be written as 80 × (1/10) × 2. To do 80 / (10 × 2) would be mathematically incorrect because that would be equivalent to doing 80 × (1/10) × (1/2), which is not what 80 / 10 × 2 means. Another way of seeing how it is incorrect is noticing that there is a multiplication symbol in front of the 2, meaning 2 is being multiplied. If you do 80 /(10 × 2) you're dividing by 2 instead.
Someone else mentioned that some textbooks use 1/2x to mean 1/(2x). In six years of higher level math, I never once saw this notation. In my experience, they use a vertical fraction since 1/2x means 1/2 × x. If a textbook does use that notation to mean 1/(2x), it's wrong.


FabricJs Multiple Canvases Load Same Image Multiple Times

Question: I have a loop from 1-2, inside the loop I created 2 canvases on the screen and store them in an object and then load in the same 2 images on each canvas, but the images are only appearing on the last canvas. Why is it not loading on both canvases? There is also a text object which works on both canvases in the same loop.
Example code, it literally is just adding the images to the second canvas on the screen and ignoring the first, but the text object is added to both?
var canvases = {};
var imageUrls = ['url here','url 2 here'];
for(var p = 1; p <= 2; p++){
    canvases[p] = new fabric.Canvas('canvas-element-'+p);
    var t = new fabric.Text('Testing',{top:600,left:0});
    canvases[p].add(t);
    canvases[p].renderAll();
    for(var i in imageUrls){
        fabric.Image.fromUrl(imageUrls[i],function(img){
            img.set({
                width:500,
                height:500,
                top:0,
                left:0
            });
            canvases[p].add(img);
            canvases[p].renderAll();
        }
    });
}

Answer:
imageUrls array contains images at 0 and 1 position you are accessing at 1 and 2.
fabric.Image.fromUrl function name is fabric.Image.fromURL
As it is a loading image is async function you need to keep in a self invoking function or simply use let in for loop for (let p = 1; p <= 2; p++) {

var canvases = {};
var imageUrls = ['', 'https://via.placeholder.com/300x300?text=canvas1', 'https://via.placeholder.com/300x300?text=canvas2'];
for (var p = 1; p <= 2; p++) {
  canvases[p] = new fabric.Canvas('canvas-element-' + p);
  var t = new fabric.Text('Testing', {
    top: 600,
    left: 0
  });
  canvases[p].add(t);
  canvases[p].renderAll();
  (function(index) {
    fabric.Image.fromURL(imageUrls[p], function(img) {
      img.set({
        width: 500,
        height: 500,
        top: 0,
        left: 0
      });
      canvases[index].add(img);
      canvases[index].renderAll();
    });
  })(p);
}
canvas{
 border :2px solid #000
}

<canvas id='canvas-element-1' width=300 height=300></canvas>
<canvas id='canvas-element-2' width=300 height=300></canvas>
Comment: brilliant thanks, I didn't realise load from url was async , my bad. And the loop you mentioned 1 and 3, I know this one, the code is a snippet from a wider bit of code so you can ignore that loop it's not relevant. Thanks for the answer.


Searching a number of files for a string in LInux

Question: How do I search files, some of which might be directories (in this case recursively) for a given string?
I'd like to search source files for a class definition, so it would also be great if there was the name of the containing file before each output string.
Comment: I'm searching source files for a method definition.
Comment: May I ask why would you need that?
Answer: You could use grep:
grep -rn 'classname' /path/to/source

This will also print the line number next to each match.
Case insensitive:
grep -rin 'classname' /path/to/source

Search non-recursively in all cpp files:
grep -n 'classname' /path/to/source/*.cpp

Answer: All the above answers will work perfectly well, but may cause false positives if you've got the string in more than just source code. Say you are looking for where you use the FooBar class in a java project, you can search for all files named *.java and grep just those.
# grep "FooBar" -Hn $(find -name "*.java")

The section in between the $() will expand to the output of that command. The -H prints out the filename. It's the default where there is more than one file name, but we explicitly add it here in case the expansion only returns one file name. The -n prints the line number of the match.
This will work for small projects, but if you're dealing with a larger project, there the potential for the find to expand to a string longer than the command line limit. It's therefore safer to use:
# find -name "*.java" -print0 | xargs -0 grep "FooBar" -Hn

xargs will take input from standard in and split it up so it fits on the command line, running the command multiple times if necessary. The -print0 and -0 are required to deal with files with spaces in their name.
You can also look for all the filesnames with a match in using:
# find -name "*.java" -print0 | xargs -0 grep "FooBar" -l

The -l will just display the file name and stop looking in a particular file as soon as it finds a match.
If you're going to be doing this sort of thing frequently, you may want to look at a tool like ctags or exuberant tags, which maintain a search index of your source code and can answer these sorts of questions quickly. Both vim and emacs have support for these tools. You may also like to look at an IDE like eclipse, which can do cross referencing very well.
(I know you were looking for a class definition, but in Java a class will be defined in a file with the same name as the class. If you were doing cpp, you could do something like:
# find -name "*.cpp" -o -name "*.cc" -o -name "*.h" -o -name "*.hpp" -print0 | \
  xargs -0 egrep "class\s+FooBar" -Hn

Comment: Very comprehensive answer.
Answer: For searching through source code, I've found that ack (betterthangrep.com) is, to quote the marketing, better than grep. Its output is easier to read and it will do a lot of stuff automagically, like ignoring non-source code files: VCS directories (eg CVS and .svn), backup files.
Answer: ack is better for searching source codes as it already recognize some of the most popular file extension (c, perl, etc). It's as fast as grep and by default ignoring all your version control artifact.
For example if you want to search some pattern perl source code you could use
ack --perl pattern

instead of
grep pattern $(find . -name '*.pl' -or -name '*.pm' -or -name '*.pod' | grep -v .svn)

Answer: grep -r string *

finds all files containing the characters "string" in all (non-hidden) files in the current directory and all sub-directories recursively. You can use the usual regexes to tune the string. See the grep info/man pages for more options.
Answer: Already answered (I think this is what you are looking for) on this serverfault post:
Recursive text search with grep and file patterns
Answer: this is something I find myself using alot so I have put two bash functions in my .bashrc
First one does a recursive search for text in filenames.
Second one will do a recursive search for text inside of files returning the filenames of the files that match.
ff () {
        find . -name "*$@*" -print;
}

fff () {
    find . -type f -print0 | xargs -0 grep -l $@
}

example usage:
[lunix@godzilla ~/tmp]$ ff foo
./slideshow/foo
./slideshow/velocity_puppet_workshop_2009/repo/modules/foo

[lunix@godzilla ~/tmp/test]$ fff  commodo
./file2
[lunix@godzilla ~/tmp/test]$ ll
total 16K
drwxr-xr-x 2 lunix lunix 4.0K 2009-06-29 23:01 .
drwxr-xr-x 4 lunix lunix 4.0K 2009-06-29 22:57 ..
-rw-r--r-- 1 lunix lunix 1.3K 2009-06-29 22:59 file1
-rw-r--r-- 1 lunix lunix 1.7K 2009-06-29 23:00 file2

Answer: This classical find + exec could also be handy:
find /path/to/ -type f -exec grep -i 'string' {} \;

Answer: Try the command:
grep -rn *

It will work !!
Comment: Why are you yelling?


At most two of the events $A$, $B$, or $C$ occur? Set theory

Question: Question: Consider a sample space $S$ and three events $A$, $B$, and $C$. For each of the following events draw a Venn diagram representation as well as a set expression.  At most two of the events $A$, $B$, or $C$ occur?
I'm having a challenge understanding the solution to this, which is:
$(A \cap B \cap C)^c = A^c \cup B^c \cup C^c$
and the following diagram:

I can see from the Venn Diagram that only two events may occur due to the intersection visually, however not so with the set expression.  Is the diagram necessary to understand this solution or is there some property of the set expression that can be used to explain the solution "At most two of the events $A$, $B$, or $C$ occur"?
Answer: $x\in A\cup B$ means $x$ belongs to at least one of the sets between $A$ and $B$, might belong to both.
So $x\in A\cup B\cup C$ means $x$ belongs to at least one of the sets among $A,B,C$.
$x\in A^c \cup B^c \cup C^c$ means $x$ belongs to at least one of the sets $A^c,B^c,C^c$, that is to say,  for at least one set $A,B,C$, $x$ does not belong to it. So $x$ can belong to at most two of them.
Edit: Here's an example as asked by OP in the comments, consider the universe of tossing $3$ coins, i.e the entire sample space is $\{HHH,HHT,HTH,THH,HTT,THT,TTH,TTT\}$ and consider the events:
$A=$ exactly one head
$B=$ at least one tail
$C=$ last toss is a head
so that we have the corresponding sets:
$A=\{HTT,THT,TTH\}$
$B=\{HHT,HTH,THH,HTT,THT,TTH,TTT\}$
$A=\{HHH,HTH,THH,TTH\}$
so the event "at most two of $A,B,C$ occur" is the set of those combinations in the sample space where all three don't occur (check below)
$(A\cap B \cap C)^c= \{TTH\}^c=\{HHT,HTH,THH,HTT,THT,HHH,TTT\}$
Comment: It does.  The answer is written in this form: $(A \cap B \cap C)^c = A^c \cup B^c \cup C^c$.  Does that imply the form is satisfied by $!= {emptyset}$?
Comment: Saying "At most $2$ of the events occurs" for a total of $3$ possible events is same as saying "All $3$ events do not occur" i.e. the complement of the occurrence of all three events. The occurrence of all three events $A,B,C$ is what $A\cap B\cap C$ means, we don't want that to happen, so it's complement. The empty set $\phi$ does satisfy the condition "at most $2$ ($\le 2$) events occur", because in case of the empty set $0\le 2$ events occur, if that's what you're asking, but of course it's not the exact set describing "at most $2$ events occur".
Comment: Do you have an actual example using a sample space of elementary events?
Comment: @Nick I have edited an example into the answer. Since this is a fundamental property of set, you can think of any experiment  (like tossing $3$ coins), and define any $3$ events $A,B,C$ (not necessarily distinct) to verify this. Basically, any example you can think of will work.
Answer: At most two from $A,B,C$ is: $(A\cap B\cap C)^{\small\complement}$, that is everything except that which is in the triple intersection. (Everything inside the Venn diagram except that in the innermost overlap).
That is to say: everywhere that at least one does not occur.
$$(A^{\small\complement}\cup B^{\small\complement}\cup C^{\small\complement})$$


Can a motif be found outside of a phrase?

Question: Can motifs be found outside of phrases, like by itself? Or do you think that would actually make that "motif by itself" act like a phrase in it's own right?
Comment: Can a sentence exist outside of words? What exactly do you mean by the terms "motif" and "phrase"?
Comment: As a motif is comparable with a word, and phrase is comparable with a sentence, what you said doesn't make sense?
Answer: Let's define both terms, as there seems to be a little confusion with what a motif and a phrase is.
A phrase is defined as:

A musical phrase is a unit of musical meter that has a complete musical sense of its own, built from figures, motifs, and cells and combining to form melodies, periods and larger sections; or the length in which a singer or instrumentalist can play in one breath.

A motif is defined as:

In music, a motif or motive is a short musical idea, a salient recurring figure, musical fragment or succession of notes that has some special importance in or is characteristic of a composition: "The motive is the smallest structural unit possessing thematic identity".

So a phrase  can be thought of as a complete musical sentence, whereas a motif can be thought of more as an idea or theme that makes up that sentence.
Even if you do write just a motive as a complete musical sentence, by definition it is still a phrase, so no matter how you try to write your motif, it will still be a phrase or part of one.


Find LSB/MSB values for voices in Yamaha CP5's MIDI implementation

Question: I got Yamaha CP5 and I try to define banks so that I can use its instruments from the computer (using the Rosegarden sequencer). Each bank should be specified by a MSB/LSB combination. The data list gives listing of all instruments, but it gives MSB/LSB values only for performances (combination of several parts, with different effects etc), not for voices:

Is there a way to access individual voices via MIDI? Likewise, is there a way to access drum banks?
Answer: well, i'd just try sending some program change / bank msb control change / bank lsb control changes to it and see what shows up as the selected voice.
try 0, 0, 1;  then 0, 1, 0;  then 1, 0, 0;  eventually you should be able to figure it out.


2D Int Array print using pointers

Question: While executing the below code:
int main()
{
  int abc[3][3]={0};
  for(int *ip=&abc[0][0];ip<=&abc[3][3];ip++)
  {
    printf("%d   \n",*ip);
  }
}

Expected result is 9 zeros but it displays 12 data.  What might be reason?
Answer: If you look at the memory layout of a 3x3 array, it looks like:
[0][0]          [1][0]        [2][0]
+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+

Where is the element [3][3]?
[0][0]          [1][0]        [2][0]         [3][0]         [3][3]
+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+

That explains why you end up accessing 12 elements.
Your code is subject to undefined behavior for accessing the beyond valid indices but that's another issue.
You could use:
for (int *ip = &abc[0][0]; ip <= &abc[2][2]; ip++)
{
  printf("%d   \n",*ip);
}

However, it is  better to access a 2D array as a 2D array.
for (size_t i = 0; i < 3; ++i )
{
  for (size_t j = 0; j < 3; ++j )
  {
    printf("%d   \n", abc[i][j]);
  }
}

Comment: Yes Its right. While printing last 3 values shows junk values instead zero.
Comment: @alk, `<=`  is right. `abc[2][2]` is a valid element.

2D Int Array print using pointers


A question on Zhang's result on prime gaps

Question: I'd like to know which is the right way to mention the result that Yitang Zhang obtained in his paper "Bounded gaps between primes".
In some places it is said that Zhang proved that there are infinitely many pairs of prime numbers which differ by $70,000,000$ or less, whereas in other places it is said that he proved that there are infinitely many pairs of prime numbers which differ by less than $70,000,000$.
In his paper, Zhang mentions that it is conjectured that
$$\liminf_{n\to\infty}(p_{n+1}-p_n)=2,$$
which is the Twin Prime Conjecture. Besides, the abstract states that he proves that
$$\liminf_{n\to\infty}(p_{n+1}-p_n)<7\times 10^7.$$
So, I think that the right thing is to say that Zhang proved that there are infinitely many pairs of prime numbers which differ by less than $70,000,000$.
Any comments?
Comment: Thank you for your commment. I know that he did not prove the Twin Prime Conjecture and that his result has been significantly improved. My question is about how to properly mention Zhang's result.
Comment: Basically, I'm comparing the mathematical expressions in my question to figure out how to properly mention Zhang's result. I think that if the expression $\liminf_{n\to\infty}(p_{n+1}-p_n)=2$ represents the Twin Prime Conjecture and the abstract states that Zhang proves that $\liminf_{n\to\infty}(p_{n+1}-p_n)<7\times 10^7$, then the right thing is to say that he proved that there are infinitely many pairs of prime numbers which differ by less than $70,000,000$.
Comment: So, basically, I'm comparing "$70,000,000$ or less ($\leq 70,000,000$)" with "less than $70,000,000$ ($<70,000,000$)".
Answer: I think that the right way to formulate this is the following:
There is a number $L < 70000000$ such that there are infinitely many pairs of primes which differ by $L$.
Comment: @user135328 yes.
Comment: Thank you for your comment. This is another way of mentioning Zhang's result. So you say that it is more appropriate to say that Zhang proved that there are infinitely many pairs of prime numbers $p_n$ and $p_{n+1}$ such that $p_{n+1}-p_n<70,000,000$ (instead of saying that he proved that there are infinitely many pairs of prime numbers $p_n$ and $p_{n+1}$ such that $p_{n+1}-p_n\leq 70,000,000$)?
Answer: If there are infinitely many pairs of primes which differ by at most $L$, then there must be some $\ell\le L$ such that there are infinitely many pairs of primes which differ by exactly $\ell$ (since if not, the total number of pairs of primes differing by at most $L$ is at most $L$ times some finite number which is still finite). So the formulations are equivalent.
Another equivalent formulation is that there is some $\ell\le L$ for which there are infinitely many pairs of consecutive primes which differ by exactly $\ell$.
(Expanding on the first paragraph as requested:)
As an example, consider the current bound: there are infinitely many prime gaps of length at most 246. Since any such gap must be a positive even integer, the only choices for such a gap are 2, 4, …, 244, and 246. If there were only finitely many gaps of length 2, and only finitely many gaps of length 4, and so on up to 246, then there would have to be only finitely many gaps of length at most 246. Hence one of these must be wrong, and there is some $2 \le n \le 246$ such that there are infinitely many gaps of length n.
Comment: @TheGhostOfGaussPossessesMe Done. Does that help?
Comment: Can you elaborate more on the proof in your first paragraph?  Thanks.  I don't understand why it's true.