text:
Q: Logistics of code reuse (OOP) One of the driving points behind OOP is code reuse. I am curious about the actual logistics of this and how others both in team or solo handle it. For example lets say you have 5 projects you have worked on and between them you have a ton of classes that you think would be useful in other projects.
How do you store them? Are they just in the normal project repository or do you break out the relevant classes and have them (as now copies) in another unique source repository that only houses code pieces that are intended to be reused?
How do you go about finding or even knowing that there is a good piece of code out there that you should reuse? It's easier if your solo because you remember that you have coded something similar but even then it becomes kind of a stretch.
If there is some way that you are storing these pieces of code do you then also have them indexed and searchable by tag or something. I fear that it just boils down to some tribal knowledge that you just know that for situation A i need solution B and we have a good piece of code that already can help here.
A bit verbose but I hope you get what I am aiming at. If you think of a better way to make the question clearer please have at it :)
TIA!

A: Reusable classes of a company are just like any other vendor library and should be treated the same way. The only difference is how new versions are created.
If a project that is using that library discovers a bug there, or the project simply needs a new feature that would make sense to be there, then the code of the library can be changed locally in the project.
Later, when the change is running smoothly again, a new version of the library can be generated, by applying all the needed changes to the repository of the library.
At this point the new version should be published to all developers in the company such that they can decide wether to update any project that uses an older version.
In my PHP projects for example, that library is stored as a sibling of the Zend Framework library in the library/vendor directory and it shares the same naming convention such that the same autoloader can be used for both.

A: I don't share "objects" between projects, I share classes which define the objects.
How it's done varies: Sometimes I build a compiled library with commonly shared classes that are related to each other. Sometimes I manually copy the files between projects, if it's only one or two files and much less likely to be reused again - though if I do this more than twice I usually start wondering if I should add those classes to an existing library or make a new one.
How do I find code that can be re-used? I have to know the project. For very large projects that have been worked on for years by numerous developers, yes it has happened once or twice where I start creating new functionality only have have it pointed out to me that it already exists. How "discoverable" the preexisting functionality is really depends on the earlier developers and how well they documented what they did. The better the documentation, the less likely it is that someone will later fail to find the pre-existing classes.

A: Depends on the shared code really.
If it is common functionality which is general and could be useful to various projects such as how to handle file uploads or how to measure distance between points.
Or common operations such as String manipulation or common data structures such as a concurrent asynchronous queue. Then I believe the preferred method would be to take it out as a different project and build a common library.
Some notable Java examples can be found on many big projects, for instance:

*

*Apache commons are used by many different projects.

*Guava is used in many places in Google.

*Twitter commons is what twitter use across projects.

There are many such examples...
If on the other hand the reused code is much more specific, as in a Servlet which does authentication and interfaces with your companies propriety protocols. I would recommend modularization of the 5 projects so that they depend on the same sub-project and in your own development environment you can keep whatever projects you want checked out and just have them reference each other (simple with most modern IDEs).
So in the second case you would have (I'm using java jars but it'll be the same for anything):
 + project1.jar
 + project2.jar
 + project3.jar

And you would change it to be:
 + project-core.jar
   |- project1.jar
   |- project2.jar
   |- project3.jar

A:
For example lets say you have 5 projects you have worked on and between them you have a ton of objects that you think would be useful in other projects.

That's not the code reuse OOP helps with.  That's complex and difficult no matter what design process you follow.
The OOP code reuse is about inheritance.

A: 1) First, Code reuse is not an end on itself. Remember that code reuse implies increased dependency. if the code being reuse is not stable (meaning that features or fixes are being still added to it) it means that it might affect all places that depend on it
2) If a piece of code is not written from the beginning with reusability in mind, its very unlikely you will be able to isolate it back.
3) a reusable component should have little or no external dependencies. It should have its own test suite, i should be able to download/check it from repository, build it and run the test suite on its own
So its a bit more complicated that just reusing some classes in other projects, if you are doing it, you cannot do it half-heartedly; you need to go all the way down. If you "reuse" by copying into other projects, its not reuse, but copy & paste programming


text:
Q: How best to handle Constraint Violations in Spring JDBC What is considered the best/most correct way to handle a Constraint Violation in Spring JDBC?
As a real example. I've got a users table that contains, amongst other things, columns of url_slug and email. Both of these are UNIQUE. When creating a new record, or updating an existing record, if I try to make one record contain a duplicate value of another record in this table I want to return a sensible error back to the caller.
The only options I can think of are both flawed. I'm doing this in Postgres 10, using Spring NamedParameterJdbcTemplate in case that matters at all.
Check the data before doing the INSERT/UPDATE.
This will involve an extra query on every Insert/Update call, and has a race condition that means it might still not catch it. i.e.

*

*Thread 1 starts transaction

*Thread 2 starts transaction

*Thread 1 queries data

*Thread 2 queries data

*Thread 1 does update

*Thread 2 does update

*Thread 1 does commit

*Thread 2 does commit <-- Constraint Violation, even though at #4 the data was fine

Handle the DuplicateKeyException.
The problem here is that it's not thrown until the Transaction is committed, at which point it might well be unclear exactly which SQL call failed, which constraint failed, or anything else like that.

A: There is no "best" way to handle these kind of exceptions, except putting it into a try catch block and propagate back the error message to the user.
Of course in your example the problem is that you most probably don't want to use Serializable isolation level which essentially executes every transaction one-by-one, making sure that this cannot happen. Another way would be to lock the table for the entire transaction, but I wouldn't advise that either.
Simply put your transactional call into a try-catch block and handle it as you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring REST controller partial update existing resource I want to perform a partial update for a resource. I had an idea that I could combine @ModelAttribute (to load the existing resource) and @RequestBody to populate it with the provided fields and then run @Valid. As I understand @ModelAttribute is invoked before anything else.
My Controller invokes the ModelAttribut and is using my ContentPatternConverter to create the ContentPattern entity correctly. Though after that is done I want to populate the "pattern" with the provided fields from @RequestBody and finally check if it is valid. Though my the ContentPattern is not populated with RequestBody after it was created via ModelAttribute.
@RequestMapping(value = "/patterns/{id}", method = RequestMethod.PUT, produces = "application/json")
@ResponseBody
public ResponseEntity<ContentPattern> updateContentPattern(Principal principal, @ModelAttribute("id") @RequestBody ContentPattern pattern) { //implementation }

Any ideas how to solve this using my approach or if there is another (better) solution?
UPDATE 1
After some more researching I came up with following solution.

*

*Created my own annotation @RequestBodyPathVariable

*Wrote RequestBodyPathVariableMethodArgumentResolver which implements HandlerMethodArgumentResolver. What it does is 1) Based on the URI path variable (e.g. patterns/{id}) gets the existing resource from a custom converter. 2) Creates an object from the request body. 3) Merges the existing and the provided resource. 4) Validates the final object. 5) Returns the final object

See gist for source code: https://gist.github.com/2687913
(A better/other merge method might be needed for other cases.)
Helpful links:
http://blog.42.nl/articles/leveraging-the-spring-mvc-3.1-handlermethodargumentresolver-interface
http://stackoverflow.com/questions/6591665/merging-two-objects-in-java

A: I was thinking about this, and here is what I would do (disclaimer, I haven't tried this):
First of all, @ModelAttribute will only serve if you want to pass that object to the view.
@RequestBody allows Spring to parse your input body (let's say it's Json) and build a ContentPattern object. But you want to get that object from your repository and then update the relevant fields.
First, I would create an implementation of WebArgumentResolver. Using MethodParameter you check that it is from class ContentPattern. This implementation will receive as Dependency Injection, the HttpMessageConverter you use to create the ContentPattern object.
Then you create a HttpInputMessage from the NativeWebRequest, like this:
return new ServletServerHttpRequest((HttpServletRequest)nativeWebRequest.getNativeRequest());

Then using the Converter, you create your ContentPattern object. This object will have some fields populated, the ones you want to update, and also its identifier.
Using the identifier, and your repository, or an EntityManager persistence context (both injected to the class by Spring), you get the object from your repository.
Now you have two ContentPattern objects, the one obtained from the repository, and the one created from the request body.
Using your object's setters, update the object from the repository with the fields of the other object, and then validate it using your Validator also injected to this class by Spring.
If everything is ok, optionally save the updated object to persistance, and use it as the returning value of the resolverArgument method.
I hope this is clear enough!


text:
Q: Data incorreta no retorno do json Boa tarde,
O retorno do Json traz a data mal formatada = "/Date(1420077600000)/", como tratar ?
{"TB1":1,"DTADMISSAO":"\/Date(1420077600000)\/"}

Esse é o trecho onde seto o campo Data:
$.ajax({
                        url: "ObterFuncionario",
                        type: "post",
                        datatype: "json",
                        contentType: "application/json charset=utf-8",
                        data: JSON.stringify({ "id": id }),
                        processData: false,
                        beforeSend: function () {
                            $("#divCarregando").show();
                        },
                        complete: function () {
                            $("#divCarregando").hide();
                        },
                        success: function (data) {
                            $("#DTADMISSAO").val(data.DTADMISSAO);
                        },
                        error: function (result) {
                            alert(result.responseText);
                        }
                    });

HTML:

                            ADMISSÃO:

                            <input type="text" id="DTADMISSAO" class="form-control input-sm" />

A: Esse valor que está dentro do Date() é o número de milissegundos desde meia-noite de 1 de Janeiro de 1970.
Você pode converter pra Data novamente criando uma nova data com esse valor:
function retornaData(valor){
    var dataAdmissao = valor;
    var milisegundos = parseInt(dataAdmissao.slice(dataAdmissao.indexOf('(') + 1, dataAdmissao.indexOf(')')));
    var data = new Date(milisegundos);

    return (("0" + (data.getMonth() + 1)).slice(-2) + "/" +  ("0" + (data.getDate())).slice(-2) + "/" + data.getFullYear())
}

Uso:
$("#DTADMISSAO").val(retornaData(data.DTADMISSAO));

Exemplo: https://jsfiddle.net/g5n300ud/1/
Referências: Date.prototype.getTime(), getTime (Date) (JavaScript)

A: Tem essa "solução de contorno".
var dataAdmissao = obj.DTADMISSAO
var milisegundos = parseInt(dataAdmissao.slice(dataAdmissao.indexOf('(') + 1, dataAdmissao.indexOf(')')));
var data = new Date(milisegundos);

Com certeza tem algum jeito muito melhor de fazer isso.
Caso não encontre nenhuma solução, talvez sirva.

A: No retorno da sua data você pode converter ela para ToShortDateString, ai no success do seu ajax ela ja vem formatada
Exempo:
DateTime.Now.ToShortDateString();

A: Faça essa alteração no retorno da Controller
Exemplo:

public ActionResult RetornarData([DataSourceRequest] DataSourceRequest request) {
  DateTime data=DateTime.Now;
  return Json(data.ToString(), JsonRequestBehavior.AllowGet);
}


text:
Q: subscr_payment using paypal ipn simulator The paypal IPN simulator "currently" (As in I'm assuming never will) does not have functionality to test the subscr_payment payment option, this is really putting a dead hault in my project. I've read that I can just create a button that simulates this, but I don't have a clue how and after looking I can't find any information on it.
I'm creating a subscription based system for hosting a special type of website, I have everything done besides for the subscription model now and it seems like it's going to be the hardest part.

A: It is completely possible to test recurring billing with Paypal.
There are multiple ways possible for this.
One is the paypal subscribe button and another way (which i have used) is via a subscription form.
For the subscribe button you can refer this documentation, it contains all the information you need to setup this.
For second method, you need to create a form and place all the required variable in that form.
All the required variables are listed here.
I hope this helps.

A: Hopefully this workaround will help you. From within the PayPal developer site, you can go to the IPN simulator, select Transaction Type as Web Accept, click Show All Fields. You can then edit txn_type to be subscr_payment, subscr_signup, etc.
It's not perfect, as it doesn't give you all of the variables, but you can put info in other entries, and use a logical to determine whether or not the correct entry exists.
Do one test subscription, so that you have the values, and then work from there.


text:
Q: Transform "4CA2CACA" to "CCCCACCACA" I have already tried this (as somebody told me on another question):
 import re

 def decode(txt):
     list = []
     for cnt, char in re.findall(r"([\d*])([^d])", txt):
         list.extend((char * (int(cnt) if cnt else 1)))
     list = "".join(list)
     return list

Example:
print(decode("2CACA2CACA3CACACA3CAC"))

This is what I get
CCCCCCCCCC

And this is what I need
CCACACCACACCCACACACCCAC

A: re.sub can take a named function or lambda as its second argument, and you can use this to accomplish your goal. Using this approach you simply don't do any substitution when a letter does not have a number in front of it.
def decode(s):
  return re.sub(r'(\d+)([a-zA-Z])',
                lambda m: m.group(2)*int(m.group(1)),
                s)

decode("2CACA2CACA3CACACA3CAC")
# 'CCACACCACACCCACACACCCAC'

A: What you are missing is characters without a digit in front. This will include those:
import re

def decode(txt):
    _list = []
    for cnt, char, single_char in re.findall(r"(\d)([^\d])|([^\d])", txt):
        if single_char:
            _list.extend(single_char)
        else:
            _list.extend((char * (int(cnt) if cnt else 1)))
    _list = "".join(_list)
    return _list

print(decode("2CACA2CACA3CACACA3CAC"))

A: You can do this easily with functools and re. 1 line of code does all the work.
import re, functools

#create a partial of the `sub` method and it's `repl` arg
#the `lambda` takes the match, and multiplies the letter by the number
decode = functools.partial(re.compile(r'(\d+)([a-z])', re.I).sub,
                           lambda m: m.group(2)*int(m.group(1)))

rle = '4CA2CACA2CACACACA'
print(decode(rle)) #CCCCACCACACCACACACA

A: If you want to do it without any imports, then you could do something like this:
x = '2CACA2CACA3CACACA3CAC0M'
int_string = ""
char_list = []
for char in x:
    if char.isnumeric():
        int_string += char
        continue
    else:
        if not int_string:
            char_list.append(char)
        else:
            char_list.append(char * int(int_string))
        int_string = ""
print("".join(char_list))

This will work for any positive integers, even zero, as you can see in the above example.


text: Q: AWS RDS VPC Connection Elasticbeanstalk I really tried hard...I have a RDS MySQL Instance. Its security group is configured with MyIP such that I can access it with MySQL Workbench without any problems. Now I add to the SG my Elasticbeanstalk instance SG just as I do successfully with another Elasticbeanstalk Instance and another RDS DB. In both cases I use the JDBC_CONNECTION_STRING parameter. I ran out of ideas why one beanstalk/RDS pair works fine while the other doesn't. I even deleted the RDS instance and created a new one but to no avail. When I have the server output the connection string it is correct. Using the other RDS instance (via the JDBC_CONNECTION_STRING parameter), the server connects successfully to the other DB (whose SG was added this S2 instance SG). The 2 connection strings only differ by the DB name. Any idea highly apprechiated!


text:
Q: Expand Fancybox width to match an  PDF I've got a Fancybox (2) whose content is an <embed src='some_pdf.pdf'/>, i.e.
var embed = $("<embed></embed>"),
    pdf_url = "http://mysite.science.uottawa.ca/rsmith43/Zombies.pdf";

embed.attr('src', pdf_url);

$.fancybox.open(embed);

Here it is on jsFiddle.
I'd like the Fancybox to automatically resize the width to the size of the PDF (which, I should note, may vary because the PDF contains landscape or portrait pages), and about 90% the height of the window.
Unfortunately the best I've come up with so far is a hard-coded width, and setting the embed height, i.e.
embed.attr('width', '900');
embed.attr('height', parseInt($(window).height() * 0.9, 10));

I'd be grateful for any thoughts on how one might resize a Fancybox to the size of a PDF included with <embed>.
I'm using Chrome 15, and ideally I'd like a solution that works across recent versions of Chrome, Safari, and Firefox.
Thank you for reading.

A: When Fancybox is unable to calculate the size of the coming content (most likely will happen with object elements) then it uses its minWidth and minHeight default settings.
Try passing the right <embed> tag attributes like:
var embed = $("<embed></embed>"),
pdf_url = "http://mysite.science.uottawa.ca/rsmith43/Zombies.pdf";

embed.attr('src', pdf_url);
embed.attr('width', '100%');
embed.attr('height', '100%');
embed.attr('type', 'application/pdf');

and tell fancybox not to use its autoSize settings so it will take the values coming from the <embed> width and height attributes like:
$.fancybox.open(embed,{
autoSize: false
});

That will do the trick and will resize the PDF viewer to the viewport.
NOTE: If you are using HTML5 <!DOCTYPE html>, I would recommend you to set the height just to 99% like:
embed.attr('height', '99%');

to avoid a double vertical scroll bar in your PDF viewer. This is because the way HTML5 initializes margins.


text:
Q: Sharing ideas without risk of leaking As freelancers, we meet somewhere and chat about a new idea for a project, brainstorm etc. Up to this point, we have taken notes of the ideas, but we would like to be able to share more efficiently the ideas with each other. However, I fear that if I use some online product (such as Google Docs) these ideas could be seen by people outside the team (employees of the company of the online product, other users...). I am not sure if I am being a little Paranoid parrot...
One solution that we have considered is to install a Subversion with just one ideas.txt. But that would require a server in one of our houses, which is a little unconfortable.
So how do you share your ideas for a new project with your team without risking the ideas to be stolen?

A: You offer two basic choices:
1.  Store ideas on a server you control.
2.  Store ideas on a server you do not control (e.g., Google's)
I say that none of these matter.  Do either 1 or 2, but encrypt the ideas document and send the key to the relevant freelancers via Sneakernet.

A: You are at a greater risk of the leak coming from a member of the group than you are through someone hacking, or snooping your document.
Ask yourself how much that document is worth with out the context of the group brainstorm?  I know most of my working documents would not be worth the effort to figure out rather than just solve the problem myself.  But with the context they are invaluable.  So assuming your document was open to the world, unless you have the context it is likely worthless.  If you put the document somewhere that keeps it away from all but determined eyes your risk is about as low as you can get it.


text:
Q: Find the requirement for a list of vectors to be linearly independent
Suppose there is a list $((r,1,1),(0,s,1),(1,1,t))$(r,s,t$\in \mathbb Q$) and then find the requirement needed this list to be linearly independent in $\mathbb R^3$.

I find that this question is not very approachable to me. I know the requirement for a list being linearly independent should be:  $a(r,1,1)+b(0,s,1)+c(1,1,t)=0 \iff a=b=c=0$
Then
$\begin{array}
    ar+c=0  \\
    a+bs+c=0 \\
    a+b+ct=0
\end{array}$
Then the aim becomes if these three equations are satisfied, then it must be a=b=c=0. Then I think all I need to do is to find the proper value of r,s, and t such that they will force a=b=c=0.
However,(if my idea is correct) I don't know how to find such r,s, and t. The way I tried is to use the equivalent negation, i.e. if $a\neq0$ or $b\neq0$ or $c\neq0$. Then one of these equations can't be zero if r,s,t are rational numbers, but I failed. Any suggestions?

A: Construct the matrix whose columns are the vectors, i.e.,
$$
\begin{bmatrix}
r & 0 & 1 \\
1 & s & 1 \\
1 & 1 & t
\end{bmatrix}\,,
$$
and compute the determinant.  When the determinant is non-zero, the columns of the matrix are linearly independent, so the condition for linear independence is
$$
0 \neq 1 - r - s +r s t\,.
$$

A: You have the right idea looking for negation, just have some details off - we have the associated set of equations associated with the scaled sums of the vectors equaling zero given by $$ \begin{matrix}ar + c = 0 \\ a + bs + c = 0 \\ a + b + ct = 0. \end{matrix}$$ From here, notice that $$ ar + c = 0 \Rightarrow c = -ar$$ which tells us something important - if $a = 0$, then $c = 0$ - however, note that this would imply that $b$ would have to be zero and as such the vectors would be linearly independent! As such, continuing from here we can assume that $a \not= 0$. Now, let's handle the cases where either $r = 0$ or $r \not= 0$ separately :
First, the case where $r = 0$. Then $c = 0$, so we get from the third equation $$ a + b = 0 \Rightarrow a = -b $$ and plugging that into the second equation gives us $$ a + bs = 0 \Rightarrow -b + bs = 0 \Rightarrow b(s - 1) = 0 $$ which means that if $b \not= 0$, $s = 1$. However, if $b = 0$ then $a = -b = 0$, and hence if $r = 0$ we have that the set of vectors given is linearly independant if and only if $s = 1$.
Now, we handle the case where $r \not= 0$. In this case, note that we have $$c = -ar \Rightarrow a = -c(\frac{1}{r})$$ which we weren't able to derive before, since $\frac{1}{r}$ is undefined for $r = 0$. Now, plugging this into the third equation gives us $$ a + b + ct = 0 \Rightarrow -c(\frac{1}{r}) + b + ct = 0 \Rightarrow b + c(t - \frac{1}{r}) = 0 \Rightarrow b = c(\frac{1}{r} - t) $$ and a substitution of both the identity for $a$ and $b$ into the second equation gives $$ a + bs + c = 0 \Rightarrow c(-\frac{1}{r}) + c(\frac{s}{r} - st) + c = 0 \Rightarrow c(1 + \frac{s - 1}{r} - st) = 0 \Rightarrow c(r + s - 1 - str) = 0$$ with the final implication being particularly useful in this case since $r \not= 0$. Now, since we know that if $c = 0$ then $a = 0$ (because $r \not= 0$) then this is equivalent to the statement that $$ r + s - 1 - str = 0. $$ From here, notice something interesting - if $r = 0$ then $$r + s - 1 - str = 0 \Rightarrow s - 1 = 0 \Rightarrow s = 1$$ which means that we can summarize the entire discussion up to this point (including the case where $r = 0$) by the following: the vectors $\lbrace (r, 1, 1), (0, s, 1), (1, 1, t) \rbrace$ are linearly independant if and only if $r + s - 1 - str \not= 0$.
While this post (and problem) was very computation heavy, this problem comes with a lesson for other problems like it - from a setup, you will be able to extract givens from other assumptions (in this case, is was that $c = -ar$ under the assumption that the sums of the scaled vectors equal $0$). From there givens, think extremely deeply about what such a given would imply (in this case it was that if $a = 0$ then $a = b = c = 0$), and see how those findings interact with other assumptions.


text:
Q: Laptop reboots shortly after selecting grub entry on live USB Possibly related items
The following question has the same exact behaviour as me. They suspected bad USB drives, but that is not my case as I have been trying 5 different ones I have laying around. They work on other laptops I own (older models).

*

*Live USB hangs after selecting GRUB menu entry -- new PC

*https://www.reddit.com/r/archlinux/comments/tixdun/cant_boot_live_usb_on_new_laptop/ (someone very recently had the same issue as me, on the same model)

What are my PC specs?
I have two laptops, same behaviour:

*

*Asus Flow X13 (2021). Nvidia 3050, AMD Ryzen 9 5900HS, 16 gb ram

*Asus Flow X13 (2021), Nvidia 3050Ti, AMD ryzen 9 5900HS, 32 gb ram

What happens?

*

*I plug in my newly created Ubuntu USB drive to my machine

*I boot from the USB drive, I select "Ubuntu" from the grub menu

*I get a blank screen. After a few seconds, the machine just reboots. Removing grub entries like "quiet", shows me text saying: Booting command list, but no more output.

What have I tried?

*

*I have tried to modify the grub boot entry on the live USB by pressing e and then add items like nomodeset, modprobe.blacklist="nouveau", nouveau.modeset=0 - that in hope for it being GPU related. No luck.

*I have tried both of my laptops, with same behaviour

*I have downgraded my BIOS from v409 to V408. No luck.

*Made 190% sure that Secure boot is off.

*Tried 5 different USB drives

*Been using different tools to flash the Ubuntu images; Rufus, Balena Etcher, YUMI, UUI

*Been trying 20.04, 21.04 and 21.10 with same results.

*Linux mint 20.3 boots without issues from Live USB.
My question
I am in a situation where I am lost on where to go next. I have tried to get all the information I possibly can. What is Ubuntu doing differently from Linux mint? How can I proceed to identify the issue?

A: BIOS UPDATE 410 FIXES IT
Please check your model carefully (mine was GV301QE) and download the latest bios. 410 was dropped in the end of April 2022, and fixes the issue booting into newer kernels than 5.15.18 that previous BIOS versions couldn't.
https://www.asus.com/supportonly/ROG%20Flow%20X13%20GV301/HelpDesk_BIOS/


text:
Q: My code causing infinite loop, can't see the bug I am working on a WordPress project, using the Advanced Custom Fields plugin.
However I am getting a crazy infinite loop from my code, so I've obviously messed things up somewhere, however after a good two hours looking at it I can't see the problem.
<?php get_header(); ?>

    <?php
    // If the loop has posts
    if (have_posts()) :
        // For each post this page has
        while (have_posts()) : the_post();

            // Display the Flexible Content
            while(has_sub_field('add_row')):

                // If the content type is Tagline
                if(get_row_layout() == 'tagline'): ?>

<?php the_sub_field('tagline'); ?>

                <?php
                // If the content type is a Featured Image
                /*elseif ( get_row_layout() == 'featured_image' ): ?>

                        <?php
                            $attachment_id = get_sub_field('featured_image');
                            $size = "full-width"; // (thumbnail, medium, large, full or custom size)
                            $image = wp_get_attachment_image_src( $attachment_id, $size );
                        ?>
                        <img src="<?php echo $image[0]; ?>" alt="<?php the_title(); ?>" />

                <?php*/
                // If the content type is a horizontal rule
                elseif ( get_row_layout() == 'horizontal_rule' ) : ?>

                <?php
                // If the content type is Columns
                elseif ( get_row_layout() == 'columns' ):
                    // If there is at least one column section
                    if(get_sub_field('column')):
                        // For each column section
                        while(has_sub_field('column')): ?>

                                <?php
                                    if(get_sub_field('column_content_type')):
                                        $count_rows = 0;
                                        // Counting
                                        while(has_sub_field('column_content_type')):
                                            $count_rows++;
                                        endwhile;
                                        // Loop
                                        while(has_sub_field('column_content_type')): ?>
                                            <div class="
                                                <?php /*
                                                    if ( $count_rows == 1 ) :
                                                        echo "col-xs-12";
                                                    elseif ( $count_rows == 2 ) :
                                                        echo "col-xs-6";
                                                    elseif ( $count_rows == 3 ) :
                                                        echo "col-xs-6 col-sm-4";
                                                    elseif ( $count_rows == 4 ) :
                                                        echo "col-xs-6 col-sm-6 col-md-4";
                                                    endif; */
                                                ?>
                                            "> <?php
                                                // Title
                                                if ( get_sub_field('title') ) : ?>

<?php the_sub_field('title');?>
<?php
                                                endif;
                                                // Text Area
                                                if ( get_sub_field('text') ) :
                                                    the_sub_field('text');
                                                endif;
                                                // Link
                                                if ( get_sub_field('link') ) : ?>
                                                    <?php // eventually need to make it so you can change the link text ?>
                                                    <a class="textCenter" href="<?php the_sub_field('link'); ?>">
                                                        More info
                                                     <?php
                                                endif; ?>

 <?php
                                        endwhile;
                                    endif;
                                ?>

                            <?php
                        endwhile; // end for each column section
                    endif; // end checking for at least one column section

                endif; // end checking content type is columns

            endwhile; // end flexible content

         endwhile; // end for each post
    endif; // end checking for at least one post
    ?>

<?php get_footer(); ?>

A: while(has_sub_field('column_content_type')):
     $count_rows++;
endwhile;

That's your problem...  But it could be one of many based on what I'm seeing.  It looks like you think while loops work like if statements...  All you are doing in that loop is incrementing it over and over.  It will never end.

A: I think the mistake is
// Display the Flexible Content
        while(has_sub_field('add_row')):
i think you need to use if(){
// Code
}
instead of "while"


text:
Q: Print every year in a loop with XSLT My source documents contain two values (years) that define a range. I put them in variables $year1 and $year2. I now need to print to output a -Element for every year in between these two values, including start and end-year. I see a way in creating a loop with recursion, but esp. don't see how to increment the value by one every time. Any ideas?

A: The Piez method isn't applicable when the size of the sequence that must be generated isn't known in advance and isn't limited.
In such case an XSLT solution must use recursion.
Here is a generic "iterate" template that performs an action on an initial input and then on its result, until a given condition is specified.
This transformation is tail-recursive and works without stack overflow with an intelligent XSLT processor:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output method="text"/>

 <my:action>
   <end>1000000</end>
 </my:action>

 <xsl:variable name="vAction"
      select="document('')/*/my:action"/>

 <xsl:template match="/">
  <xsl:call-template name="iterate">
   <xsl:with-param name="pAction" select="$vAction"/>
   <xsl:with-param name="pInput" select="0"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="iterate">
   <xsl:param name="pAction"/>
   <xsl:param name="pInput"/>

   <xsl:if test="string-length($pInput)">
       <xsl:variable name="vResult">
         <xsl:apply-templates select="$pAction">
           <xsl:with-param name="pInput" select="$pInput"/>
         </xsl:apply-templates>
       </xsl:variable>

       <xsl:copy-of select="$vResult"/>

       <xsl:call-template name="iterate">
         <xsl:with-param name="pAction"
              select="$pAction"/>
         <xsl:with-param name="pInput" select="$vResult"/>
       </xsl:call-template>
   </xsl:if>
 </xsl:template>

 <xsl:template match="my:action">
  <xsl:param name="pInput" select="0"/>

  <xsl:if test="not($pInput >= end)">
   <xsl:value-of select="concat($pInput+1,'
')"/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), an intelligent XSLT processor that optimizes tail recursion into iteration produces the wanted result without stack overflow. This is the case with Saxon 6.5.4, which I used to produce the result.
The problem is that not all XSLT processors recognize and optimize tail-recursion.
For such processors, one can use DVC - style recursion:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
  <xsl:call-template name="displayNumbers">
    <xsl:with-param name="pStart" select="1"/>
    <xsl:with-param name="pEnd" select="1000000"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="displayNumbers">
  <xsl:param name="pStart"/>
  <xsl:param name="pEnd"/>

  <xsl:if test="not($pStart > $pEnd)">
   <xsl:choose>
    <xsl:when test="$pStart = $pEnd">
      <xsl:value-of select="$pStart"/>
      <xsl:text>
</xsl:text>
    </xsl:when>
    <xsl:otherwise>
      <xsl:variable name="vMid" select=
       "floor(($pStart + $pEnd) div 2)"/>
      <xsl:call-template name="displayNumbers">
       <xsl:with-param name="pStart" select="$pStart"/>
       <xsl:with-param name="pEnd" select="$vMid"/>
      </xsl:call-template>
      <xsl:call-template name="displayNumbers">
       <xsl:with-param name="pStart" select="$vMid+1"/>
       <xsl:with-param name="pEnd" select="$pEnd"/>
      </xsl:call-template>
    </xsl:otherwise>
   </xsl:choose>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

this transformation produces the correct result without any crash using MSXML4.
With this DVC transformation the maximum recursion-depth is only Log2(N) -- in this case 19.
I would recommend using the FXSL library. It provides DVC variants of commonly used higher-order functions, such as foldl() and map() making it possible to produce the DVC variant of almost any recursive algorithm.
Of course, in XSLT2.0 one would simply write:
<xsl:sequence select="1 to 1000000"/>

A: XSLT 1.0 Solution
Refer to the Piez technique.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="year1" select="2010" />
<xsl:variable name="year2" select="2013" />

<xsl:template match="/">
  <xsl:for-each select="(//node()|//@*)[position() < ($year2 - $year1 + 2)]">
    <xsl:value-of select="concat($year1+position()-1,'
')" />
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

XSLT 2.0 Solution
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="year1" select="2010" />
<xsl:variable name="year2" select="2013" />

<xsl:template match="/">
  <xsl:value-of select="$year1 to $year2" separator="
" />
</xsl:template>

</xsl:stylesheet>

Output
Both these style-sheets will yield product...
2010
2011
2012
2013

A: Thanks for all the help
I am working with xslt 2.0, so Dimitris last short note has done the trick:
<xsl:template name="yearranges">
   <xsl:param name="year1" />
   <xsl:param name="year2" />
   <xsl:for-each select="$year1 to $year2">
      <year>
         <xsl:sequence select="."  />
      </year>
   </xsl:for-each>
</xsl:template>

I have to print every year in a -tag. That was simple. Trickier was, that the year has to be formatted as xs:integer for xsl:sequence which is done in the call-template:
<xsl:call-template name="yearranges">
   <xsl:with-param name="year1" as="xs:integer" select="xs:integer($year1)" />
   <xsl:with-param name="year2" as="xs:integer" select="xs:integer($year2)" />
</xsl:call-template>

Thanks again
Oliver


text: Q: The most of the images don't appear, although URLs are correct I don't understand. The most images on my website Eslovaquia.sk don't appear despite the fact that all are in a valid folder. E.g. logo. There is broken-image-icon instead the logo in the header. However, link displays a right image, when I right-click on that icon, copy an URL address and paste it into the new window. It happens after moving wordpress from subfolder into the root (eslovaquia.sk/wp > eslovaquia.sk)


text:
Q: getting errors installing strongloop I am using
nodejs 4.2.0.
npm 2.14.7

I am on RHEL.
When I try npm install -g strongloop, I get this :
npm ERR! Linux 2.6.32-504.30.3.el6.x86_64
npm ERR! argv "/home/rbal/Downloads/node-v4.2.0-linux-x64/bin/node" "/home/rbal/Downloads/node-v4.2.0-linux-x64/bin/npm" "install" "-g" "strongloop"
npm ERR! node v4.2.0
npm ERR! npm  v2.14.7
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! strong-arc@1.8.8 preinstall: `node .sl-blip.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the strong-arc@1.8.8 preinstall script 'node .sl-blip.js'.
npm ERR! This is most likely a problem with the strong-arc package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node .sl-blip.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls strong-arc
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/rbal/Downloads/node-v4.2.6-linux-x86/npm-debug.log

Can anyone tell me why do i get these errors ? I tried to search using error :
Failed at the strong-arc@1.8.8 preinstall script 'node .sl-blip.js'

but could not find anything.


text:
Q: Start brew-installed applications from terminal I just set up homebrew on my new macbook and used the brew and brew cask commands to install some applications. I can now open the applications from the launchpad but not from the terminal.
I know it's not working because the applications have not been saved to one of the directories in my $PATH variable, but none of the installation guides I have read for homebrew mention how you can set it up to put links to the binaries there. Some tutorials mention you should change the order of directories in your /etc/paths file, but I already did that and my problem persists.
Can anyone help me out? :)

A: Add the following to your ~/.bash_profile:
export PATH=/usr/local/bin:$PATH

This prepends /usr/local/bin to your existing $PATH.


text:
Q: Is it possible to determine if an object created with Object.create inherits from Array in JavaScript? Identifying which objects are which is complicated in JavaScript, and figuring out which objects are arrays has something of a hacky solution. Fortunately, it manages to work in both of the following cases:
Object.prototype.toString.call([]);           // [object Array]
Object.prototype.toString.call(new Array());  // [object Array]

Great, no [object Object] in sight! Sadly, this method still manages to fail with this:
var arr = Object.create(Array.prototype);
Object.prototype.toString.call(arr);          // [object Object]

This is frustrating, so say the least. My arr object has all the methods of an array, it functions like an array, and for all purposes, it is an array. Yet JavaScript doesn't provide the tools to identify it as such.
Is there any way to figure out if an object inherits from a particular prototype? I suppose you could iterate through the prototypes like so:
function inherits(obj, proto) {
    while (obj != null) {
        if (obj == proto) return true;
        obj = Object.getPrototypeOf(obj);
    }
    return false;
}

inherits(Object.create(Array.prototype), Array.prototype);  // true

But it feels a tad hacky. Is there any cleaner approach?

A: How about an instanceof operator? It returns true for all your cases:
[] instanceof Array //true
new Array() instanceof Array //true
Object.create(Array.prototype) instanceof Array //true

However:
Object.create(Array.prototype) instanceof Object //also true

So be careful.

A: ECMAScript 5 has introduced Array.isArray() into javascript which provides a reliable way to check. For older browsers, we fix that by (quoted from this book)
function isArray(value) {
    if (typeof Array.isArray === "function") {
         return Array.isArray(value);
    } else {
         return Object.prototype.toString.call(value) === "[object Array]";
    }
}

But i just found out the built-in function Array.isArray does not work correctly when we use Object.create (tested in chrome). I came up with a method that works:
function isArray(value) {
     if (typeof value === "undefined" || value === null) {
          return false;
     }
     do {
          if (Object.prototype.toString.call(value) === "[object Array]") {
               return true;
          }
          value= Object.getPrototypeOf(value);
     } while (value);

     return false;
}

Use it:
var arr = Object.create(Array.prototype);
var arr1 = Object.create(Object.create(Array.prototype));
var arr2 = new Array();
var arr3 = [];
isArray(arr);
isArray(arr1);
isArray(arr2);
isArray(arr3);

A: See http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/ for the definitive exposition of the problems in inheriting from Array.
Anyway, in the simplest case, where you are doing
var sort_of_an_array = Object.create(Array.prototype);

you can check using isPrototypeOf:
Array.prototype.isPrototypeOf(sort_of_an_array)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf.

A: How about checking the constructor?
function inherits(obj, proto) {
    return obj.constructor === proto.constructor;
}

inherits(Object.create(Array.prototype), Array.prototype);  // true

A:
it functions like an array, and for all purposes, it is an array

No. It has no auto-updating length property. See this article why it's quite impossible to subclass Array.

Is there any way to figure out if an object inherits from a particular prototype? I suppose you could iterate through the prototypes, but it feels a tad hacky.

That's just how to do it. A cleaner approach than a self-written function would be to use the instanceof operator:
arr instanceof Array; // true


text:
Q: SecurityError: The operation is insecure I am creating an AngularJS application which has a canvas where the user can upload a picture. I am using
scope.image = scope.canvas.toDataURL()

to achieve what I want to do, which is to create a BASE64 encoded string out of my image. When the user has finished picking his picture he submits the BASE64 string to the web service which changes it to a .jpg file. Everything is working fine.
But the user has the opportunity to change his image. He can get it from the database into the same canvas and select a different image. The canvas can show the old image but when I want to choose another image I get the following error:
SecurityError: The operation is insecure

I have tried to add the following line to my code:
image.setAttribute('crossOrigin', 'anonymous')

which allows me to change the image without the error but then the image from the database is not displayed for some reason that is unknown to me.
Does anybody know of a way to be able to get an image from a server and display it into a canvas and then be able to change it into another image from my computer without getting the SecurityError?


text:
Q: Typescript return an array with manipulation on the objects My question seems very simple, but I didn't find a simple way to do it.
In Typescript, I want to return an array with manipulation on each object inside.
For example:
foo = [{code: 1, desc:"a"},
       {code: 2, desc:"b"},
       {code: 3, desc:"c"}];

get Foo() {
   return this.foo.forEach((item) => {
       return {code:item.code + 1, desc: item.desc};
   });
}

This getter returns undefined.
What is the correct way to do it?

A: The forEach method does not return anything, or undefined.
You probably want the map method instead.


text:
Q: Flash newbie- Can I create web apps (or websites) that can be accessed from browser in mobile devices viz ios/android/blackberry I am very new to Flash and I read a lot of articles that Flash was not supported on ios until recently.
From what I understand, Adobe AIR runtime enables desktop apps created in Flash to be seen in ios/android/others.
What I want to do is create a simple website/web app using Flash (with Flex/AIR- any one of the SDKs) - but in such a way that the same website can be accessed with the browser in desktop/tablet/mobile devices-- including iphone/android. And I want the site to consist of HTML/JS/CSS/SWF files...I am OK if different SWF files are required for each type of device...Can such a website be created in Flash? Because in many sites it is mentioned that FLash is not supported on ios devices, but some sites also mention that native apps can be created using Flash which work in ios devices... But I am looking to create flash-powered websites that work across all mobiles(including ios/android/blackberry/pcs/tablets)...Also, if this can be done, then what are the IDEs that I can use for such dev work? Finally, can I use the Flex SDK for creating such web apps?

A:
Adobe AIR runtime enables desktop apps created in Flash to be seen in
  ios/android/others.

Adobe AIR can be used to create desktop apps for Windows and Mac.  And native mobile applications for iOS, Android, and the Blackberry Playbook.  So, your understanding is correct.

I am very new to Flash and I read a lot of articles that Flash was not
  supported on ios until recently.
From what I understand, Adobe AIR runtime enables desktop apps created
  in Flash to be seen in ios/android/others.
What I want to do is create a simple website/web app using Flash (with
  Flex/AIR- any one of the SDKs) - but in such a way that the same
  website can be accessed with the browser in desktop/tablet/mobile
  devices-- including iphone/android.

You're out of luck, then.  You cannot access Flash in the browser on iOS; and it is not supported on many Android devices.
Native apps are different than browser based apps.


text:
Q: Generating a Fourier Series from a set of discrete values? I have a large list of pairs of values (x, f(x)). Importantly, the distance between each value of x is not consistent. For instance, x might be 2, then 3, then 7, then 9.
How would I use this data to find a Fourier Series?

A: Use least squares $$\min_c J(c),\qquad J(c)= \sum_{k=1}^K|\sum_{n=0}^{N-1} c_n e^{2i\pi n x_k}-f(x_k)|^2$$
As every least square problem the solution is found from $c$ such that $\partial J(c)=0$, which is a linear equation in $c$. There are some gradient descent algorithms to solve for $c$ where $NK$ is large.
Often we add a regularization term, replacing $J(c)$ by $J(c)+\epsilon \|c\|^2$.


text:
Q: Localhost:8080 showing blank page with react-native-web i followed a tutorial for adding web support to a react native app. using react-native-web and webpack. looks like it works for everyone. but for me, i get a blank web page. even though it works just fine on the emulator.
i get no error in the console.

this is the tutorial i followed:
as shown in the tutorial, i was hoping to see my simple react native code result both on the emulator and the webpage.
ps. my project is TypeScript based
this is my App.web.ts
   import {AppRegistry} from 'react-native'
import {name as appName} from './app.json'
import App from './App'

AppRegistry.registerComponent(appName, () => App)

AppRegistry.runApplication(appName, {
  initialProps: {},
  rootTag: document.getElementById('app-root'),
})

my package.json:
{
  "name": "reactnativewebapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint .",
    "web":"cd web && webpack-dev-server"
  },
  "dependencies": {
    "react": "17.0.2",
    "react-dom": "^18.0.0",
    "react-native": "0.68.0",
    "react-native-web": "^0.17.7"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/react": "^17.0.43",
    "@types/react-native": "^0.67.3",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "html-webpack-plugin": "^5.5.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.67.0",
    "react-native-typescript-transformer": "^1.2.13",
    "react-test-renderer": "17.0.2",
    "ts-loader": "^9.2.8",
    "typescript": "^4.6.3",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  },
  "jest": {
    "preset": "react-native"
  }
}

and my index.js from which App.js should be rendered:
/**
 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);


text:
Q: How to get rid of paper-menu-button first item highlight in Polymer? I'm trying to get rid of paper-menu-button first item being selected, because when I'm press menu button and paper-menu drops down there always are first item highlighted (not selected but highlighted with gray color). Is there any workaround to disable that auto highlight function? Property (focused="false") not working and by default it's false.
<paper-menu-button vertical-offset="42" horizontal-align="right">
    <paper-icon-button icon="menu" class="dropdown-trigger"></paper-icon-button>
    <paper-menu class="dropdown-content">
        <paper-item>Item 1</paper-item>
        <paper-item>Item 2</paper-item>
    </paper-menu>
</paper-menu-button>

A: I'm guessing I've found a solution, don't know does my solution affects any "deep" functions but while I'm tested everything worked fine. So to get rid of auto highlight first item in paper-menu-button or paper-dropdown-menu add folowing.
<paper-menu-button>
<paper-icon-button icon="menu" class="dropdown-trigger"></paper-icon-button>

<paper-menu class="dropdown-content" tabindex="0">
<paper-item>Item 1</paper-item>
<paper-item>Item 2</paper-item>
</paper-menu>
</paper-menu-button>

So as in code shown you have to add before dropdown content an empty div with same class and to dropdown content add tabindex. If someone will find any bug this solution causes just reply here and I will try find a different solution.


text:
Q: Independence of $\sigma$-algebras Let $\mathcal{A}$, $\mathcal{B}$ and $\mathcal{C}$ be sub-$\sigma$-algebras of $\mathcal{F}$, with $(\Omega,\mathcal{F},P)$. Assume that $\sigma(\mathcal{B},\mathcal{C})$ is independent of $\mathcal{A}$ and $\mathcal{B}$ is independent of $\mathcal{C}$. Now I want to show that $\mathcal{A}$, $\mathcal{B}$ and $\mathcal{C}$ are independent, and so in particular $\mathcal{C}$ is independent of $\sigma(\mathcal{A},\mathcal{B})$.
Secondly, I am looking for a example illustrating that the independence of $\mathcal{C}$ and $\sigma(\mathcal{A},\mathcal{B})$ not necessarily follow from having $\mathcal{A}$ and $\mathcal{B}$, $\mathcal{A}$ and $\mathcal{C}$ and $\mathcal{B}$ and $\mathcal{C}$ independent.
Of course we start with:
$\forall E \in \sigma(\mathcal{A},\mathcal{B})$, $\forall A \in \mathcal{A}$ and $\forall C \in \mathcal{C}$ we have that $P(A \cap E)=P(A)\cdot P(E)$ and  $P(A \cap B)=P(A)\cdot P(B)$. How to extend this information to find that:
$\forall A \in \mathcal{A}$, $\forall B \in \mathcal{B}$ and $\forall C \in \mathcal{C}:$ $P(A \cap B \cap C)=P(A)\cdot P(B)\cdot P(C)$.

A: We start with what we want to prove. Let $A\in \mathcal{A}, ~B\in \mathcal{B}, ~C\in \mathcal{C}$ and we shall prove that $P(A\cap B\cap C)=P(A)P(B)P(C).$ Since $A \in \mathcal{A}$, $~B\cap C\in \sigma(\mathcal{B},\mathcal{C})$ and $\mathcal{A},~\sigma(\mathcal{B},\mathcal{C})$ are independent, we get $P(A\cap B\cap C)=P(A)P(B\cap C).$  Since $B \in \mathcal{B},~C\in \mathcal{C}$ and $\mathcal{B},~\mathcal{C}$ are independent we get $P(B\cap C)=P(B)P(C)$, as desired.


text:
Q: Showing webView in Cordova before API has loaded I'm using PhoneGap / Cordova to build an application for iOS and Android. With the standard behaviour, the webView is not shown until the JavaScript has been initialised and the Cordova API is ready.  So until I call:
document.addEventListener('deviceready', this.onDeviceReady, false);

... the screen is entirely blank.  Only once the call to deviceready is initialised and the Cordova API has loaded is the webView made visible.
I would like to show the webView as soon as possible, with no delay, so that the static HTML elements appear almost instantly, regardless of the Javascript state.  I've got a very basic knowledge of Objective C and have had a look through the code but the Cordova library is big and I haven't yet found out how and when the webView is displayed.
Does anyone know how I can show the webView as soon as the Objective C side has loaded, regardless of whether the Cordova API is ready yet or not?  (And what downsides there might be to that if any?)
Thanks in advance!


text:
Q: Files/Media folders owned by an app on Extremal Storage on microSD card: open failed: EROFS (Read-only file system) I have an app which records videos. It has an option to record videos to external microSD card.
Some users of my app reports the next issue:

MediaRecorder init error
/storage/7491-17FD/Android/media/MY_APP_PACKAGE/2020-12-25/2020-12-25
15h 00m 16s.mp4: open failed: EROFS (Read-only file system).

I tested my real devices Samsung S10 (Android 29) and Lenovo P1ma40 (Android 21) with external microSD card. Everything works fine. Also tested with Pixels emulators. App can record video files (and creating other files) to such folders and they can be deleted without any problem within that app. So there is no need for any permissions, it should have R/W rights by default (because it is folders of that app).
So why does such issue happen for other users (their devices)?


text:
Q: When I push a project to Github, I have the files of the oldest commit, why? I have a project on local and I would like to push the project on a github repository
On local I have many commits
To push on github I use the following commande lines:
git remote add origin https://github.com/yourusername/your-repo-name.git
git pull origin master
git push origin master
It works but I have the first version of the project corresponds to the oldest commit
When I use the following command:
git branch -vv --all
I have:
 master    4da82c9 first commit
* old-state 35dd8a0 last commit

I forget something but I don't know what.

A: A pull origin master while you are on  old-state would update  old-state only, not master.
At least, checkout (or switch) to master first.
git checkout master
# or with Git 2.23+
git switch master

Then:
git push -u origin master


text:
Q: Commutant of bounded linear operators on a Hilbert space Given a Hilbert space $H$, denote by $\mathcal{A}=\mathcal{B}(H)$ the C*-algebra of bounded linear operators on $H$. Denote further by
$$\mathcal{B}(H)' := \{A\in \mathcal{B}(H) : [A,B]=0 \;\forall B \in \mathcal{B}(H)\}$$
the commutant of $\mathcal{B}(H)$.
I think $\mathcal{B}(H)' = \{\lambda \mathbb{1}:\lambda \in \mathbb{C}\}$, but how can proof this?
Are the elements of $\mathcal{B}(H)'$ invertible in $\mathcal{B}(H)'$? (Then my claim would follow by the Gelfand-Mazur theorem...)

A: If $A$ is in the commutant and $x$ is any non-zero vector, then the fact that $A$ commutes with the orthogonal projection to the line spanned by $x$ implies that $Ax$ is a scalar multiple $\lambda x$ of $x$. The scalar has to be the same for all $x$ because if $x$ and $y$ are multiplied by different scalars, then $x+y$ would not be sent to a scalar multiple of itself.

A: I don't know if one can directly argue that all nonzero elements of $\mathcal{B}(H)'$ are invertible in $\mathcal{B}(H)'$, but it follows.
If $A \in \mathcal{B}(H)$ commutes with every bounded operator, in particular it commutes with all orthogonal projections. That means every subspace of $H$ is an invariant subspace of $A$, in particular all nonzero elements of $H$ are eigenvectors. If $A$ had more than one eigenvalue, the sum of two eigenvectors to different eigenvalues wouldn't be an eigenvector.

A: Reference: Murphy, Remark 4.1.3
Combine the following:
$$\mathbb{C}\mathbb{1}=\overline{\mathbb{C}\mathbb{1}}\quad\overline{\mathbb{C}\mathbb{1}}=\mathbb{C}\mathbb{1}''\quad\mathbb{C}\mathbb{1}'=\mathcal{B}(\mathcal{H})$$
The closure being the strong.


text:
Q: A weird mistake in determining range Consider $f(x) = x^2 + \frac{1}{x^2 + 3}$. Now we can find range of $f(x)$ using the function's derivative, but another way is this: We add and subtract  $3$ . So $f(x) = x^2 + 3 + \frac{1}{x^2 + 3} - 3 = a + \frac{1}{a} - 3$ where $a = x^2 + 3 \gt0 $ and also we know if $a\gt 0 $ then $a+ \frac{1}{a}\ge2$ so the result is that range of $f(x)$ is $[-1 , +\infty)$ but it is wrong and the right range is $[\frac{1}{3},+\infty)$. This method can used for many functions and it's right but I don't know why it is wrong here. If someone could explain when we can/cannot use it , my problem will solve .

A: Note that $a$ is not just greater than $0$, it is in fact greater than $3$. This means that, while $a + \frac1a \geq 2$ is true, that does not mean that it's also possible that $a + 1/a = 2$. In fact, $a + \frac1a \geq \frac{10}{3}$, and this bound is tight, in the sense that for the right value of $x$ we also have $a + \frac1a = \frac{10}{3}$.


text:
Q: Field of generic type with getter that returns the right type? Given the following two classes Foo and FooBar:
public abstract class Foo {
  private String type;
  private int id;

  public String getType() {...}
  public int getId() {...}
}

public class FooBar extends Foo {
  private String extraField;

  public String getExtraField() {...}
}

How do I implement a class with a field that could be either Foo or FooBar? For example, in the class Example below, I want the getFoo() method to return either an instance of Foo or an instance of FooBar such that all accessors are available:
public class Example {
  private Foo fooField;

  // Not correct!
  public Foo getFooField() {...}
}

I am thinking that I need to implement a generic class as a wrapper, but I'm not sure how to tie it into the Example class.
public interface FooWrapper<T extends Foo> {
  // Would I define some getter here?
  // Is this the right track?
}

Update: For clarification, Example does not extend Foo. Example is a completely different type that contains a field of type Foo/FooBar.

A: You can make your Example class generic like so:
class Example<T extends Foo> {
    private T fooField;
    public T getFooField() { return fooField;}
}

And then create parameterized instance, for Foo or FooBar:
Example<Foo> fooExample = new Example<Foo>();
Foo foo = fooExample.getFooField();
System.out.println(foo.getId());
System.out.println(foo.getType());

Example<FooBar> fooBarExample = new Example<FooBar>();
FooBar fooBar = fooBarExample.getFooField();
System.out.println(fooBar.getId());
System.out.println(fooBar.getType());
System.out.println(fooBar.getExtraField());


text:
Q: How to set an item to top when I do Scroll in ListView? I have a ListView and I would like to do that when I am scrolling and an determinate item goes out of display, it set to top.
Is to do for a ListView of events. I would like the date always was visible.
thanks!

A: You mean about StickListView?
https://github.com/emilsjolander/StickyListHeaders


text:
Q: Solve the following inquality
$$|x+1|+|x|>3$$

I have one simple problem. When I break the modulus function, ie. when I get the following expressions
$$-x-1-x$$ $$x+1-x$$ and $$x+1+x$$
When will the inequality corresponding to 3 change? If I don't change it, I get the wrong answer. If I change it in the first expression, I get the right answer. How do I know when to change?

A: Hint: Consider the cases $x\geq 0$, $-1\le x<0$ and $x<-1$.
By the hint you will get
$$x+1+x>3$$
$$x+1-x>3$$
$$-x-1-x>3$$
Can you finish now?
Then you will get
$$x>1$$
$$1>3$$ (no solution)
$$-2x>4$$ or $$x<-2$$ (the inequality sign must change!)

A: Maybe you are troubled by the fact that when multiplied by a negative  number inequality switches
$$ -2x>4$$
We multiply both sides by $-1/2$
$$ x<-2 $$


text:
Q: Logging entry, exit and exceptions for methods in java using aspects I am using the below code to log entry, exit and exceptions using aspects. This way I have to define a bean for every class in my application in my ApplicationContext and it becomes cumbersome to maintain such length of bean definitions and their properties. Can you help me simplify this? I don't think it is appropriate design to define bean everytime I create a class. Help is appreciated, thanks in advance.

<bean id="logEntryBean" class="com.example.logging.LogEntry" />
<bean id="logExitBean" class="com.example.logging.LogReturn" />
<bean id="logExceptionBean" class ="com.example.logging.ExceptionLogger"/>

<bean id="simpleServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="simpleServiceBean" />
    <property name="interceptorNames">
        <list>
            <value>logEntryBean</value>
            <value>logExitBean</value>
            <value>logExceptionBean</value>
        </list>
    </property>
</bean>

    <bean id="secondServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target" ref="secondServiceBean" />
    <property name="interceptorNames">
        <list>
            <value>logEntryBean</value>
            <value>logExitBean</value>
            <value>logExceptionBean</value>
        </list>
    </property>
</bean>

====================
LogEntry class:
public class LogEntry implements MethodBeforeAdvice {
private final static Logger logger = Logger.getLogger(LogEntry.class);

public void before(Method method, Object[] args, Object target) throws Throwable {

    if(logger.isDebugEnabled())
    logger.info("logged entry for method : " + method.getName());
}

=========================
LogReturn class:
public class LogReturn implements AfterReturningAdvice {
private final static Logger logger = Logger.getLogger(LogReturn.class);

public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
    if(logger.isDebugEnabled())
    logger.info("Logged exit for method : " + method.getName());
}

==============================
ExceptionLogger class
public void afterThrowing(Exception r) throws Throwable {

    loadProperties();

    // LOG the exceptions
    logger.error("Exception  : " + r.getMessage());
    logger.error(r);

    if (logger.isDebugEnabled()) {
        // Logging complete stacktrace in better format
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        r.printStackTrace(pw);
        logger.debug((sw.toString()));
    }
    // sendMail();

    if (r instanceof ProcessingException) {

        throw new OutputException(prop.getProperty("ER004"), r);
    } else if (r instanceof SystemException) {
        throw new OutputException(Error.DATABASE.toString(), r);
    }

}

public void loadProperties() {

    // use try with resource
    try {

        // load a properties file
        input = getClass().getClassLoader().getResourceAsStream("ErrorCodes.properties");
        prop.load(input);

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

=======================
Main method:
public class App {
public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    SimpleService simpleService = (SimpleService) context.getBean("simpleServiceProxy");
    SecondService secondService = (SecondService) context.getBean("secondServiceProxy");
    // simple call to demo entry and exit logging to the methods of the
    // class
    simpleService.simpleCall();
    secondService.test2();
    try {
        // processing logic where exception is generated and handled
        simpleService.processingOperator();
    } catch (Exception e) {

        System.out.println(e);
        // TODO
        // Handle exception
    }

    // test the service on a different bean
    secondService.test3();
    context.close();
}

}

A: you can use Spring's component scan to autowire your beans.
Simply add
<context:component-scan base-package="<PACKAGE>" />

to your applicationContext.xml. You have to replace "" with the package you want to scan for beans.
Also, you have to annotate your beans with
@Component

to say "hey, this is a bean" to Spring. To inject dependencies into other beans, simply tag the field with
@Autowired

and they will be injected.
I hope this will help :).
~Fabian

EDIT: How to use spring-aop and AspectJ.
You have to add
<aop:aspectj-autoproxy />

to your applicationContext.xml. Then, you have to define a class that will contain your aspects. This class is a basic Spring bean, annotated with
@Component

Then you have to define the join-points where you want to execute your logging via pointcuts.
Example:
@Around("execution(* <BASE_PACKAGE>..*.* (..))")
public Object logAll(PreecedingJoinPoint joinPoint) throws Throwable {
    Object result = null;
    Throwable throwable = null;

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    try {
        result = joinPoint.proceed();
    } catch (Throwable t) {
        throwable = t;
    }
    stopWatch.stop();

    if (throwable == null) {
        LOGGER.debug("Executed " + joinPoint.getSignature() + " in " + stopWatch.getTime() + "ms!");
    } else {
        LOGGER.debug("Executed " + joinPoint.getSignature() + " in " + stopWatch.getTime() + "ms! Threw an exception: " + throwable);
        throw throwable;
    }
    return result;
}

You continue the execution via joinPoint.proceed(). It is important that you return the result! Otherwise, every method will return null! Also, you must throw the thrown exception, otherwise it will be suppressed.


text:
Q: Counterexample to Jensen's inequality This appeared in an exam I took.
The question asked us to give an example of a convex function $g: \mathbb{R} \longmapsto \mathbb{R}$ and a measure $\mu$ on $\left(\mathbb{R}, \mathscr{B}(\mathbb{R})\right)$ such that $g\left(\int x \, d\mu(x)\right) > \int g(x)\, d\mu(x)$.
I am assuming that such an example can be constructed by violating the finiteness of the measure, but I have no idea how I would construct such an example. I guess the Lebesgue measure can be used, but am having trouble finding a function that is convex and gives this result.

A: For Jensen's inequality to hold, you need $\mu$ to be a probability measure (for other finite measures, you can obtain a rescaled version). To see that it does not hold if you remove this hypothesis, consider for example (almost any example will do)
$$\exp\left(\int_0^2 x \, dx\right) = e^2 > \int_0^2 e^x \, dx = e^2 - 1$$
However, we can rescale the measure to get a modified version of Jensen's inequality. Indeed, since $\int_0^2 f(x) \, dx = \int_0^1  2 f(2u) \, du$, we get
$$\exp\left(\int_0^2 x \, dx\right) = \exp\left(\int_0^1 (4u) \, du\right)  \le \int_0^1 e^{4u} \, du = \int_0^2 \frac{e^{2x}}{2} \, dx$$


text:
Q: How to destroy ol.Geolocation object in OpenLayers? I'm creating a geolocation object like this
var geolocation = new ol.Geolocation( {
    projection: view.getProjection(),
    tracking: true,
    trackingOptions: {
        enableHighAccuracy: true,
        maximumAge: 30000,
        timeout: 10000
    }
} );

I want to delete it eventually. How can I achieve that?

A: If you just want to stop it, use geolocation.setTracking(false)


text:
Q: What does the "honest" in "honest mistake" imply? I encountered this thread on Twitter by Will Amos.

I made a really unfortunate mistake today & obviously I'm embarrassed by it. My camera was accidentally left on as I changed into work clothes after going for a jog. I sincerely apologize to all my colleagues in the House. It was an honest mistake + it won't happen again.

I cannot comprehend what the honest in honest mistake implies. I googled it and can find this definition:

A mistake made unintentionally or unknowingly and without the intention of causing harm; a mistake that anyone might have made in similar circumstances.

But I don't know how honest relates to either unintentional or anyone might. Could anyone please help explain what the honest implies?
I wonder if it means that Will Amos honestly admitted and apologized for the mistake?

A: An honest mistake is a true or a genuine mistake. There's no such thing as a "dishonest" mistake—something is either an accident or it isn't. Rather, the term "honest mistake" is meant to contrast with an accidentally-on-purpose mistake.
For example:

*

*Two coworkers don't get along. One of them accidentally takes a drink that the other had left in the fridge. It could be that they took the drink on purpose to be mean, but that's not the case, they really thought it was their own drink—it was an honest mistake.

*A politician strips down while changing and is caught on camera. It might be that he is an exhibitionist and deliberately changed on camera for the thrill of it. But that's not the case, he really didn't realize the camera was on—it was an honest mistake.

The phrase honest mistake has become a phrase in its own right, but the underlying meaning of honest here is definition 2 at wiktionary:

(of a statement) True, especially as far as is known by the person making the statement; fair; unbiased.

i.e. it is a real mistake, definitely not something done on purpose.


text:
Q: How to use L2 pooling in Tensorflow? I am trying to implement one CNN architecture that uses L2 pooling. The reference paper particularly argues that L2 pooling was better than max pooling, so I would like to try L2 pooling after the activation function.
However, Tensorflow seems to provide only tf.nn.avg_pool / tf.nn.max_pooling / tf.nn.max_pool_with_argmax.
Is there a way to implement L2 pooling in Tensorflow?
conv = tf.....
h = tf.nn.tanh(conv)
p = tf.pow(tf.nn.ave_pool(tf.pow(h,2)), 0.5)

Will this be equivalent? Will this work well in terms of backpropagation?

A: For those who may wonder, when I tried as in Yaroslav Bulatov's response, I could see better performance:
tf.sqrt(tf.nn.ave_pool(tf.square(h))


text:
Q: Can I use if statement in constraint function for optimization using ga in MATLAB? I have a constraint functions which call another function(inverse_kinematics) for calculating some of the constraints, inverse_kinematics() will give error if c(1) and c(2) are not satisfied, how can I ensure that c(1) and c(2) are satisfied before calling inverse_kinematics() function? Can I address it by using if condition in my constraint function? Below is code of my optimization function,
function [c, ceq] = simple_constraint(l1,l2,l3)

c(1) = l3^2 + 200*l3*cos(30) + 10000 - (l1 + l2)^2;
c(2) = (100- l3*cos(30))^2 + (100*sin(30))^2 - (l1-l2)^2;

thetas = inverse_kinematics(l1,l2,l3); % Gives error when c(1) and c(2) are not satisfied

c(3) = thetas(4,1) - 160;
c(4) = thetas(4,2) - 160;
c(5) = thetas(4,3) - 160;
c(6) = 20 - thetas(4,1);
c(7) = 20 - thetas(4,2);
c(8) = 20 - thetas(4,3);
c(9) = thetas(5,1) - 340;
c(10) = thetas(5,2) - 340;
c(11) = thetas(5,3) - 340;
c(12) = 200 - thetas(5,1);
c(13) = 200 - thetas(5,2);
c(14) = 200 - thetas(5,3);
c(15) = thetas(6,1) - 340;
c(16) = thetas(6,2) - 340;
c(17) = thetas(6,3) - 340;
c(18) = 200 - thetas(6,1);
c(19) = 200 - thetas(6,2);
c(20) = 200 - thetas(6,3);
ceq = [];
end

Thanks in advance !

A: You can check the constraint by using try and catch
For example
c(1) = l3^2 + 200*l3*cos(30) + 10000 - (l1 + l2)^2;
c(2) = (100- l3*cos(30))^2 + (100*sin(30))^2 - (l1-l2)^2;
    try
        thetas = inverse_kinematics(l1,l2,l3);
    catch
        warning('C1 and C2 is wrong'); % Or you can change any parameter here
    end


text:
Q: How to combine multiple live(Video) streams in single stream? so that output will be multiple (splitted)videos in single video? I am very new to the streaming.
My requirement is to combine multiple videos/streams in to single video.
So output will be single video showing multiple videos simultaneously in single player(Like security camera video).
Here is my sample code---
IGraphBuilder oFilterGraph = (IGraphBuilder)new FilterGraph();
VideoMixingRenderer9 oVideoMixingRenderer = new VideoMixingRenderer9();
oFilterGraph.AddFilter((IBaseFilter)oVideoMixingRenderer, "Video");

IVMRFilterConfig9 oVMRFilterConfig = (IVMRFilterConfig9)oVideoMixingRenderer;
oVMRFilterConfig.SetRenderingMode(VMR9Mode.Windowed);
oVMRFilterConfig.SetNumberOfStreams(2);
oVMRFilterConfig.SetRenderingPrefs(VMR9RenderPrefs.None);

IVMRMixerControl9 oIVMRMixerControl = (IVMRMixerControl9)oVideoMixingRenderer;

NormalizedRect oNormalizedRect = new NormalizedRect();
oNormalizedRect.left = 0.0F;
oNormalizedRect.top = 0.0F;
oNormalizedRect.bottom = 0.5F;
oNormalizedRect.right = 0.5F;
NormalizedRect oNormalizedRect1 = new NormalizedRect();
oNormalizedRect.left = 0.5F;
oNormalizedRect.top = 0.5F;
oNormalizedRect.bottom = 1;
oNormalizedRect.right = 1;

int iStreamId1 = oFilterGraph.RenderFile("c:\\file1.wmv", string.Empty);
int iStreamId2 = oFilterGraph.RenderFile("c:\\file2.wmv", string.Empty);
oIVMRMixerControl.SetOutputRect(0, ref oNormalizedRect);
oIVMRMixerControl.SetOutputRect(1, ref oNormalizedRect1);
oIVMRMixerControl.SetAlpha(0, 1);
oIVMRMixerControl.SetAlpha(1, 1);

IMediaControl oMediaControl = (IMediaControl)oFilterGraph;
oMediaControl.Run();

I tried with the code but could not succeed. It is showing only one video in control & not showing other one.

A: Look at the VideoMixingRenderer in DirectShow.
This link provides an explanation of how to do it using C++:
http://www.codeproject.com/KB/directx/DirectShowVMR9.aspx
A .NET wrapper for DirectShow exists here:
http://directshownet.sourceforge.net/about.html


text:
Q: Scheduling a Cognos report based on Dates from a data warehouse table We have a report already written for Student Services, but we need to schedule it for specific times in the term; these times are from the date table in our data warehouse.  For example, we need it on the first day of the term (one of the MANY dates defined in our date table), and two weeks prior to the first day of the term.  If the current date is either one of these dates, we need the report to run; otherwise no.  Should I use trigger-based Cognos reporting?  Is there a way to do it in regular Cognos scheduling?  Should I schedule it out of an external (Oracle) stored procedure?

A: We were able to set up Event Studio to first have a daily check to see if it is 14 days before term (had to add that to the date table), and 2 weeks after start of term (also in our date table).  Set up the run condition, set up tasks for the reports required, then set up the email.  Could not set up Run Agent in Event studio (IBM was singularly unhelpful here) so we scheduled it in Cognos.  It runs like a charm.


text:
Q: GWT DockLayoutPanel blank page I'm trying to use DockLayoutPanel in Jboss-errai application.
My entry point class:
@EntryPoint
public class Application {

private Caller<UserService> userService;

private Label registerConfirmMessage;

@AfterInitialization
public void createUI() {

    DockLayoutPanel p = new DockLayoutPanel(Unit.EM);
    p.addNorth(new HTML("header"), 2);
    p.addSouth(new HTML("footer"), 2);
    p.addWest(new HTML("navigation"), 10);
    p.add(new HTML("content"));
    RootLayoutPanel.get().add(p);
}

My Application.gwt.xml:
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.4//EN"
    "http://google-web-toolkit.googlecode.com/svn/releases/2.4/distro-source/core/src/gwt-module.dtd">

<!-- GWT module definition: the rename-to attribute is used to have a shorter
module name that doesn't reflect the actual package structure. -->
<module>
 <inherits name="org.jboss.errai.common.ErraiCommon" />
 <inherits name="org.jboss.errai.bus.ErraiBus" />
 <inherits name="org.jboss.errai.ioc.Container" />
 <inherits name="org.jboss.errai.enterprise.CDI" />
 <inherits name="org.hibernate.validator.HibernateValidator" />

 <source path="client" />
 <source path="shared" />
</module>

I detected different result when I change DOCTYPE. So:
In IE6 it works with either doctype
<!DOCTYPE HTML>

Blank page in Mozilla Firefox 14, Chrome
<!DOCTYPE>

Blank page in FF14, but it works in Chrome.
All other doctypes result in blank page.
Advise me please correct solution!

A: From the documentation:

This widget will only work in standards mode, which requires that the
  HTML page in which it is run have an explicit  declaration.

So that means that:
1.The browser needs to be running in standards mode, and not in quirks mode.
2.In the beginning of your HTML file you should have this:
<!doctype html>
<!-- The DOCTYPE declaration above will set the     -->
<!-- browser's rendering engine into                -->
<!-- "Standards Mode". Replacing this declaration   -->
<!-- with a "Quirks Mode" doctype is not supported. -->

The doctype is defined in the HTML page where the application starts.
and not the gwt.xml
Also check the the link below, it describes how a gwt project is organized:
https://developers.google.com/web-toolkit/doc/latest/DevGuideOrganizingProjects


text:
Q: Send a POST ajax to add products to quotation My background is more server-side than front-end. So I may be lacking in some basic front-end knowledge.
I have a endpoint called
/quotations/:id/products

which if you do a POST action, this means you want to add products to the specified quotation where :id represents the quotation id.
In my schema, quotations and products have a many-to-many relationship.
The endpoint also expects the data is sent in the form of products[].
Meaning to say, if I want to add products with id 2, 7, and 154 to the quotation 3
I am POSTING
<input name="products[]" value="2" />
<input name="products[]" value="7" />
<input name="products[]" value="154" />

to the url /quotations/3/products
My question is how do I create the Model and View using Backbone for this setup?
I bought Addy Osmani's book on Developing Backbone.js Applications. So I have setup my backbone similar to his example.
There is only an example of a straight forward add model.
Hopefully I get an answer that follows the convention that Osmani sets out for adding children to a parent type of behavior.
Osmani also mentioned about Backbone Relational.
I am not sure if I should use this or even how. I have read the documentation, but I am not sure how to fit this into the way Osmani has structured his Backbone example apps.
UPDATE:
If it is a success, I want the page to redirect to another page called /success.
If it is a failure, I want the page to display a failure message somewhere. Assume there is a

 for me to update.
In other words, for failure, the page stays as a single page app.
For success, the page goes to another page.
As for server-side code for returning JSON replies etc, I can do this without any problems. Assume I use PHP.

A: I faced a similar problem recently, I can't tell your for certain this is the best way to do it but it's the way i've found to work reliably. I tried BackboneRelational but was having troubles with it.
This assumes you will need to create the Quote object & ProductQuotation in 1 step.

*

*Set up a view for New Quote

*On initialization of this view:
A) Create a new empty Quote model
B) Create a new collection for ProductQuotes
C) Create a new ProductQuote view for each ProductQuote you're adding
D) Subscribe the Quote view to a custom Backbones event binding (Backbone JS: can one view trigger updates in other views?), i.e.
Backbone.pubSub.on('quote_new-product-save', this.AddProduct, this)
This view will now call AddProduct any time you trigger this event.

*On initializing each ProductQuote view create a new Product model

*Wire this view up for your user to fill in any applicable information & when they are done set this information to that views Product model & trigger the "quote_new-product-save" event mentioned above and pass it that product model.

*Back in the Quote view, AddProduct will automatically be called as it was binded to this event. You should wire this to receive the new Product model & add it to the ProductQuotes collection.

*So now you have your Product model data set to your ProductQuotes collection but this is still not directly linked to the current Quote (which still hasn't been saved) so set the 'order_items' attribute on your model to all models in your ProductQuote collection i.e.
this.model.set('product_quotes', this.collection.models)
Now your unsaved Quote model will have all members of your ProductQuotes collection set as an attribute.
Now you'll need to call save on the Quote model & send the data to the server. Things to keep in mind here is that your urlRoot is set properly & that the data being sent to the server is being properly formatted. I recommend reading Saving nested objects with Rails, backbone.js, and accepts_nested_attributes_for about overriding the toJSON method in your Quote model.


text:
Q: Receiving broadcast UDP packets under Linux I'm having a similar problem to Linux Kernel not passing through multicast UDP packets only broadcast rather than multicast, and nothing I've tried has helped.
I've got a device at 192.168.0.1 spewing out broadcast UDP packets, connected directly to eth1 (192.168.0.2).  eth0 is my real network.  ifconfig tells me the broadcast address, as expected, is 192.168.255.255
$ sudo ifconfig
eth0  Link encap:Ethernet  HWaddr 54:04:a6:64:b5:a6
      inet addr:172.16.128.1  Bcast:172.16.255.255  Mask:255.255.0.0
      inet6 addr: fe80::5604:a6ff:fe64:b5a6/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:1526809 errors:0 dropped:0 overruns:0 frame:0
      TX packets:986480 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:807179430 (807.1 MB)  TX bytes:747692150 (747.6 MB)

eth1  Link encap:Ethernet  HWaddr 00:50:b6:15:6e:9a
      inet addr:192.168.0.2  Bcast:192.168.255.255  Mask:255.255.0.0
      inet6 addr: fe80::250:b6ff:fe15:6e9a/64 Scope:Link
      UP BROADCAST RUNNING PROMISC MULTICAST  MTU:1500  Metric:1
      RX packets:544315 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:572619380 (572.6 MB)  TX bytes:77544 (77.5 KB)

tcpdump confirms I've got data hitting the port.
$ sudo tcpdump -c 4 -l -n -i eth1 'udp and port 61440'
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes
09:24:51.101619 IP 192.168.0.1.0 > 255.255.255.255.61440: UDP, length 1024
09:24:51.103980 IP 192.168.0.1.0 > 255.255.255.255.61440: UDP, length 1024
09:24:51.106205 IP 192.168.0.1.0 > 255.255.255.255.61440: UDP, length 1024
09:24:51.108584 IP 192.168.0.1.0 > 255.255.255.255.61440: UDP, length 1024
4 packets captured
114 packets received by filter
0 packets dropped by kernel

But from anything I've tried to actually pick those packets up, I've got radio silence, whether I run them as user or root.
$ nc -lu 192.168.255.255 61440
$ socat UDP4-RECV:61440,reuseaddr,bind=192.168.255.255 STDOUT,nonblock=1

Also tried writing my own C and my own Python.  Nada.  Something in all this is stealing my packets.  Any ideas on what?  Ubuntu 14.04.
Edit to add:
No firewall running.  ufw reports inactive, and iptables reports all 3 tables as a bare ACCEPT.
I also tried having netcat and socat bind the overall broadcast address of 255.255.255.255, or the eth1 local address 192.168.0.2.  No packets received on any attempt.
Routing tables show nothing out of the ordinary:
$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.16.0.1      0.0.0.0         UG    0      0        0 eth0
172.16.0.0      0.0.0.0         255.255.0.0     U     1      0        0 eth0
192.168.0.0     0.0.0.0         255.255.0.0     U     0      0        0 eth1

I know that the network interface is working correctly.  If I disconnect this device and attach a different type (which is trying to DHCP) it successfully connects with the dnsmasq instance and gets assigned a lease properly.
Interestingly, asking socat to give me raw IP packets turns them up just fine:
$ sudo socat IP4-RECVFROM:17 STDOUT | hexdump
0000000 0000 00f0 0804 4bb1 6463 6665 6867 6a69
0000010 6c6b 6e6d 606f 6261 6463 6665 6867 6a69
*
0000408

FINAL EDIT:
Going in and looking more deeply at the packets, it looks like they've got bad checksums.  I think they're not getting passed along through the UDP stack because of that.  I've also run out of time for elegant solutions to this problem, and have decided to brute force it by opening a socket on raw IP packets and filtering them myself.  Thanks, everyone, for your help.

A: Here is a python script for testing UDP connections that I have used in the past:
import socket
#---socket creation
connexion = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#---Bind
try:
    connexion.bind(('', 10015))
except socket.error:
    print "connexion failed"
    connexion.close()
    sys.exit()

#---testing
while 1:
    data, addr = connexion.recvfrom(1024)
    print "messages : ",addr , data

The following can be entered into shell prompt to test sending a message
echo -n "TEST MESSAGE" >/dev/udp/127.0.0.1/10015

Testing it from localhost to localhost would be the first troubleshooting step, and then from another computer to the computer in question.

A: I have had similar problems when I set up a secondary network interface by hand, and didn't set up routing properly for that interface.
Try running: route -n and see what what the routing configuration is for eth1.


text:
Q: Why I receive "too many documents writes sent to bulkwriter" when using the 'serverTimestamp' tag?
*

*I wanted to test the batch use case and I'm a bit confused.
Initially I've used the Batch() method from the firestore GO SDK. When I use this method I don't receive any error.

*I've seen a message on my IDE when I was using Batch():
Deprecated: The WriteBatch API has been replaced with the transaction and the bulk  writer API. For atomic transaction operations, use Transaction. For bulk read and write operations, use BulkWriter.

*By reading the message I started using the BulkWriter but when I'm using it I receive an error:
too many document writes sent to bulkwriter

*When I remove the serverTimestamp there is no error.
The code:

// Storer persists tickets in Firestore.
type Storer struct {
    client *firestore.Client
}

// createTicket contains the data needed to create a Ticket in Firestore.
type createTicket struct {
        Title       string    `firestore:"title"`
        Price       float64   `firestore:"price"`
        DateCreated time.Time `firestore:"dateCreated,serverTimestamp"`
    }

func (s *Storer) CreateTicket(ctx context.Context, ticket tixer.Ticket) error {
    bulk := s.client.BulkWriter(ctx)

    ticketRef := s.client.Collection("tickets").Doc(ticket.ID.String())
    _, err := bulk.Create(ticketRef, createTicket{
        Title: ticket.Title,
        Price: ticket.Price,
    })
    if err != nil {
        return err
    }

    bulk.Flush()

    return nil
}


text:
Q: Bad CPU Type when running mono script I'm trying to get mono to work on my iMac. I'm running the latest version (3.2.4) and OSX 10.9. Whenever I use the "mono" command in Terminal.app, I get this error:

-bash: /usr/bin/mono: Bad CPU type in executable

What's the issue here?
Edit:
More information:
$ file:
/usr/bin/mono: Mach-O executable ppc
$ arch
i386
$ machine
i486
$ uname -a
Darwin Ethan-Baileys-iMac-2.local 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64 x86_64

A: I had the same issue, it was because mono was trying to run 32-bit (even though it's supposed to default to 64-bit from 5.2).
https://www.mono-project.com/docs/about-mono/supported-platforms/macos/:
"Starting from Mono 5.2 the mono command defaults to 64-bit,
you can use the --arch=32/64 switch to control the bitness."
However, I also found this still didn't work so I just went to /Library/Frameworks/Mono.framework/Commands and deleted mono32 all together, everything runs fine now. I cannot, however, say with certainty that this is a good or safe thing to do. But it did fix my problem.

A: It looks like that build of mono does not support any of the same architectures as your version of OS X does on your computer.
What are the outputs of the commands file /usr/bin/mono, arch, machine, and uname -a?
With this information, I can tell you that you are trying to run a PowerPC-only build of mono on a version of OS X which no longer includes Rosetta, and thus is incapable of running it.

A: For me, I re-installed mono and it worked. I bet I had really really old version of it.
https://www.mono-project.com/download/stable/


text:
Q: Package installation process struck in ubuntu I try to install zip package in my lamp stack in ubuntu 16.04. I'm getting below error after that installation process not moving further. I tried n number of times also I googled I'm not getting any solutions. Please guide me to resolve this issue.
Renaming removed key_buffer and myisam-recover options (if present)

Note: Facing issue not only for this package(php-zip) installation, It's happening for all the package installation.
Thanks in advance.
Edited:


text:
Q: How to create a new window of data graph with the click of a button in the GUI I want to create a new window when a button is clicked.
I will later have windows be created dynamically depending on inputted data.
When the button is clicked, the error code is generated as follows.
Process completed with exit code -1073740791 (0xC0000409).
import sys
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QPushButton, QGridLayout, QWidget, QLabel
from PyQt5 import uic

main_ui = uic.loadUiType("GUI_01.ui")[0]

class OptionWindow(QDialog):
    def __init__(self, parent):
        super(OptionWindow, self).__init__(parent)
        option_ui = "GUI_01.ui"
        uic.loadUi(option_ui, self)
        self.show()

class MainWindow(QtWidgets, QMainWindow, main_ui, QPushButton):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.btnclicked1)
        self.pushButton_2.clicked.connect(self.btnclicked2)
        self.pushButton_3.clicked.connect(self.btnclicked3)
        self.pushButton_4.clicked.connect(self.btnclicked4)

    def btnclicked1(self):
        self.setGeometry(2000, 600, 800, 600)
        self.new_window.show()
        self.fig = plt.Figure()
        self.canvas = FigureCanvas(self.fig)
        self.dialog.setWindowModality(Qt.ApplicationModal)
        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        cb = QComboBox()
        cb.addItem("TEMP")
        cb.addItem("Voltage")
        cb.addItem("Ampere")
        cb.addItem("pH")
        cb.activated[str].connect(self.onComboBoxChanged)
        layout.addWidget(cb)
        self.layout = layout
        self.onComboBoxChanged(cb.currentText())
        plt.show()

    def onComboBoxChanged(self, text):
        if text == "TEMP":
            self.doGraph1()
        elif text == "Voltage":
            self.doGraph2()
        elif text == "Ampere":
            self.doGraph3()
        elif text == "pH":
            self.doGraph4()

    def doGraph1(self):
        x = np.arange(0, 10, 0.5)
        y = np.sin(x)
        self.fig.clear()
        ax = self.fig.add_subplot(111)
        ax.plot(x, y)
        ax.set_xlabel("Time")
        ax.set_ylabel("Temp")
        ax.set_title("TEMP")
        ax.legend()
        self.canvas.draw()

    def btnclicked2(self):
        self.canvas.draw()

    def btnclicked3(self):
        self.canvas.draw()

    def btnclicked4(self):
        self.canvas.draw()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_dialog = MainWindow()
    main_dialog.show()
    # window = WindowClass()
    # window.show()
    plt.show()
    app.exec_()

A: I cannot reproduce your problem because you did not include the "GUI_01.ui" file, but it is likely that the crash is due to the fact that you use the matplotlib.pyplot module in PyQt. These modules don't mix, pyplot has it's own event loop that clashes with the Qt event loop.
If you look at this example from the MatPlotLib documentation, you'll see that they don't use import matplotlib.pyplot as plt. Instead they import the Figure as follows from matplotlib.figure import Figure. There is also no need for plt.show, so remove those statements
When I did this your code looks as follows...
import sys
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QPushButton, QGridLayout, QWidget, QLabel
from PyQt5 import uic
from matplotlib.figure import Figure

main_ui = uic.loadUiType("GUI_01.ui")[0]

class OptionWindow(QDialog):
    def __init__(self, parent):
        super(OptionWindow, self).__init__(parent)
        option_ui = "GUI_01.ui"
        uic.loadUi(option_ui, self)
        self.show()

class MainWindow(QtWidgets, QMainWindow, main_ui, QPushButton):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.btnclicked1)
        self.pushButton_2.clicked.connect(self.btnclicked2)
        self.pushButton_3.clicked.connect(self.btnclicked3)
        self.pushButton_4.clicked.connect(self.btnclicked4)

    def btnclicked1(self):
        self.setGeometry(2000, 600, 800, 600)
        self.new_window.show()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.dialog.setWindowModality(Qt.ApplicationModal)
        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        cb = QComboBox()
        cb.addItem("TEMP")
        cb.addItem("Voltage")
        cb.addItem("Ampere")
        cb.addItem("pH")
        cb.activated[str].connect(self.onComboBoxChanged)
        layout.addWidget(cb)
        self.layout = layout
        self.onComboBoxChanged(cb.currentText())

    def onComboBoxChanged(self, text):
        if text == "TEMP":
            self.doGraph1()
        elif text == "Voltage":
            self.doGraph2()
        elif text == "Ampere":
            self.doGraph3()
        elif text == "pH":
            self.doGraph4()

    def doGraph1(self):
        x = np.arange(0, 10, 0.5)
        y = np.sin(x)
        self.fig.clear()
        ax = self.fig.add_subplot(111)
        ax.plot(x, y)
        ax.set_xlabel("Time")
        ax.set_ylabel("Temp")
        ax.set_title("TEMP")
        ax.legend()
        self.canvas.draw()

    def btnclicked2(self):
        self.canvas.draw()

    def btnclicked3(self):
        self.canvas.draw()

    def btnclicked4(self):
        self.canvas.draw()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_dialog = MainWindow()
    main_dialog.show()
    # window = WindowClass()
    # window.show()
    app.exec_()

You can give it a try. Like I said, I could not test myself because I'm missing the "GUI_01.ui" file. Therefore please make your MRE reproducible next time. Make it so that others can copy-paste-execute the code themselves and test this by doing this yourself.