Will taskDelay(0) yield the CPU to a lower priority task

Question: If there are 3 tasks(T1,T2,t3) with priority P1 P2 P3.
P1 is pended.
Assume that task P2 is doing some computation. During its execution, it wants to Yield the CPU to other tasks in the system.
Will TaskDelay(0) still works in this condition? or it works only when all the tasks are with same priority?
Regards, Prabhu
Answer: taskDelay(0) will not cause a lower priority task to take control of the CPU.
Only if a task at the same priority is ready to execute would taskDelay(0) cause a context switch.
taskDelay(0) essentially causes a task at priority x to be put at the end of the priority x ready queue.  If it is the only task at that priority, it retains the CPU.


Setting up .htaccess for Zend Framework

Question: I'm following a tutorial on Zend Framework here (http://www.ibm.com/developerworks/opensource/tutorials/os-php-zend2/section2.html). I barely got started, but I'm having problems setting up this .htaccess file. Under Listing. 1 in the link, there is a block of code the article says I need to create:
htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

php_value include_path ".;c:\ZendFramework\library"

How do I create the .htaccess file properly so that an index.php file, which is nothing more than just a few prints on the page, will be opened properly on my localhost? My Zend is at E:\zendframekwork\library. So far, I have the following:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

set_include_path('.;E:\zendframekwork\library');

As you can see, I removed the "htaccess" part (do I need that?) and rewrote the last line, but it is obviously incorrect as I still get an error when trying to open index.php. How do I write this correctly?
Also, the tutorial mentions HTTPD.CONF directives having correct paths for Zend.. I looked up my HTTPD.CONF file on Apache, but there is nothing refering to Zend. Do I need to do something about this as well?
TIA!!
Comment: What is the error you are getting ?
Comment: Error is ...Server error!
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.

If you think this is a server error, please contact the webmaster.
Comment: index.php works without the htaccess file.
Answer: I think, the last line set_include_path('.;E:\zendframekwork\library'); should actually be php_value include_path ".;c:\ZendFramework\library".
*php_value* is needed to tell Apache that this not for processing & should be passed on to php.
Answer: Better you follow the Zend Quickstart
Zend Quickstart
.htaccess
    RewriteEngine on
    RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

Check your httpd.conf for an option "overwrite" set it to All
Comment: so it is not too important to have the rewriting rules and conditions in the IBM link? Also, could you elaborate on the "overwrite" options? I see a bunch of "override" options but no overwrites.
Comment: the rules at the ibm document are "old style" :-)

Setting up .htaccess for Zend Framework


How to modify files in post-build script depending on a menuconfig flag?

Question: I need to find a way to modify/edit a given file after Buildroot compilation and right before the creation of the rootfs depending on a menuconfig flag selection. I could find in the Buildroot documentation that it is possible to do that by using post-build scripts.
My problem is that I would do the script action only if I selected something in menuconfig, for example:
(x) Enable my_login_system;

If I select my_login_system, then I need to change the nsswitch.conf file according:
passwd:        my_login files

If I don't select in menuconfig the "my_login_system", then the nsswitch.conf should be:
passwd:        files my_login

So, my main question is how to know if the "my_login_system" was selected or not in the post-build script.
Answer: When a post-build scripts is executed, it can access the BR2_CONFIG environment variable, which holds the path to the Buildroot .config file. Your script can parse that file and act accordingly.
Thus you could have a condition like:
if grep -q ^BR2_MY_LOGIN_SYSTEM=y ${BR2_CONFIG}
then
    # do some tweaks
else
    # do other tweaks
fi

Alternatively, you could use the BR2_ROOTFS_POST_SCRIPT_ARGS configuration variable to pass arbitrary command line parameters (as opposed to environment variables) to the post-build scripts.
Both possibilities are documented in the Buildroot manual, at section Customizing the generated target filesystem.


Firefox unmaximizes when I exit fullscreen mode

Question: When firefox is maximized if i enter fullscreen mode (e.g. with F11, or open video in fullscreen) and then exit it, firefox becomes unmaximized with a little gap between window borders and screen borders. I searched for it, but found nothing. I use ubuntu 18.04 on xfce, and didn't experience that kind of problem on Gnome or KDE. I don't even know if it's a WM issue, or something wrong with firefox. Maybe somebody knows how to fix it?
Answer: Its a bug in current (64) version related to CSD support. This will be fixed once you upgrade to 65 or 66 (depends on release schedule).
Answer: I have the same problem in Centos 7.6. A workaround is to unmaximze the window before you press F11. Then you manually make the window as big as it would be when you maximize it. Next you press F11. And when press F11 again it returns to the size it had before the fullscreen.


MaterialCardView change background color and stroke color programmatically

Question: Pro devs. I'll try to change the card view background and stroke color programmatically but all times card.setCardBackgroundColor() override the stroke color. Statically in XML, it works well. But programmatically it make an effect like this.
val colorWithAlpha = ColorUtils.setAlphaComponent(tagColor, 128)
tagView.card.setStrokeColor(ColorStateList.valueOf(colorWithAlpha))
tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))

Same for: card.backgroundTintList = ColorStateList.valueOf(tagColor)
XML:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#DB8A61"
    app:cardCornerRadius="8dp"
    app:cardElevation="0dp"
    app:cardUseCompatPadding="true"
    app:cardPreventCornerOverlap="true"
    app:strokeColor="#EBD3C7"
    app:strokeWidth="4dp">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/tag_text"
        style="@style/SmallLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:lines="1"
        android:paddingStart="8dp"
        android:paddingTop="4dp"
        android:paddingEnd="8dp"
        android:paddingBottom="4dp"
        android:textColor="@color/white"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="5sp"
        app:autoSizeStepGranularity="1sp"
        app:autoSizeTextType="uniform"
        tools:text="Some Text" />

</com.google.android.material.card.MaterialCardView>

How it looks:
XML:
Doing that in code:
private fun createAddTagView(tagName: String, tagColor: Int, container: ViewGroup) {
        val tagView = LayoutTagBinding.inflate(inflater, container, true)
        tagView.tagText.text = tagName
        val colorWithAlpha = ColorUtils.setAlphaComponent(tagColor, 128)
        tagView.card.setStrokeColor(ColorStateList.valueOf(colorWithAlpha))
        tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))
    }

When Removing: tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))

When there are no Programmatic changes (colors setup by XML) Looks like expected:

How to make it like in XML show?
Answer: I believe that the problem is not in the MaterialCardView background/stroke methods; but that the used color shades in the layout are different than those used programmatically.
The used colors in layout:
app:cardBackgroundColor="#DB8A61"
app:strokeColor="#EBD3C7"

But programmatically, you use tagColor and add alpha channel to it with colorWithAlpha; you didn't provide the tagColor; but adding 128 alpha component would not change that much; and that is totally different than the layout colors that don't have alpha component at all.
So, to have the same colors programmatically, just reuse the same layout colors without alpha component:
tagView.card.setCardBackgroundColor(ColorStateList.valueOf(Color.parseColor("#DB8A61")))
tagView.card.setStrokeColor(ColorStateList.valueOf(Color.parseColor("#EBD3C7")))

Comment: Thank you for the answer. Seems the strokeColor= not apply a alpha channel color. Do you have an idea, how to make color from DB8A61 get same like with alpha but not with alpha EBD3C7 ?
Comment: @billygates, instead of using alpha component method, you can add the first two hex digits to the color the will represent the opacity; so the entire color will be 8 digits instead of 6. Something like `#80EBD3C7` instead of `#EBD3C7`; and use the same procedure in the answer
Comment: `setStrokeColor` not working with the alpha channel.
Comment: Not sure .. but let us check the documentation .. probably it's a bug


Custom JSF validator message for a single input field

Question: I'd like to have different validation messages for every validator for different input fields.
Is it possible in JSF to have a different validation messages for a single validator (e.g. <f:validateLongRange>) for every input field?
Answer: There are several ways:

The easiest, just set the validatorMessage attribute of the UIInput component.
<h:inputText ... validatorMessage="Please enter a number between 0 and 42">
    <f:validateLongRange minimum="0" maximum="42" />
</h:inputText>

However, this is also used when you use other validators. It will override all messages of other validators attached to the input field, including required="true" and Bean Validation such as @NotNull. Not sure if that would form a problem then. If so, then head to following ways.

Create a custom validator which extends the validator of interest, such as LongRangeValidator in your specific case, wherein you catch the ValidatorException of the super.validate() call and then rethrow it with the desired custom message. E.g.
<h:inputText ...>
    <f:validator validatorId="yourLongRangeValidator" />
    <f:attribute name="longRangeValidatorMessage" value="Please enter a number between 0 and 42" />
</h:inputText>

with
@FacesValidator("yourLongRangeValidator")
public class YourLongRangeValidator extends LongRangeValidator {

    public void validate(FacesContext context, UIComponent component, Object convertedValue) throws ValidatorException {
        setMinimum(0); // If necessary, obtain as custom f:attribute as well.
        setMaximum(42); // If necessary, obtain as custom f:attribute as well.

        try {
            super.validate(context, component, convertedValue);
        } catch (ValidatorException e) {
            String message = (String) component.getAttributes().get("longRangeValidatorMessage");
            throw new ValidatorException(new FacesMessage(message));
        }
    }
}

Use OmniFaces <o:validator> which allows setting a different validator message on a per-validator basis:
 <h:inputText ...>
     <o:validator validatorId="jakarta.faces.Required" message="Please fill out this field" />
     <o:validator validatorId="jakarta.faces.LongRange" minimum="0" maximum="42" message="Please enter a number between 0 and 42" />
 </h:inputText>

See also:

Change the default message "Validation Error: Value is required" to just "Value is required"
How to customize JSF conversion message 'must be a number consisting of one or more digits'?
Internationalization in JSF, when to use message-bundle and resource-bundle?
JSF converter resource bundle messages
Comment: I will go for number 2 as I need different messages for different validation errors as well. Your solution approved my fear that I would need a solution beyond standard behaviour.


What is the recommended spacing for siesmic hold-down bolts for sill-plates to the foundation?

Question: Our 1951 house has 2x4" sill plates atop of concrete. We are in seismic zone D.
How frequently should the sill plate be bolted to the concrete?
Answer: Depends on the load (weight and height above sill) acting parallel to the wall and sill plate.
We've learned that a load on the wall will just unzip it from the sill plate as the load gets transferred along the wall without a shear anchor bolt to stop the load in the first foot or so. That is to say that a bolt installed in the first foot of the wall will stop the load from traveling along the wall and just unzipping the wall from the sill plate.
Remember, the holddown must be installed in a 8" thick footing wall for it to be effective.
Generally in Zone D a 5/8" dia. x 24" deep rod with hook will be acceptable in a one story building with a roof that transfers the load to the sill using solid sheathing and nailed at 6" oc staggered.
I'd use something like this at each corner both ways:
https://www.google.com/search?q=simpson+hdu8-sds2.5&rlz=1CDGOYI_enUS900US900&oq=simpson+hdu&aqs=chrome.2.69i57j0i512l5.13468j0j7&hl=en-US&sourceid=chrome-mobile&ie=UTF-8#imgrc=XrxmqTzahUeAiM
Also, I'd use a 5/8" x 10" anchor bolt with hook at 24" oc along the wall and nail the sheathing 4" oc into sill.
Comment: Questions: (1) What do you mean by "[...] and nailed at 6" oc staggered"?  Are you referring to the nailing schedule (6", 4", 2") around the plywood sheathing, or something else? (2)  Also, this is existing concrete, so we won't get a hook at the end. Do we need to drill down 24" and epoxy?  Or something else?
Comment: Also what did you mean by "[...] at each corner both ways" ?   I understood that to mean put a bolt at each end of each wall when the walls meet at a corner, so a total of 2 bolts at each corner; is this correct?
Comment: Yes, add two holddown bolts at each corner (one for each direction of resistance).
Comment: Thanks!  Can you also answer the 2 questions in my other comment?
Comment: Installing nails to secure the plywood (structural sheathing) to the sill by staggering the nails into the sole plate will help keep the sole plate from splitting out and being useless. If concrete wall is already poured, there are many "retrofit" anchors (try Simpson on Google) that can be used by drilling into the concrete wall and installing an "expansion anchor".
Comment: So stagger the nails 1/2" off-center for every other nail to prevent splitting?  (You said "sill" and "sole" plate.  Are those different things, or a typo?)
Comment: Sill and sole plate are the same to me.


Can you encode a reflection in a quaternion?

Question: Say we have the transformation:
\begin{bmatrix}
1 & 0 & 0\\
0 & 0 & 1\\
0 & 1 & 0\\
\end{bmatrix}
i.e. the matrix that encodes swapping the z and y axes. This is equivalent to a reflection around the z=y line.
Is it possible to encode this same transformation in a quaternion?
Comment: The short answer is: yes. Search for "Quaternion to Matrix" and "Matrix to Quaternion" to get code examples.
Comment: All the vectors in the matrix must be unit length though. But the example you gave they are.
Answer: No; quaternions can only represent proper rotations (i.e. without reflection).
If you use non-unit quaternions, you can represent a combination of rotation and uniform scaling, but still not reflection.
Comment: https://www.euclideanspace.com/maths/geometry/affine/reflection/quaternion/index.htm the math is slightly different for reflections
Comment: It's a non-standard application of quaternions. If you want to change the math, then you can do whatever you want of course. You can represent arbitrary reflections as a scale of (-1, 1, 1) followed by a quaternion rotation, too.
Comment: This isn't inventing new math, and it certainly isn't changing the rules. And this little "trick" can be very handy.
Comment: @pmw1234 it says you can't use them for reflections and rotations simultaneously.


Usability Concerns with Parallax Scrolling

Question: I work for an agency that is very parallax happy. Clients seem to love it, so we keep pushing it.
My goal is to build solutions that end-users love, so I've been trying to push more user-centered practices here. It's been an uphill battle.
Does anyone have any information from real user studies or articles that speak about the usability of parallax scrolling? I've been unable to find anything of substance by searching.
Comment: Agencies often don't do work for users. As you have found out, they often do 'cool' work for a) the person writing the checks and b) awards competitions.
Comment: Clients love it...do users? Have you done any tests with users? Not formal usability studies, just some simple questions even.
Comment: In what context is parallax scrolling being used? Do you mean some kind of web page where not all elements scroll to the same degree, creating a 3D effect?
Comment: That's my struggle. I'm pushing for more open dialog with users. We're still in the mind set of "do whatever makes the client happy" and "don't talk to the public until we're 100% ready". I plan to argue for more of a collaboration with users for our next project, but I was just looking for some good resources before our startup meeting. Thanks!
Comment: Your test users can sign NDAs, it's not necessary to involve "the public"...plus you can run usability studies on past projects (with client approval where necessary) or tests projects...
Comment: @DA01 +1 for straight up truth.
Comment: @DA01 That's a lesson I've been learning the hard way.
Comment: Do you find they affect the UX or are you just looking answers? It's not totally clear.
Comment: @DA01 Great point. Just a few of the reasons I will never work at an agency again!
Comment: Extended exposure to parallax animations makes me nauseous. Someone should conduct a study on that.
Comment: You might find this related question interesting : http://ux.stackexchange.com/questions/52759/parallax-scrolling-and-accessibility
Answer: See:
(a) Frederick D., Mohler J., Vorvoreanu M., Glotzbach R. (2015) The effects of parallax scrolling on user experience in web design, Journal of Usability Studies, 10 (2), 87-95: http://uxpajournal.org/the-effects-of-parallax-scrolling-on-user-experience-in-web-design/
Excerpt from article abstract:
Participants believed that the parallax scrolling website was more fun than the non-parallax scrolling website. The results of the study also showed parallax scrolling to be more effective when used in a hedonic and fun context. In spite of these benefits two of the participants suffered motion sickness and experienced significant usability issues while interacting with the parallax scrolling website. As a result, this potential risk to participants raises some ethical issues that UX practitioners and web designers should consider when planning to implement parallax scrolling.
(b) Parallax Scrolling: Attention Getter or Headache?: http://www.uxmatters.com/mt/archives/2014/11/parallax-scrolling-attention-getter-or-headache.php
Excerpts:
With few exceptions, parallax scrolling is just a flashy gimmick from a user experience perspective. Its primary usefulness is to show off how cools a designer is... The pro-parallax camp feels that the stunning visual nature of this effect improves the user experience. Parallax can guide and delight users. On the other hand, the anti-parallax camp feels that parallax scrolling stunts the effectiveness of Web sites... Although this article may seem to be a scathing denunciation of the usefulness of parallax scrolling, it's not all bad news for parallax lovers. If you use parallax in moderation and stay within the bounds of these sophisticated optimization strategies, parallax scrolling actually has the potential to delight users, thus improving a Web site's user experience.
Comment: This (revised answer) is great.  Nice references!
Comment: Great reference and good excerpts.
Answer: The only thing I'm aware of is related to the parallax user studies for interactive touch screens, try searching for "User Model for Predictive Calibration Control on Interactive Screens" but this is user studies related to mechanical touch screen studies. You might have better luck looking for 'Parallax Error' and 'User Viewpoint' if your goal is to disprove that it coincides with user-centered practices.
I'd personally say that the best thing is to create your own study and publish your findings. I think the parallax effect can add to the user interface's 3D depth, thus increase emotional response to using the interface: I think it can be good thing, depending on the audiences' bias, as long as it is keyboard accessible.
Of possible interest related to the topic: http://3.7designs.co/blog/2012/01/parallax-scrolling-effect-12-tutorials-an/
Answer: Something not mentioned but very important is that parallax effects often break a users mental model of a page. If we look at an extreme example like this one from Sony, we can see some of the shortcomings very easily. No way to navigate, no awareness of state. Essentially it's not a web page, it's an ad(or "experience") that hijacks scrolling for another purpose.
Comment: Thanks for a good addition to my "Design idiocy" collection... ;θ)


Why do I get a TypeError if I pass only one argument?

Question: def divide(num1,num2):
    try:
        return num1/num2
    except TypeError:
        return "Please provide two integers or floats"
    except ZeroDivisionError:
        return "Please do not divide by zero"

Comment: You don't enter the body of the function if you don't pass the two positional argument it requires. You can't catch that *inside* the function.
Comment: @jonrsharpe OMG this is the first question I dared to ask, you replied straight away and I understood your reply! How can I express my gratitude? I see only a flag next to your reply!
Comment: @nadjmental, if you think  his answer helps you then upvote it, don't trigger flag/
Comment: I've turned it into an answer now, that was just a comment.
Comment: @jonrsharpe apparently votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score - anyway thank you very much!
Comment: @nadjmental you're right, that's in https://stackoverflow.com/help/someone-answers guidance - *"if you have earned the appropriate voting privilege..."*
Comment: @TaohidulIslam same for you, votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score, thank you so much for your help! :)
Comment: @nadjmental, You can accept the best answer by clicking on the green checkmark beside the answer.
Comment: @jonrsharpe I read your link and it also says not too add a comment to say "Thank you", oopsie ;)
Answer: If you don't supply all of the required arguments, the function is never entered, so there's no way to catch that TypeError from inside the function.
To illustrate, consider a function that immediately errors out:
>>> def func(a, b, c):
...     raise Exception("inside the function")
...

Now let's call it with the required arguments:
>>> func(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
Exception: inside the function

Here you can see from the traceback (in func) that the function was entered and the error thrown from there. However, if we call it again without the arguments:
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 3 arguments (0 given)

Note that the traceback doesn't include in func, the error happens before entering the function body. You can only catch it outside the function:
>>> try:
...     func()
... except TypeError:
...     print('oh no!')
...
oh no!

Answer: For positional parameters, you have to pass the same number of arguments. You can use the default argument concept, like :
def divide(num1=1,num2=1):
    try:
        return num1/num2
    except TypeError:
        return "Please provide two integers or floats"
    except ZeroDivisionError:
        return "Please do not divide by zero"

You can call this function using 0,1 or 2 arguments.
Answer: Because your try/except statement is catching that exception and returning the designated message.
Try something like this:
try:
   if num1 and num2:
      return num1 / num2
   else:
      return "Please provide two numbers"
except ZeroDivisionError:
   return "Please do not divide by zero"
except TypeError:
   return "Please provide two integers or floats"


AWS Lambda function with .NET Framework

Question: Is it possible to write a .NET Framework (not .NET Core) lambda function?
I have a legacy WCF SOAP service that is not compatible with .NET Core. I know I can write a .NET Framework application and deploy to EC2. Is it possible to deploy a .NET Framework application to AWS in a more scalable/serverless way such as a lambda function?
Answer: At this time there is no built in support for the legacy .NET framework, all available runtime and version are here.
If you wanted to run a framework/language that is not included on this list your best option is to look at building a Lambda Layer containing the packages you require.
Other than this your only option would be to deploy it to another service, if you can package it into a container then you could run it on Fargate (which is a serverless container orchestration service).
Comment: Are there any examples of a .NET Framework Lambda Layer you have seen?
Comment: Not from what I have seen unfortunatelly there are for other languages such as PHP: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/

AWS Lambda function with .NET Framework


How can we know whether any view is used anymore or not

Question: I am trying to find about views whether they are used anymore or not.
I have tried the below queries but not much helpful
SELECT UPDATE_TIME
FROM   information_schema.tables
WHERE  TABLE_SCHEMA = 'dbname'
   AND TABLE_NAME = 'tabname'

SHOW TABLE STATUS FROM your_database LIKE 'your_table';

Can anyone tell me how to find the views usage.
I am using InnoDB.
Comment: I think it will be better if you show us your input and desired output.
Answer: You can use INFORMATION_SCHEMA.ROUTINES only if VIEW is used in PROCEDURE,FUNCTION and TRIGGERS, it will not work if VIEW is called any individual SELECT query.
SELECT DISTINCT ROUTINE_NAME, ROUTINE_TYPE
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%view_name%';

Comment: What if VIEW is called any individual SELECT query?
Comment: Most of the views in our database are called with individual SELECT query, then how to find them?


Render html in nodejs like in php

Question: It seems like a simple question, but I can't find anything about it in google or stackoverflow. Probably I haven't found the right keywords.
In php you can write something like this
example.php
<?php
//a bunch of sloppy logic, or maybe some includes but for this I'll just define the variables below...
  $title = "Word to your mother";
  $heading = "Too legit";
  $paragraph = "Extensive research has shown that people's taste in music stops changing once they are forced to earn a living. Maybe that's when they learn how dumb the lyrics really are or maybe they don't have time to waste on things that no longer matter...";
?>
<!DOCTYPE html>

  <title><?=$title?></title>

<?=$heading?>

<?=$paragraph?>

Counting

  <?php
    for($x=1;$x<=10;$x++){
  ?>

<?=$x?>

  <?php
    }
  ?>

Is there some equivalent of this in nodejs?
The broader question has something to do with serving dynamic content from a nodejs server that the browser sees as static. Solutions that require any kind of JavaScript on the client side will not work for me.
I saw ejs and vue but they both have something like

Render html in nodejs like in php


connecting python to the command prompt

Question: I'm watching a video on YouTube that that is telling me to type cd documents and then within that file type cd python to connect python, but every time I try this it says "the system cannot find the path specified" I don't understand why it is saying this because I can see that python is in my documents folder.
Comment: what is in the documents folder ? a file named `python` or a folder ?
Comment: there is no file named just python, there is  IDLE (python  3.8 32-bit), Python 3.8 (32-bit), Python 3.8 Manuals (32-bit), and Python 3.8 Module docs (32-bit).    these are in within a folder within documents, these files are directly in my documents
Comment: "I can see that python is in my documents folder." - if there is no folder or file is in your documents folder named python, why do you say that there is such ? "cd python" - how do you think you can cd to a directory that does not exist ? "I'm watching a video on YouTube" - If you talk about a video on YouTube, how about providing a link to it so that other people can watch it and tell you what you understood wrong / what is wrong in the video ?
Answer: If you are using Windows CMD or Powershell, use the command py instead of python.
Example: py myscript.py (or py.exe .\myscript.py also works)
Answer: if you want to run the python code which is located in your documents folder then open cmd and type "cd documents" and if your python code is in same folder then type "python 'filename'.py" pre enter to run

connecting python to the command prompt


Trying to change regular outlets with GFCI in both bathrooms

Question: A few months ago, both outlets stopped working at the same time.
I thought one of them would be feeding another one. So I bought two GFCI outlets to replace both of them in case. When I opened the outlet and tried to find which wire is line and which is load, it seemed like neither has power in them in either of the outlets. They both have four cables with white and black wires in them. So two of them should be line and two should be load (at least that is what my understanding is).
Could it be that it is getting load from somewhere else and that is where the problem is?
Comment: There may also be a 3rd GFCI that you haven't found yet.
Answer: It seems likely the breaker for the bathroom outlets has tripped.  Or possibly become disconnected somehow.
Start with the easiest first.  Inspect the breaker panel.  Most residential breakers do not visibly move the breaker handle when they trip.  To reset the breaker, turn it fully off and then back on.


Animate translate3d and scale with jquery?

Question: So I have a css command that edits the 3d translation of an object and its scale simultaneously to different values.
_this.css('-webkit-transform', 'translate3d('+X+'px, '+Y+'px, 0) scale('+scaleFactor+', '+scaleFactor+')');

This works great but it happens instantly, I want to animate it using jquery similarly to how you can animate width and height. So the solution I keep seeing on SO is a variation of this.
$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('transform','rotate('+now+'deg)');
    },
    duration:'slow'
},'linear');

Where borderSpacing is some value set to 0, the end goal would be -90 and it would step and slowly rotate. however this only works for one variable is it possible for me to do this when I have 3 totally different variables? and if so how? In the aforementioned solution the stepping creates a now variable that is some incremental step towards the final goal but when I have 3 independent variables I am not sure how this could work.
Answer: You best route would be to just apply a css rule to your element
#foo{
   transition: all 700ms linear;
}

and use the first part of your script only (where you apply the new transform values)

If you have to go the .animate way then the object can hold more than one properties and the step function will be called for each one
$('#foo').animate({  borderSpacing: -90, otherProp: 80 }, {
    step: function(now,fx) {
      switch(fx.prop){
          case 'borderSpacing':
               $(this).css('transform','rotate('+now+'deg)');
               break;
          case 'otherProp':
               $(this).css('something else', now);
               break;
      }
    },
    duration:'slow'
},'linear');


How do I make some values of child node '.read': true, while other values '.read': false?

Question: I have a database having a node called 'details', which has some numeric valued child nodes. Each child node store details like Name, Age, Gender, etc. I need to make the Name to be visible to all and Age, Gender not visible. Please help me with the Firebase Rule and JavaScript code.
I have already did a Rule as given below
{
    "rules": {
        "register" : {
            "details": {
                ".read": false,
                ".write": true,
                "$userid": {
                    "name": {
                        ".read": true
                    },
                    "age": {
                        ".read": false
                    },
                    "gender": {
                        ".read": false
                    }
                }
            }
        }
    }
}

My database looks like this
mainblock
    register
        details
            1
                name: "ALPHA"
                age: "10"
                gender: "Male"
            18
                name: "BETA"
                age: "15"
                gender: "Female"
            19
                name: "GAMMA"
                age: "18"
                gender: "Male"

And the JavaScript code used is
var query = firebase.database().ref("register/details/").orderByKey();
query.once("value").then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        var nm = childSnapshot.child("name").val();
        console.log(nm)
    });
});

But I have got an error saying
Uncaught (in promise) Error: permission_denied at /register/details: Client doesn't have permission to access the desired data.
    at H (firebase-storage.js:3476)
    at onComplete (firebase-storage.js:3476)
    at Object.onComplete (firebase-storage.js:3476)
    at firebase-storage.js:3476
    at e.vr (firebase-storage.js:3476)
    at t.vr (firebase-storage.js:3476)
    at t.cr (firebase-storage.js:3476)
    at e.onMessage (firebase-storage.js:3476)
    at e.nt (firebase-storage.js:3476)
    at e.handleIncomingFrame (firebase-storage.js:3476)

Answer: You have to remove the first read statement. Only the first ".read" rule is accounted when trying to access the database because "cascade in such a way that granting a read or write privilege to a parent node always grants that read/write access to all child nodes". Same is for ".write", only ".validate" does not cascade and therefore all validation rules in the tree must apply to allow a write.
More on that here.
{
    "rules": {
        "register" : {
            "details": {
                ".write": true,
                "$userid": {
                    "name": {
                        ".read": true
                    }
                }
            }
        }
    }
}

The other ".read": false statements are unnecessary because the permissions are false by default/when not set.


How to generate model from a user uploaded file?

Question: I have created a file upload section that uploads and reads CSV files as a table:
ui <- fluidPage(

titlePanel("Upload Transaction Data Set"),

 sidebarLayout(

    sidebarPanel(

  fileInput("file1", "Choose CSV File",
            multiple = FALSE,
            accept = c("text/csv",
                     "text/comma-separated-values,text/plain",
                     ".csv")),
  tags$hr(),

  checkboxInput("header", "Header", TRUE),

  radioButtons("sep", "Separator",
               choices = c(Tab = "\t"),
               selected = "\t"),

  radioButtons("quote", "Quote",
               choices = c(None = "",
                           "Double Quote" = '"',
                           "Single Quote" = "'"),
               selected = '"'),

  tags$hr(),

   radioButtons("disp", "Display",
               choices = c(Head = "head",
                           All = "all"),
               selected = "head")

),

mainPanel(

  tableOutput("contents")
       )
)

I have also created linear regression models that takes input from a data set:
thedata <- readxl::read_xlsx("data/transactionDataAlteredXLSX.xlsx")

set.seed(2)
library(caTools)
split <- sample.split(thedata, SplitRatio=0.7)

train <- subset(thedata, split=TRUE)
Actual <- subset(thedata, split=FALSE)

# Create the model
Model <- lm(Class ~.,data=train)
#Prediction
Prediction <- predict(Model, Actual)

#Comparing predicted vs actual model
plot(Actual$Class,type = "l",lty= 1.8,col = "red")
lines(Prediction, type = "l", col = "blue")
plot(Prediction,type = "l",lty= 1.8,col = "blue")
#Finding Accuracy

shinyApp(ui, server)

How do I make the linear regression models form the output of the file upload, and not from the dataset 'thedata'?
Thanks.
Edit:
Converted the file to data frame as suggested in server code, I then changed "thedata" to "df" on the regression code, but now I receive the error "unique() applies only to vectors data frame", Any ideas?:
server <- function(input, output) {

output$contents <- renderTable({

req(input$file1)

df <- read.csv(input$file1$datapath,
         header = input$header,
         sep = input$sep,
         quote = input$quote)

if(input$disp == "head") {
  return(head(df))
}
else {
  return(df)
}

})

}

Comment: I have a hunch that  I need to convert the CSV file into a data frame and use it as a variable for the model to read.
Comment: Yep, it sounds like you are on the right track. Try it out. Accept the csv input from the user, convert it into a data frame (on the server side code), check if it is in an acceptable format then perform the regression and display the results.
Comment: I've made changes, any thoughts? @Sada93
Comment: is the regression code in the server function?
Comment: Yes, is that why the models are not displaying? @Sada93
Answer: Here is a simplified version of the code you have attached. The file I chose is the standard mtcars dataset. You can save this to your computer by calling this function:
write.csv(mtcars,file = "~/Desktop/Data.csv",row.names = FALSE)

What I do here is read in the full training dataset, perform a simple linear regression, and output the predicted dataframe against a sample test dataset (i hard coded this for now).
ui <- fluidPage(

  titlePanel("Upload Transaction Data Set"),

  sidebarLayout(

    sidebarPanel(

      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv"))

    ),
    mainPanel(
      tableOutput("prediction")
    )
  )
)

server = function(input,output){
  df = reactive({
    req(input$file1)
    read.csv(file = input$file1$datapath)
  })

  #Perform Regression
  output$prediction = renderTable({
    req(df())
    model = lm(mpg ~ disp+hp,data = df())

    sample_df = data.frame(disp = c(100,200),hp = c(100,200))
    prediction = predict(model,sample_data)

    predict_df = data.frame(mpg = prediction)
    output_df = cbind(sample_df,predict_df)
    return(output_df)
  })
}

shinyApp(ui,server)

Comment: Hey this is much better, thanks! However, the only thing being returned is the selected columns from the data, and not the actual regression model, do you know why that is? @Sada93
Comment: I am not sure if it is supposed to be a table output in the mainPanel?
Comment: Think of this code as scaffolding to help you. You may replace the output with a text output or you may format the table to output the model coefficients.


How to parse a web use javascript to load .html by Python?

Question: I'm using Python to parse an auction site.
If I use browser to open this site, it will go to a loading page, then jump to the search result page automatically.
If I use urllib2 to open the webpage, the read() method only return the loading page.
Is there any python package could wait until all contents are loaded then read() method return all results?
Thanks.
Comment: Have you considered using Mechanize? http://wwwsearch.sourceforge.net/mechanize/
Answer: How does the search page work? If it loads anything using Ajax, you could do some basic reverse engineering and find the URLs involved using Firebug's Net panel or Wireshark and then use urllib2 to load those.
If it's more complicated than that, you could simulate the actions JS performs manually without loading and interpreting JavaScript. It all depends on how the search page works.
Lastly, I know there are ways to run scripting on pages without a browser, since that's what some functional testing suites do, but my guess is that this could be the most complicated approach.
Comment: Thanks for replay.

The problem is,  I've not learned javscript thus reverse engineering is difficult to me. So I ask if there is any package could check the web page state like xmlhttprequest.readyState==4 does.

I've try mechanize but this seems useless in ajax page.

Right now seems learning javascript is the best solution....
Comment: @seed. You don't need to know javascript. Just use firebug to look at what the ajax is requesting. Then load that using urllib2.
Answer: After tracing for the auction web source code, I found that it uses .php to create loading page and redirect to result page. Reverse engineering to find the ture URLs is not working because it's the same URL as loading page.
And @Manoj Govindan, I've tried Mechanize, but even if I add
br.set_handle_refresh(True)
br.set_handle_redirect(True)

it still read the loading page.
After hours of searching on www, I found a possible solution : using pywin32
import win32com.client
import time

url = 'http://search.ruten.com.tw/search/s000.php?searchfrom=headbar&k=halo+reach'
ie = win32com.client.Dispatch("InternetExplorer.Application")
ie.Visible = 0
ie.Navigate(url)

while 1:
  state = ie.ReadyState
  if state == 4:
    break
    time.sleep(1)

print ie.Document.body.innerHTML

However this only works on win32 platform, I'm looking for a cross platform solutoin.
If anyone know how to deal this, please tell me.


Are there sideeffects in python using `if a == b == c: pass;`?

Question: if a == b == c:
    # do something

Let's assume a, b, c are string variables. Are there any possible side effects if I use the snippet above to execute # do something if and only if all three strings are equal?
I am asking because I have to check three variables against each other and I get many cases:
if a == b == c:
    # do something
elif a == b != c:
    # do something
elif a != b == c.
    # do something
etc...

Perhaps there is a better way to code this?
Comment: No, there aren't any side-effects.
Comment: The word *sideeffects* is misleading here. As a technical term, there obviously **can** be any possible sideeffects - if `a`, `b` or/and `c` are instances of classes, for which comparison operators are overridden in a way that causes sideeffects.
Answer: From the documentation:

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

There should be no side effects.
Answer: There should be no side effects until you use it in a such way.
But take care about things like:
if (a == b) == c:

since it will break chaining and you will be comparing True or False and c value).
Comment: Thanks for mentioning the parenthesis. I missed, that it would break the chaining!
Answer: s = set([a, b, c])

if len(s) == 1:
    print 'All equal'
elif len(s) == 3:
    print 'All different'
else:
    l = list(s)
    print '%s and %s are different' % (l[0], l[1])

Answer: is there any comment on x!=y!=z ?
i could use the stupid way to get a correct answer.
def aligndigits(list):

   return ((x, y , z ) for x in list for y in list for z in list if   x != y and y != z and x != z )


Prove that $\sum _{i=0}^{p} \left( \binom {p+1}{i+1} \times \sum _{j=1}^{n} j^{p-i} \right)=(n+1)^{p+1}-1$

Question: Problem as follows:
Let $S^p_n := 1^p+2^p+3^p+...n^p$
Prove that $$\binom {p+1}{1}S^{p}_n+\binom {p+1}{2}S^{p-1}_n+\binom {p+1}{3}S^{p-2}_n+...+\binom {p+1}{p+1}S^{0}_n=(n+1)^{p+1}-1$$
Or, condensed in the capital sigma notation, prove that
$$\sum _{i=0}^{p} \left( \binom {p+1}{i+1} \times \sum _{j=1}^{n} j^{p-i} \right)=(n+1)^{p+1}-1$$
I tried induction on $p$ and got stuck on the inductive step:
Assume that
$\binom {p+1}{1}S^{p}_n+\binom {p+1}{2}S^{p-1}_n+\binom {p+1}{3}S^{p-2}_n+...+\binom {p+1}{p+1}S^{0}_n=(n+1)^{p+1}-1$, then show that
$\binom {p+2}{1}S^{p+1}_n+\binom {p+2}{2}S^{p}_n+\binom {p+2}{3}S^{p-1}_n+...+\binom {p+2}{p+2}S^{0}_n=(n+1)^{p+2}-1$.
I tried subtracting the first sum from the second by subtracting alike $S^x_n$'s and using Pascal's identity, and got
$$\binom {p+2}{1}S^{p+1}_n+\binom {p+1}{2}S^{p}_n+\binom {p+1}{3}S^{p-1}_n+...+\binom {p+1}{p+1}S^{1}_n=n(n+1)^{p+1}$$
I have no idea where to go from here. I also tried subtracting the two sums by subtracting alike coefficients, but didn't get anything sensible either.
Answer: Firstly it should be a bit easier to use induction in $n$ instead of $p$, since you have $S_{n+1}^p = S_{n}^p + (n+1)^p$ in the induction step.
Secondly, this can be proven directly without using induction if you consider binomial expansions of $2^p$, $3^p$, ..., $(n+1)^p$ as shown in this table:
\begin{array}{ccc}
2^{p+1}&=&\binom{p+1}{0}1^{p+1}&+&\binom{p+1}{1}1^{p}&+&\ldots&+&\binom{p+1}{p}1^{1}&+&\binom{p+1}{p+1}1^{0}\\
3^{p+1}&=&\binom{p+1}{0}2^{p+1}&+&\binom{p+1}{1}2^{p}&+&\ldots&+&\binom{p+1}{p}2^{1}&+&\binom{p+1}{p+1}2^{0}\\
\vdots&&&&&&&&\\
(n+1)^{p+1}&=&\binom{p+1}{0}n^{p+1}&+&\binom{p+1}{1}n^{p}&+&\ldots&+&\binom{p+1}{p}n^{1}&+&\binom{p+1}{p+1}n^{0}\\\hline
S_{n+1}^{p+1}-1^{p+1}&=&\binom{p+1}{0}S_{n}^{p+1}&+&\binom{p+1}{1}S_n^{p}&+&\ldots&+&\binom{p+1}{p}S_{n}^{1}&+&\binom{p+1}{p+1}S_{n}^{0}
\end{array}
Now just subtract $S_{n}^{p+1}$ from last line and notice that $S_{n+1}^{p+1} - S_{n}^{p+1} = (n+1)^{p+1}$, and the identity follows.


What's the difference between the two?

Question: Question
Which of the following two can define the derivative $f'(a)$:
1)$$\lim_{n \to \infty}n \left[f\left(a+\frac{1}{n}\right)-f(a)\right],n \in \mathbb{Z}.$$
2)$$\lim_{x \to \infty}x\left[f\left(a+\frac{1}{x}\right)-f(a)\right],x \in \mathbb{R}.$$
Comment: Here, the fact $\lim\limits_{x \to \infty}$ exists implies that $\lim\limits_{x \to +\infty}$ and $\lim\limits_{x \to -\infty}$ both exist and equal.
Comment: The second one is the definition of derivative as can be seen by using substitution $x=1/h$. The existence of first limit does not imply the existence of second limit, but existence of second limit implies the existence of first one so the first limit does not match the definition of derivative.
Comment: yes,I agree with you. But when can we make the subsitution?In another word, why we can not substitute $x$ for $1/n$?@ParamanandSingh
Comment: Refer to this answer for substitution rule of limits: https://math.stackexchange.com/a/1073047/72031 See the theorem mentioned at the end. It can be modified suitably for the case when variables tend to infinity.
Comment: The $1/n$ can't be substituted by $h$ because $1/n$ takes only a specific set of values namely rationals with numerator $1$ whereas $h$ takes all real values.
Comment: According to 2) the absolute value function would be differentiable at $0$.
Answer: Let $f(x)=
\begin{cases}
   0 & \text{If $x$ is rational.} \\
   1 & \text{If $x$ is irrational}
\end{cases}$
Then $\displaystyle \lim_{\substack{n \to \infty} \\ n \in \mathbb{Z}}n \left[f\left(0+\frac{1}{n}\right)-f(0)\right] = 0$
and
$\displaystyle \lim_{\substack{n \to \infty} \\ n \in \mathbb R \setminus \mathbb{Q}}n \left[f\left(0+\frac{1}{n}\right)-f(0)\right] = \infty$.
Hence
$\displaystyle \lim_{\substack{n \to \infty} \\ n \in \mathbb R}n \left[f\left(0+\frac{1}{n}\right)-f(0)\right]$ does not exist.

What's the difference between the two？


What's the best title for Web Application pages?

Question: In a typical Web Application we use the CRUD model to manipulate objects in a data store. The user will see a list of the objects on an index page, create a new object on the new page, edit an existing object on the edit page etc. What is the best title to put at the top of the new and edit pages?
I assume the most common title for a new page would be "New {object name}" so if the objects were Posts the title would be "New Post".
Comment: I fear, it is way too generic and with this information, the kind of suggestions you'd get would be too generic too. That would not help you.
Answer: Forget about CRUD
This answer may help explain why CRUD is helpful as a programming pattern but not very helpful as a UX pattern:

Form design for CRUD actions

Page titles are useful for:

Informing (or reminding) users about the purpose of the page.
Providing users with an orientation of where they are in the application/site.
Providing an entry point to the workflow of the page.

Therefore, a decent way to decide on what page title to use is to look at those design objectives and figure out:
What would help the user accomplish the page workflow?

For example, if your CRUD revolves around financial payments it might be: Make a payment,   Adjust payment details,  Revoke a payment.

If your CRUD app is a restaurant app your titles might be:  Create a reservation, Change a reservation, Cancel a reservation.

...in each of these cases, the language of the title has been crafted to suit a particular business task rather than a technical function (Create, Edit, Delete, etc).
Comment: I think you make some really good points there. While there may not be a better generic answer there might well be better answers for specific situations.
Answer: My advice is: test it.
"New {object name}" is a quite standard structure, but it's not necessarily the best option.
As always, the answer depends on many factors (e.g. context, type of user, conventions, etc.).
Answer: As a guideline, a good title is what you want visually-impaired people to hear first (via a screenreader) when the page loads.
So yeah - "New post" is good, but for editing a post you'd put something like "editing [post name]".
Essentially, the title should reflect the purpose of the page.


Trying to execute PHP from JavaScript, not working?

Question: I am using the following code: <a href="#" onclick="<?php var_dump($_SERVER)?>">$_SERVER Variable. is this even possible? if not then how would I do this? I amn using $_SERVER for very specific - experimental purposes.
Thanks in advance!
Comment: No, see [AJAX](http://en.wikipedia.org/wiki/Ajax_(programming))
Comment: Can I see a simple example that will get this to work?
Answer: No, but you can always send AJAX requests to a php file on the server and parse the response back into your HTML/JS. Check out jQuery's AJAX if you want the easy route ;)  http://api.jquery.com/jQuery.ajax/  A much easier example found at: Sorry, for the self promotion, but on jQuery's Ajax Tutorial I cover this :)
Comment: ok, but I repeat: Can you please show me something that will get this to work as I am experienced in PHP but I am far from experienced in JavaScript, I don't know what Ajax is exactly, it would help if you showed me some code that would work with what I am asking to do. Thanks!
Comment: +1 very clean sum up on your site :)
Answer: Here's a simple PHP/AJAX example:
http://www.w3schools.com/ajax/ajax_aspphp.asp
Comment: I appreciate the link :D but I am not advanced in js and I don't exactly understand that example, can u just show me the example that will work with this?
Comment: W3schools is not a recommended resource. See http://w3fools.com as to why
Answer: No because PHP is server side scripting while JS is client side
Comment: Can you please show me something that will get this to work as I am experienced in PHP but I am far from experienced in JavaScript
Comment: Are you trying to dump the PHP variable into a JS variable ?
Answer: You just try the echo to get the specific server value you want instead of using the var_dump


What is the benefit of larger pointers on 64-bit systems?

Question: I am trying to understand 64-bit compiling, so I did a little test in C++ Builder:
  int i = 12345;
  ShowMessage(i);
  int *pi = &i;
  ShowMessage(sizeof(pi));

  Largeint li = 9223372036854775807;
  ShowMessage(li);
  Largeint *pli = &li;
  ShowMessage(sizeof(pli));

When I compile this program as 64 bit, the  size of the pointer increases to 8 bytes (64 bits).
What is the advantage of the increased pointer size?
Comment: A `4`-byte pointer can only address ~4GB of memory. That can run out fast in a modern program.
Comment: The size of a pointer usually just reflects the underlying system. If you're on a 32-bit system, you get 32-bit pointers, and on a 64-bit system you get 64-bit pointers. It really doesn't make sense to have anything else.
Comment: Except of course that many 64 bits systems have 32 bits subsystems. That means a 4 GB limit per 32 bit process, but the total system memory can then be much more.
Answer: A pointer can hold the address of a single byte in memory. Based on its size you can calculate the maximum number of different values a given pointer can store.
With a pointer of 4 bytes (32 bits) you are limited to address only 4GB of memory, since:
2^32 = 4294967296

On the other hand, a 8 bytes (64 bit) pointer is able to address a much wider range of 17179869184GB theoretically:
2^64 = 18446744073709551616

This are 16EB (exabytes).
In practice, it is much less than that, because of limitations on most processors and the physical size of the memory etc.
You can read more on this topic here:https://en.wikipedia.org/wiki/64-bit_computing#Limitations_of_practical_processors
Comment: @İsmailKocacan you don't even necessarily need the physical RAM to benefit from this - in any modern OS, all your process memory is virtualised. you can run out of virtual address space long before you run out of physical RAM. For example, by default, a 32-bit application on 32-bit windows can only spawn about 2000 threads - even though each of those only takes around 4 kiB of your RAM, they also take around 1 MiB of your address space. Of course, you don't want 2000 threads anyway, but there are other places to take up address space without requiring RAM (and not just by using a paging file).
Comment: I added a little explanation on the top of my answer. is it clear now? with 32bits (4bytes) you have "only" 4294967296 possible values. So you can address 4294967296 different bytes in memory, which is 4gb
Comment: more memory is always nice :), but even with my 8GB a 32bit pointer would be not sufficient.
Comment: @CodesInChaos: That's only if the kernel doesn't claim a virtual address space of its own. You clearly see this on 64 bits OS'es running a 32 bits application, where the virtual address space of the process is the wrong size for the kernel. That means there's only a small interfacing stub in the 32 bits address space, leaving 3.5+ GB for the application.
Comment: "With a pointer of 4 bytes (32 bits) you are limited to address only 4GB of memory" good answer. But Why is there this limit ?
Comment: we need more memory,for more addressing.
Comment: Note that in practice you can only use 2-3 GB of address space in a 32 bit application, since part of the 4 GiB is reserved for the kernel.
Comment: @nwp: ah ok. I understand what you mean. I fixed it.
Answer: Unless you want to go back to the old days of memory paging (remember those 16 bit Z80 machines in the 1980s with 128k RAM), or early DOS expanded memory, then you need more than a 32 bit pointer to address all the available memory on a modern machine.
A 64 bit pointer is a natural (though not a necessary) choice for a 64 bit architecture.
Note that pointers of different types do not have to be the same size: sizeof(double*) does not necessarily have to be the same as sizeof(int*), for example.
Comment: @Tonny You mean you never noticed it. That or you never programmed in C++, because the standard implementation for pointers to member functions (using adjustor thunks) means that those pointers can have varying sizes in a single program. Or more classical there were far and near pointers back in the good old days.
Comment: @Tonny While selectors certainly didn't make for a particularly nice programming model, to the best of my knowledge the correct technical term was still "far pointer" (what else would you call them?). And if you had more than one module you needed far pointers, so yes you would mix them (well use both kinds in one application) if you wanted say use the clipboard.
Comment: @Tonny Mixing different sized pointers was common in DOS programs that used larger amounts of memory.  Note only NEAR vs FAR calls for code, but NEAR vs FAR data segments (not to mention HUGE "segments").
Comment: Z80 and such would have a 16-bit address range.
Comment: Amended. I remember those days well; lovingly!
Comment: Of course, there's also been tricks like PAE, that allowed addressing more than 4 GiB on a 32-bit system. However, 64-bit is vastly simpler, and it gives you effectively infinite address space (for the moment; we'll see how that still holds up in a hundred years :D).
Comment: We still have memory paging today! The difference is that the support is now transparent to applications, but the OS still has to initialize page tables.
Comment: Are there any examples of systems where pointers to different types have a different size?
Comment: @Ferruccio I'm curious about that too. Even though I've been programming in many different environments for 35 years now, I never encountered any system that mixed different size pointers in 1 program. (Different pointer sizes in one OS is certainly possible: E.g 64-bit Windows having a 32-bit sub-system so you can encounter both sizes, but not in a single program. Those sub-systems are effectively another program even if you can call a 32-bit component from a 64-bit program.)
Comment: @Luaan memory paging (say expanded memory on DOS) is different to PAE. The former can be used to give more virtual memory to a single process, while the later allows the kernel to handle more physical memory (every single process will still be limited by the normal 32bit rules). Two pair of shoes.
Comment: @Voo I do C++, but never had a reason to delve that deeply in the technicalities of the generated code. I'll take your word for it. As for the olden days (note I don't call them "good") of far and near pointers... I wouldn't call those real pointers. They were a very ugly kludge to circumvent the 16-bit index to more than 16-bit addressable memory problem. And usually you wouldn't mix them in the same program. Lucky for me I worked mostly on Unix and Aix systems in the 80's and 90's that already had true 32-bit CPU's and pointers (MC680x0, MIPS and PowerPC).
Comment: @Voo Given your reference to the clipboard I presume you mean in 16-bit Windows code? I didn't get into Windows programming until the late 90's on Windows 95/98. Anything I wrote then was already real 32-bit, so I never got much exposure to 16-bit environments. What little I recall from those days (it's been a while) if you really needed this you just declared everything "far" and let the compiler sort it out. (My recollection is probably not entirely correct :-)
Comment: @MSalters Actually, that's just a reuse of the same name for a different concept. Old-school paging was about manually selecting memory segments, while modern paging means that memory is *allocated* (or reserved) in distinct pages. Modern paging uses a flat memory model on the instruction level - as you say, it's transparent. But on the CPU-level, OS-level and application-level, it handles completely differently.
Comment: @Tonny, "real" pointers they are; just not simple.  Farther back, the IBM 360 architecture had a selector and offset fields inside one pointer value, and that was the fundamental pointer used by all such instructions.
Comment: @Tonny I could provide examples of OSes and hardware where pointers to different types had different sizes. In particular, pointers to functions often were of a different size than pointers to data types.
Answer: As explained in the other answers, it is natural to have a pointer type that can uniformly and seamlessly indicate an arbitrary location in the memory.
Now if you have a complicated data structure that uses small objects and pointers between them (like a graph, a tree), the memory taken by the pointers will be doubled when you compile in 64 bits, which is a drawback (and this is probably why you asked the question).
Note that all these data structures (graph, tree, hash map, etc...) can also be implemented in contiguous arrays in memory, and accessed through indices (it is how FORTRAN programmers implement them for instance), and if you know in advance that you have less than 4 billion elements, then you can represent your indices as 32 bit integers, even when you compile in 64 bits mode (this is what I'm doing for a 3D mesh modeling software).


Is this graph bipartite?

Question: A planar depiction of a loop-free connected graph has 7 regions, each is a
polygon. The numbers of edges on the boundaries of the regions are respectively
3,3,3,3,3,4,5. (a) Find the number of vertices of the graph.
(b) Is G bipartite?
I figured out that part a) is 7 vertices.
So now we have
|V| = 7 |F| = 7 and |E| = 12
so for part b) I began trying to draw sample graphs and my initial intuition is that it isn't but how do I go ahead and properly prove that?
Comment: Are you acquainted with the theorem that [a graph is bipartite if and only if it has no odd-length cycles](https://www.math.hmc.edu/~kindred/cuc-only/math104/lectures/lect03.pdf)?
Comment: Yes, I was just reading into that. But didn't really understand it fully. I will read the link you have provided.
Comment: Still need help on this
Comment: @DevAllanPer: Math.SE gets a lot of traffic, so, very unfortunately, not every question gets the attention one might like ... or as quickly as one might like. "Bumping" a question with a "still need help" edit is not the appropriate way to bring more attention to it.
Comment: There is a region bounded by three edges.  Can you two-color its vertices?
Comment: A graph is bipartite if and only if you can properly color its vertices in 2 colors. But vertices of a triangle can't be colored in three colors so this graph is not bipartite.
Comment: did you mean two when you said "can't be colored in *three* colors so this graph is not bipartite"?
Comment: can't be color in two colors sorry
Answer: Also, the graph on part a) could look like this:

Is this graph bipartite?


SQL Like statement not working in Visual Basic

Question: Dim strText As String = tbRefine.Text
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group FROM tblGame WHERE user_name LIKE '" + strSearchText + "' & '*'"
Dim dsRefine As New DataSet
GetDataset(sql, "tblGame", dsRefine)

MsgBox(dsRefine.Tables("tblGame").Rows(0).Item(2).ToString)

This is not working, it crashes and says there is nothing in the dataset.
I know the dataset function works as its worked successfully before.
When i print out the sql statement into microsoft access it works fine. What am i doing wrong
Comment: Do you place values like '%somepattern%' in textbox?
Comment: We need to know the contents of tbRefine.Text (hopefully not a SQL injection exploit). And also the code in the GetDataSet method.
Answer: Try this:
"SELECT user_name,forename,surname,game_cash,reg_group
 FROM tblGame
 WHERE user_name LIKE '%" + strSearchText + "%'"

Answer: Try to use the RTRIM() function in your line:
Dim sql As String = "SELECT user_name,forename,surname,game_cash,reg_group
                      FROM tblGame
                      WHERE RTRIM(user_name) LIKE '" + strSearchText + "' & '*'"
Answer: What about leading or trailing % symbols in your like?
At the moment you will end up with a where clause like:
LIKE 'searchtext''*'

which looks a bit odd (I assume SQL server?).
Answer: It's wiser to use SQL parameters as your method is open to SQL injection. The link below will help with how to format the SQL statement. I would also suggest doing it via a store procedure, but hats optional...
http://forums.asp.net/t/1256985.aspx
Answer: I think there's one more thing to be mentioned:
the "*" wildcard character works for the "Like" operator in VB/VBA/MS-Access, but not in T-SQL.
The correct wildcard character for the "Like" operator in T-SQL is "%".
That's why this T-SQL statement:
Select... WHERE ... LIKE 'sText*'

returned no data without any syntax error in MS-SQL(using T-SQL), but works in MS-Access.


How do I change the amount of health players have in Rec-Room?

Question: Is there a way to change the default amount of health on Rec-Room?
I see too many people having one-shot kill PVP and I find it ridiculous. I want to add some health to them so that they're immune to at least 5 shots.
Answer: There are Two ways to change health:

The Game Rules Chip allows you to change how much health and shield a player generally has and if/how/when it should regenerate.
You can switch to manual health management by disabling the respective settings in the Game Rules Chip, and using the Player Hit Chip instead. When a player gets shot, it outputs the player who shot and have been shot, as well as their teams and the damage. Now you have 2 options:

Simply respawn a player when he is hit.
Use the get and set player stats chips to count hits, manage the players health manually, etc.


scipy odeint with complex initial values

Question: I need to solve a complex-domain-defined ODE system, with complex initial values.
scipy.integrate.odeint does not work on complex systems.
I rod about cutting my system in real and imaginary part and solve separately, but my ODE system's rhs involves products between dependent variables themselves and their complex conjugates.
Haw do I do that? Here is my code, I tried breaking RHS in Re and Im parts, but I don't think the solution is the same as if I wouldn't break it because of the internal products between complex numbers.
In my script u1 is a (very)long complex function, say u1(Lm) = f_real(Lm) + 1j* f_imag(Lm).
from numpy import *
from scipy import integrate

def cj(z): return z.conjugate()

def dydt(y, t=0):
    # Notation
    # Dependent Variables
    theta1 = y[0]
    theta3 = y[1]
    Lm = y[2]
    u11 = u1(Lm)
    u13 = u1(3*Lm)
    zeta1 = -2*E*u11*theta1
    zeta3 = -2*E*3*u13*theta3
    # Coefficients
    A0 = theta1*cj(zeta1) + 3*theta3*cj(zeta3)
    A2 = -zeta1*theta1 + 3*cj(zeta1)*theta3 + zeta3*cj(theta1)
    A4 = -theta1*zeta3 - 3*zeta1*theta3
    A6 = -3*theta3*zeta3
    A = - (A2/2 + A4/4 + A6/6)
    # RHS vector components
    dy1dt = Lm**2 * (theta1*(A - cj(A)) - cj(theta1)*A2/2
                     - 3/2*theta3*cj(A2)
                     - 3/4*cj(theta3)*A4
                     - zeta1)
    dy2dt = Lm**2 * (3*theta3*(A - cj(A)) - theta1*A2/2
                     - cj(theta1)*A4/4
                     - 1/2*cj(theta3)*A6
                     - 3*zeta3)
    dy3dt = Lm**3 * (A0 + cj(A0))
    return array([dy1dt, dy2dt, dy3dt])

t = linspace(0, 10000, 100) # Integration time-step
ry0 = array([0.001, 0, 0.1]) # Re(initial condition)
iy0 = array([0.0, 0.0, 0.0]) # Im(initial condition)
y0 = ry0 + 1j*iy0 # Complex Initial Condition

def rdydt(y, t=0): # Re(RHS)
    return dydt(y, t).real
def idydt(y, t=0): # Im(RHS)
    return dydt(y, t).imag

ry, rinfodict = integrate.odeint(rdydt, y0, t, full_output=True)
iy, iinfodict = integrate.odeint(idydt, y0, t, full_output=True)

The error I get is this
    TypeError: array cannot be safely cast to required type
    odepack.error: Result from function call is not a proper array of
    floats.
Answer: As you've discovered, odeint does not handle complex-valued differential equations, but there is scipy.integrate.complex_ode. complex_ode is a convenience function that takes care of converting the system of n complex equations into a system of 2*n real equations.  (Note the discrepancy in the signatures of the functions used to define the equations for odeint and ode.  odeint expects f(t, y, *args) while ode (and complex_ode) expect f(y, t, *args).)
A similar convenience function can be created for odeint.  In the following code, odeintz is a function that handles the conversion of a complex system into a real system and solving it with odeint.  The code includes an example of solving a complex system. It also shows how that system can be converted "by hand" to a real system and solved with odeint.  But for a large system, that is a tedious and error prone process; using a complex solver is certainly a saner approach.
import numpy as np
from scipy.integrate import odeint

def odeintz(func, z0, t, **kwargs):
    """An odeint-like function for complex valued differential equations."""

    # Disallow Jacobian-related arguments.
    _unsupported_odeint_args = ['Dfun', 'col_deriv', 'ml', 'mu']
    bad_args = [arg for arg in kwargs if arg in _unsupported_odeint_args]
    if len(bad_args) > 0:
        raise ValueError("The odeint argument %r is not supported by "
                         "odeintz." % (bad_args[0],))

    # Make sure z0 is a numpy array of type np.complex128.
    z0 = np.array(z0, dtype=np.complex128, ndmin=1)

    def realfunc(x, t, *args):
        z = x.view(np.complex128)
        dzdt = func(z, t, *args)
        # func might return a python list, so convert its return
        # value to an array with type np.complex128, and then return
        # a np.float64 view of that array.
        return np.asarray(dzdt, dtype=np.complex128).view(np.float64)

    result = odeint(realfunc, z0.view(np.float64), t, **kwargs)

    if kwargs.get('full_output', False):
        z = result[0].view(np.complex128)
        infodict = result[1]
        return z, infodict
    else:
        z = result.view(np.complex128)
        return z

if __name__ == "__main__":
    # Generate a solution to:
    #     dz1/dt = -z1 * (K - z2)
    #     dz2/dt = L - z2
    # K and L are fixed parameters.  z1(t) and z2(t) are complex-
    # valued functions of t.

    # Define the right-hand-side of the differential equation.
    def zfunc(z, t, K, L):
        z1, z2 = z
        return [-z1 * (K - z2), L - z2]

    # Set up the inputs and call odeintz to solve the system.
    z0 = np.array([1+2j, 3+4j])
    t = np.linspace(0, 4, 101)
    K = 3
    L = 1
    z, infodict = odeintz(zfunc, z0, t, args=(K,L), full_output=True)

    # For comparison, here is how the complex system can be converted
    # to a real system.  The real and imaginary parts are used to
    # write a system of four coupled equations.  The formulas for
    # the complex right-hand-sides are
    #   -z1 * (K - z2) = -(x1 + i*y1) * (K - (x2 + i*y2))
    #                  = (-x1 - i*y1) * (K - x2 + i(-y2))
    #                  = -x1 * (K - x2) - y1*y2 + i*(-y1*(K - x2) + x1*y2)
    # and
    #   L - z2 = L - (x2 + i*y2)
    #          = (L - x2) + i*(-y2)
    def func(r, t, K, L):
        x1, y1, x2, y2 = r
        dx1dt = -x1 * (K - x2) - y1*y2
        dy1dt = -y1 * (K - x2) + x1*y2
        dx2dt = L - x2
        dy2dt = -y2
        return [dx1dt, dy1dt, dx2dt, dy2dt]

    # Use regular odeint to solve the real system.
    r, infodict = odeint(func, z0.view(np.float64), t, args=(K,L), full_output=True)

    # Compare the two solutions.  They should be the same.  (As usual for
    # floating point calculations, there could be a small difference.)
    delta_max = np.abs(z.view(np.float64) - r).max()
    print "Maximum difference between the complex and real versions is", delta_max

    # Plot the real and imaginary parts of the complex solution.

    import matplotlib.pyplot as plt

    plt.clf()
    plt.plot(t, z[:,0].real, label='z1.real')
    plt.plot(t, z[:,0].imag, label='z1.imag')
    plt.plot(t, z[:,1].real, label='z2.real')
    plt.plot(t, z[:,1].imag, label='z2.imag')
    plt.xlabel('t')
    plt.grid(True)
    plt.legend(loc='best')
    plt.show()

Here's the plot generated by the script:

Update
This code has been significantly expanded into a function called odeintw that handles complex variables and matrix equations.  The new function can be found on github: https://github.com/WarrenWeckesser/odeintw
Answer: I think I found a solution by myself. I'm posting it as anybody would find it useful.
It appears that odeint cannot deal with complex numbers. Anyway scipy.integrate.ode does
by making use of the 'zvode' integration method.


Comparison between 2 different ways of writing Merge Sort

Question: I have learned Merge Sort algorithm in C++ recently and have come across 2 different ways by which it is implemented in tutorials.
1st way:
void merge(int arr[], int low, int mid, int high) {
    const int n1 = (mid - low + 1);
    const int n2 = (high - mid);
    int *a = new int[n1], *b = new int[n2];//dynamically allocated because of MSVC compiler
    for (int i = 0; i < n1; i++)
        a[i] = arr[low + i];
    for (int i = 0; i < n2; i++)
        b[i] = arr[mid + 1 + i];
    int i = 0, j = 0, k = low;
    while (i < n1 && j < n2) {
        if (a[i] < b[j]) {
            arr[k] = a[i];
            i++;
        } else {
            arr[k] = b[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = a[i];
        k++, i++;
    }

    while (j < n2) {
        arr[k] = b[j];
        k++, j++;
    }
    delete[] a;
    delete[] b;
}

void mergeSort(int arr[], int start, int end) {
     if (start < end) {
        int mid = (start + end) / 2;
        mergeSort(arr, start, mid);
        mergeSort(arr, mid + 1, end);
        merge(arr, start, mid, end);
    }
}

int main() {
    int arr[] = { 9, 14, 4, 8, 6, 7, 5, 2, 1 };
    unsigned size = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, size);
    mergeSort(arr, 0, size - 1);
    printArray(arr, size);
    return 0;
}

2nd way:
Using temp array passed in the arguments.
void merge(int arr[], int temp[], int low, int mid, int high) {
    int i = low, k = low, j = mid + 1;
    while (i <= mid && j <= high) {
        if (arr[i] < arr[j]) {
            temp[k] = arr[i];
            i++;
        } else {
            temp[k] = arr[j];
            j++;
        }
        k++;
    }
    while (i <= mid) {
        temp[k] = arr[i];
        k++, i++;
    }
    while (j <= high) {
        temp[k] = arr[j];
        k++, j++;
    }
    for (int i = low; i <= high; i++)
        arr[i] = temp[i];
}

void mergeSort(int arr[], int temp[], int start, int end) {
    if (start < end) {
        int mid = (start + end) / 2;
        mergeSort(arr, temp, start, mid);
        mergeSort(arr, temp, mid + 1, end);
        merge(arr, temp, start, mid, end);
    }
}

int main() {
    int arr[] = { 9, 14, 4, 8, 6, 7, 5, 2, 1 };
    unsigned size = sizeof(arr) / sizeof(arr[0]);
    int *buffer = new int[size];
    printArray(arr, size);
    mergeSort(arr, buffer, 0, size - 1);
    printArray(arr, size);
    delete[] buffer;
    return 0;
}

printArray method:-
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

Which way of writing Merge Sort is better and faster ?
Comment: Well, you could experiment and [measure](https://stackoverflow.com/questions/22387586/measuring-execution-time-of-a-function-in-c) yourself?
Comment: Does this answer your question? [Measuring execution time of a function in C++](https://stackoverflow.com/questions/22387586/measuring-execution-time-of-a-function-in-c)
Answer: Doing a one time allocation of the temp array and passing it as a parameter will be significantly faster than allocating an instance of a temp array on every merge call.

Side note - Almost all library implementations for stable sorts are some type of hybrid insertion sort + bottom up merge sort such as TimSort. Top down merge sort is mostly used for classrooms, not actual implementations in libraries.
Answer: The second implementation allocates ancillary memory just once and passes the pointer recursively whereas the first calls the allocator and deallocator once per merge call. For large arrays, the second code is likely faster than the first.
Note however that both codes have problems:

they use int for the index variables, limiting the length of arrays to INT_MAX, which is smaller than capabilities of current hardware.
the compute mid as int mid = (start + end) / 2; which causes an arithmetic overflow for arrays larger than INT_MAX / 2, leading to undefined behavior and likely crashes. mid should be computed this way: int mid = start + (end - start) / 2;
they allocate too much memory: the second temporary array is useless in the first code and the temporary array could be half the size for the second code.
they copy too much data: copying the remainder of the second half is useless as these elements are already in place.
they do not implement stable sorting: elements should be compared with arr[i] <= arr[j] instead of arr[i] < arr[j].
the top down recursive merge sort algorithm is suboptimal: bottom-up merge sort implementations are usually more efficient, switching to insertion sort for small chunks tends to improve performance and testing for sorted subranges further improves performance in real life cases.
Comment: Which one of the 2 will be faster on average case with smaller arrays?
Comment: The second approach should be faster even for small arrays, but only careful benchmarking will give actual figures, albeit specific to a compiler and platform.


iOS UITableView and Master-Detail view

Question: I am working on a Master-Detail like app (for both iPhone and iPad) and I can't reproduce the same behavior of the Notes native app while inserting new item. Besides, I haven't found any interesting help on Google. On insertion I want to redirect the user to the detail view of the newly inserted item. I tried to call the selectRowAtIndexPath: in the didChangeObject: method of the controller like this :
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  newIndexPath:(NSIndexPath *)newIndexPath
{
    UITableView *tableView = self.tableView;

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            break;

But nothing happens... may be because the newly inserted item didn't have the time to appear in the table view?
Thanks in advance for any help
Answer: Try to add [tableView reloadData]:
[tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
[tableView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

Edit:
scrollToRowAtIndexPath only highlights the cell, and won't fire didSelectRowAtIndexPath, try to manually call it by:
[tableView.delegate tableView didSelectRowAtIndexPath:indexPath];

Comment: Yes the row is successfully inserted, but the detail view does not come
Comment: Ah you need to fire the tableView:didSelectRowAtIndexPath delegate: try this after selectRowAtIndexPath [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
Comment: It works perfectly on iPad (just by using [self tableView:tableView didSelectRowAtIndexPath:newIndexPath];) but not on iPhone probably because of didSelectRowAtIndexPath: implementation, it does something only for the iPad. For the iPhone it is based on storyboard segues, I thing I have to perform a segue manually without forgetting to update the detailItem ivar, but I don't know how to do that
Comment: Nice, for segue you can put the action in: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender.
Comment: In prepareForSegue: Apple already did the job, but I don't know how to perform the segue programmatically, [self performSegueWithIdentifier:@"showDetail" sender:self] will not set detailItem, any idea? Anyway thank you for your help
Comment: If this was helpful, please consider to check the answer as accepted, for firing the segue programmatically you can put another question. cheers.

iOS UITableView and Master-Detail view


Are Mario & Luigi orphans?

Question: For one thing, I'm prettty sure the mustache'd duo is definitely human. No doubt.  But what I think I've never found out is whether or not they had parents.
IS there anything not non-canon that explains their birth, or better yet, their ancestry?
Are Mario & Luigi orphans? Or do they have parents we just don't know about?
Comment: Arqade is for passionate videogamers from all platforms, including consoles, computers, handhelds, and mobile devices. If your question generally covers things such as …

Gameplay strategies and tactics
Puzzle solving or obstacle clearing
Game mechanics and terminology
**Plot and characters in games**
Comment: @Retrosaur How is this a problem you are facing in a game?
Comment: I don't see any problem in this question, if you read the About page it says that you can ask about "Plot and characters in games"
Comment: @badp then I think this question was judged rashly and without knowledge of the answer, this question should be considered valid according to the rules of the site
Comment: @Retrosaur I downvoted because this question seems pointless. Also, it shows no research, since literally the first hit on Google for "Mario and Luigi parents" answers this question.
Comment: @Celta It does say that, but [we stop where the game canon stops and don't speculate any further.](http://meta.gaming.stackexchange.com/questions/2291/game-canon-questions-which-extend-beyond-the-context-of-the-story-and-its-materi) (Not that I know if this is speculative or not; apparently [Mama Mario](http://www.mariowiki.com/Mama_Mario) and [Papa](http://www.mariowiki.com/Papa) are things that exist.)
Comment: @badp it's not speculation if the game as the answer, even if a partial response
Comment: Holy controversy Batman!
Comment: I'd like it if people could explain downvotes
Comment: @Celta Yes, it does appear this rule doesn't apply here.
Comment: @Celta I _did_ reopen it.
Comment: Yes @badp ,I don't earn anything with it but thanks, I just want to see it being done right, and those who did it should not have much hurry to judge and think about their vote
Comment: You expect coherent story?  From a Mario game?
Comment: Why does Mario rescue the princess every time?  Heck, why does Bowser kidnap her all the time?  WHY ARE WE KILLING GOOMBAS!?
Answer: Mario's parents are shown in Yoshi's Island, among other related anime and comics.
Mama Mario:

At the end of Super Mario World 2: Yoshi's Island, Mario and Luigi's mother made her first video game appearance. She is portrayed as a wide-set woman wearing a pink nightgown, and only her lower half and hands are seen.

Papa:

The video game's artists portrayed him as a skinny man in a nightshirt of indeterminate color. Only his lower half and hands are seen.

The Mario Wiki has articles on both Mama Mario and Papa, although there are a lot of references to the live action Super Mario Super Show, which is probably not canonical.
Likewise, the story is told differently in the 1993 Super Mario Bros movie, where the two are orphaned when Luigi is still a baby.  Again, there were major rewrites to canon for the movie.
Answer: Luigi and mario were babies when they flew on a stork to their parents. The ride got interrupted by the things on a broomstick and they fell on Yoshi island. The yoshis took care of them until they got older. That's why one of the first Mario games was Yoahi island.

Are Mario & Luigi orphans?


How do I turn a JsonElement into Json without the members tag?

Question: I have a method that parses the differences between two JsonElements and then returns a JsonElement that represents an object containing only the differences between the two elements.
I am then attempting to send the returned JsonElement via API PUT request and generically parse the response to an object type. The problem is that JsonElements parse to Json with the members tag in front of all of its contents.
For Example:
{"members":{"id":1172327,"assets":[{"id":436379,"licenseState":"MI","odometer":"12345"}]}}

How can I remove the members tag from the JsonElement.  I would prefer not to do it manually. I tried JsonElement.getAsJsonObject() and that fails. I also attempted to get the JsonElement as a JsonArray (JsonElement.getAsJsonArray().get(0)) but this failed because the JsonElement is not a JsonArray.
Answer: import org.json.JSONObject;

/** Assuming json_string is your json string **/

JSONObject jsonObj = new JSONObject(json_string);

JSONObject jsonMembers = jsonObj.getJSONObject("members");

//will return "{"id":1172327,"assets":[{"id":436379,"licenseState":"MI","odometer":"12345"}]}"
Log.d("Members only:",String.valueOf(jsonMembers));

Note: Make sure to surround with try/catch in case it's not valid json!!
Hopefully this is what you're looking for.
Comment: JsonObject test = new JsonObject(jsonString);
The constructor JsonObject(String) is undefined
Comment: @user2962960 You need the correct import. I've updated the code. If you're using eclipse, you can hover over the red underlined text, and click "Import _____" in the popup and it will add the required imports.
Comment: I am using JsonElements (gson) and not JSONElements
EDIT: I can use JsonObject test = JsonELement.getAsJsonObject(); to achieve a similar result but after checking test.getAsJsonObject("members") returns as null
Comment: @user2962960 That's fine. It shouldn't make a difference. Gson is just a library to convert objects to JSON. Just take the JSON that the (Gson) library spits out, cast it as string, and drop it into a new "JSONObject"
Answer: What if you just do JsonElement.getJSONObject("members") ? That will grab the element with the key "members"
Comment: JsonElements do not have a method .getAsJsonObject(string) only .getAsJsonObject()

I am trying to convert it to a JsonObject, then grab the "members" element now. I will Edit with results.

EDIT:
    JsonObject test = JsonElement.getAsJsonObject();

test.getAsJsonObject("members") returns as null.


how can i increase the width of an element when hover

Question: How can I increase the width of an element in HTML when someone hover on that element.
I wrote some code for that animation using CSS but I am not getting the expected result.
Here's what I am getting when I hover on that element:-
image.gif
Here's what I want:-
image
here is my code:-
HTML:-
<!DOCTYPE html>

      <title>home</title>
      <link rel="stylesheet" type="text/css" href="css/index.css" />
      <link rel="stylesheet" type="text/css" href="animations/index.css" />
      <meta name="viewport" content="width=device-width, initial-scale=1">

Home

blog

subjects

contacts

PHYSICS

CHEMISTRY

MATHS

CSS:-
header {
    width:100%;
    height:350px;
    position:relative;
    overflow:hidden;
    z-index:-1;
    border:3px solid grey;
    background-position: center center;
    display: flex;
    background-image:url("../images/index/header/header.jpg");
    background-size: cover;
}

.main-wrapper {
  position: relative;
}

#navul01 {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: transparent;
    position: absolute;
    right: 0;
    bottom: 0;
}

#navul01 li {
    float: left;
}

#navul01 li a {
    display: block;
    color: white;
    font-weight: bold;
    text-shadow: 2px 2px black;
    text-align: center;
    padding: 14px 16px;
    font-size: 25px;
    text-decoration: none;
    border:2px solid white;
}

#navul01 li a:hover {
    background-color: lightgreen;
}

#subjects_nav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    position: absolute;
    left: 10%;
    width: 80%;
}

#subjects_nav li {
    float: center;
}

#subjects_nav li a {
    display: block;
    color: white;
    font-size: 5vw;
    font-weight: bold;
    text-shadow: 2px 2px black;
    text-align: center;
    padding: 50px 50px;
    text-decoration: none;
    border:3px solid white;
}

#subjects_nav li a:hover {
    animation-name: subject_animation;
    animation-duration: 1s;
}

#physics_image {
    background-position: center center;
    display: flex;
    background-image:url("../images/index/subjects/physics.jpg");
    background-size: cover;
}

#chemistry_image {
    background-position: center center;
    display: flex;
    background-image:url("../images/index/subjects/chemistry.jpg");
    background-size: cover;
}

#maths_image {
    background-position: center center;
    display: flex;
    background-image:url("../images/index/subjects/maths.jpg");
    background-size: cover;
}

#space {
  list-style: none;
}

(ANIMATION) CSS :-
@keyframes subject_animation {
    from {
        width: 80%;
    }
    to {
        width: 90%;
    }

UPDATE - 1:-
i used this code in CSS transform: scale(1.2, 1); but it stretch the images and make them look ugly and i only want transformation in x-axis so i used transform: scaleX(1.4); this also stretch the image
Answer: Think differently and instead of changing the width change the margin to make them negative values. You can also use transition instead of animation:
By the way there is no float:center, you need to correct this on your code.
Here is the relevant part of the code to show the result:

#subjects_nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  position: absolute;
  left: 10%;
  width: 80%;
}

#subjects_nav li a {
  display: block;
  color: white;
  font-size: 5vw;
  font-weight: bold;
  text-shadow: 2px 2px black;
  text-align: center;
  padding: 50px 50px;
  text-decoration: none;
  border: 3px solid white;
  transition: 1s;
}

#subjects_nav li a:hover {
  margin: 0 -30px;
}

#physics_image {
  background-position: center center;
  display: flex;
  background-image: url("https://lorempixel.com/1000/1000/");
  background-size: cover;
}

#chemistry_image {
  background-position: center center;
  display: flex;
  background-image: url("https://lorempixel.com/800/1000/");
  background-size: cover;
}

#maths_image {
  background-position: center center;
  display: flex;
  background-image: url("https://lorempixel.com/1000/600/");
  background-size: cover;
}

#space {
  list-style: none;
}

PHYSICS

CHEMISTRY

MATHS


Error in vecseq data, merge (join many-one) data.table r

Question: I have 2 data.tables:

train.o with 160057 rows, column id is unique
train.t with 187105085 rows, column id is not unique, there are 160057 unique id, all in train.o

I want to merge it, to have a single data.table with 187105085 rows.
When I type
> setkey(train.o,id)
> setkey(train.t,id)
> trainbig=merge(train.t,train.o)

I get

Error in vecseq(f__, len__, if (allow.cartesian) NULL else
  as.integer(max(nrow(x),  :   Join results in more than 2^31 rows
  (internal vecseq reached physical limit). Very likely misspecified
  join. Check for duplicate key values in i, each of which join to the
  same group in x over and over again. If that's ok, try including j
  and dropping by (by-without-by) so that j runs for each group to
  avoid the large allocation. Otherwise, please search for this error
  message in the FAQ, Wiki, Stack Overflow and datatable-help for
  advice.

What do I wrong?
EDIT:
> head(train.o)
 offer       id chain market repeattrips repeater  offerdate category quantity   company
1: 1197502    86252   205     34          16        t 2013-03-27     3203        1 106414464
2: 1208251    86246   205     34           5        t 2013-04-24     2202        1 104460040
3: 1197502 12682470    18     11           0        f 2013-03-28     3203        1 106414464
4: 1197502 12996040    15      9           0        f 2013-03-25     3203        1 106414464
5: 1204821 13089312    15      9           0        f 2013-04-01     5619        1 107717272
6: 1197502 13179265    14      8           0        f 2013-03-29     3203        1 106414464
   offervalue  brand
1:       0.75  13474
2:       2.00   3718
3:       0.75  13474
4:       0.75  13474
5:       1.50 102504
6:       0.75  13474

> head(train.t)
     id chain dept category    company brand       date productsize productmeasure
1 86246   205    7      707 1078778070 12564 2012-03-02          12             OZ
2 86246   205   63     6319  107654575 17876 2012-03-02          64             OZ
3 86246   205   97     9753 1022027929     0 2012-03-02           1             CT
4 86246   205   25     2509  107996777 31373 2012-03-02          16             OZ
5 86246   205   55     5555  107684070 32094 2012-03-02          16             OZ
6 86246   205   97     9753 1021015020     0 2012-03-02           1             CT
  purchasequantity purchaseamount
1                1           7.59
2                1           1.59
3                1           5.99
4                1           1.99
5                2          10.38
6                1           7.80

Comment: At least show us the structure, column names of your data sets and also show us that there are no duplicated elements on the column you're joining.
Comment: The data come from [link]http://www.kaggle.com/c/acquire-valued-shoppers-challenge/data

-train.o is merge(trainHistory,offers,by="offer")
-train.t is subset(transactions,id %in% trainHistory$id)

The transactions file can be joined to the history file by (id,chain). But setkey for both id and chain doesn't help.
Comment: I've also edited post to include heads of both data.tables
Comment: what does `sum(!duplicated(train.o$id))` and `sum(!duplicated(train.t$id))` give?
Comment: Both 160057, I wrote it in the beginning.
Comment: Okay one last test before I give up. What does `sum(is.na(match(unique_values_from_train.o, unique_values_train.t)))` give? Just to verify if the keys are identical in both. I'm sorry I don't have the time to download GBs of data from Kaggle. The objective should be to produce a minimal example, but that seems to be not the case here. So, this'll be my last attempt.
Comment: It seems as though you are just running up against the language limits on the integer class.
Comment: If you mean unique values of id in both data.tables it gives 0. I'm wondering if it is not a bug in data.table. When I merge in the same way offers and trainHistory to get train.o it works.
Comment: Especially that plyr's join(train.t,train.o,by="id") succeed.
Comment: Could you tell what's the class of `id` in all these data.tables?
Comment: Could you please try again from the current development version from [github](https://github.com/Rdatatable/data.table)?
Answer: Have you tried an unelegant (but effective):
trainbig=merge(train.t,train.o, by=.EACHI, all=T)

and then manually removing the variables you are not interested in?


Error php and mymql

Question: First time programming a simple database.
But I cant figure out how to solve this error:

Parse error: syntax error, unexpected '$row' (T_VARIABLE) in
  W:...\index.php on line 39

This is my script..
$result = mysqli_query($link,"SELECT * FROM studenten");

echo "

first name
last name
studentnummer

";

while($row = mysqli_fetch_array($result)) {

  id = $row[id]; //this is line 39
  echo "
";
  echo "" . $row['voornaam'] . "	";
  echo "" . $row['studentnummer'] . "	";
  echo " Edit";
  echo " Delete";
  echo "
";
}

echo "
";

can someone help me?
Comment: change `id = $row[id];`     to      $id = $row['id'];
Comment: forget $ and quotes `$id = $row['id'];` //this is line 39
Comment: yeah, `id` is being treated as a constant. (for one thing).
Comment: Not enough coffee yet. Change that row to be `$id = $row['id'];` Note the `$` for the variable and the quotes around the array key identifier.
Comment: @Jay Blanchard  how to store value in variable inside the loop it returns in array format
Comment: What do you mean @KarthikKeyan
Comment: Not possible to store the variable inside the loop i this it stored in array format like $id[] = $row['id'];
Comment: Guys, You we are all putting minus to question , It just a question
Answer: id = $row[id]; //this is line 39

Shouldn't that be
$id = $row['id']; //this is line 39

You're missing the $ from your id variable and quotes for your array key.
Answer: use
mysqli_fetch_assoc
because
mysqli_fetch_array

returns a indexed array
and on line 39
$id = $row['id'];

Error php and mymql