What test should I use for a unipolar ordinal rating-scale?

Question: I am trying to analyze answers to 5-point unipolar rating items.
The possible answers can for instance be:
Not at all difficult, Slightly difficult, Moderately difficult, Very difficult, or Extremely difficult.
The respondents have answered each item twice, once regarding an assistive device they are currently using, and one regarding a proposed assistive device.
I'd like to answer:

if any device is regarded better for each item;
if a given item is
an issue for each device.

I'm assuming that the answers to the items are ordinal and can be asymmetrical. N = 14
For 1, I'm using a paired, two-sided Wilcoxon signed rank test, and am plotting the contingency matrix. I'm decently satisfied with this setup (but suggestions are always welcome).
It's mainly about 2 I'd like some feedback. All questions I find regarding this concerns two-sample tests and/or real likert items (bipolar items, e.g. agree/disagree). Since this is a one-sample test the Mann–Whitney U test many seem to rely on is ruled out, and as unipolar items probably are not symmetrical the Wilcoxon signed rank test shouldn't be used either.
The only nonparametric, one-sample test that does not assume symmetry I've found is the sign test. So currently I am using a one-sided sign test, testing that the median is not at 0 (Not at all difficult). In addition I am plotting histograms for the answers.
Does this sound right? Any feedback would be very appreciated!
Comment: What does "a given item is an issue for each device" exactly mean? It seems you optimally want all answers at 0 (not at all difficult), but are prepared to tolerate some deviation. A test will not tell you how much deviation you should be willing to tolerate. You can test median=0 with the sign test, alright, but whether median=0 is actually what you're interested in, neither we nor the data can know.
Comment: To be somewhat provocative: I have the impression that you are not at all sure whether median=0 is what you think an issue really means, but want to test this because you have found a test that does it. If you had a different definition, it may be possible to construct a tailor-made test. It is not clear whether you need a statistical test at all. You could also say, more than 20% nonzero is too much, absolute, in the numbers, without testing. Your decision. Why do you think you need a test?
Comment: @ChristianHennig Well put! It means basically what you're suggesting: if an item, say "Using the device is mentally..." has a median=0 ("not at all taxing"), I would interpret that as that the device in question doesn't have an issue with this. It feels a bit arbitrary, but would it then make sense to for instance test the alternate hypothesis median < 0.5?
Comment: If you reject, there's evidence that the median is in fact smaller than 0.5. It really boils down to your decision. If this is what you think an "issue" means, then this is OK (of course you also have to decide the test level). I'm not really sure how you think we know better than you whether this makes sense, as obviously you understand the setup and we don't.
Comment: @ChristianHennig Thank you for your comments, this is exactly the kind of feedback I was hoping for!
Comment: You're right that a statistical test might not be optimal, II more-or-less want a way to say "this item here is not an issue for this device, as can be seen by x". I might have been too focused on finding a test for this, possibly due to that it would feel less arbitrary than a frequency threshold.  But thinking about it more it seems both less convoluted and more intuitive, with about the same amount of "arbitrariness".
Answer: Regarding question 2: The first thing to acknowledge here is that it is your decision what counts as "an issue". It looks like the answer coded 0/zero ("not at all difficult") is the desirable response, and even "slightly difficult" is already something of a problem. On the other hand you do not expect in any case that everybody will respond zero, so it seems that you are willing to say that if there is a good proportion of zeroes but less than 100%, it's fine.
The problem here is that the data can't tell you which proportion of zeroes is fine. This has to be decided on subject matter grounds. You may be tempted to say that it's 50% on grounds that there is a statistical test that tests that, but (a) obviously this is not a reason to believe that that's the correct number on subject matter grounds, and (b) in principle you could test any other percentage based on the Binomial distribution (just test $q=0.8$ one-sided with $q$ being the probability for zero or $p=0.2$ as probability for nonzero by a Binomial test).
So you could well say "80% (or whatever) zeroes are required" and test that. Neither the data nor statistical theory can tell you which percentage to demand.
A problem with this kind of test (incl. your sign test idea) is that this will not take into account how the nonzeroes are distributed, i.e., 80% 0, 20% 1 is counted in the same way as 80% 0, 5% 1, 15% 4. It will be more difficult to construct tests if you want to set more complex requirements to take into account also the actual distribution of nonzeroes (for example you might want to say min 80% zero, max 5% 3 or 4). It may well be be possible but I don't know out of the top of my head how to do it (it will depend on what exactly your criterion is).
Another question is whether you need any test al all. You could also say that you decide whether there is an issue just from looking at the empirical numbers. If you did that, obviously there were no problem with a criterion such as "min 80% zero, max 5% 3 or 4", you could just check this directly.
I'm using the 80% criterion as example below but there's nothing special about 80%, ultimately you have to decide what your criterion is.
Advantage of using a test: You may want to avoid to declare an "issue" if what you see may just be caused by random variation. For example, if you say your criterion is min 80% zeroes and you see just 77%, you may think that in fact in the population there might be 80% and you just observed 77% because of an unlucky sample. (This would require thinking about whether you have something that can be treated as a proper random sample of a well defined population, because if you don't, a test will be invalid anyway.)
But keep in mind that if you observe 77%, these 77% are your best guess of how many zeroes you'd find in the population. If the test doesn't reject 80%, it doesn't mean that 80% is in fact true. The test gives you something of a "probability guarantee" (i.e., not a 100% reliable one;-) that if indeed the proportion is 80% or higher, your "alarm" will not normally be triggered, but the true proportion may well be lower. Whether this is a good thing depends on whether in a situation in which you observe below 80%, you'd be happy to not declare an issue because the true probability might be 80%, even though in fact it may also be lower. This depends on the consequences of this decision. It may also depend on the sample size, because if the sample size is reasonably big, you will not reject 80% only if the empirical (and also in all likelihood the true) population is pretty close to 80%, if potentially slightly lower, whereas if the sample size is low, you may still not reject 80% with a certain probability even in case of a true population proportion around 0.5, say. You may be willing to tolerate the former but not the latter.
So it all depends on (a) what your definition of a "borderline issue" is, and (b) what the consequences are of your "declaration of an issue" (or the absence of it).
Comment: Thank you for your comprehensive and thoughtful answer! As I noted earlier, this is the sort of feedback I was hoping for, and you've given me a lot to consider :)


php5:pass objects through Form ? can it be done?

Question: i have this littel problem with a test app.
Current look:
<form>
1:Question goes here
<input type=hidden name=true_1 value=10>
<input type=hidden name=false_1 value=20>
<input type=hidden name=target_1 value=color>
<select name=answer_1[]><option>blah</option><option>etc</option></select>

2:Question goes here
<input type=hidden name=true_2 value=40>
<input type=hidden name=false_2 value=20>
<input type=hidden name=target_2 value=size>
<select name=answer_2[]><option>blah</option><option>etc</option></select>
</form>

currently i use a script that explode("_",$get); so i can handle each question with its own properties.
Current approach
1.Get questions from database. (question,target,true,false,answers)
2.loop throught them and creat a form similar to one i wrote above for all questions
3.When posted i explode to get each question properties alone
4.pass them to function that evaluate if answer correct or false and give score
what im trying to do is to turn this into oop
1.creating an object for each question and assign its own properties(question,true,false,target,answer) foreach($question)$q[1]=new question();
2.echo the $q[] for user to answer.
3.receive the $q[] after user answer and $_POST them.
hope i described this right.but its very important for me to keep every thing dynamically so i need to include hidden fields.
is it doable ?
Answer: You could use json datatype for this kind of task (assuming your objects just store data, not methods nor require __sleep, __wakeup, etc).
<input name="fooBar" value="<?php echo json_encode(/*some_array_with_data*/);?>">

After form POST you can do something like
$_POST['fooBar'] = json_decode($_POST['fooBar']);

and start iterating resulting array.
NB. since json_encode results in string containing chars like " you should also use base64_encode, url_encode or something like that.


Tornado Request Handler

Question: For some reason i am unable to instantiate the set_cookie outside of the MainHandler..
This is a little code to show what im wanting to do..
Can Anyone help??
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from GenCookie import *

class MainHandler(tornado.web.RequestHandler):
     def get(self):
       g=GenCookie()
       response = g.genCookie()

class GenCookie:
 def genCookie(self):
    print self.request.remote_ip
    print self.cookies
    print self.request.headers
    expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
    if ("uid" in cookies):
       self.set_cookie("uid", value=cookies["uid"],expires=expires)
    else:
       self.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
    return

Any ideas?
Answer: I thought that explains itself.
set_cookie is a method of tornado.web.RequestHandler
while in your code "self.set_cookie", self refers to object of class GenCookie.
Your code can be modified to pass the necessary reference
class MainHandler(tornado.web.RequestHandler):
     def get(self):
       g=GenCookie(self)
       response = g.genCookie()

class GenCookie:
 def __init__(self, reqHandler):
    self.reqHandler = reqHandler

 def genCookie(self):
    print self.request.remote_ip
    print self.cookies
    print self.request.headers
    expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
    if ("uid" in self.cookies):
       self.reqHandler.set_cookie("uid", value=self.cookies["uid"],expires=expires)
    else:
       self.reqHandler.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
    return

Tornado Request Handler


How to print a 2D matrix as a one-line string?

Question: How would one take a matrix and convert it to a string with all the values being on one line?
For example:
input: [[3,4,1,5],[5,3,2,1]]
output: "34155321"

Comment: Does this answer your question? [How to print a 2D list in one line?](https://stackoverflow.com/questions/47752354/how-to-print-a-2d-list-in-one-line)
Comment: I updated your title because it was misleading. There is no dictionary, that's a 2D list or a list of lists.
Answer: There are many ways to do this. Here's one:
L = [[3,4,1,5],[5,3,2,1]]
print(''.join([''.join(map(str, L_)) for L_ in L]))

Output:
34155321

Answer: This code will combine all item from a given list to a String
input_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

output = ""

for item in input_list:
    for num in item:
        output += str(num)

print(output)

The output of the code:
123456789

Answer: First of all: Your input is not a dicionary but a list.
Solution:

flatten your list of lists
join the elements of the list

# 1. flatten your list:
def flatten(xs: list):
    for x in xs:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x

# 2. join the list to string
result = "".join(map(str, flatten(input)))

The map(str, x) takes an iterable x and converts each element in x into a string which is necessary to apply join() on x.


An upper bound for number of edges

Question: Prove that if the complement of a graph $G$ is disconnected, then we have the following inequality:
$$ |\text{number of edges of}~ G| \leq\Delta(G)^2$$
Such that $\Delta(G)$ is the maximum degree in the main graph G.
My problem with this question is that I do not know how we can use the disconnectivity fact, Is there any similar problems that gives the lower or upper bound on edges when a graph or its complement is disconnected?
Answer: I'll use two claims to prove this:

$\frac{\vert V(G)\vert}{2}\leq\Delta(G)$

$E(G)\leq \frac{\vert V(G)\vert }{2}\cdot\Delta(G)$

Using that, we get:
$$\vert E(G)\vert \leq \frac{\vert V(G)\vert}{2}\cdot\Delta(G)\leq \Delta(G)^2$$
Which is what we wanted to prove.
Proof of 1:
If $\bar G$ (the complement of $G$) is disconnected, it has more than one connected component, (so at least two).
Therefore, one of those connected components size is at most $\frac{\vert V(G)\vert}{2}$.
Denote it by $A$.
Now, let $v$ be some vertex in $G$.
$v$ is adjacent (in $G$) to every vertex $u\notin A$.
Therefore $$\deg_G(v)\vert V(G)\vert-\vert A\vert\geq \frac{\vert V(G)\vert}{2}$$
and since $\Delta(G)\geq \deg_G(v)$, we get $\frac{\vert V(G)\vert}{2}\leq\Delta(G)$
Proof of 2:
$$2\vert E(G)\vert = \sum_{v\in V(G)} \deg(v)\leq\sum_{v\in V(G)} \Delta(G)=\vert V(G)\vert\cdot\Delta(G)\implies \\
\vert E(G)\vert\leq \frac{\vert V(G)\vert}{2}\cdot\Delta(G)$$

An upper bound for number of edges


Undefined offset error 0

Question: I have this code that will check if the month eg. january has a value of 0 and if its true it will execute the update query.
But i'am getting this error "Notice: Undefined offset: 0 "
$value_result = mysql_query("SELECT form_no FROM table_2014 WHERE form_no = '$formnumber'");
    while($row = mysql_fetch_assoc($value_result)){
        if ( $row['january' == '0']){
            $sql = "UPDATE `table_2014` SET january = '$contri_amnt' WHERE form_no = '$formnumber'";
            if (!mysql_query($sql,$con))
            {
                die('Error: ' . mysql_error());
            }
        }
        else{
            echo "Already contributed!";
            }
    }

Comment: There is **no more support** for `mysql_*` functions, they are [**officially deprecated**](https://wiki.php.net/rfc/mysql_deprecation), **no longer maintained** and will be [**removed**](http://php.net/manual/en/function.mysql-connect.php#warning) in the future. You should update your code with [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) to ensure the functionality of your project in the future.
Answer: $row['january' == '0']

will return $row[false], which is $row[0]
i think you meant
$row['january'] == '0'

Answer: You should not use mysql_* functions anymore. They are deprecated + they are insecure because you wouldn't have to escape anything. I suggest you to use PDO instead and prepared statements.
You should do :
$value_result = mysql_query("SELECT form_no FROM table_2014 WHERE form_no = '".(int)$formnumber."'");
//guessin that the fields where all integers, since compareing against a "0"
while($row = mysql_fetch_assoc($value_result)) {
    if ( isset($row['january']) && $row['january'] == '0') {
        $sql = "UPDATE `table_2014` SET january = '".(int)$contri_amnt."' WHERE form_no = '".(int)$formnumber."'";

        if (!mysql_query($sql,$con)) {
            die('Error: ' . mysql_error());
        }
    }
    else {
        echo "Already contributed!";
    }
}

Undefined offset error 0


Unable to get desired output from python list

Question: I have a little issue with my the following python code I have.
I have a list which contains the following elements. This list could also be empty with NO contents.
As you can see, the This is my first stock I bought 01.27.2019 is encode and I have to decode it to remove the b''. When I perform the split operation on the mylist, I get '' as the first item in the list, and I am not sure why.
mylist = "$17$b'This is my first stock I bought 01.27.2019'"
The fields in mylist are seperated by a $ rather than a ,

        tmp_list = mylist.split('$')
        print (tmp_list) # ['', '17', "b'This is my first stock I bought 01.27.2019'"] ---> Not sure why I have the '' as the first item in the tmp_list
        tmp_iter = iter(tmp_list)
        res['myinfo']= '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}'

I want my res['myinfo'] to be "{{17, This is my first stock I bought 01.27.2019}, ...many more {,}}.
At times, the res['myinfo'] could just be "{}" if the mylist = [""].
I am not sure on how to fix my code, any help would be appreciated.
Comment: `mylist = [$17$b'This is my first stock I bought 01.27.2019']` That's not valid Python code.  What are those dollar signs doing?
Comment: Those are the contents of my list. Not sure what you mean its invalid code? The fields in my list are seperated by a ```$``` rather than a ```,```.
Comment: It causes a `SyntaxError`. My guess is you actually  have something like `mylist = "$17$b'This is my first stock I bought 01.27.2019'"`
Comment: @RobBricheno Exactly!! Made update to the question
Comment: "_When I perform the split operation on the mylist, I get '' as the first item in the list_" That's probably because the first character in the string is your separator (`$`). What comes before that? Nothing.
Comment: You can also try to do something like this: tmp_list = mylist[1:].split('$')
Answer: First of all
mylist = "$17$b'This is my first stock I bought 01.27.2019'"

Should be
mylist = "17$b'This is my first stock I bought 01.27.2019'"

Just as @takendarkk said

That's probably because the first character in the string is your
  separator ($). What comes before that? Nothing. – takendarkk

As for decoding your string assuming they are all like: " b' some string ' " and have an age before them you have to decode every odd indexed elements in your list. A very straigth forward solution could be:
def decodeString(stringToDecode):
    decodedList = []
    for i in range(2, len(stringToDecode)-1):  #every character except the first 2 and the last one
        decodedList.append(stringToDecode[i])
    decodedString = ''.join(decodedList)
    return decodedString

for i in range(len(tmp_list)):
    if i % 2 == 1:                                 #every odd indexed element
        decodedString = decodeString(tmp_list[i])
        tmp_list[i] = decodedString

And also it seems like you need 1 more layer of '{}' here:
res['myinfo']= '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}'

This way your res['myinfo'] is {17,This is my first stock I bought 01.27.2019},{18,This is my second stock I bought 01.28.2019} but if you want it to be '{{17,This is my first stock I bought 01.27.2019},{18,This is my second stock I bought 01.27.2019}}' as you said you need:
res['myinfo']= '{' + '{' + '},{'.join(f'{n},{s}' for n, s in zip(tmp_iter, tmp_iter)) + '}' + '}'


Select all rows where ID, but only the most recent where duplicates occur

Question: I have a table called Stats in my database:
| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       1 |    1  |    2017-04-03 |
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |
|       1 |       1 |    4  |    2017-05-03 |

And I currently use the following query to fetch all rows for a specific Game_ID:
"SELECT * FROM Stats WHERE Game_ID = 2 ORDER BY Rank ASC"

This returns exactly what is shown above, I would however like to return only one row per User_ID (The one with the most recent Creation_date), like this:
| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |
|       1 |       1 |    4  |    2017-05-03 |

Any help would be appreciated!
EDIT
I tried the solution above, and I'm certain it is the right one. I dont get duplicates anymore of the User_ID. However, I don't get the latest Creation_date. What am I missing?
The updated query:
SELECT a.Game_ID, a.User_ID, a.rank, a.Creation_date
            FROM stats a
            INNER JOIN (
                SELECT User_ID, MAX(Creation_date), Creation_date
                FROM stats
                WHERE Game_ID = 2
                GROUP BY User_ID
            ) b ON a.User_ID = b.User_ID AND a.Creation_date = b.Creation_date ORDER BY rank ASC;

Returns:
| Game_ID | User_ID |  Rank | Creation_date |
---------------------------------------------
|       1 |       1 |    1  |    2017-04-03 |
|       1 |       2 |    2  |    2017-04-03 |
|       1 |       3 |    3  |    2017-04-03 |

In other words, not the row with the most recent Creation_date for User_ID 1.
Answer: Try this -
SELECT Game_ID, User_ID, MAX(Rank), Max(Creation_date)
FROM Stats
WHERE Game_ID = 2
GROUP BY Game_ID, User_ID, Creation_date
ORDER BY Rank, Creation_date

Comment: Still gives me all four rows, ordered by Creation_date instead of Rank.
Comment: @Stim, try the edited one.


How do I round -13422.8450 to -13422.84 in SQL Server

Question: I want to round off -13422.8450 as -13422.84 in SQL Server.
But using ROUND(-13422.8450, 2) is returning -13422.85
This is the full query:
SELECT ROUND(CAST(-1 * 50 * 26845.69 / 100 AS NUMERIC(13, 4)), 2)

Comment: While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example):
(1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements.
(2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL.
(3) Desired output, based on the sample data in the #1 above.
(4) Your SQL Server version (SELECT @@version;).
Answer: Add a third parameter having non-zero value to ROUND function; the function will truncate instead of rounding:
SELECT ROUND(-13422.8450, 2)
-- -13422.8500

SELECT ROUND(-13422.8450, 2, 1)
-- -13422.8400

Be advised that casting from numeric to numeric will round the result before the round function is called. In your example you need to round (truncate), then cast.


How to pick only certain data

Question: I would like to pick up only data in column x and x-date for each person.
(in condition of x-date is between day1 and day2 columns for each person). Please see the picture below
For example,
a, x=111, x-date=2/2/2016
b, x=8990, x-dates=2/3/2016
c, x=333, x-dates=5/5/2011

Comment: My first suggestion would be to paste your data using `dput(df)` instead of using an image, see -  http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: What have you done so far? And +1 on `dput(df)`; the structure of your data (e.g. the format of your dates) is relevant here.
Answer: If I got your question right, and if all your dates are in Date format, you could probably just do something like that :
Base R :
 df[(df$x-date > df$day1 & df$x-date < df$day2), c('person', 'x', 'x-date')]

Answer: you could use the subset function.
subset(df, x==111 & x-date=='2/2/2016', select = c(person,x,x-date))

How to pick only certain data


why does adding a space makes the compiler go into an infinite loop?

Question: Case 3 is an option to add a book to the structure. As long as books with titles without spaces are added, they are ok, whenever I try to put a name that has a space in it, the compiler goes crazy, sorta like what it would do if you execute an infinite loop. Why and what is the solution?
struct bookStruct
{
    string bookTitle;
    int bookPageN;
    int bookReview;
    float bookPrice;
};

const int MAX_BOOKS=10;

case 3:
        {
            for(int i=0;i<MAX_BOOKS;i++)
            {
                if(books[i].bookTitle=="\0")
                {
                cout << "\nPlease Enter the Title: ";
                cin >> books[i].bookTitle ;
                cout << "\nPlease Enter Total Number of Pages: ";
                cin >> books[i].bookPageN ;
                cout << "\nPlease Enter Rating (stars): ";
                cin >> books[i].bookReview ;
                cout << "\nPlease Enter Price: ";
                cin >> books[i].bookPrice;
                cout << "\n\nBook Added.\n\n";
                break;
                }
            }break;

        }

Comment: You've posted 3 questions regarding your code. Don't you think you should figure this stuff out on your own via searching like google or using a debugger?
Comment: The *compiler* doesn't do anything unusual.  It is your program that the compiler created on your behalf that gets stuck.
Comment: @Rapptz I have trying that all day, with no luck and no valid answers from here either.
Comment: If you don't think none of the answers given to your questions are valid, or rather "acceptable", then you should not mark them as accepted.
Comment: By the way, comparing with `"\0"` is a bit redundant as `""` contains one `'\0'` character, and the former contains two. Even better is `if (books[i].bookTitle.empty())`.
Comment: @chris I think the problem is in the loop, rather than the comparison.
Comment: The comparison's fine. I was merely commenting on the redundancy and suggesting the ideal way of checking whether a string is empty.
Comment: Also see: http://stackoverflow.com/a/14312884/14065
Answer: The input operator >> stops at space when reading strings.
What you want to use is std::getline.
cout << "\nPlease Enter the Title: ";
std::getline(std::cin, books[i].bookTitle);

The input operator >> when reading a number will also stop at a space or newline (leaving them on the input stream). Thus when you wrap around to the next book there is still a '\n' character on the input stream. So for numbers you also need to use std::getline(). But in this case you need to convert the value to an integer.
cout << "\nPlease Enter Total Number of Pages: ";
std::string line;
std::getline(std::cin, line);

std::stringstream linestream(line);
linestream >> books[i].bookPageN ;

Comment: @MokammelHossainSanju Read my answer again.
Comment: @MokammelHossainSanju: The reason it goes into an infinite loop is the stream becomes bad and there is a bug in some other part of your code that you have not shown. To fix the local problem see the updated answer.
Comment: @MokammelHossainSanju: But you are doing it wrong. You should be defining an input operator for the class `bookStruct`.
Comment: any suggestions on how to fix it?
Comment: why this doesnt work and still is putting my code through an infinite loop when I use a space.


JavaScript array to PHP via AJAX

Question: I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...
But what i get is something like this:
a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...
I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?
The JS code is as follows:
window.onbeforeunload = function() {
  var jsonString = JSON.stringify(tabela);
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {
            text1: jsonString
        }
    });
}

And the PHP side is this:

    $text1 = json_decode(stripslashes($_POST['text1']));
    $string_data = serialize($text1);
    file_put_contents("your-file.txt", $string_data);

Comment: You dont `stripslashes()` a json format unless encoded with `JSON_UNESCAPED_SLASHES` and **never** serialize user input as its a security risk.
Comment: True, sorry, but even if i remove that, it still does not work as expected...
Comment: As @Rafael says, just store it directly into the file: `file_put_contents("your-file.txt", $_POST['text1'] . PHP_EOL);`
Answer: The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize.
If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.
Comment: Thank you, your anwser helped me.
Comment: @TadejBogataj if it helped, have the courtesy to upvote and you can mark it as in answer in 15 minutes after asking your question.

JavaScript array to PHP via AJAX


Equations with mod 8

Question: I need help answering this math question. What is $$123456789^{25} - 323\times 1212121212 \mod 8$$ I get about half ways and get lost. Please help me figure this out.
Comment: Should the exponent be 2 or 25?
Comment: Write your expressions using mathjax. Else they cannot be understood.
Comment: $789^{25}\equiv 789^{25\pmod {4}}\pmod{8}$ by Euler's theorem, so $\equiv 789^{1}\equiv 5\pmod{8}$. Also $323\cdot 212\equiv 3\cdot 4\equiv 12\equiv 4\pmod{8}$.
Comment: In general $\overline{a_na_{n-1}\cdots a_2a_1a_0}\equiv \overline{a_2a_1a_0}\pmod{8}$.
Comment: @Mikaela, for now I have re-written your expression with mathJAX, to learn how to do it, see
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: Hint: $123456789\equiv5\pmod 8$, so $123456789^2\equiv5^2=25\equiv1\pmod8$; and $323\equiv3\pmod8$ and $1212121212\equiv4\pmod 8$. This should make it easy to answer the original question, in your head even! This is the moral of problems like this: always reduce early on, to make the arithmetic easier.
Answer: The answer is 1 and it goes as: 789^25-212. Now the group of units is isomorphic with Z_2+Z_2 and so the maximal order is 2. Thus 789^25=789^1=5. And 212=4. The answer is 1.
Comment: In my opinion, the reduction of the original numbers doesn't go far enough. See my comment on the main question.

Equations with mod 8


Migrate from Kontakt 5 to 6 in Logic Pro X

Question: I purchased NI Kontakt 5 in 2017, and I upgraded to 6 just today in Oct 2020.
I have a bunch of Logic Pro X projects using Kontakt 5 instruments, and I want to migrate them to Kontakt 6 and then uninstall Kontakt 5 to save some disk space.
How do I mass-convert my Kontakt 5 tracks to Kontakt 6?
Answer: Track-by-track conversion is possible by first saving the Kontakt 5 instrument as an *.aupreset file then switch to Kontakt 6 and load that file.
To save a Kontakt instrument as an *.aupreset file,

click on the instrument rack in the track strip to open the instrument settings window;

click on the drop-down menu bar to the right of the blue track-enable indicator button;

click "Save As" option and save the instrument.

To load the just-saved instrument in Kontakt 6, go to the same drop-down menu and click the "Load..." option and select the just-saved *.aupreset file.
Mass-convert don't seem possible, as the "bundle identifier" of the main "Info.plist" are different for 2 versions: Kontakt 5.MusicDevice.component and Kontakt.MusicDevice.component. You can check them in /Library/Audio/Plug-Ins/Components
So while it's a shame there's no easy way to mass convert K5 to K6, there's hope K6 to K7 conversion will be viable in the future if NI developers drop version number entirely in the bundle identifier.
Comment: I'm not a programmer, but plenty of folks on this site are (as it's a descendant of Stack Overflow). Surely somebody can come up with a bit of terminal code to manipulate logic files to replace the Kontakt 5 references with Kontakt 6. Or maybe I'm wrong, because all the plugin settings might be different too, which would cause errors...
Comment: @BobBroadley I don't think "terminal code" is feasible, as terminal shells function by executing external programs and Logic is probrably not installing any additional programs. I've probed Logic project data using the [file(1)](https://man.freebsd.org/file) command and it doesn't show recognizable structure. Apple Script might be possible, but I haven't tried.
Comment: @DannyNiu Can you please explain how to save the Kontakt 5 instrument as an `*.aupreset`? I can't find that information anywhere.
Comment: @jordanbtucker Done.


Drupal 6: display CCK Field value with php in views_customfield

Question: SORTED
http://drupal.org/node/467190#comment-2068324

Hi friends,
I've spent all day to find but can't find :(
How can I display CCK Field value with php in views_customfield? I tried the ones below, but no result
$node->field_homepage_linking[0]["view"]

$node->field_homepage_linking[0]["value"]

value_get('field_homepage_linking')

Appreciate helps!!

$node->field_homepage_linking[0]["view"]
this works in tpl.php files, not not
  working in View Module panel as below
  (screenshot)

alt text http://img.skitch.com/20100616-dy2pxkdichni7nu1h747tptfa8.jpg
<?php
 if ($node->field_homepage_linking[0]["view"] == 1) { ?>
    <a href="<?php print drupal_get_path_alias("node/" .$data->nid) ; ?>" title="<?php print $data->node_title; ?>">
<?php } ?>
<?php print $data->node_title; ?>
<?php  if ($node->field_homepage_linking[0]["view"] == 1) { ?>

<?php } ?>

Comment: Are you trying to do this in the views_ui or in a template file? Can you please also provide a screenshot or dump of your views definition.
Comment: added screenshot to question. Thanks a lot for giving time!
Answer: Looks like a clerical error.
$node->field_homepage_linking["0"]["value"]

Should be:
$node->field_homepage_linking[0]["value"]

Although, if its a CCK field, why not just add it as a Field? All CCK fields are under the Content category of the Fields. Also, to do this, you need the $node object loaded and ready to use by Views, which may also be why you aren't seeing anything.
Looks like you want to have a conditional display. I am not sure how to do this in Customfield, but I have done this many times with a .tpl field for particular fields. You can add theme tpl files to Views and have PHP code inside it, and also dump out the $row and $data object of views to see what fields/values you have to work with.
Comment: yes yes I tried $node->field_homepage_linking[0]["value"], but still not working. I have created this block with block, then I need to add such a silly control, that's why I'm trying to implement this to my current view. Themer gives views-view.tpl.php name as candidate. it looks so common name, I created many blocks with view, and i dont wanna mess :/ offf
Comment: It can override all views or very specific views, its up to you. Views gives you the choice of specificity when it comes to TPL overrides.
Answer: SORTED
http://drupal.org/node/467190#comment-2068324
Answer: This works for me:
The PHP code in customfield for loading cck field
$node = node_load($data->nid, NULL, TRUE);
echo $node->field_name_of_field[0]["value"];


Skipping unmapped SAML 2.0 attribute, even though name and nameFormat match

Question: SP running Shibboleth 2.5.6. For one particular IdP, I have these attribute mappings:
<Attribute name="role"
    nameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"
    id="role" />
<Attribute name="urn:mace:dir:attribute-def:givenName"
    nameFormat="urn:mace:shibboleth:1.0:attributeNamespace:uri"
    id="givenName" />

I receive a wire message containing:
<AttributeStatement>
    <Attribute Name="role" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
        <AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Educator</AttributeValue>
    </Attribute>
    <Attribute Name="urn:mace:dir:attribute-def:givenName" NameFormat="urn:mace:shibboleth:1.0:attributeNamespace:uri">
        <AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">intraguest</AttributeValue>
    </Attribute>
</AttributeStatement>

Which logs:
Shibboleth.AttributeExtractor.XML : creating mapping for Attribute role, Format/Namespace:urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified
Shibboleth.AttributeExtractor.XML : creating mapping for Attribute urn:mace:dir:attribute-def:givenName
...
DEBUG Shibboleth.AttributeDecoder.String [1]: decoding SimpleAttribute (role) from SAML 2 Attribute (role) with 1 value(s)
INFO Shibboleth.AttributeExtractor.XML [1]: skipping unmapped SAML 2.0 Attribute with Name: urn:mace:dir:attribute-def:givenName, Format:urn:mace:shibboleth:1.0:attributeNamespace:uri

Why is givenName skipped, when its name and nameFormat match?
I note that the Format/Namespace comment is missing from the "creating mapping" log line for givenName, but I presume that's because the given nameFormat matches the default.

Update:
The IdP is a PingFederate source, whose metadata claims to SAML 2. Here is the relevant excerpt from the meta-data:
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" ID="..." entityID="...">
    <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
        <saml:Attribute xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Name="urn:mace:dir:attribute-def:givenName" NameFormat="urn:mace:shibboleth:1.0:attributeNamespace:uri"/>
        <saml:Attribute xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Name="role" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"/>
    </md:IDPSSODescriptor>
</md:EntityDescriptor>

Comment: Is the IDP passing you saml2 attributes and you are mapping 1?
Comment: @Sum1sAdmin We're wanting to map SAML2, and the IdP claims SAML2, but its meta-data shows this 1.0 `NameFormat` uri. Which, to me, is odd. See update.
Answer: We were having the same issue. Apparently Shibboleth cannot mix the formats of SAML 1 and SAML 2. You have to use them as follows (https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPAddAttribute):

SAML 1:

urn:mace:shibboleth:1.0:attributeNamespace:uri (default)
If you want to map an attribute with another format (but not a SAML 2 format), you have to specify it in the attribute mapping using the nameFormat attribute.

SAML 2:

urn:oasis:names:tc:SAML:2.0:attrname-format:uri (default)
urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified (default)
If you want to map an attribute with another format (but not a SAML 1 format), you have to specify it in the attribute mapping using the nameFormat attribute.

So the problem you are having is that you receive a SAML 2 message with an attribute using a SAML 1 format and that is not supported by Shibboleth, even if you explicitly tell Shibboleth to use the SAML1 format using the nameFormat attribute.
We solved the problem by asking the PingFederate IdP team to send us the attributes using the SAML 2 "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified" format (because that is apparently a format that is easy to support in PingFederate). In our attribute mapping, we do not use the nameFormat attribute because this format is a default of Shibboleth.
I hope this helps you solve the problem.


To evaluate $\text{Pr}(X=k| X+Y=n)$

Question:
I have to show that if $X\sim Poisson(\lambda_1), Y\sim Poisson(\lambda_2)$ are independent then   $$ Pr(X=k| X+Y=n)={n \choose x}p^k q^{n-k} $$ where $p=\frac{\lambda_1}{\lambda_1+\lambda_2}$ and $q=\frac{\lambda_2}{\lambda_1+\lambda_2}$.

My attempt:
\begin{align*}
Pr(X=k| X+Y=n) & = \frac{Pr(X=k,X+Y=n)}{Pr(X+Y=n)}\\
               & = \frac{Pr(X+Y=n,X=k)}{Pr(X+Y=n)}\\
               & = \frac{Pr(X+Y=n| X=k)\cdot Pr(X=k)}{Pr(X+Y=n)}\\
               & = \frac{Pr(Y=n-k)\cdot Pr(X=k)}{Pr(X+Y=n)}\\
               & = \frac{\frac{e^{-\lambda_2}\lambda_2^{n-k}}{(n-k)!}\cdot \frac{e^{-\lambda_1}\lambda_1^{n-k}}{k!}}{\frac{e^{-\lambda_1-\lambda_2}{(\lambda_1+\lambda_2)}^{n}}{n!}}\\
&= {n\choose k}p^k q^{n-k}
\end{align*}
Please check my solution.
Thanks.
Comment: I still see some typos in the same place. Assuming they are typos, this should be conceptually correct.
Comment: Something looks off in the second to the last line.
Comment: Yeah that was typos, so I corrected it. Thanks.
Answer: Some comments. $X$ and $Y$ are independent? (Independence has been used in the fourth equality). In fifth equality there are typos regarding factorials. Is $X+Y$ random variable a poisson random variable? (Check it's validity if the score for this question in test is set "very" high!)
Comment: Sorry they are independent.
Comment: No need to be sorry. Glad to be of help.

To evaluate $\text{Pr}(X=k| X+Y=n)$


python find substrings based on a delimiter

Question: I am new to Python, so I might be missing something simple.
I am given an example:
 string = "The , world , is , a , happy , place "

I have to create substrings separated by , and print them and process instances separately.
That means in this example I should be able to print
The
world
is
a
happy
place

What approach can I take? I was trying to use the string find functionality, but
Str[0: Str.find(",") ]

does not help in finding 2nd, 3rd instances.
Answer: Try using the split function.
In your example:
string = "The , world , is , a , happy , place "
array = string.split(",")
for word in array:
    print word

Your approach failed because you indexed it to yield the string from beginning until the first ",". This could work if you then index it from that first "," to the next "," and iterate across the string that way. Split would work out much better though.
Answer: Strings have a split() method for this.  It returns a list:
>>> string = "The , world , is , a , happy , place "
>>> string.split(' , ')
['The', 'world', 'is', 'a', 'happy', 'place ']

As you can see, there is a trailing space on the last string. A nicer way to split this kind of string would be this:
>>> [substring.strip() for substring in string.split(',')]
['The', 'world', 'is', 'a', 'happy', 'place']

.strip() strips whitespace off the ends of a string.
Use a for loop to print the words.
Answer: Another option:
import re

string = "The , world , is , a , happy , place "
match  = re.findall(r'[^\s,]+', string)
for m in match:
    print m

Output
The
world
is
a
happy
place

See a demo
You could also just use match  = re.findall(r'\w+', string) and you will get the same output.
Answer: Simple thanks to the convenient string methods in Python:
print "\n".join(token.strip() for token in string.split(","))

Output:
The
world
is
a
happy
place

By the way, the word string is a bad choice for variable name (there is an string module in Python).


Erro ao subir site

Question: Pessoal acabei de subir um site meu feito no Laravel 5.2 com pho 5.6 localmente. Subi para uma hospedagem compartilhada na Locaweb que tenho. Configurei o PHP 5.6 de forma correta e subi o site ai esta me dando a seguinte mensagem de erro.

Fatal error: Call to undefined function Symfony\Polyfill\Mbstring\iconv_strpos() in /home/storage/b/71/41/supra/public_html/vendor/symfony/polyfill-mbstring/Mbstring.php on line 351

Este é o primeiro site que subo na versão 5.2 do Laravel. Na versão 5.1 nunca tive nenhum problema.
Veja se vocês conseguem me ajudar. Muito Obrigado
Comment: A melhor opção talvez seja trocar de hospedagem :D
Comment: **Mbstring PHP Extension**. Essa extensão está habilitada no server ? Locaweb... tem que duvidar de tudo.
Comment: @PeterParker Olha esta assim no phpinfo de la. Additional .ini files parsed:  /etc/php56.d/20-mbstring.ini entre outras bibliotecas nesta linha. Acredito que esteja habilitada sim.
Comment: Tem o site aí ?
Answer: Essa função que está dando erro não é a MBSTRING do PHP.
Perceba que há um namespace antes:
Symfony\Polyfill\Mbstring\icon_strpos()

Essa é  uma biblioteca do Symfony que provê  funções caso  a mesma não exista no sistema.
Talvez isso pode ser um erro de versão que foi instalada dessa biblioteca.
Você pode tentar rodar composer update antes de enviar os arquivos para o servidor.
Outro problema que percebi para quem está tendo esse problema é quando o php5-mbstring não está instalado.
Veja como proceder a instalação:
 sudo yum install php55-mbstring

Fonte: Laravel: Call to undefined function Symfony\Component\Console\mb_convert_variables()?
Caso seja um servidor compartilhado, contate o suporte técnico para ver se eles podem ativar essa extensão (dependendo da alteração,  mesmo sendo servidor compartilhado, eles alteram).
Comment: olha eu fiz isto. Inclusive por via das duvidas eu removi a pasta Vendor e e enviei novamente e o erro persiste. Ja pesquisei e não encontrei nada. Liguei no suporte da Locaweb e eles disseram que não dão suporte em programação.
Comment: @JoaoNivaldo dá uma pesquisada na internet para ver se você consegue ativar a extensão mbstring via `htaccess`... Não sei, mas pode ajudar!
Comment: O suporte da Locaweb resolveu o problema. O servidor php estava com problemas e reinstalaram ele ai deu certinho. Muito obrigado a todos.
Comment: O -1 deve ter um bom motivo, né, já que a resposta foi aceita

Erro ao subir site


Converter funções de adicionar e remover na árvore para recursiva

Question: Estou com dificuldades para fazer a conversão de duas funções de árvore em C para a forma recursiva.
int insere_arvore(ArvBin* raiz, int valor){
if(raiz == NULL)
    return 0;
NO* novo;
novo = (NO*) malloc(sizeof(NO));
if(novo == NULL)
    return 0;
novo->info = valor;
novo->dir = NULL;
novo->esq = NULL;

if(*raiz == NULL)
    *raiz = novo;
else{
    NO* atual = *raiz;
    NO* ant = NULL;
    while(atual != NULL){
        ant = atual;
        if(valor == atual->info){
            free(novo);
            return 0;
        }

        if(valor > atual->info)
            atual = atual->dir;
        else
            atual = atual->esq;
    }
    if(valor > ant->info)
        ant->dir = novo;
    else
        ant->esq = novo;
}
return 1;
}

NO* remove_atual(NO* atual) {
NO *no1, *no2;
if(atual->esq == NULL){
    no2 = atual->dir;
    free(atual);
    return no2;
}
no1 = atual;
no2 = atual->esq;
while(no2->dir != NULL){
    no1 = no2;
    no2 = no2->dir;
}
if(no1 != atual){
    no1->dir = no2->esq;
    no2->esq = atual->esq;
}
no2->dir = atual->dir;
free(atual);
return no2;
}

Tentei da seguinte forma:
int insere_rec_arvore(ArvBin* raiz, int valor, NO* atual){
if(raiz == NULL)
    return 0;
NO* novo;
novo = (NO*) malloc(sizeof(NO));
if(novo == NULL)
    return 0;
novo->info = valor;
novo->dir = NULL;
novo->esq = NULL;

if(*raiz == NULL)
    *raiz = novo;
else{
    NO* atual = *raiz;
    NO* ant = NULL;
    if (atual != NULL) {
        ant = atual;
        if(valor == atual->info){
            free(novo);
            return 0;//elemento já existe
        }

        if(valor > atual->info) {
            atual = atual->dir;
        } else {
            atual = atual->esq;
            insere_rec_arvore(raiz, valor, atual);
        }
    }
    if(valor > ant->info)
        ant->dir = novo;
    else
        ant->esq = novo;
}
return 1;
}

NO* remove_rec_atual(NO* atual, NO *no1, NO *no2 ) {
if(atual->esq == NULL){
    no2 = atual->dir;
    free(atual);
    return no2;
}
no1 = atual;
no2 = atual->esq;
if(no2->dir != NULL){
    no1 = no2;
    no2 = no2->dir;
    remove_rec_atual(atual, no1, no2);
}
if(no1 != atual){
    no1->dir = no2->esq;
    no2->esq = atual->esq;
}
no2->dir = atual->dir;
free(atual);
return no2;
}

Não consegui rodar o código.
Obrigado.
Answer: Boa tarde amigo, bom vamos ver !! Para você implementar recursivamente a inserção ficaria assim
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
int dado;
Node* esq;
Node* dir;
} Node;
typedef struct Node Arv;

// Insere o elemento recursivamente !!
void InsereArvore(Arv *Raiz,int dado){
Node* novo = (Node*)calloc(1,sizeof(Node));
novo->dado = dado;
novo->dir= NULL;
novo->esq= NULL;

if(Raiz == NULL)
{
    printf("Insere");
    Raiz = novo;
}
else
{
    Arv* auxiliar = Raiz;
    if(dado>auxiliar->dado)
    {
        InsereArvore(auxiliar->dir,dado);
    }
    else
    {
        InsereArvore(auxiliar->dir,dado);
    }

    }

    }

int main()
{

Arv *begin = NULL ; // Inicializando a arvore

InsereArvore(begin,5);
InsereArvore(begin,6);
InsereArvore(begin,4);
return 0;
}

Só consegui implementar o de inserção, não por que o de remoção seja difícil, porém eu esqueçi da regra para remover um elemento de uma árvore binária quando se tem filhos, quando é um Nó folha é fácil, mas eu esqueci da regra para remover um nó que tem um ou dois filhos.
Answer: Amigo também tem outro jeito de implementar sem precisar criar nós que é uma chatisse !! para árvore binárias você pode implementar desse jeito
#include <stdio.h>
#include <stdlib.h>
#define infinito 10000
#define aloc (int*)calloc(infinito,sizeof(int))
#define null -987789654

void InsereArvore(int *arvore,int dado,int indice) {

if(!arvore[indice]) {
    arvore[indice]=dado;
} else {
    if(dado<arvore[indice]){
        InsereArvore(arvore,dado,(2*indice)+1);
    } else {
        InsereArvore(arvore,dado,(2*indice)+2);
    }
}

}

void RemoveArvore(int *arvore,int dado,int indice) {

// Buscando pelo elemento a ser removido
if(dado==arvore[indice]) {
    // Encontrou o elemento a ser removido !!
    int filhoesq = 2*indice+1;
    int filhodir = 2*indice+2;
    /* tres casos para tratar !! Elemento é folha, elemento tem um filho,
dois filhos*/

    if(!arvore[filhoesq]&&!arvore[filhodir]) {
        // Folha apenas remove
        arvore[indice]=0; return;
    }

    if(!arvore[filhodir]&&arvore[filhoesq]!=0) {
        // apenas o nó da esquerda
        int filhoesq = 2*indice+1;
        arvore[indice]=arvore[filhoesq]; // colocando o filho no lugar do pai
        arvore[filhoesq]=0; // removendo o filho
    }

    if(!arvore[filhoesq]&&arvore[filhodir]!=0) {
        // apenas o nó da direita
        arvore[indice]=arvore[filhodir]; // colocando o filho no lugar do
        arvore[filhodir]=0; // removendo no da direita
    }

    if(arvore[filhodir]!=0&&arvore[filhoesq]!=0) {
        // o nó a ser removido tem dois nós filhos !!

        arvore[indice]=arvore[filhoesq];
        arvore[filhoesq]=arvore[filhodir];
        arvore[filhodir]=0;
    }

} else {
    if(dado<arvore[indice]){
        RemoveArvore(arvore,dado,(2*indice)+1);
    }else {
        RemoveArvore(arvore,dado,(2*indice)+2);
    }
}

}

void ImprimiArvore(int *arvore,int indice) {

int filhoesq = 2*indice+1;
int filhodir = 2*indice+2;

if(!arvore[indice])return;

printf("Dado: %d\n",arvore[indice]);
if(arvore[filhoesq]!=0)ImprimiArvore(arvore,filhoesq);
if(arvore[filhodir]!=0)ImprimiArvore(arvore,filhodir);
}

int main() {

int *arvore = aloc;
/* Para inserção, remoção, ou impressão da árvore sempre entrege o indice
como sendo 0*/
/* Está arvore não aceita elemento 0 , como dado !! mas você pode modificar
para aceitar
*/
InsereArvore(arvore,5,0);
InsereArvore(arvore,3,0);
InsereArvore(arvore,6,0);
InsereArvore(arvore,1,0);
InsereArvore(arvore,2,0);
ImprimiArvore(arvore,0);
return 0;

}


Make Android ImageButton look like Button

Question: The documentation for ImageButton says:

By default, an ImageButton looks like a regular Button

This is obviously wrong because when I put both into a layout:
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/imageButton3"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        app:layout_constraintStart_toStartOf="@+id/button2"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

and run it, it looks like this:

The Button has a color and a shadow while the ImageButton is just a gray rectangle (with round corners I think).
Unfortunately I don't understand at all how styles work. My main question though is how do I need to change the ImageButton's configuration to actually make it look like a regular Button.
Comment: This answer shows how widgets styling works https://stackoverflow.com/questions/13222858/android-default-button-style/#13223330
Answer: Are you using material design? Your Button does not look like the regular button that default style is @style/Widget.AppCompat.Button, but like the material button, which default style is @style/Widget.MaterialComponents.Button. If you set the style of the Button to @style/Widget.AppCompat.Button, you will see it looks the same as the ImageButton with default style @style/Widget.AppCompat.ImageButton
This is @style/Widget.AppCompat.Button, you can see that it has been expanded on the basis of @style/Widget.AppCompat.Button:

So, you can customize a new style for ImageButton, and then add those new style attributes of material button to the custom style (mainly cornerRadius, elevation, and rippleColor)
or set the button's style to @style/Widget.AppCompat.Button, while will also make the ImageButton looks like the Button :P
Comment: "Are you using material design?", what does that mean? This is just what buttons look like when I open a fresh install of Android Studio and create a "Basic Activity" project. I didn't know there was a choice.
Comment: Check the module build.gradle dependencies, if there is "implementation  'com.google.android.material:material:X.X.X'", that means you are using material design, it will change the default style of some widgets to material style
Comment: Yes, it says `implementation 'com.google.android.material:material:1.4.0'`.


Pandiatonicism in "She's leaving home" (Beatles)?

Question: In a documentary about the Beatles it was said She's leaving home is in aeolian mode. I thought this would be rather dorian as we have a major 6th in the scale passage of the cello after the first phrase of the song.  But then the refrain and also the beginning is a major (ionian) scale or even mixolydian ...
Recently I've read the first time the term pandiatonicism and this song was mentioned as an example.
Can somebody explain the pandiatonicism term based on this song?
Comment: Isn't funny how _diatonic_ in the context of pandiatonic is clearly understood as the Medieval gamut, but in the context of minor keys https://music.stackexchange.com/questions/95513/a-better-word-for-diatonicism/95520?noredirect=1#comment164048_95520 people seem to have trouble with what diatonic means!
Answer: Pandiatonicism is the technique of free use of all seven degrees of the diatonic scale, melodically, harmonically or contrapuntally.......The added sixth and ninth,widely used in popular American music, are pandiatonic devices. Thus spake Nicolas Slonimsky.
I've omitted the middle of this lengthy definition, but what's here sums up what can be an explanation of She's Leaving Home', from a musical point of view. All the diatonic notes, but swapping tonics.
Answer: It seems like pandiatonic is applied to Beatles songs with nothing much more than the meaning of not very chromatic.
IMO The Beatles examples I have seen cited aren't particularly good examples.
It seems to me the key elements of pandiatonic are: non-functional progressions and all diatonic intervals treated as consonances.
When both of those things are combined, it excludes...

jazz extended chord harmony when it's functional like ii V I.
modal music (like folk modal) where the harmonization is largely simple triadic

I wish I had notation of the Beatles songs at hand. My impression from listening is it doesn't really show lots of non-traditionally dissonant intervals being treated as consonances. Especially not given the democratic treatment of all diatonic tones being equal.
The Wikipeadia article gets into that particular point. Pandiatonicism is analogous to 12 tone in an equal treatment of all diatonic tones. When listening to examples from Ravel, Milhaud, Stravinsky, etc. I get that sense of all the white piano keys played randomly with the damper pedal held down. The diatonic tones all smudge together. All the edge is taken off the (traditional) dissonances. Harmonically it's soft and static. But it also can sound fairly dense, because one of the techniques is grouping a lot of notes together to "equalize' them.
There aren't strict methods for pandiatonicism like 12 tones music so it's a bit hard to describe it objectively. But these Beatles songs do not sound like those early 20th century examples in terms of a pandiatonic harmonic palette.

Pandiatonicism in “She’s leaving home” (Beatles)?


Divisibility problem, number theory

Question: Is $10^{is}-1$ divisible by $10^{s}-1$ there i, s are natural numbers. If so, how do I prove it? Thanks for help, I've delt with it. How I should go about proving this a bit harder divisibility problem?
I need to prove that $10^s+1$ divides both $10^{2ks}-1$ and $10^{(2k-1)s}+1$
I've tackled that problem too. Thank you Math Gems for showing me the way :)
Comment: Hint: let $\, x = 10^s\,$ in $\,x-1\,$ divides $\,x^i-1.\ $ Or $\ 10^s\equiv 1\:\Rightarrow\:10^{si} = (10^s)^i\equiv 1^i\equiv 1 \ \ $
Comment: There is nothing special about 10. Why don't you check that $x^s-1|x^{is}-1$
Answer: Hint: What happens when you multiply out $(x^s - 1)(1 + x^s + x^{2s} + \cdots + x^{(i-1)s})$?

Divisibility problem, number theory


Converting from mysql to SQL SERVER

Question: I am working on a project where I am migrating from mysql to SQL server. I have actually looked for equivalent functions, but haven't found it. I have came this far and have been able to connect to my DB, the next was to select all from pools and show it in the HTML select (dropdown) options. I am unsure if it's just to convert the mysqli_query to sqlsrv_query e.g ?
Hope someone could be able to show me the correct path for solving my issue.
<?php
$conn_array = array (
"UID" => "sa",
"PWD" => "root",
"Database" => "nih_bw",
) ;

$conn = sqlsrv_connect('TEST' , $conn_array);

if ($conn)
{

$result = mysqli_query($con,"Select name from pools");

    echo "<select name='mypool' class='form-control'>";

    $default_name = "foo_bar";
    while($row = mysqli_fetch_array($result)){
      $opt_name = $row['name'];
      $str_selected = "";
      if($opt_name == $default_name){
          $str_selected = "selected";
    }
      echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
    }

    echo "</select>";

}
else
{
die( print_r( sqlsrv_errors(), true));
}

sqlsrv_close( $conn );

?>

Comment: Start here http://www.php.net/manual/en/book.mssql.php Or here http://webcheatsheet.com/php/connect_mssql_database.php
Comment: I am very unsure how that would be implemented in my case.
Comment: OR maybe you want other people to do the work for you.
Comment: No, absolutely not! I want to learn by my self, thats the point of life.
Comment: Switch to PDO. The `mssql_*` functions are just as bad as `mysql_*`, and had you been using it in the first place the only difference in your code would likely be the connection string.
Comment: What about the sqlsrv functions ?
Answer: <?php

$conn = mssql_connect('Host', 'User', 'Password');

if (!$conn || !mssql_select_db('database', $conn)) {
    die('Unable to connect or select database!
 ' . sqlsrv_errors());
} else {
    $result = mssql_query($con, "Select name from pools");

    echo "<select name='mypool' class='form-control'>";

    $default_name = "foo_bar";
    while ($row = mssql_fetch_array($result)) {
        $opt_name = $row['name'];
        $str_selected = "";
        if ($opt_name == $default_name) {
            $str_selected = "selected";
        }
        echo "<option value='" . $opt_name . "' " . $str_selected . " >" . $opt_name . "</option>";
    }

    echo "</select>";
}

mssql_free_result($result);
mssql_close($conn);
?>

Hope it works for you! Check php manual for MS SQL connectivity at http://www.php.net/manual/en/book.mssql.php
Editing after comments! mssql failed to run?
MS SQL Client Tools to be installed on the system where PHP is installed to work it properly. copy ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access through named pipes. Configuration of the client will require installation of all the tools. This extension is not available anymore on Windows with PHP 5.3 or later. Install appropriate extensions or use sqlsrv which also requires some installation!
sqlsrv_connect,
sqlsrv_query,
sqlsrv_fetch_array,
sqlsrv_errors and
sqlsrv_close functions are available to work with. More functions are available at PHP sqlsrv manual http://www.php.net/manual/en/ref.sqlsrv.php
Comment: Hmm! Get this error:  Fatal error: Call to undefined function mssql_connect()
Comment: MS SQL Client Tools to be installed on the system where PHP is installed. ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access through named pipes. Configuration of the client will require installation of all the tools.

This extension is not available anymore on Windows with PHP 5.3 or later.

Converting from mysql to SQL SERVER


Python Dictionary Method Calls win32com

Question: I have run makepy on Autodesk Inventor to be able to script certain tasks.  I am having trouble understanding the appropriate protocol for using properties/methods stored in class dictionaries.  I have read a lot about this, including the other stackoverflow question regarding _prop_map_get_ but for some reason, don't get it.  Here is an example:

two classes in question, AssemblyComponentDefinition, and WorkPoints

These two classes are excerpt from makepy:
class AssemblyComponentDefinition**(DispatchBaseClass):
"""Assembly Component Definition Object"""
CLSID = IID('{AA044AA1-D685-11D3-B7A0-0060B0F159EF}')
coclass_clsid = None

    _prop_map_get_ = {
    # Method 'WorkAxes' returns object of type 'WorkAxes'
    "WorkAxes": (100663817, 2, (9, 0), (), "WorkAxes", '{28DD48B5-8D70-11D4-8DDE-0010B541CAA8}'),
    # Method 'WorkPlanes' returns object of type 'WorkPlanes'
    "WorkPlanes": (100663816, 2, (9, 0), (), "WorkPlanes", '{46785C3B-7F4A-11D4-8DDB-0010B541CAA8}'),
    # Method 'WorkPoints' returns object of type 'WorkPoints'
    "WorkPoints": (100663818, 2, (9, 0), (), "WorkPoints", '{28DD48C7-8D70-11D4-8DDE-0010B541CAA8}'),
}

class WorkPoints(DispatchBaseClass):
"""WorkPoints Collection Object"""
CLSID = IID('{28DD48C7-8D70-11D4-8DDE-0010B541CAA8}')
coclass_clsid = None

# Result is of type WorkPoint
def AddFixed**(self, Point=defaultNamedNotOptArg, Construction=False):
    """Creates a new work point at the position specified by the input point"""
    ret = self._oleobj_.InvokeTypes(83893254, LCID, 1, (9, 0), ((9, 1), (11, 49)),Point
        , Construction)
    if ret is not None:
        ret = Dispatch(ret, 'AddFixed', '{28DD48C9-8D70-11D4-8DDE-0010B541CAA8}')
    return ret

# Result is of type WorkPoint
# The method Item is actually a property, but must be used as a method to correctly pass the arguments
def Item(self, Index=defaultNamedNotOptArg):
    """Allows integer-indexed access to items in the collection"""
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index
        )
    if ret is not None:
        ret = Dispatch(ret, 'Item', '{28DD48C9-8D70-11D4-8DDE-0010B541CAA8}')
    return ret

_prop_map_get_ = {
    "Application": (2130706433, 2, (9, 0), (), "Application", None),
    "Count": (2130706438, 2, (3, 0), (), "Count", None),
    # Method 'Parent' returns object of type 'ComponentDefinition'
    "Parent": (2130706434, 2, (9, 0), (), "Parent", '{5DF8601E-6B16-11D3-B794-0060B0F159EF}'),
    "Type": (2130706435, 2, (3, 0), (), "Type", None),
}
_prop_map_put_ = {
}
# Default method for this class is 'Item'
def __call__(self, Index=defaultNamedNotOptArg):
    """Allows integer-indexed access to items in the collection"""
    ret = self._oleobj_.InvokeTypes(0, LCID, 2, (9, 0), ((12, 1),),Index
        )
    if ret is not None:
        ret = Dispatch(ret, '__call__', '{28DD48C9-8D70-11D4-8DDE-0010B541CAA8}')
    return ret

def __str__(self, *args):
    return str(self.__call__(*args))
def __int__(self, *args):
    return int(self.__call__(*args))
def __iter__(self):
    "Return a Python iterator for this object"
    ob = self._oleobj_.InvokeTypes(-4,LCID,2,(13, 10),())
    return win32com.client.util.Iterator(ob, '{28DD48C9-8D70-11D4-8DDE-0010B541CAA8}')
def _NewEnum(self):
    "Create an enumerator from this object"
    return win32com.client.util.WrapEnum(self._oleobj_.InvokeTypes(-4,LCID,2,(13, 10),()),'{28DD48C9-8D70-11D4-8DDE-0010B541CAA8}')
def __getitem__(self, index):
    "Allow this class to be accessed as a collection"
    if '_enum_' not in self.__dict__:
        self.__dict__['_enum_'] = self._NewEnum()
    return self._enum_.__getitem__(index)
#This class has Count() property - allow len(ob) to provide this
def __len__(self):
    return self._ApplyTypes_(*(2130706438, 2, (3, 0), (), "Count", None))
#This class has a __len__ - this is needed so 'if object:' always returns TRUE.
def __nonzero__(self):
    return True

This is some code I have tried to have an object of type WorkPoints returned through the AssemblyComponentDefinition class.
    import win32com.client
    from win32com.client import constants
    oApp = win32com.client.Dispatch('Inventor.Application')
    oApp.Visible=True #makes Inventor Application visible
    from win32com.client import gencache
    mod = gencache.EnsureModule('{D98A091D-3A0F-4C3E-B36E-61F62068D488}', 0, 1, 0)
    oApp=mod.Application(oApp)
    oAssemblyDoc=oApp.Documents.Add(constants.kAssemblyDocumentObject, "", True)
    oAss = oAssemblyDoc.Activate
    oTG = oApp.TransientGeometry
    oPoint = oTG.CreatePoint(XCoord=1.2, YCoord=3.4, ZCoord=5.3) #this works
    z=mod.AssemblyComponentDefinition('WorkPoints')

This returns z as a class object of AssemblyComponentDefinition.  What I really want to do is to say (I know this is the naive way to think of this):
newpoint = mod.AssemblyComponentDefinition.WorkPoints.AddFixed(oPoint)

I get an error that AssemblyComponentDefinition has no attribute 'WorkPoints'.  Again, I need help understanding how to use the _prop_map_get_ part to be able to create a Work Point in my file and then run WorkPoints method AddFixed.
Answer: Here is something that works:
        i=0
        for line in range(len(oPointsOnly3)):
            oPointF = oApp.TransientGeometry.CreatePoint(XCoord=(float(oPointsOnly3[i][2].strip('"')))/.032808399, YCoord=(float(oPointsOnly3[i][1].strip('"')))/.032808399, ZCoord=float((oPointsOnly3[i][3].strip('"')))/.032808399)
            oPoint = oPartDoc.ComponentDefinition.WorkPoints.AddFixed(oPointF)
            oPoint.Name=oPointsOnly4[i][0].strip('"')
            oPartDoc.Update()
            i+=1

This works after early binding the application object to mod.Application and oPartDoc to mod.PartDocument.

Python Dictionary Method Calls win32com


Proof of trigonometric identity using vector calculus

Question: Question:
Using vector calculus, show that $\sin (A+B) = \sin A \cos B + \cos A \sin B$
I have no idea how to even attempt the question. A small hint to help me get started would be greatly appreciated!
Comment: The vector calculus approach can be seen as a translation of $\cos(A+B)+i\sin(A+B)=e^{i(A+B)}=e^{iA}e^{iB}=(\cos(A)+i\sin(A))(\cos(B)+i\sin(B))$.
Comment: I drew two vectors that make an angle A and B with their resultant. I tried taking components of one of the vectors along the other, but that didn't help me :/ @pbs
Comment: How are you using vectors to represent sine and consine? Also you are missing a $
Comment: @user166967 Ummm I drew two vectors that make an angle with their resultant? So taking components you get sine and cosine. And thanks for the heads up
Comment: @KimJongUn Ummm vector analysis would be a better term I guess?
Answer: Hint:
The matrix $\begin{pmatrix}\cos B&-\sin B\\\sin B&\cos B\end{pmatrix}$ is a counter-clockwise rotation by angle $B$. Apply it (via left-multiplication) to the point $\begin{pmatrix}\cos A\\\sin A\end{pmatrix}$. The result is $\begin{pmatrix}\cos (A+B)\\\sin (A+B)\end{pmatrix}$. But
$$
\begin{pmatrix}\cos B&-\sin B\\\sin B&\cos B\end{pmatrix}\begin{pmatrix}\cos A\\\sin A\end{pmatrix}=\begin{pmatrix}\cos A\cos B-\sin A\sin B\\\sin A\cos B+\cos A\sin B\end{pmatrix}.
$$
Comment: I expanded the post slightly. For intuition, draw the point $(\cos A,\sin A)$ in the plane. What will happen after you rotate that point counterclockwise by the angle $B$?
Comment: See http://en.wikipedia.org/wiki/Rotation_matrix.
Comment: Don't understand it I'm afraid.
Comment: Ohhh.... I see what you did there now. But where did you get the matrix from? Any proof for that/
Comment: I see now. Very ingenious way of doing it. Any easier way to do it though?
Comment: I was a bit worried about circular reasoning: that the rotation matrix above must be derived using the trig sum identities. But look at the accepted answer in this post: http://math.stackexchange.com/questions/53143/how-do-we-prove-the-rotation-matrix-in-two-dimensions-not-by-casework.
Answer: Consider the unit vectors $\langle \cos(90-A), \sin(90-A)\rangle $ and $\langle \cos B, \sin B \rangle $
Take the dot product
$$\langle \cos(90-A), \sin(90-A)\rangle \bullet  \langle \cos B, \sin B \rangle = \cos (90 -A -B) $$
Comment: Hmmmm..... So shouldn't I take the cross product? As I need sine?
Comment: $\cos(90-A-B) = \cos (90 - (A+B)) = \sin(A+B) $
Comment: Indeed it does use polar form and the euler's definition. its a simple proof :
$$ \begin{align} \\ \sin(A+B) &=  \mathcal{Img} \left(e^{i (A+B)}\right)\\&= \mathcal{Img} \left(e^{iA} . e^{iB}\right) \\&=  \mathcal{Img} \left( (\cos A + i\sin A) . (\cos B + i\sin B)\right) \\&=  \mathcal{Img} \left( \cos A \cos B - \sin A \sin B +  i(\sin A \cos B + \cos A \sin B)\right) \\&= \sin A \cos B + \cos A \sin B \end{align} $$
Comment: That works too ! But the dot product is a bit simple to visualize for me :)
Comment: $$(a_1,a_2) \bullet  (b_1, b_2)  =  a_1b_1 + a_2b_2$$
Comment: But how would I get the identity for sine from that?
Comment: For the left side, use the previous dot product formula in coordinate plane :  $$(a_1,a_2) \bullet  (b_1, b_2)  =  a_1b_1 + a_2b_2$$
Comment: Yeah lol sorry.
Comment: no worries haha! the proof using complex numbers is more fun, look it up in goolge sometime :)
Comment: There's a proof for this using complex numbers?? But that must also use the polar form I take it?


discrete math probability question

Question: To find an object X, one needs to search linearly through two lists: L1 of 50 elements and L2 of 40 elements. All the elements from both lists are distinct. The probability of X∈L1 is 40%, of X∈L2 is 30%, and there is 30% probability of X being absent altogether.
You are to decide whether searching first L1 or first L2 would lead to a smaller expected value of the number of accesses.
I think ii should select from L1 first as it got high probability to get the right answer,
but i am not sure the calculation behind this, please correct me if i am wrong.
Comment: you should consider the fact that L2 is shorter, hence searching in L2 requires less time...
Answer: The probability of an element in $L_1$ being $X$ is $\frac{40\%}{50}=0.8\%$. For $L_2$ this is $\frac{30\%}{40}=0.75\%$. It is thus better to search $L_1$ first.
Answer: If you search $L_1$ first, the expected number of checks is $0.4\cdot 25 +0.3(50+20)+0.3\cdot 90=58.$
Comment: Thank you for your detailed answer, i really want to know how to form this equation, do you where i can find the common formula for this kind of question? thank you
Comment: The first term is the chance it is in L1 times the expected number to look at. The second is the chance it is in L2 times the 50 you checked in L1 plus half L2
Comment: so if I search L2 first, the formula would be: 0.3*20 + 0.4(40+25) + 0.3 * 90 = 59, is that correct?
Comment: Yes, that is right
Comment: What about the expected value when you search $L_2$ first? From this only, one cannot conclude it's better to start with $L_1$!
Comment: @Ragnar I was leaving that to OP, who did it correctly
Comment: @RossMillikan, then it's OK. (didn't read the comments well enough I guess)

discrete math probability question


Expectation as a minimizer of the loss function

Question: It is a well-known fact that the minimizer of the mean-squared loss (MSE) $$\min\limits_\mu \mathbb{E}_{X} \left(X - \mu \right)^2$$ equals the expectation of $X$.
Are there any alternative non-trivial loss functions $f\left(X, \mu\right)$ such that $$\arg\min_\mu \mathbb{E}_X f\left(X, \mu\right) = \mathbb{E}_X X?$$ And if they exist, what are their pros and cons in comparison with MSE?
Comment: For some distributions and some parameterisations of these distributions, intrinsic loss functions like Kullback, Hellinger loss functions return the mean of the distribution.
Comment: I do not think it makes much sense to use *mean* square loss instead of square loss when evaluating predictions. Each prediction error costs you $(X-\hat X)^2$, and the more such errors, the larger the cost. Taking the mean would neglect that. You can use MSE as an estimate of expected square loss for a single new observation, though.
Comment: @RichardHardy Thanks for your comment. Currently, I do not care about the value of cost. I'm only interested in the family of loss functions $f(X, \mu)$ with the specified property
Comment: Sure. I am just saying MSE does not make much sense as a loss function in most applications while squared error does, and so the question sounds kind of weird to me when formulated in terms of MSE rather than square loss. The use of MSE invites the reader to think the argument of the loss function is a vector rather than a scalar, as otherwise what will you be taking the mean of? A single scalar?
Answer: Gneiting (2011, JASA):

Subject to weak regularity conditions, a scoring function for a real-valued predictand is consistent for the mean functional if and only if it is a Bregman function, that is, of the form
$$ S(x,y) = \phi(y)-\phi(x)-\phi'(x)(y-x), $$
where $\phi$ is a convex function with subgradient $\phi'$ (Savage, 1971, JASA).

Here $S$ is a scoring function, $x$ is a point prediction, and $y$ is an observation. Gneiting (2011) gives more pointers to literature in his section 3.1.


Como usar forelse sem erro no form - LARAVEL?

Question: Boa tarde, eu tenho um form que ele traz um array do banco de dados pelo user_id, só que tem um problema depois que coloquei o forelse ele não está trazendo todos os dados, porque se tiver mais de um dados ele duplica o form.
Não sei se coloquei as div no lugar errado segue o código abaixo, A principio só queria passar uma mensagem caso não tenha cadastro relacionado ao id do usuário
@extends('layouts.app') @section('content')

    <form class="form-horizontal " id="regForm" action="{{route('renovacao.store')}}" method="POST">

Solicitar Renovação

            {{ csrf_field()}}

                @forelse($matricula as $matric)

                        <right>
                         **Dados Cadastrados**
                    </right>

has('user_id') ? 'has-error' : ''}} ">
                        Nome do Pai:
                       <input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomerespo]" value="{{ $matric->nomedopai }}">

has('user_id') ? 'has-error' : ''}} ">
                        Nome do Aluno(a):
                        <input type="text" class="form-control" name="rematricula[{{ $loop->index}}][nomealuno]" value="{{ $matric->nomealuno }}">

                        Voltar
                            arrow_back_ios

                        <button type="submit" class="btn orange darken-4 btn-info right">Confirmar
                            save
                        </button>

                @empty

Não existe registro

              @endforelse

    </form>

@endsection
-- Controller que manda os dados para form
public function listardados(){
    $matricula = Matricula::where('user_id', Auth::id())->get();

    //dd($matricula);
    return view('dashboard.renovacao.teste', compact( 'matricula'));
}

Answer: O @forelse é igual ao @foreach, a diferença é que essa diretiva possui um tratamento para arrays vazios.
Exemplo com @foreach
@section('content')
    @if($matriculas->count())
        @foreach($matriculas as $matric)
            <input type="text" value="{{ $matric->donomepai }}">
        @endforeach
    @else

Não possui matriculas.

    @endif
@endsection

Exemplo com @forelse
@section('content')
    @forelse($matricula as $matric)
        <input type="text" value="{{ $matric->nomedopai }}">
    @empty

Não possui matrículas.

    @endforelse
@endsection

Blade Templates - Loops
Comment: Vlw mano, funcionou :D


Identifying An Unusual Curve (Parametric)

Question: NOTE that: The upper boundary (for positive values of $t$) is defined in terms of infinity, that is at $t=∞$. (There is no lower boundary for negative values of $t$.)
NOTE. To any re-reading this, I was tired when I wrote it and mixed up the equations; now the post should make much more sense!
Note that the function does not cross $y$ at the top! This upper bound is at $1.618^{3}$. As you can see, it rounds off as it approaches the upper bound!
See this Graph for further insight:
https://www.desmos.com/calculator/qqqfuyrhyp
I'm looking for the parametric equations for the curve shown: I already know $y(t)$, it's $y(t)=\frac{1-φ^{-1+t}}{1-φ}+φ^{-1}$; here $φ$ is $\frac{-1+\sqrt5}{2}$. So, all I need is to find $x(t)$, which will also be defined in terms of $φ$.

Thank you all!
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/104332/discussion-on-question-by-jinny-ecckle-identifying-an-unusual-curve-parametric).
Answer: The given parametric equation for $y(t)$ is incompatible with the graph of the curve. According to the graph, there should exist a real number $T$ such that
$$
y(T)={1-\varphi^T\over1-\varphi}=\varphi^{-3}.
$$
But that implies:
$$
1-\varphi^T=\varphi^{-3}(1-\varphi)=\varphi^{-1},
\quad\text{that is:}\quad
\varphi^T=1-\varphi^{-1},
$$
and that is impossible, because $1-\varphi^{-1}=-\varphi<0$.
The same conclusion can be reached studying function $y(t)$, which is monotonically increasing and has upper bound
$$
\lim\limits_{t\to+\infty}y(t)={1\over1-\varphi}=\varphi^{-2}<\varphi^{-3}.
$$
EDIT.
With the modified definition $y(t)={1-\varphi^{t-1}\over1-\varphi}+\varphi^{-1}$ one can repeat the above computation for $T$ to find:
$$
\varphi^{T-1}=1+\varphi-\varphi^{-1}=0,
$$
which is possible only in the limit $T\to+\infty$.
Comment: Even in that case, by repeating my argument above one gets $\varphi^{T-1}=0$, which is impossible.
Comment: See my edit: $\varphi^{-3}$ is a limiting value of $y(t)$ for $t\to+\infty$.
Comment: It reaches the limit only for $t\to+\infty$, hence you should find a function $x(t)$ defined on $[0,+\infty)$ and vanishing both at $t=0$ and for $t\to+\infty$.
Comment: Something like $x(t)=-t/(1+t^2)$.
Comment: Thank you very much for taking the time. I made an error in my statement, it should have been this:
https://www.desmos.com/calculator/eci0zk3ues
Comment: Sorry, I was very tired when I wrote this and mixed up the equations. The correct equations should make the problem a lot more sensible!
Comment: I'm not sure I understand this version of the argument, can you expand it?
Comment: For the correct equation, y seems to be bounded at $1.618^{3}$. What's impossible about bounding x at that y?
Comment: Based on this approximation, you seem to be right:
https://www.desmos.com/calculator/suhkikwpl6

I'm still missing why?

If this is the case then the boundary should be the highest possible one, which is apparently less than $1.618^{3}$
Comment: Actually, I think there must be an issue with your argument, please see here!:
https://www.desmos.com/calculator/qqqfuyrhyp

What do you make of this.
Comment: Thank you, but how does this get synthesized with the fact that this graph: https://www.desmos.com/calculator/qqqfuyrhyp Does what I describe at this limit?
Comment: At least it seems to, does it never quite reach the limit? **Note** that this graph shows a good approximation of what I'm looking for at $1.618^{3}$. Only it should curve more gently / look less square.
Comment: Thank you! This is getting closer!
https://www.desmos.com/calculator/uxp4slp94d
Comment: This: https://www.desmos.com/calculator/s4thqylejl Is pretty close. Can you think of something better / closer? If you wouldn't mind? **Note** It's not lower bounded.
Comment: As I wrote above the graph starts at $t=0$. That is unavoidable, because $y(0)=0$.
Comment: Yes; this is most certainly true!! It should start there, as in my fig., however, you should get 'more graph' from minus $t$. Thank you!
Comment: See my update which should explain everything.
Comment: anyhow. now that the question should fully make sense, I'd be very happy to accept your answer if you can find such a function. (Hint: the function will probably be the sum of an infinite series somehow connected to the sum in $y(t)$)


How do rock singers avoid ruining their voice?

Question: Take Dave Grohl for instance... it seems like he's really putting his voice out there in terms of singing volume, and on a lot of songs is on the edge of screaming. I don't think I could manage for a whole song without my throat being raw but he does it for 90 minutes, day after day when on tour - and presumably even longer when in the studio.
How is this possible? Is it just a case of practice building up vocal stamina, or is this a specific technique which doesn't actually thrash your vocal chords the way it sounds?
Comment: Note that some singers do ruin their voices. Chris Cornell and Steven Tyler spring to mind.
Comment: Have you tried vocal fry's, shows you the right pressure / shape to get the effect without strain.
Comment: @DaveEngineer got a link or care to post an answer? I found this but it doesn't seem too relevant: https://en.wikipedia.org/wiki/Vocal_fry_register
Comment: One of the reasons such performers are prone to substance abuse is so they don't feel the pain...
Answer: To sing with the type intensity you hear from singers such as Dave Grohl without blowing out your vocal chords or making your throat raw requires both proper technique and some stamina (as well as certain precautions).
First let's talk about stamina.  Singing involves many muscles in the face, mouth and throat but the most important muscles used in singing is the diaphragm which can be controlled by the the internal intercostal muscles and abdominal muscles that work in conjunction with the diaphragm (the diaphragm itself is an involuntary muscle).  These muscles are able to push a large volume of air from the lungs and using the diaphragm as the primary means of pushing the air across your vocal chords will reduce the strain on your throat.
The diaphragm muscles and the abdominal muscles that work in conjunction with contraction of the diaphragm, can be strengthened with exercises that won't damage your throat or vocal chords. One excellent way to strengthen these muscles is to put a weight (such as a barbell weight plate) on your stomach while lying on your back and push it up and down as if you are doing it with your stomach.  In other words force your belly to rise and fall as much as possible with each repetition.  Do this exercise two to three times a week.  It's essentially weight lifting for the muscles (the ones you can actually strengthen)used in singing.
A stronger diaphragm and supporting muscles,  means less effort will be required to push air across your vocal chords.
As far as technique, you should avoid singing with your throat.  Many singers tighten their throat muscles to sing higher notes.  If you do this, you will become hoarse and get a scratchy throat and your vocal cords will become inflamed.  If you are tightening your throat too much, your vocal chords will be straining to push sound through a constricted airway in your tightened throat.  To some extent tightening of your throat will tighten the muscles surrounding your vocal chords and force them to work harder to vibrate.
Try this exercise.  Sing a note that is in the higher end of your range.  If you are like many folks, you may feel a tightening of the throat as you sing the higher notes.  Next try singing that note while making a conscious effort to push air from your diaphragm and keep your throat relaxed.  It takes practice to learn to sing without constricting your throat but if you plan to sing like Dave Grohl very often, it will be necessary to learn to do this.
I should mention that not everyone has the vocal range to comfortably sing like Dave Grohl.  You should never be straining to sing outside of your comfort zone.
Other things that you can do to minimize strain on your voice is to warm up before singing and/or begin your performance with some easy to sing songs that don't require belting or high intensity and are in the lower part of your range.
Another thing that is important is to stay hydrated.  This means drinking plenty of water before (starting the day before) your performance, during your performance and after.  Avoid caffeine and medicines or other substances that have a diuretic effect.
Separate from hydration is lubrication of the throat.  Water will help you stay hydrated but it's not actually a "lubricant" (although if your throat is dry it will definitely help).  For lubricating the voice I use raw honey and coconut oil.  These natural food sourced lubricants will actually coat your throat and protect it.  Some folks I know use cough drops.  Just don't sing with a cough drop in your mouth or you might accidentally inhale it and someone will have to do the heimlich maneuver on you. I have tried the syrup in pineapple juice before as it seems pretty slippery, but I think the citric acid may actually cause my throat to tighten up so I quite using pineapple juice.
Although many rock singers smoke, I would recommend avoiding any type of smoking if you want to preserve your singing ability.
It is also important to take periodic breaks during your performance to allow your vocal chords to rest and recover.  A fifteen minute break after every 45 minutes of singing will go a long way towards preventing overuse injury.  You can even take breaks by allowing other singers to help with the lead singing duties on certain songs or playing an instrumental as part of your set.
Finally, it's a good idea to have a few rest days between performances to allow your vocal folds to recover from whatever stress you put on them while singing.  If you are a rock star on tour and have back to back dates on successive nights, try not talking any more than absolutely necessary between shows.
In summary, building stamina in your diaphragm and the muscles that assist it will allow you to more effectively use proper technique to minimize damage to your vocal chords and throat.
Comment: *A fifteen minute break after every 45 minutes of singing* So **THAT** is why rock concerts feature 15 minute drum solos! Thanks for your answer.
Comment: As for the supporting muscles: As Rockin Cowboy states, not only the diaphragm is important, but also the surrounding muscles. You have to widen your body so you can use the full volume of your body. If you inhale, try to place your hands above your hips, about at the height where your kidneys are. You have to press those sides out, that way you can get more power out of your belly without straining your throat. Additionally the muscles in your back. Also posture is very important, stand upright, widen your rips and only breathe with your diaphragm. But most important: Get a coach =)
Comment: "you will become hoarse and get a scratchy throat" - that's me all over. Trying to sing in a nice tone I seem to sing _only_ using my throat! I can feel the pressure there as I try to force air through!
Answer: Well, I can't give you a fully qualified answer, but I am currently working on the same problem myself.
In my band, I am singing quite raw and agressive most of the time. Still clean singing but quite raw.
At first I had some problems doing it, especially when the set list grew longer. After my first gig I had great problems regaining my voice because I used too much power and pressure to sing my songs.
I am working with my coach to improve this kind of singing. The most important thing is of course your breathing. You really have to relax. But that is mostly easier said than done.
I am especially training singing the songs and consciously relax myself. In most cases you don't need half the pressure and power you think you need. I trained with my band. I sang the songs with as less power as possible imaginable and step up bit by bit until they said it sounds good. The air has to flow freely when you sing, if you feel pressure on your larynx, your are already doing it wrong.
I can't tell you exactly what to do or which technique to use (I don't think there is much of a technique, growling set aside), I am currently firguring it out myself. But just train to sing the songs with much less power and pressure. By the time you figure it out more and more what to do. A good tip also is, if you want to sing raw, you don't have to sing the whole word or even sentence raw. Just emphasize and distort for example the first and the last part of a phrase. That will relieve your voice of a lot of stress and the audience won't hear a big difference. Also, when not singing, even in very short breaks, try to releax, breathe deeply, try to calm down your throat so to say (sorry, no native speaker, don't how to describe it properly) When you sing a stressfull singing style, your voice needs every bit of relaxation and break it can get.
Also, there are a few practices to relax your voice. Google after them, some of them, you can do while you have a short break to releax your voice (not into the microphone of course) that will also help. Humming is always good, it massages your larynx and your vocal chords so to say. Also good preparation is crucial. Don't just start singing and screaming. When singing, muscles are involved, so treat them accordingly. You don't get out of bed and start to run a marathon either.
I hope I could provide some useful tips. But again, I am still trying to figure out how to do it correctly myself, so I can't say that all I am saying is really the right way to do it. I just describe my experiences.
Comment: All good advice!
Answer: Rockin' Cowboy makes some great points - just a few things to add - the importance of finding a great "vocal colour" that works with your sound system or vocal-chain can be just as important.  If you can find a great microphone-compression-eq-fx chain that takes some of the work, you don't need to work as hard.  You'll also have a much more consistent sound gig to gig.  It can take some time but nailing this down can allow you to sing with much less throat pressure (let's face it, a great rock sound is going to have some throat constriction at least some of the time, for effect.  Additionally, you don't have to sing with the same colour all the time.  Changing it up is not only more interesting to the listener, but also lets you cut loose with a killer sound only when it's super important in the song, and lets you relax sometimes.
Breathing and breath pressure is really important.  It used to be taught as "sing from your diaphragm".  This anatomically-incorrect imagery has persisted even though that's not what's going on....that being said - Rockin' Cowboy is correct that you need to breathe all the way around into your back and lower ribcage.  Try not to have your shoulders rise when you take a breath.  The big shoulder-high breath plus 'bearing down' on a high note is GUARANTEED to mess up your voice at some point.  Make sure when you're standing that you're not standing sway-backed with your a** sticking out.  An exaggerated arch in your lower back will reduce the amount of air you can take in and cause other muscles to tighten when they don't need to.
TONS of trained singers mess up their voices when they tour.  Some can mitigate damage by doing a song from the album that's particularly high in a lower key instead - or by changing how they sing the song - (the "tour" version).  You can use prerecorded sections for a really strenuous section or 'vocal wail' integrated into any stems you use with any click-tracked pieces to save your voice a bit in extreme situations. (lots of famous singer do and have done this - because no human being is capable of singing their album tracks full out wailing every night without doing some damage or causing fatigue).
This approach can seem to not be fully 'authentic', but failing to find some way to give your self a break will result in a "fully authentic", but completely laryngitic singer.
Answer: blah blah blah - the truth is most pop and trad vocalists use 'blend voice' and more of a light chest, then mix phonation - rock singers are encouraged to use head voice, or "above the pencil", if you imagine a pencil in your mouth for all vowel sounds, register shifts and also for speaking during the day, which shouldn't be excessive.
Zen of Screaming with Melissa Cross explains how you can make high output/gravelly singing noise without constriction, forcing the vocal chords or holding your jaw unnaturally.


Lowest multiple of $n$ over a certain threshold, $y$.

Question: I'm looking for an equation to calculate the lowest multiple of any value $n$ greater than or equal to a given threshold, $y$. I've come up with a solution that works, but it's rather ugly and not incredibly efficient. I'll be using this within software, so efficiency matters to some degree.
Here's what I've come up with:
$x$ = $y$ (mod $n$) and $1$ x = 0 if y (mod n) = 0, otherwise 1
$m$ = $x(n(floor(y/n)+1)-y)+y$
This only needs to work for positive values of $y$ and $n$. Any suggestions would be greatly appreciated.
Comment: Use the ceil function (not floor).
Answer: It's $n\cdot\lceil y/n \rceil$.
Comment: I used floor because that's the default python uses when doing integer division. The answer is incredibly simple using ceiling, though. Thanks!
Comment: If for some reason your programming system has only floor ($\lfloor x\rfloor$) and not ceiling ($\lceil x \rceil$) you can synthesize ceiling as `if (x == floor(x)) then x else 1+floor(x)`.


a typescript code confusing me

Question: There is a question confusing me so much。
The tutorial on the site(http://www.typescriptlang.org)introduces the grammar  as follows:
https://i.stack.imgur.com/3t4ui.png
It means that {name:"Alice"} is the subtype of {name:"Alice",location:"seattle"}( obviously,has excess property),but the typescript document tells us as follow:
"S is a subtype of a type T, and T is a supertype of S, if S has no excess properties with respect to T"
Comment: I am not sure that you completed your question. Would you care to elaborate more?
Comment: this is my first visit to this site,
so sorry
Comment: Why can't mesend two links?
Comment: completed  now ,could you help me
Comment: I believe what is telling you is that the object y must be of the same type as the object x. This is a more specific example of the differences.
Comment: ya,is there something wrong with the sentence "The type system enforces that the source function's return type be a subtype of the target type's return type." 。I think the y is not the subtype of x(y has excess property) ,because the typeScript document say that "S is a subtype of a type T, and T is a supertype of S, if S has no excess properties with respect to T"
Answer: I believe what it is telling you is that the object y must be of the same type as the object x or at least a sub-type. x is part of y, but not the other way around. This is a more specific example of the differences using classes instead of objects,
<code>class x {
constructor(public name: string){}
}

class y extends x {
constructor(public name: string, public location: string){
    super(name);
}
}

let myX: x = y; // OK
let myY: y = x; // Error:  "Type 'typeof x' is not assignable to type 'y'. Property 'location' is missing in type 'typeof x'. let myY: y"
</code>
// PLUG this code in the typescript playground to see it work, or not... :)
Comment: first thank you very much,i agree with you ;I just guess there is something wrong with the sentence  "The type system enforces that the source function's return type be a subtype of the target type's return type." 。I think the y is not the subtype of x(y has excess property) ,because the typeScript document say that "S is a subtype of a type T, and T is a supertype of S, if S has no excess properties with respect to T"

a typescript code confusing me