text:
Q: Connecting OAuth with User or Person Model in ASP.NET MVC C# So there's plenty of tutorials online on how to get oAuth working with ASP.NET, even a tutorial on how to set roles for those logged in accounts with MVC but none of these tutorials explain what's next. What is that called when you connect a user you've registered with Google to the person or user model in your app? How do you act as one of those persons based on who you're logged in as with Google?  I've figured out how to register first and last name and all that jazz but still I'm not sure how to make it so that I'm in or acting as the person.
For example, I have a person model and some other models that inherit from the person model, such as Engineer and Manager:
public class Person
    {
        [Key]
        public int PersonId { get; set; }

        [Required(ErrorMessage = "The First Name field is required.")]
        [Display(Name = "First Name")]
        [MaxLength(50)]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "The Last Name field is required.")]
        [Display(Name = "Last Name")]
        [MaxLength(50)]
        public string LastName { get; set; }

        [NotMapped]
        [Display(Name = "Name")]
        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }

    }

public class Engineer : Person
    {
        public ICollection<Manager> managers { get; set; }
    }

public class Manager : Person
    {
        public ICollection<Engineer> engineers { get; set; }
    }

Here I have the following added to the AccountController:
[AllowAnonymous]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            string firstName;
            string lastName;
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }
            if (loginInfo.Login.LoginProvider == "Google")
            {
                var externalIdentity = AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
                var lastNameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
                var givenNameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);

                firstName = givenNameClaim.Value;
                lastName = lastNameClaim.Value;

            } else
            {
                firstName = "Error";
                lastName = "Error";
            }
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
                case SignInStatus.Failure:
                default:
                    // If the user does not have an account, then prompt the user to create an account
                    ViewBag.ReturnUrl = returnUrl;
                    ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                    return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email, FirstName = firstName, LastName = lastName });
            }

And the account view model:
public class ExternalLoginConfirmationViewModel
{
    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

So how do I log in with google and then be one of the persons? What is this even called? Is there a name for doing this? I assume everyone does this at some point. I can create persons, managers and engineers in my initialization class but I don't know how to do it with oAuth.
Note, I would prefer to force all users to log in with Google rather than create a local user account so I didn't bother with registering site accounts.
Also for good measure here's my IdentityModel:
public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

A: During the external login process, an authorization token is returned by the third party API. You should add this token as a claim for the user. You can do this by changing the code in Startup.Auth.cs to something like the following:
var googleOptions = new GoogleOAuth2AuthenticationOptions
{
    ClientId = Properties.Settings.Default.GoogleClientId,
    ClientSecret = Properties.Settings.Default.GoogleClientSecret,
    Provider = new GoogleOAuth2AuthenticationProvider
    {
        OnAuthenticated = (context) =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:access_token", context.AccessToken, XmlSchemaString, "Google"));
            return Task.FromResult(0);
        }
    }
};
googleOptions.Scope.Add("foo");
app.UseGoogleAuthentication(googleOptions);

Where "foo" is above, you'll need to add the scope(s) you need the user to authorize your application for. Consult the Google API docs for a full list of scopes. If you need multiple scopes, add additional googleOptions.Scope.Add lines.
Later, you can retrieve the token using:
var googleTokenClaim = user.Claims.FirstOrDefault(m => m.ClaimType.EndsWith("google:access_token"));

For the purposes of Google's APIs, the token returned is a "refresh token". The refresh token is good until the user revokes access to your app, but you need to "trade it in" for an access token. Details for how to do that can be found in the Google Identity Platform docs, or you can just use one of the client libraries to handle all this for you.
Long and short, once you have a true access token, you simply authorize requests that need authorization by adding an Authorization: Bearer [token] header to the request.
Now, different APIs handle some of this differently, but you specifically mentioned Google. Consult the docs of other APIs you may need to utilize to see what you should do with those.
UPDATE: Getting User Instance
With Identity, the user principal exposed by User.Identity is not a complete representation of the user instance in the database. In order to get all the information for a user, including their claims, you need to query the user from the database. First, you need to get the user's id, so you have something to query by. Identity exposes an extension GetUserId() on User.Identity for that:
var userId = User.Identity.GetUserId();

If you've customized the primary key for IdentityUser, then you need to use the generic version instead:
var userId = User.Identity.GetUserId<int>();

In either case, you then use that user id to query the user from the database. You can actually query your context directly, since "users" are just another DbSet on IdentityDbContext:
var user = db.Users.Find(userId);

However, you'll most often use an instance of UserManager since it essentially wraps your context and provides additional, helpful features:
var user = UserManager.FindById(userId);

This is based off the default implementation of AccountController when you've scaffolded your project with Individual Authentication. By default, the UserManager property on AccountController is an instance of UserManager<ApplicationUser>, or if you've customized the primary key, something like UserManager<ApplicationUser, int>, for example, where int would be the type of the primary key. If you're doing this in a different controller or simply not using the scaffolded version of AccountController, then you just need to similarly define an instance of UserManager.


text:
Q: Mongoose model, Can I do this? var category = mongoose.model('category', {
     text : String,
     todo : {
              text: String,
              done: Boolean
            }
});

I am making a to-do list using the MEAN stack. The user can add/delete categories (Ex. work /home ) and in each category will be a list of to-do's they can add/delete. Is this how should I model the data?
Edit: Also! hwo would i make the API call for the todo's ? would it be ... category.todos.find(err, category.todo) { ....}

A: I don't think that there is only one discrete way of creating models to achieve your requirement, If I were you I would do something like below :
var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var TodoSchema = newSchema({
     whattodo : String
     , dueDate :{type:Date, default:Date.now}
});

var CategorySchema = new Schema({
    type:String
    , name : String
    , __some__other__fields__ : __SOME_TYPE__
    , todos : [TodoSchema] //as each category can have multiple todos
});

var Category = mongoose.model('categories', CategorySchema);

module.exports = Category;

Another approach could be
Create separate todo model and store the reference to category model, which is something like storing foreign key in RDBMS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to update a form based on a checkbox status I'm currently trying to code some macros for a software (Revit), and I ran into an issue I do not know how to solve.
So I have a windows form with two checkboxes and a list of elements, and I would like that list of elements to be updated depending on what the status of the checkboxes is.
Here's my checkbox status' code:
        If StructcheckBox.Checked = True Then
            Select Case tmpView.ViewType
                Case ViewType.EngineeringPlan
                    vpList.Add(tmpVP)
            End Select
        End If

        If LegcheckBox.Checked = True Then
            Select Case tmpView.ViewType
                Case ViewType.Legend
                    vpList.Add(tmpVP)
            End Select
        End If

Now the problem with that code is that it only checks the initial status of the checkboxes, but do not update the list when the checkboxes are checked/unchecked.
How to make it so that the list VpList is updated everytime a checkbox status is changed?
Thanks!

A: The key here is to add a sub that does the checkboxes checking. You will need that sub because it will called multiple times depending on the user's actions.
Because you are not providing any insights about tmpView and vpList I will stick with your code, however you should note that depending on what exactly are you trying to do your code can be simplified or rewritten to be a bit more efficient. For example you don't specify if you want the tmpVP value to be unique in the list or to be more than one times, I assume that you want to be unique, so here is the sub's code (please read the comments in the code):
Private Sub CheckBoxesStatus(StructcheckBoxChecked As Boolean, LegcheckBoxChecked As Boolean)
    If StructcheckBoxChecked Then
        If tmpView.ViewType = ViewType.EngineeringPlan Then
            'Add code here to check if the tmpVP element is already in the vpList
            'and add it only if there isn't otherwise it will be added each time the
            'StructcheckBox is checked by the user...
            'An example code is as follows:
            If Not vpList.Contains(tmpVP) Then vpList.Add(tmpVP)
        End If
    End If

    If LegcheckBoxChecked Then
        If tmpView.ViewType = ViewType.Legend Then
            'Add code here to check if the tmpVP element is already in the vpList
            'and add it only if there isn't otherwise it will be added each time the
            'LegcheckBox is checked by the user...
            'An example code is as follows:
            If Not vpList.Contains(tmpVP) Then vpList.Add(tmpVP)
        End If
    End If
End Sub

Now that you have the sub you can call it whenever you want. "Whenever you want" means on various user's actions, like checking or un-checking a checkbox and in various other places like form's initialization (loading) these are events. According to your question you need to call it from 3 different events.
1.When the form is loading in order to get the initial status:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

2.When the user changes the StructcheckBox status:
Private Sub StructcheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles StructcheckBox.CheckedChanged
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

3.When the user changes the LegcheckBox status:
Private Sub LegcheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LegcheckBox.CheckedChanged
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

Here is the full form's code:
Public Class Form1

Private Sub CheckBoxesStatus(StructcheckBoxChecked As Boolean, LegcheckBoxChecked As Boolean)
    If StructcheckBoxChecked Then
        If tmpView.ViewType = ViewType.EngineeringPlan Then
            'Add code here to check if the tmpVP element is already in the vpList
            'and add it only if there isn't otherwise it will be added each time the
            'StructcheckBox is checked by the user...
            'An example code is as follows:
            If Not vpList.Contains(tmpVP) Then vpList.Add(tmpVP)
        End If
    End If

    If LegcheckBoxChecked Then
        If tmpView.ViewType = ViewType.Legend Then
            'Add code here to check if the tmpVP element is already in the vpList
            'and add it only if there isn't otherwise it will be added each time the
            'LegcheckBox is checked by the user...
            'An example code is as follows:
            If Not vpList.Contains(tmpVP) Then vpList.Add(tmpVP)
        End If
    End If
End Sub

Private Sub StructcheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles StructcheckBox.CheckedChanged
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

Private Sub LegcheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LegcheckBox.CheckedChanged
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    CheckBoxesStatus(StructcheckBox.Checked, LegcheckBox.Checked)
End Sub

End Class

Hope this helps.


text:
Q: Working with sed linux command In my shellscript code I saw that there is line that is handling Telephone number using sed command.
sed "s~<Telephone type[ ]*=[ ]*\"fax\"[ ]*><Number>none[ ]*</Number></Telephone>~~g" input.xml > output.xml

I am not understanding what the regular expression actually does.
<Telephone type[ ]*=[ ]*\"fax\"[ ]*><Number>none[ ]*</Number></Telephone>

I am doing revere engineering to get this working.
My xml structure like below.
<ContactMethod>
    <InternetEmailAddress>donald.francis@lexisnexis.com</InternetEmailAddress>
    <Telephone type = "work">
        <Number>215-639-9000 x3281</Number>
    </Telephone>
    <Telephone type = "home">
        <Number>484-231-1141</Number>
    </Telephone>
    <Telephone type = "fax">
        <Number>N/A</Number>
    </Telephone>
    <Telephone type = "work">
        <Number>215-639-9000 x3281</Number>
    </Telephone>
    <Telephone type = "home">
        <Number>484-231-1141</Number>
    </Telephone>
    <Telephone type = "fax">
        <Number>none</Number>
    </Telephone>
    <Telephone type1 = "fax12234">
        <Number>484-231-1141sadsadasdasdaasd</Number>
    </Telephone>
</ContactMethod>

A: That regex recognises <Telephone type = "fax"> entries where the number is given as none, and deletes them.
Breakdown:
s sed command for "substitution".
~ pattern separator. You can choose any character for this. sed recoginizes it because it comes right after the s.
<Telephone type This matches the literal text "<Telephone type".
[ ]* matches zero or more spaces.
= matches a literal "="
[ ]* matches zero or more spaces.
\"fax\" matches literal text. The quotes are escaped because the whole pattern appears inside quotes, but the shell removes the quote characters (\) before sed sees them.
[ ]* matches zero or more spaces.
><Number>none matches literal text.
[ ]* matches zero or more spaces.
</Number></Telephone> matches the literal text.
~~ the pattern separators end the search pattern, and surround an empty replace pattern.
g is a flag that means the substitution will be performed multiple times on each line.
The only thing that confuses me is that this pattern won't match anything that has line breaks in it, so I presume your input.xml isn't actually formatted like you have in your example data?


text:
Q: Why does this regex in bash not match the line despite matching in regex tester? I am trying to match a line in netstat where the local port matches some port that's passed in to my script. But this regex (while it matches in a regex tester) doesn't seem to work.
# Get lines from netstat
IFS=$'\r\n' GLOBIGNORE='*' command eval  'NetstatLines=($(netstat -anq))'

for line in "${NetstatLines[@]}"; do

    # This never matches
    if [[ "$line" =~ ^\s*(TCP|UDP)\s+(\d+\.\d+\.\d+\.\d+:$iPort|\[::\d*\]:$iPort)\s+ ]]; then
        echo "found it!!"
    fi

done

The lines look like:
Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:623            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:2179           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:5040           0.0.0.0:0              LISTENING
  TCP    0.0.0.0:7680           0.0.0.0:0              LISTENING

So if $iPort is 135, it should match the 4th line.

A: Thanks to @Shawn and these sites:

*

*https://www.regextester.com

*https://www.regular-expressions.info/posix.html
I was able to figure it out:
^[[:space:]]*(TCP|UDP)[[:space:]]+([[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+:$iPort|[[]::[[:digit:]]*[]]:$iPort)

That is equivalent to the non-posix version I started with.


text:
Q: Changes in clarity-ui.min.css not working I tried to add one more attribute to clarity modal css in clarity-ui.min.css but the changes are not reflecting.

A: Without any details about what you've done, its hard to understand what is going on. However, you should not directly edit clr-ui.min.css and instead write your own CSS that is included afterwards and overrides any values you need.


text:
Q: Anyway to get a fullscreen background clickable even with div's on top of it? I am trying a fullscreen background which must be clickable. So far i got this going.
But now i have put some div's on top of the background and the background isn't clickable just the part not covered by div's works.
Here is my stripped source

<img src....

here bunch of div's

here's my css
html, body {height:100%; margin:0; padding:0;}#page-background {position:fixed; top:0; left:0; width:100%; height:100%;}#wrapper {position:relative; z-index:1; padding:10px;}

A: Try using jQuery live() method which supports click event propagation: http://api.jquery.com/live/#typefn

A: Also, here's a nice article about event bubbling, maybe that helps as well:
http://www.quirksmode.org/js/events_order.html


text:
Q: How to inform other objects(how to "close" queue) that there will be no more elements in ArrayBlockingQueue, I have an ArrayBlockingQueue<String> queue; and an Author object puts elements in there:
public static final String END = "db8097f51282a0188e988d6bfa994430258e24ce";

[...]

for (String text : texts) {
            queue.put(text);
            Thread.sleep(300);
        }
queue.put(END);

and a Printer objects which takes elements from the qeue and prints them on the console:
 String text;
 do {
     text = queue.take();
     if (!text.equals(Author.END))
            System.out.println(text);
} while (tekst != Author.END);

I wanted inform Printer object that there will be no more elements put into the qeue. I cannot pass null into ArrayBlockingQueue so I decided to pass very unusual String inside. I think it is bad solution.
Can I somehow close the ArrayBlockingQueue?

A: your solution seems fine. Two points to consider:

*

*If you're going to have more than one Printer reading values off of the same queue you may want the printer to push the END value back into the queue so that other Printers will get a chance to see it

*Consider storing not just a plain string but instead an object of a class which you define. This class can have a string field to carry the actual payload and additional boolean field such as 'isEnd`. this will make the distinction between regular items and end-of-queue item more explicit in your code.


text:
Q: ASP.NET core 2.2: what is the safest way of sharing request-specific data between framework classes? I'm trying to figure out which is the cleanest and safest way to share some request-specific data between framework classes in an ASP.NET core 2.2 web application.
When I say framework classes I mean classes like middlewares or authorization handlers, broadly speaking the framework classes involved in the process of handling the user request.
The idea of sharing I'm looking for is having some sort of implicit request context or request data bag that is accessible from all the framework classes involved in the HTTP request handling.
In the past I did something similar in .NET core console applications by using the AsyncLocal class.
The possible alternatives I have found are the followings:

*

*using a custom service as a bag of data and register it as a scoped service on the ASP.NET core DI container

*using the HttpContext.Items property as a way to save data for a specific request context
Which is the best approach to accomplish what I'm trying to do ? Are there other ways to do so in ASP.NET core ?
As a sidenote, is it safe to use the AsyncLocal class as a way to share data between classes inside an entire ASP.NET core request handling flow ? I didn't find any microsoft guidelines about the usage of AsyncLocal with ASP.NET core
Thanks for helping

A: You practically answered yourself (which is a huge plus, because you not only asked a proper question but did research on possible solutions).
Using items of HttpContext is the simplest and the most straightforward way. But it comes with the pain of casting the object when receiving values, maybe serializing and remembering the key under which you would store it (otherwise you are gonna end up with magic strings).
On the other hand, using scoped service is more mature and dedicated way. If you know what to expect in your data bag, then you could implement a complex service for it with properties and maybe more narrowed down sections. That way, receiving data would be sheer pleasure.
I suggest you to analyse the real demand and how frequently that logic would be used. Whether it's going to be used in many places or is it just once, maybe two times scenario. Having that in mind you should be perfectly capable of making the right decision.
Sadly, I know nothing about using AsyncLocal<T> in ASP.NET Core.


text:
Q: Cannot connect Jenkins jlnp slaves to Centos 7 master installed using Docker jenkins/jenkins? Jenkins Centos 7 master was installed from Docker jenkins/jenkins.
I cannot connect my old Windows 7, macOS, and Linux slaves to the master using jlnp.
Usually the Jenkins slave agent displays:

*

*"Trying protocol: JNLP4-connect"

*"Terminated"

*Repeat

Clues:

*

*Occasionally Windows7 "Jenkins slave agent" will display "Connected".

*However, the Jenkins master displays the node as not connected.

Installed Using:
sudo systemctl start docker
sudo docker pull jenkins/jenkins
sudo docker run --name jenkins -p 8080:8080 -p 50000:50000 -u 1001 -v /home/jenkins/jenkins:/var/jenkins_home jenkins/jenkins
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --reload

Added Clues:

*

*This is my first time using a Docker install of jenkins.

*It is running a /home/jenkins/jenkins.

*I can find no useful clues in /jenkins/logs/slaves/

*I tied disabling Centos & firewall on both master and slave
I am docker newbie.
sudo docker logs -f jenkins
displayed a JNLP4 connect error saying root was not writable.
My issue sounds very similar to this:
docker-slave never connects to master if User is defined in configuration #474
I changed to run the LTS version and now I can connect a slave:
sudo docker run -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts

A: If you are still having issues I suggest as a starter to try run as privileged user. That is of course not a good secured practice, but at least it can assist you in finding the root cause. for more details see:https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities
docker run  --privileged=true  -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts

I would do a better dive also on the network you expose on the docker run, i.e. --network=host. for more options see: https://docs.docker.com/engine/reference/run/#network-settings
docker run  --network=host -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts

will allow your jenkins docker to take over the network interface of the machine. Again, not a good practice but excellent for debugging purposes.


text:
Q: jQuery Chosen move div content to another div I use the jQuery Chosen plug-in and I am trying to move the complete Div Content to another div when an user on a checkbox near it.
The problem is that, when I click on the checkbox, the divs are not rendered correctly, it looses the Chosen information and the result is just ugly.
The HTML I have:
Div A:

Div B:

        <input type="checkbox" id="chkChosen" value="1" />
        <select data-placeholder="Testing" id="selectChosen" class="chzn-select" multiple="multiple" style="width:350px;">
            <option value="A">Option A</option>
            <option value="B">Option B</option>
            <option value="C">Option C</option>
        </select>

The Javascript code:
$("#selectChosen").chosen();

$('#chkChosen').change(function () {
    if ($(this).prop('checked')) {
        $('#divB div').hide().appendTo('#divA').fadeIn('fast');
    } else {
        $('#divA div').hide().appendTo('#divB').fadeIn('fast');
    }
});

I have created a jsFiddle with both a working example (normal select) and the problem (jQuery Chosen) : http://jsfiddle.net/Moonlight/fRHhh/1/
What is wrong? I thought that "appendTo" copies everything.
EDIT: I have created a new example of what I am trying to achieve: http://jsfiddle.net/Moonlight/fRHhh/5/

A: I changed your jquery and now it works fine. Your where moving the created html by the plugin, instead of using the html to create a "chosen". After putting the html inside the correct container i call the .chosen again e voila.
 $("#selectChosen").chosen();

$('#chkChosen').live("change",function () {
    if ($(this).prop('checked')) {
        $('#divB').html("");;
        $('#divA').hide().html('\
        <input type="checkbox" checked="checked" id="chkChosen" value="1" /> \
         <select data-placeholder="Testing" id="selectChosen" class="chzn-select" multiple="multiple" style="width:350px;">\
            <option value="A">Option A</option>\
            <option value="B">Option B</option>\
            <option value="C">Option C</option>\
        </select>').fadeIn('fast');
    } else {
        $('#divA').html("");
        $('#divB').hide().html('\
        <input type="checkbox" id="chkChosen" value="1" /> \
         <select data-placeholder="Testing" id="selectChosen" class="chzn-select" multiple="multiple" style="width:350px;">\
            <option value="A">Option A</option>\
            <option value="B">Option B</option>\
            <option value="C">Option C</option>\
        </select>').fadeIn('fast');
    }

      $("#selectChosen").chosen();
});

$('#chkNormal').change(function () {
    if ($(this).prop('checked')) {
        $('#divD div').hide().appendTo('#divC').fadeIn('fast');
    } else {
        $('#divC div').hide().appendTo('#divD').fadeIn('fast');
    }
});


text:
Q: Who or what is named character Andy? I suspect \[Andy] was meant to represent a staff member, or at least a person of importance.
I tried the F1-"Wolfram Search", Wolfram|Alpha and a simple mathematica.SE & Google search.
Can somebody please tell me why \[Andy] is a named character in Mathematica?
My installation is on version 11.3

A: The original MMa fonts were designed by Andre Kuzniarek and Andrew Hunt.
From Andre:

Indeed, those are old easter eggs, and there used to be glyphs for each of us. They were "abandonded" in later releases. All were involved in dealing with font design, encoding and integration going back to the initial Unicode release (V3). Myself, Andy Hunt, Robby Villegas (rest his soul), and a cat named Spooky (mascot for Karen Fernsler).

Rest well, Robby, indeed.


text:
Q: Angular JS. My output should give Hello but it is showing {{message}} I am new and started practicing Angular JS.
My output should give Hello but it is showing {{message}}
Below is HTML code:
<!DOCTYPE html>

{{message}}

Below is Angular js code:
angular.module('HelloWorldApp', [])
  .controller("HelloWorldController", ["$scope", function ($scope){
     $scope.message = "Hello";
  }]);

A: I do not see any error with your code, Check your angular version
DEMO

angular.module('HelloWorldApp', []) .controller("HelloWorldController", ["$scope", function ($scope) { $scope.message = "Hello"; }]);
<!DOCTYPE html>

{{message}}


text:
Q: How are different HTML elements equivalent? Some HTML elements (
, ,
,
,
, ...,
 , , and so on) seem to behave the same way except for default styling. For example,  x  seems equivalent to  x . Some elements such as  have special properties but behave mostly the same way.
Can someone make this precise?
In particular, is there a subset of elements that "covers" all of HTML?

Edit: I understand that elements are meant to carry semantics. But suppose that I don't care about semantics, and I only want to deal with the smallest subset of HTML that will give me access to some given browser behavior. I'm wondering how to find that subset.

A: HTML is meant to mark up text semantically. That means giving meaning to a piece of text, like this is a headline, this is a paragraph, this is a quote, this should be emphasized. Some/most of them are displayed very similar by default, but that's not the point. The point is to be able to programmatically extract meaning and process elements according to their meaning, for example by styling them. Don't confuse semantics with style.
If you want to leave that aside, you pretty much only need block level elements like a div and inline elements like span, plus anything that has a specific function like links, objects etc.

A: This depends on what you mean by browser behavior. All browsers will treat e.g. a elements with href attributes in a special way, as links, and this cannot be expressed in CSS. Similarly, form input fields are special, and so is img, even though you can simulate much of its behavior by using a background image in CSS. But what about abbr for example? Although most browsers just apply some default styling to it, some special browsers or assistive tools used with them give the user optional access to the value of the title attribute. Similarly, while most browsers treat h1 and other heading elements just by applying some default styling to them, some browsers have e.g. a mode where the browser only reads the headings to the user.
Similarly, you can create tables using CSS (display: table etc.) without using any table markup in HTML—though older browsers won't get this right—but then your "tables" will not have accessibility features that HTML tables can have.
Search engines are not browsers, but they may be very important, and they are known to pay attention to HTML markup, though the details have not been disclosed. However, if you start e.g. using styled div elements intead of heading elements, you will probably lose something in search engine friendlyness.

A: Some reasons why an element cannot fully be replicated by  ignoring mere semantics and just considering browser or other HTML consumer behaviour:

*

*The element is the root element.

*The element is a metadata element

*The element is a scripting element

*The element is an embedded content element

*The element is a forms element

*The element is an interactive element

*The element is a links element

*The element is used by the document outline algorithm; including:

*

*Sectioning content elements

*Sectioning root elements

*Heading content elements

*The element goes in a place in the DOM where a span is precluded from going by the parser

*The element forms part of a specific rendering binding

*The element has a default WAI-ARIA role other than 'no role'

*The element's DOM interface extends beyond that of HTMLElement

*The element is the span element itself.

By my reckoning that leaves abbr, address, b, bdi, bdo, br, cite, code, dd, dfn, div, dl, dt, em, footer, header, kbd, mark, p, pre, rp, rt, ruby, s, samp, strong, sub, sup, u, var and wbr as the maximum list of elements replaceable by span if one ignores semantics. That's 31 out of 107 different elements in HTML5. Of the other 76, each has a specific job in browsers.
I note that of the above list, there are a number where I don't know what the equivalent styling would be, and that in all cases it's less typing to use the correct semantic element than to replace it with a span+class.

A: Some elements have a very specific purpose, for example html, head, body, script, meta, embed, object, hr, table, tr, td, form, input. They do things that isn't possible to do by just specifying a style.
The rest of the elements, for example span, div, b, i, u, h1, p, only differ in their default style. You can use a span tag and apply display:block to it, and it works as a div tag.
Note though that there are block elements like div, and there are inline elements like span. You can't put a block element inside an inline element (until all browsers support HTML 5).
So, you strictly don't need all different elements. Some elements are even deprecated in HTML 4, for example b and i, as they are not needed and doesn't follow modern markup usage, so they should be replaced by styling.
You should however consider the semantics that the different elements add. The h1 element for example is important for search engines when they try to find out what the page is about. If you don't use the h1 element for your headline, search engines will rate your page lower.

A: The main difference between them is semantic. To illustrate, in HTML5 for example, you have div, section, header, footer etc., which are all block elements. In HTML4 you're required to use div for all of those. Which is easier to read, to look at, to style - a page full of div's or something divided into headers, and sections, and footers?
As you state, some elements have attributes that are specific to that element type/or certain types (e.g., a). So there's another difference.
Finally, in your list, you also have some block level (e.g., div, p) and some inline level (e.g., span, b) elements - those have very different default behaviors. See: http://www.webdesignfromscratch.com/html-css/css-block-and-inline/


text:
Q: Red5 Flex Application: Shared Object sends "change" or "delete" event only when server is started and client connects for the first time I have a shared object created in WebScope. when I start the server and clients connect for the first time, it sends change and delete events just fine. but after that it only sends clear event. any ideas?

A: It seems that you use SyncEvent.changeList property, but what for?
I suggest you to iterate over data via SharedObject.data or SyncEvent.data properties.
 var busySO:SharedObject = ...;
 for each (var obj:Object in busySO.data) {
        ...
 }


text:
Q: Dialog (popup) bootstrap rendered by MVC I use Bootstap table to present collection. In my table last column is button for details. After click on it, I want to display dialog, which will be filled by model from MVC action.
So, how can I do this:

*

*Click on button in row (there is <a href='MVC_action\ROW_ID'>

*MVC_action will be executed and return model

*Model is pass to view and dialog is visible with filled data.

A: *

*Do not use <a href> for the button. That will make a refresh on the page. Instead, create a button and add a javascript event handler, like <button onclick="detail(ROW_ID)">

*The detail() function will call MVC_action\ROW_ID. The result from this call must be injected in a hidden div which handles the bootstrap dialog.

*MVC_action returns a partial view with the content of the dialog.

*After the injection, you must open the dialog.

Here you can see an example of an ajax call and a Bootstrap modal.
Greetings


text:
Q: Selenium WebDriver: clicking on elements within an SVG using XPath I have an SVG object with a few circle and rectangle elements. Using webdriver, I can click on the main svg object, but not any of the elements within it. The problem only seems to be with clicking (or any mouse interaction), as I can use getAttribute() to return the value(s) of width, ID, x/y, text, etc, for anything under it.
Here is an example of the HTML:
    <div id="canvas">
        <svg height="840" version="1.1" width="757" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;">
            <image x="0" y="0" width="757" height="840" preserveAspectRatio="none">
            <circle cx="272.34" cy="132.14">
            <rect x="241.47" y="139.23">
            <text style="text-anchor: middle; x="272.47" y="144.11">
        </svg>
    </div>

And an example of WebDriver trying to right click a rectangle element (and failing):
    WebElement mapObject = driver.findElement(By.xpath("//*[name()='svg']/*[name()='rect']"));
    Actions builder = new Actions(driver);
    builder.contextClick(mapObject).perform();

But this works and returns a value:
    driver.findElement(By.xpath("//*[name()='svg']/*[name()='rect']")).getAttribute("x");

When WebDriver errors, it's usually this:
    org.openqa.selenium.WebDriverException: '[JavaScript Error: "a.scrollIntoView is not a function" {file: "file:///var/folders/sm/jngvd6s97ldb916b7h25d57r0000gn/T/anonymous490577185394048506webdriver-profile/extensions/fxdriver@googlecode.com/components/synthetic_mouse.js" line: 8544}]' when calling method: [wdIMouse::move]

I've spent some time researching this and it seems to be a somewhat common issue with Selenium and SVGs, however I'm wondering if there is a workaround. The only solutions I've found are interacting with the SVG itself, which I can already do.
I'm using Selenium 2.28 (and tried 2.29) w/ Java + Firefox 17.
Any ideas greatly appreciated.

A: We were able to avoid the odd xpath select by doing these two things
WebElement mapObject = (WebElement) driver.executeScript('return document.querySelector(arguments[0])', "svg rect")

((JavascriptExecutor) driver).executeScript("arguments[0].dispatchEvent(new MouseEvent('click', {view: window, bubbles:true, cancelable: true}))", mapObject);

This worked on osx and phantomjs but I think it should be ok in any modern browser.
(We used the js driver so feel free to fix any compile errors)

A: For anyone interested, I solved this in the following ways:
1) I was originally testing this on OSX with Firefox 17 and Selenium 2.28/29, but figured out it only works (at least for me) on Windows with Firefox 18 and Selenium 2.29
2) interacting with SVGs with the standard:
driver.findElement(By.xpath(YOUR XPATH)).click();

doesn't work. You need to use Actions.
3) to interact with SVG objects, the following XPath works:
"/*[name()='svg']/*[name()='SVG OBJECT']";

The SVG object being anything under the SVG element (e.g. circle, rect, text, etc).
An example of clicking an SVG object:
WebElement svgObject = driver.findElement(By.xpath(YOUR XPATH));
Actions builder = new Actions(driver);
builder.click(svgObject).build().perform();

Note: you need to call the path inside the click() function; using:
moveToElement(YOUR XPATH).click().build().perform();

doesn't work.

A: Here you go:
driver.findElement(By.cssSelector("#canvas > svg > rect")).getAttribute("x")
driver.findElement(By.cssSelector("#canvas > svg > rect")).getAttribute("y")

This way you can do it.

A: Try this workaround :
WebElement mapObject = driver.findElement(By.xpath("//*[name()='svg']/*[name()='rect']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", mapObject);

Whenever I have too many problems with some elements while trying to click them, I use this workaround.

A: For a JS solution:
var selector = "//*[name()='svg']/*[name()='rect']";
browser.moveToObject(selector, 5, 5);//Move to selector object with offsets.
browser.buttonPress(null);//Left-click

A: I have different high charts in my project and my aim was to double click on a section of a chart to drill down for further information and I've managed to do it using following lines of code.
XPath didn't work for me but CssSelector worked just fine.
var elementToClick= Browser.Driver.FindElementEx(By.CssSelector("#highcharts-0 > svg > g.highcharts-series-group > g.highcharts-series.highcharts-tracker > path:nth-child(1)"), 10);
Actions action = new Actions(Browser.Driver);
action.Click(elementToClick).Build().Perform();
action.DoubleClick(elementToClick).Build().Perform();

A: Here is an example of a workaround in C#:
IWebElement svgElement = Driver.FindElement(By.CssSelector("svg"));

IList<IWebElement> rectElements = svgElement.FindElements(By.CssSelector("rect"));

A: actual = driver.findElement(By.xpath(
"//div[contains(@class,'review-action')]//div[contains(@class,'rating')]/*[name()='svg'][1]/*[name()='g']/*[name()='path'][2]"))
.getAttribute("stroke");


text:
Q: Displaying subsets of objects in R summary I would like to know if I could have only specific components of the R Summary output to be displayed. From the output below, I would like only the F-statistic (or only the following line-F-statistic: 0.834 on 2 and 10 DF,  p-value: 0.4624) to be displayed. I am actually dealing with an imputed data and trying to extract this value from a series of summary outputs.
Thank you!
 > hanes=with(nhanes, lm(bmi~hyp+chl))
 > summary(hanes)
 Call:
 lm(formula = bmi ~ hyp + chl)

 Residuals:
 Min     1Q Median     3Q    Max
-6.425 -3.296  0.035  3.123  7.632

 Coefficients:
 Estimate Std. Error t value Pr(>|t|)
 (Intercept) 20.10564    5.70716   3.523  0.00551 **
 hyp         -0.68459    3.39596  -0.202  0.84428
 chl          0.03783    0.03054   1.239  0.24370
 ---
 Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 Residual standard error: 4.66 on 10 degrees of freedom
 (12 observations deleted due to missingness)
 Multiple R-squared:  0.143,    Adjusted R-squared:  -0.02846
 F-statistic: 0.834 on 2 and 10 DF,  p-value: 0.4624

UPDATE WITH REPRODUCIBLE EXAMPLE WITH NHANES2 DATA IN R:
  > imp10=mice(nhanes2, m=10, seed=11111)

  > hanes=with(imp10, lm(bmi~hyp+chl))

  > summary(hanes)

above yields summary for each of the 10 imputations:
  ## summary of imputation 1 :

  Call:
  lm(formula = bmi ~ hyp + chl)

  Residuals:
  Min      1Q  Median      3Q     Max
  -7.4597 -3.1938  0.1403  2.8153  7.0753

  Coefficients:
            Estimate Std. Error t value Pr(>|t|)
  Intercept) 19.30988    4.47439   4.316 0.000279 ***
  hyp2        -0.38202    2.41568  -0.158 0.875789
  chl          0.04265    0.02398   1.779 0.089101 .
  ---
  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

  Residual standard error: 4.332 on 22 degrees of freedom
  Multiple R-squared:  0.1425,  Adjusted R-squared:  0.06456
  F-statistic: 1.828 on 2 and 22 DF,  p-value: 0.1843

The fs=summary(hanes)$fstatistic code still produces complete summary. Thank you again!

A: As following to my comment:
to retrive the F-statistic you may use:
fs <- summary(mode)$fstatistic

and the P values associate with it:
pva <- anova(mode)$"Pr(>F)"[1]

and then combine together with a sprintf etc.
Or just use capture.output that save all the outputs in a character vector where each element corresponds to a line; you have just to take the line of interest, in this case the 18:
capture.output(summary(mode))[18]
[1] "F-statistic: 30.19 on 1 and 30 DF,  p-value: 5.766e-06"

I have used a fitted model with the mtcars dataset in R.


text:
Q: Got "UnsupportedOperationException" when try to retransformClasses JDK1.6, modify class loaded in jvm dynamically. When I comment the code:classReader.accept(classAdapter, ClassReader.SKIP_DEBUG);, the exception "UnsupportedOperationException" disapear.
Actually, for testing my code, I didnt modify any field or method. But the program catch exception "UnsupportedOperationException", after calling retransformClasses(). Anyone has similar exception? Can any give me some advices? thx
Codes are as follow:
public byte[] modifySleepMethod() throws Exception {
     System.out.println("Call modifySleepMethod");
     ClassReader classReader = new ClassReader(classfileBuffer);
     System.out.println("new classreader");
     ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
     System.out.println("new classwriter");
     ClassAdapter classAdapter = new ModifyMethodClassAdapter(classWriter);

     classReader.accept(classAdapter, ClassReader.SKIP_DEBUG);

     byte[] classFile = null;
     classFile = classWriter.toByteArray();

     FileOutputStream fos;
     try {
        fos = new FileOutputStream("D:\\testfos\\b\\Example2.class");
        System.out.println("ddddddmodifymethodtest");
        fos.write(classFile);
        fos.close();
     } catch (FileNotFoundException e) {
        e.printStackTrace();
     }catch (IOException e) {
        e.printStackTrace();
     }
     return classFile;
     }
}

|
protected void transform(Class<?> clazz, ClassLoader classLoader) {
    DemoTransformer dt = new DemoTransformer(clazz.getName(), classLoader);
    instrumentation.addTransformer(dt, true);
    try {

        instrumentation.retransformClasses(clazz);

    } catch (Exception ex) {
        throw new RuntimeException("Failed to transform [" + clazz.getName() + "]", ex);
    }


text:
Q: jQuery toggle slides DIV up and down, but UL content animates left to right. How can I make the content slide up and down? I have a jQuery toggle that slides a DIV up/down, but its content animates left to right. How can I prevent the content from animating left to right?
JS Fiddle: http://jsfiddle.net/CqREn/6/
CSS:
#myMenu ul{
    display: none;
}
#myMenu ul li{
    display: inline-block;
    width: 49%;
}
#myMenu{
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    background-color: rgb(100,100,100);
}

JS:
$("#MenuToggle").click(function(event){
    event.preventDefault();
    $('#myMenu ul').toggle('slow');
});

HTML:

    Page Navigation

1

2

3

4

5

6

A: toggle() simply toggles the showing/hiding, but doesn't specify how to show/hide. Try:
$('#myMenu ul').slideToggle('slow');

jsfiddle


text:
Q: How to extend doc() functionality in saxon I am looking for an extension of doc() functionality currently available in SAXON in a way that it will read XML not from filesystem or from http network, but from memory, where I have those xmls.
The way I want to use it is like:
mydoc('id')/root/subroot/@myattr

or
doc('mydoc://id')/root/subroot/@myattr

What I have considered so far:

*

*use queryEvaluator.setContextItem() - does not solve my use case as I can have multiple XML sources in one query

*register some own URL scheme protocol into Java - seems to me like overkill and I have never done this

*write own ExtensionFunction - seems to be the right way so far, but i am confused whether I should use ExtensionFunction or rather ExtensionFunctionDefinition. Also I am littel bit confused by Doc_1 and Doc Saxonica source  code as it uses Atomizer and other unknown internall stuff.

So the questions are:

*

*Is it variant 3 the best one (in the means of simplicity) or would you recommend some other approach ?

*Is it OK to use ExtensionFunction and return XdmNode from my in-memory xmls ? It seems to me it should work, but I really do not want to step into some edge cases or saxon minefield.

Any comment from experienced Saxon user will be appretiated.

A: The standard way of doing this is to write a URIResolver and register it with the transformer. The URIResolver is called, supplying the requested URI, and it is expected to return a Source (which can be a StreamSource, SAXSource, or DOMSource, for example). In this scenario you would typically return a StreamSource wrapping a StringReader which wraps the String containing the XML.
You could equally well use an extension function, but it's probably a little bit more complicated.


text:
Q: NOT NULL constraint failed: shipping_ship.user_id Django So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below.
models.py
from django.db import models
from django.contrib import get_user_model
User = get_user_model()
class Container(models.Model):
    container_type = models.Charfield(max_length = 30, blank=False, null = False)
    max_users = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True)
    users = models.ManyToManyField(User)

class Ship(models.Model):
    container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE)
    location = (
    ('France', 'France'),
    )
    from_location = models.CharField(max_length=30, choices=location, blank=False, null=False)

    to_location = (
    ('Lagos', 'Lagos'),
    ('Abuja', 'Abuja'),
    ('Abeokuta', 'Abeokuta'),
    ('Osun', 'Osun'),
    )
    to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False)
    date_leaving = models.DateField(auto_now=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True)

    def __str__(self):
      return self.user

then my serializer.py file
from rest_framework import serializers
from .models import Container, Ship

class ContainerSerializer(serializers.ModelSerializer):

   class Meta:
      model = Container
      fields = '__all__'

class MiniContainerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Container
        fields =['container_type', 'price']

class ShipSerializer(serializers.ModelSerializer):
    class Meta:
       model = Ship
       fields = '__all__'
       read_only_fields = ('user', 'price')

class MiniShipSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ship
        fields = ['container', 'from_location', 'to_location']

and now my views.py file which I have issues with
from django.shortcuts import render
from django.shortcuts import get_object_or_404

from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView

from .serializers import ContainerSerializer, MiniContainerSerializer, ShipSerializer, MiniShipSerializer

from rest_framework import permissions, status

from rest_framework.response import Response

from .models import Container, Ship

class ShipAPI(ListCreateAPIView):
    serializer_class = ShipSerializer

    def get_queryset(self):
       user = self.request.user
       queryset = Ship.objects.filter(user=user)
       return queryset

    def Book_shipping(self, request, *args, **kwargs):
       user = request.user
       container = get_object_or_404(Container, pk=request.data['container'])
       if container.users.count() >= container.max_users:
           return Response('container already full')# here i'm trying to set limits so the users joining each container won't surpass the max users.
       cont = container(users=user)
       cont.save()
       from_location = (request.data['from_location'])
       to_location = (request.data['to_location'])
       date_leaving = int(request.data['date_leaving'])
       price = container.price / container.max_users
       cart = Ship(container=container, user=user, from_location=from_location, to_location=to_location, date_leaving=date_leaving, price=price)
       cart.save()
       serializer = ShipSerializer(cart)
       data ={'message': 'shipping successfully created',
             'data':serializer.data}
       return Response(data=data, status=status.HTTP_201_CREATED)

and then after testing the endpoint it returns this error:
IntegrityError at /Shipping/Ship/
NOT NULL constraint failed: shipping_ship.user_id
I've tried debugging and looking at it over and over again can someone please help me? Thanks in advance. And yes I've tried deleting migrations and the database.

A: As your Container model have a ManyToMany relationship with the User model.
So it may not work like cont = container(users=user)

For me it worked like this:
cont = container.users.add(user)
cont.save()


text:
Q: Why does overflow-x: hidden make my absolutely positioned element become fixed? I'm trying to figure out, why setting overflow-x: hidden to body of an HTML page makes my element position: fixed even if I set it to position: absolute.
The effect is better understood in this demo.
Here is the code:

html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  overflow-x: hidden;/* If I remove this line everything is how I expect it to be! */
}

div.page {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 100%;
  border: 1px solid red;
  margin-bottom: 200px;
}

div.background {
  background: blue;
  position: absolute;
  width: 100%;
  height: 10%;
}

Question
What's the relationship between overflow-x: hidden and positioning? Why does setting that property cause my element to become position: fixed instead of position: absolute?

A: You need to add position: relative to body. Your div.background has position: absolute on it, which is causing it to stick to the top of the HTML document. If you don't want that, you need to give its parent (in this case, the body tag) position: relative.
DEMO #1: http://tinkerbin.com/nmI74RpC
Alternatively, you can remove position: absolute from div.background, but I'm not sure how that would affect the rest of your layout.
DEMO #2: http://tinkerbin.com/PP5PpbuC

A: The element is still position: absolute, but it appears fixed thanks to some rather complicated interactions between position, overflow and the box model. Incredibly, none of these behaviors is unspecified or a bug in any browser — it's actually completely by design, if a little counter-intuitive.
It basically boils down to the following:

*

*An absolutely positioned element is anchored to the initial containing block unless any of its ancestors is positioned. (This is why adding position: relative to body works as suggested in another answer.)

*You have width: 100%; height: 100%; on both html and body; this prevents the initial containing block from ever expanding beyond the viewport (the visible area), so the initial containing block never scrolls.

*Since the initial containing block doesn't scroll, neither does the absolutely positioned element. This causes it to appear fixed even though the rest of the page does scroll.
Oddly enough, this works on IE6 too.

Longer explanation:

*

*An absolutely positioned element is anchored to the initial containing block unless any of its ancestors is positioned.
The spec on the overflow property, which incidentally contains another example of the same issue you're observing where an element with overflow: scroll is interacting with an absolutely positioned descendant element, states the following:

This property specifies whether content of a block container element is clipped when it overflows the element's box. It affects the clipping of all of the element's content except any descendant elements (and their respective content and descendants) whose containing block is the viewport or an ancestor of the element.

Your absolutely positioned element is a descendant whose containing block is the initial containing block (also the containing block of the html element), because both html and body are not positioned. This is according to another section of the spec. This prevents overflow clipping on html and body from having any effect on your absolutely positioned element since it's anchored to the initial containing block.

*You have width: 100%; height: 100%; on both html and body; this prevents the initial containing block from ever expanding beyond the viewport (the visible area), so the initial containing block never scrolls.
The spec then states the following, further down the same section:

UAs must apply the 'overflow' property set on the root element to the viewport. When the root element is an HTML "HTML" element or an XHTML "html" element, and that element has an HTML "BODY" element or an XHTML "body" element as a child, user agents must instead apply the 'overflow' property from the first such child element to the viewport, if the value on the root element is 'visible'. The 'visible' value when used for the viewport must be interpreted as 'auto'. The element from which the value is propagated must have a used value for 'overflow' of 'visible'.

To put it more simply:

*

*If html is not overflow: visible, apply that to the viewport instead, and turn html to overflow: visible. The overflow value given to body is not affected.

*If html is overflow: visible, but body is not, apply that to the viewport instead, and turn body to overflow: visible.
(Setting overflow-x or overflow-y to anything other than visible for an element causes the shorthand overflow to no longer be equal to visible for that element.)
Normally, this means the viewport should scroll naturally along with html and body, since only one scrollbar should exist at a time.
However... you also give both html and body a width and height of 100%! That means 100% those of its container. The container of body is html, and the container of html is the initial containing block. But since you can't actually use CSS to control the size of the viewport — that's entirely handled by the browser — you're left with the two elements being constrained to 100% the height of the viewport (also known as the fold). The viewport itself does not have to expand beyond the fold since none of its contents require more space than is visible (note that absolutely positioned elements are never taken into account). The viewport therefore does not generate a scrollbar (and neither does html); the scrollbar that you see belongs to body.
If you had not set the width or height properties, then they would have defaulted to auto, causing both html and body to expand with their contents and always be the same size as the entire area covered by the initial containing block, including the area below the fold. This prevents body from ever generating a scrollbar because it will always stretch to fit its contents, so you only see the viewport scrollbar, and the absolutely positioned element will scroll with the rest of the page.

*Since the initial containing block doesn't scroll, neither does the absolutely positioned element. This causes it to appear fixed even though the rest of the page does scroll.
What happens when you scroll, then, is that you're really scrolling the body element. Since the absolutely positioned element is anchored to the initial containing block, which never scrolls, it appears to be fixed instead of scrolling.
By the way, this is also why the element appears to overlap the scrollbar when it doesn't scroll at all. The scrollbar belongs to body, which is beneath the absolutely positioned element. If you remove the overflow-x declaration or the width and height declarations from html and body, the scrollbar that you see belongs to the viewport instead. However, if you position body, the scrollbar still belongs to body, but the element also becomes a child of body so it won't overlap the scrollbar.


text:
Q: Capistrano Staging Deploy Requires Whole New Database Migration I have Capistrano set up such that it allows me to deploy the staging version of my Ruby on Rails website to an amazon server from a git repository successfully. However, after deploying, I must run a migration on the database on the server. If I do not, any page with login forms or database-based content cannot load. When I run the migration on the server, I see every singly migration on the site being migrated, not just the most recent ones.
I know that Capistrano can maintain the previous migrations, and I thought it did that automatically. My question is, how do stop the apparent database wipe or loss which is occurring so that a migration is only needed if there are actually new migrations?
I see no unusual errors in the Capistrano output and I am a novice when it comes to Capistrano and databases. I noticed that my database.yml file has no entry for staging and I was wondering if it could be as simple as adding an entry for staging with the database set to db/development.sqlite3?
here is my deploy.rb file:
set :application, "staging"
set :scm, :git
set :repository, "."
set :deploy_via, :copy
#set :copy_cache, true
set :copy_exclude, [".git"]
set :user, "username"
set :use_sudo, false

default_run_options[:pty] = true

server "server_url", :app, :web, :db, :primary => true
set :deploy_to, "/var/www/staging"

# if you want to clean up old releases on each deploy uncomment this:
set :keep_releases, 3
after "deploy:restart", "deploy:cleanup"

# If you are using Passenger mod_rails uncomment this:
namespace :deploy do
  task :start do ; end
  task :stop do ; end
  task :restart, :roles => :app, :except => { :no_release => true } do
     run "touch #{File.join(current_path,'tmp','restart.txt')}"
  end
end

And my database.yml file:
# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

A: Capistrano is not the one that maintains your migration number. rails does. If you want capistrano to run the migrations for you as part of deploy, add this to your config/deploy.rb
after "deploy:update_code", "deploy:migrate"

you should probably have a different location for production sqlite3 file where it will not get rewritten for every deploy, instead of db/production.sqlite3. Something like /home/user/production.sqlite3


text:
Q: How to retrive data from restAPI in component in angular 4? I want to access restAPI parameters in my Component in angular 4. but I don't know how to do it.
At my Component code for rest API is as follows, here I get complete data in result
this.apiSerivce
    .userlist({'offset':'0','limit':'10'})
    .subscribe( resultObj => this.userlist = resultObj)

and at my service code for user list is
userlist(data): Observable<userlist> {
    const headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
    });
    const options = new RequestOptions({ headers: headers });
    return this.http
               .post(this._url+'/Admin/User/UserList',data,options)
               .map((response: Response) => {

                   return <userlist>response.json();
                })
                .catch(this.handleError);
}

so I get result in my component.ts file on console.log
{
    "status": false,
    "message" : "User List"
    "response": [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    "total_rows" :8
}

I want to access status and message on my component. So how I am able to do this like in angular.js I am simply use
$scope.status = response.data.status

but I don't know how to do it in angular 4

A: You can access the data in JSON easily. The code is based on the JSON display in your question:
this.apiSerivce.userlist({'offset':'0','limit':'10'})
    .subscribe( resultObj => {
    console.log(resultObj)
    this.userlist = resultObj.response
    //or
    //this.userlist = resultObj['response']
    this.status = resultObj.status
})

You can also define an interface for your turn type which will make the IDE recognise the property like this.


text:
Q: Change background of group label in plotly R hoverlabel Is there a way to change the background color of the group label in plotly R? I can see that the main label can be styled but cannot find any solutions for the group label, preferably background color and font color if possible.

A: I don't know of a native Plotly method, but I can give you a workaround.
Right now, the default is to have a white background at 80% opacity.
You didn't make your question reproducible (which will typically get you great answers much faster), so I created some.
library(plotly)
library(tidyverse)

df <- data.frame(
  x = LETTERS[1:3],
  y = c(1:3)
)

I created this little chunk to replace the background color with a color of your choice...where I've currently set colr to #444.
# current background of the trace label is white at .8 opacity
colr = "#444"  # this is the current text color in the tooltip data

plot_ly(df, x = ~x, y = ~y, name = "trace", type = 'bar',
        showlegend = T, color = ~x) %>%
  htmlwidgets::onRender(
    paste0(
      "function(el, x) {
      colr = '", colr, "';
      el.on('plotly_hover', function(d){
      hd = document.querySelector('g.hoverlayer');
      hd.innerHTML = hd.innerHTML.replace('rgb(255, 255, 255)', colr);
    });
    }"
  ))

If you changed it to:  colr = 'black'

Although, it's probably more proper to change the color this way (this does the same exact thing). One of the two may be faster if you have a lot of data, though.
plot_ly(df, x = ~x, y = ~y, name = "trace",
        showlegend = T, color = ~x, type = "bar") %>%
  htmlwidgets::onRender(
    paste0(
      "function(el, x) {
      el.on('plotly_hover', function(d){
        hd = document.querySelector('g.hoverlayer');
        if(hd.innerHTML !== '') { /* if there's a tooltip then... */
          rct = document.querySelector('g.hoverlayer rect');
          rct.style.fill = '", colr, "';
        }
      });
      }"
    ))


text:
Q: Phasors with tikz This afternoon I was looking for a way to draw phasors with tikz (you know the thing which is represented in the complex plane as r*exp(i \theta) or simply x + iy)
For me, the first representation would be much easier to deal with.
Should I use the polar system simply ? But then it comes tricky to make vector summations...

A: It is taken from Phasor Diagram:

%& -shell-escape
% Phasor diagram
% Author: Urs Zellweger (urs@zellweger.li)
% GNUPLOT required
\documentclass[11pt]{article}
%%%<
\usepackage{verbatim}
\usepackage[active,tightpage]{preview}
\setlength\PreviewBorder{5pt}%
%%%>

\begin{comment}
:Title: Phasor diagram

\end{comment}
\usepackage{ifthen}
\usepackage{tikz}
\usepackage{pgf}
\usepackage{pgffor}
\usepgfmodule{shapes}
\usepgfmodule{plot}
\usetikzlibrary{decorations}
\usetikzlibrary{arrows}
\usetikzlibrary{snakes}

\newcommand{\Gitter}[4]{
    \draw[very thin,color=gray] (#1,#3) grid (#2,#4);
}
\newcommand{\Koordinatenkreuz}[6]{
    \draw[->, >=latex, color=green!50!black] (#1,0) -- (#2,0) node[right] {#5};
    \draw[->, >=latex, color=green!50!black] (0,#3) -- (0,#4) node[left] {#6};
}
\newcommand{\KoordinatenkreuzOhneLabelsVerschobenKeinPfeil}[5]{
    \draw[-] (#1,0) -- (#2,0);
    \draw[-] (#5,#3) -- (#5,#4);

}
\newcommand{\ZeigerdiagrammText}[4]{
\begin{tikzpicture}[scale=.72, samples=100, >=latex]

    \def\Alpha{#1}
    \def\Phase{#2}
    \def\AmplitudeSpannung{#3}
    \def\AmplitudeStrom{#4}
    \def\SpannungsWert{{\AmplitudeSpannung*sin(\Alpha)}}
    \def\StromWert{{\AmplitudeStrom*sin(\Alpha+\Phase)}}
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \def\FarbeSpannung{blue!90!white}
    \def\FarbeStrom{red!90!white}
    \def\FarbeWinkelZeichnung{green}
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \def\Beta{\Alpha+\Phase}
    \def\AlphaRad{\Alpha*3.141592654/180}
    \def\PhaseRad{\Phase*3.141592654/180}
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \Gitter{-.1}{7.1}{-3.1}{3.1}
    \Koordinatenkreuz{-.2}{7.3}{-3.2}{3.3}{$\omega t$}{}
    \draw (1.570795,0) node[below]{$\frac{\pi}{2}$};
    \draw (3.14159,0) node[below]{${\pi}$};
    \draw (4.71238898,0) node[below]{$\frac{3\pi}{2}$};
    \draw (6.283185307,0) node[below]{${2\pi}$};
    \draw (-4,0) circle (3cm);
    \KoordinatenkreuzOhneLabelsVerschobenKeinPfeil{-7.2}{-.8}{-3.6}{3.6}{-4}
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % voltage
    \draw[color=\FarbeSpannung, very thick] plot[id=voltage, domain=0:7] function{\AmplitudeSpannung*sin(x)} node[right] {$U(t)$};
    % voltage circle
    \draw[color=\FarbeSpannung, loosely dashed] (-4,0) circle (\AmplitudeSpannung cm);
    % angle
    \draw[color=\FarbeWinkelZeichnung!50!black, thick] (\AlphaRad, \SpannungsWert)--(\AlphaRad,\StromWert) node[below=18pt] {$\alpha$};
    % angle in the circle
    \filldraw[fill=\FarbeWinkelZeichnung!20,draw=\FarbeWinkelZeichnung!50!black] (-4,0) -- (-3,0) arc (0:\Alpha:1) -- cycle node[right] {$\alpha$};
    % voltage pointer
    \draw[<-,color=\FarbeSpannung, very thick] (\Alpha:\AmplitudeSpannung)++(-4,0) --(-4,0);
    \draw[color=\FarbeSpannung,  dashed] (\Alpha:\AmplitudeSpannung)++(-4,0) -- (\AlphaRad,\SpannungsWert);
    % current
    \draw[color=\FarbeStrom, very thick] plot[id=current, domain=0:7] function{\AmplitudeStrom*sin(x+\PhaseRad)} node[right] {$I(t)$};
    % current circle
    \draw[color=\FarbeStrom, loosely dashed]    (-4,0) circle (\AmplitudeStrom cm);
    % current pointer
    \draw[<-,color=\FarbeStrom, very thick] (\Beta:\AmplitudeStrom)++(-4,0) --(-4,0);
    \draw[color=\FarbeStrom,  dashed](\Beta:\AmplitudeStrom)++(-4,0) -- (\AlphaRad,\StromWert);
    % phase difference
    \ifthenelse{\Phase<0}{
        \draw[snake=brace] (pi/2 ,3.3)--(pi/2-\PhaseRad ,3.3) node[above=7pt, left=10pt] {$\phi$};
    }
    {
        \draw[snake=brace] (pi/2-\PhaseRad ,3.3)--(pi/2 ,3.3) node[above=7pt, left=10pt] {$\phi$};
    }
    % angular velocity \omega
    \draw[->, xshift=-4cm]  (120:2.4cm) arc (120:170:2) node[below] {$\omega$};
\end{tikzpicture}
}
% % % % % % % % % % % % % % % % % % % % % % % % % % %

\begin{document}

\begin{preview}
% usage: {alpha}{phasedifferenceUI}{voltage}{current}{Ualpha}{Ialpha}
% resistor
\ZeigerdiagrammText{60}{0}{2.7}{1.8}

\end{preview}

\end{document}

A: Here are 3 variants: for complex numbers a+bi, re^phi*i(where phi is an angle in rad) and re^phi*i (where phi in an angle in deg). For the first you specify the origin, a, b and the draw style, for the others the origin, r, phi and the draw style:
\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{tikz}
\usetikzlibrary{arrows}

\newdimen\xorig
\newdimen\yorig

\newcommand{\sumphasor}[4]% origin, a, b, style; (for z=a+bi)
{   \path (#1);
  \pgfgetlastxy{\xorig}{\yorig}
  \pgfmathsetmacro{\xfirst}{\xorig/28.453}
  \pgfmathsetmacro{\yfirst}{\yorig/28.453}
  \pgfmathsetmacro{\xsecond}{\xorig/28.453+#2}
  \pgfmathsetmacro{\ysecond}{\yorig/28.453+#3}
  \draw[#4] (\xfirst,\yfirst) -- (\xsecond,\ysecond);
}

\newcommand{\expphasorpi}[4]% origin, r, phi(pi), style
{   \path (#1);
  \pgfgetlastxy{\xorig}{\yorig}
  \pgfmathsetmacro{\xfirst}{\xorig/28.453}
  \pgfmathsetmacro{\yfirst}{\yorig/28.453}
  \pgfmathsetmacro{\xsecond}{\xorig/28.453+#2*cos(#3/pi*180)}
  \pgfmathsetmacro{\ysecond}{\yorig/28.453+#2*sin(#3/pi*180)}
  \draw[#4] (\xfirst,\yfirst) -- (\xsecond,\ysecond);
}

\newcommand{\expphasordeg}[4]% origin, r, phi(pi), style
{   \path (#1);
  \pgfgetlastxy{\xorig}{\yorig}
  \pgfmathsetmacro{\xfirst}{\xorig/28.453}
  \pgfmathsetmacro{\yfirst}{\yorig/28.453}
  \pgfmathsetmacro{\xsecond}{\xorig/28.453+#2*cos(#3)}
  \pgfmathsetmacro{\ysecond}{\yorig/28.453+#2*sin(#3)}
  \draw[#4] (\xfirst,\yfirst) -- (\xsecond,\ysecond);
}

\begin{document}

\begin{tikzpicture}
    \draw[->] (-4,0) -- (4,0);
    \draw[->] (0,-4) -- (0,4);
    \foreach \x in {-4,...,4}
    {   \draw (-0.1,\x) -- (0.1,\x);
        \draw (\x,-0.1) -- (\x,0.1);
    }
    \sumphasor{0,0}{3}{-2}{red,->,thick}
    \sumphasor{0,0}{1}{3}{blue,->,thick}
    \sumphasor{0,0}{4}{-0.3}{green,->,thick}
\end{tikzpicture}
\hspace{1cm}
\begin{tikzpicture}
    \draw[->] (-4,0) -- (4,0);
    \draw[->] (0,-4) -- (0,4);
    \foreach \x in {-4,...,4}
    {   \draw (-0.1,\x) -- (0.1,\x);
        \draw (\x,-0.1) -- (\x,0.1);
    }
    \expphasorpi{0,0}{3}{0.785}{red,->,thick} % pi/4
    \expphasorpi{0,0}{2}{1.047}{blue,->,thick} % 1/3*pi
    \expphasorpi{0,0}{4}{-0.785}{green,->,thick} %-pi/4
\end{tikzpicture}

\begin{tikzpicture}
    \draw[->] (-4,0) -- (4,0);
    \draw[->] (0,-4) -- (0,4);
    \foreach \x in {-4,...,4}
    {   \draw (-0.1,\x) -- (0.1,\x);
        \draw (\x,-0.1) -- (\x,0.1);
    }
    \expphasordeg{0,0}{3}{-30}{red,->,thick} % pi/4
    \expphasordeg{0,0}{2}{75}{blue,->,thick} % 2/3*pi
    \expphasordeg{0,0}{4}{-45}{green,->,thick} %-pi/4
\end{tikzpicture}
\hspace{1cm}
\begin{tikzpicture}
    \draw[->] (-4,0) -- (4,0);
    \draw[->] (0,-4) -- (0,4);
    \foreach \x in {-4,...,4}
    {   \draw (-0.1,\x) -- (0.1,\x);
        \draw (\x,-0.1) -- (\x,0.1);
    }
    \sumphasor{0,0}{3}{-2}{red,-latex,thick}
    \sumphasor{0,0}{1}{3}{blue,-latex,thick}
    \sumphasor{3,-2}{1}{3}{densely dashed,thick}
    \sumphasor{1,3}{3}{-2}{densely dashed,thick}
    \sumphasor{0,0}{4}{1}{green!50!gray,-latex,thick}
\end{tikzpicture}

\end{document}

A: The summation is not that tricky if you just use the regular polar form. Here is a simple starter:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}[>=latex]
\draw[style=help lines] (0,0) grid[step=1cm] (3,2);

\coordinate (vec1) at (60:1); % Define some complex numbers
\coordinate (vec2) at (20:2); % with r*exp(i \theta) form

\draw[->,thick,blue] (0,0) -- (vec1);
\draw[->,thick,red] (0,0) -- (vec2);
\draw[dashed] (vec2) -- ++(vec1); % This how to add a vector to another
\draw[dashed] (vec1) -- ++(vec2); % using the coordinates as vectors
\draw[->,thick,orange] (0,0) -- ($(vec1) + (vec2)$); % This is how to do arithmetic
                                                     % operations on the coordinates.
                                                     % (requires calc library of TikZ.
                                                     % See the manual )
\end{tikzpicture}
\end{document}


text:
Q: Prawn: How to iterate from a table inside an iteration in the header? I pass 3 @course ID's to courses.pdf.
Then Prawn generates a PDF of 3 pages - one course pr page.
The problem: currently it prints all @participants from all 3 courses in all 3 pages.
It should only print the @participants for the current course in a table.
I have spend several hours trying different methods, asked in Facebook groups and searched Stackoverflow + Google for solutions.
class CoursesToPrintPdf < Prawn::Document

    def initialize(courses, participations)
        @courses = courses
        @participations = participations
        header
    end

    def header
        @courses.order('day ASC').each do |course|

            text_box("#{course.course_day_pdf}",
            :align => :right)
            text "#{course.round.round_name_simple}"

            table deltakere_rows do
                self.header = true
            end
        end
    end

    def deltakere_rows
        [["ID", "Name"]] +
        @participations.map do |p|
            [p.participant.id, p.participant.full_name]
        end
    end

end

A: Does a partecipation contain a course reference? If so, it could be something like this
def deltakere_rows(course)
  [["ID", "Name"]] +
    @participations.select do |p|
      p.course_id == course.id
    end.map do |p|
      [p.participant.id, p.participant.full_name]
    end
end

And pass the course to deltakere_rows
table deltakere_rows(course) do
  self.header = true
end

This could be the idea with the info we have


text:
Q: Javascript not showing error

<form method="post" onSubmit = "return registerform();">
<input type='text' id='firstname' size="50" />

<input type='text' id='lastname' size="50" />

<input type= "Submit" value="Submit" />
</form>

what im trying to do here is to validate both my firstname and lastname but then the code only shows error for the first name.why isnt the return working?. did i use return false wrongly. could some one help and explain here

A: return statement in first condition ends the method .. So you could just store the valdiation info in variable and return it
function registerform(){
    var fullnameExp = /^[a-zA-Z]+$/;
    var firstname= document.getElementById('firstname');
    var lastname= document.getElementById('lastname');
    var isValid =true;
    if(firstname.value.match(fullnameExp)){
    }else{
        document.getElementById("errorname").innerHTML="[Please type in alphabets only!]";
        isValid= false;

    }
    if(lastname.value.match(fullnameExp)){
    }else{
        document.getElementById("errorname").innerHTML="[Please type in alphabets only!]";
        isValid = false;
    }
    return isValid;
}

A: else{
    document.getElementById("errorname").innerHTML="[Please type in alphabets only!]";
    var firstnamevalid = false;

}
if(lastname.value.match(fullnameExp)){}
else{
    document.getElementById("errorname").innerHTML="[Please type in alphabets only!]";
    var lastnamevalid =  false;
}
if (!firstnamevalid|| !lastnamevalid)
    return false;
return true;

something like this would do what you want I believe.
Essentially as someone mentioned int he comments above, having return statements in your code will immediately exit the method if the method returns something. What this is doing instead is saving your first name and last name validation and then checking to see if either one is false. If it is, THEN you return false and if they're both true then you can return true.


text: Q: Loading Ubuntu on re-built computer I'm trying to re-built an old desktop I got hold of.  There was no HDD so I added an SSD.  I have my USB key with Ubuntu iso file.  Keyboard powering through USB, but my first challenge is that screen does not display video.  Power is on (suggests no VGA input).  I've taken out the RAM and the small battery.  But still no VGA input. VGA connectors have been checked, so I guess it should be working? Thanks for tips and advice.


text:
Q: interpreting triple integrals The limits of integration on a double integral are justified because I'm essentially finding the area underneath two functions. Namely, first I integrate (say, with respect to dx) and I get an area function in terms of 'y'; then computing the next integral (with respect to dy) will give me the area of another function, which in this case means a volume.
But I don't see how I can justify the limits of integration for a triple integral. Specifically I'm doing problems including the divergence theorem. How do I interpret the triple integral?
I don't like thinking of the limits of integration as just "its from here to here, simply because those are the dimensions of the region you're integrating over". I think theres a more complete interpretation of those limits.
EDIT: I think my question basically boils down to how is the triple integral related to the fundamental theorem of calculus? I'm finding increments of what?
Take for instance ∫∫∫ p(x,y,z)dxdydz where p is the density function. How do you interpret that integral (like what does each individual integral represent, and why does it have to be an iterated integral)? And if it were the case that instead of p(x,y,z) I had Div(E) what would each integral represent?
I focused on the limits of integration, because I think these have a lot to do with the fundamental theorem of calculus.
I'm sorry if my question is unclear. Thanks.

A: It means that you are summing the contributions from all the space. With your example:
\begin{equation}
    \int\int\int p(x,y,z)\ dx\ dy\ dz
\end{equation}
you can imagine for a scalar problem that p(x,y,z) represents a spatial distribution, and you want to sum the equivalent elements in a volume. In electromagnetism, you have for example the expression of the potential vector
\begin{equation}
    A(r) = \int J(r) \frac{exp(-jkr)}{r} dr
\end{equation}
where your triple integrals are replaced by the equivalent polar coordinates, and where you take a look at the contribution of field sources depending on their positions of the space.

A: If $\rho$ is the density function, and $\Sigma$ is a solid on space, then $$\iiint_\Sigma \rho~\mathrm{d}V$$
represents the mass of $\Sigma$. The divergence theorem states that, if $\mathbf{F}$ is a vector field, then: $$\iint_{\partial \Sigma} \mathbf{F}~\mathrm{d}\boldsymbol{\sigma} = \iiint_\Sigma \mathrm{div} \ \mathbf{F}~\mathrm{d}V$$
Think of $\mathbf{F}$ as the motion of a fluid, let's say, water, inside $\Sigma$, and $\partial \Sigma$ as permeable membrane. The left-hand side is the flux of water that goes through $\partial \Sigma$ and the right-hand side would be the resulting volume of water that leaves/enters $\Sigma$. Notice that $\mathrm{div} \ \mathbf{F} \equiv 0$ doesn't mean that there is no fluid entering or leaving the surface, it just means that the quantity that enters is equal to the quantity that leaves.

A: A "triple integral" arises when you have some function $f:\>{\mathbb R}^3\to{\mathbb R}$ and a body $B\subset{\mathbb R}^3$, and you  want to compute the "total impact of $f$ over $B$". This "total impact" is denoted by $\int_B f({\bf x})\ {\rm d}({\bf x})$ and  has the following properties:
It is linear in $f$, additive with respect to $B$, and $\int_B 1\ {\rm d}({\bf x})={\rm vol}(B)$.
From this idea it follows that $\int_B f({\bf x})\ {\rm d}({\bf x})$ is the limit of sums of the following kind:
$$\int_B f({\bf x})\ {\rm d}({\bf x})=\lim_\ldots \sum_{k=1}^N f(\xi_k){\rm vol}(B_k)\ ,$$
where $B=\bigcup_{k=1}^N B_k$ is a partition of $B$ into small essentially disjoint subdomains $B_k$, and the $\xi_k$ are sampling points chosen arbitrarily in $B_k$ $\>(1\leq k\leq N)$.
The above is a geometrically intuitive description of what one has in mind, and coincides for in the one-dimensional case with the definition of the Riemann integral. Now for the one-dimensional case we have the miraculous FTC, and we want to bring that into bear for double or triple integrals as well. That's where Fubini's theorem comes in, which provides a reduction process that converts a triple integral into a nested sequence of three "simple" integrals involving only one variable. But doing this properly for a complicated body $B$ involves dealing carefully with lower and upper limits of the intermediate integrals.


text:
Q: Jquery Last-Child or Nth-Child if == "SALE" I have a drop down menu and I am trying to change the last item of the list only if the string  equals "SALE" and make it RED. I am able to successfully select any item in the list by either using nth-child or last-child but not all drop downs have the <li> string SALE. How can I achieve this using jQuery?
jQuery('ul.top-cat-links li.top-cat-tops a:last-child').css('color','#ff0000');

A: If SALE isn't directly in the li element, you can use :has:
ul.top-cat-links li.top-cat-tops:has(:contains("SALE")) a:last-child

If it is, you can just use :contains:
ul.top-cat-links li.top-cat-tops:contains("SALE") a:last-child

Using JavaScript to add classes like this isn't a good idea. Why don't you add them with your serverside language?


text:
Q: Google analytics update version to 64bytes I want to move an application in 64 bytes .
But I have a problem with Google Analytics.
In the new version , there is no file " GANTracker.h " .
My methods are in a class I call where I need it.
My existing classes so no longer works , I have to redo everything .
My initial classes:
AnalyticsService.h
#import "GANTracker.h"

@interface AnalyticsService : NSObject

- (id)init;

- (void)startTracker;

- (void)stopTracker;

- (void)restartTracker;

- (BOOL)trackPageview:(NSString *)pageURL;

- (BOOL)trackEvent:(NSString *)category
            action:(NSString *)action
             label:(NSString *)label
             value:(NSInteger)value;

@end

AnalyticsService.m
#import "AnalyticsService.h"
#import "Util.h"
#import "ServicesProxy.h"

@implementation AnalyticsService

- (id)init
{
    self = [super init];
    if(self != nil)
    {}
    return self;
}

- (void)startTracker
{
    [[GANTracker sharedTracker] startTrackerWithAccountID:kAnalyticsAccountId dispatchPeriod:kGANDispatchPeriodSec delegate:nil];

    NSString* appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey];
    NSString* numPdvInDb = [[[ServicesProxy defaultServicesProxy]pdvService]getSelectedPdv];
    if([numPdvInDb length] == 0) numPdvInDb = @"null";

    [[GANTracker sharedTracker] setCustomVariableAtIndex:1 name:@"VERSION" value:appVersion scope:kGANSessionScope withError:nil];
    [[GANTracker sharedTracker] setCustomVariableAtIndex:2 name:@"PDV" value:appVersion scope:kGANSessionScope withError:nil];
}

- (BOOL)trackPageview:(NSString *)pageURL
{
    return [[GANTracker sharedTracker] trackPageview:pageURL withError:nil];
}

- (BOOL)trackEvent:(NSString *)category action:(NSString *)action label:(NSString *)label value:(NSInteger)value
{
    return [[GANTracker sharedTracker]trackEvent:category action:action label:label value:value withError:nil];
}

- (void)stopTracker
{
    [[GANTracker sharedTracker] stopTracker];
}

- (void)restartTracker
{
    [[GANTracker sharedTracker] stopTracker];
    [self startTracker];
}

@end

What I tried to redo :
@implementation AnalyticsService

- (id)init
{
    self = [super init];
    if(self != nil)
    {}
    return self;
}

- (void)startTracker
{
    id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:kAnalyticsAccountId];

    NSString* appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey];
    NSString* numPdvInDb = [[[ServicesProxy defaultServicesProxy]pdvService]getSelectedPdv];
    if([numPdvInDb length] == 0) numPdvInDb = @"null";

    [tracker set:@"VERSION" value:appVersion];
    [tracker set:@"PDV" value:numPdvInDb];
}

- (BOOL)trackPageview:(NSString *)pageURL
{
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

    [tracker set:kGAIScreenName value:pageURL];
    [tracker send:[[GAIDictionaryBuilder createScreenView] build]];

    return YES;
}

- (BOOL)trackEvent:(NSString *)category action:(NSString *)action label:(NSString *)label value:(NSInteger)value
{
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

    [tracker send:[[GAIDictionaryBuilder createEventWithCategory:category
                                                          action:action
                                                           label:label
                                                           value:nil] build]];

    return YES;
}

- (void)stopTracker
{
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

    [tracker ????? ];

}

- (void)restartTracker
{
    [self stopTracker];
    [self startTracker];
}

@end

Well, I hope that I have explained well . Sorry for my english (I'm french )
If you have ways to help ...
Thank you in advance for your answers! :)

A: Instead of "GANTracker.h", try importing "GAITracker.h"


text:
Q: JS/ES6: Destructuring of undefined I'm using some destructuring like this:
const { item } = content
console.log(item)

But how should I handle content === undefined - which will throw an error?
The 'old' way would look like this:
const item = content && content.item

So, if content is undefined -> item will also be undefined.
Can I do something similar using destructuring?

A: One can unpack undefined value, but can't unpack from undefined.
Fixing it is as easy as setting the default params value.
Example:
(() => {
    // prepare payload
    const PAYLOAD = {
        holdingJustThis: 1
    };
    // lets unpack the payload and more
    const {
        holdingJustThis,
        itIsGoingToBeUndefined,
        itCouldThrowButWont: {
            deep
        } = {}                  // this will secure unpacking "deep"
    } = PAYLOAD;

    console.log({
        holdingJustThis
    });
    console.log({
        itIsGoingToBeUndefined  // logs {itIsGoingToBeUndefined:undefined}
    });
    console.log({
        deep                    // logs {deep:undefined}
    });
})()

A: You can use short circuit evaluation to supply a default if content is a falsy value, usually undefined or null in this case.

const content = undefined
const { item } = content || {}
console.log(item)                       // undefined

A less idiomatic (see this comment) way is to spread the content into an object before destructuring it, because null and undefineds values are ignored.

const content = undefined
const { item } = { ...content }
console.log(item) // undefined

If you are destructuring function params you can supply a default (= {} in the example).
Note: The default value would only be applied if the destructured param is undefined, which means that destructuring null values will throw an error.

const getItem = ({ item } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem())                  // undefined

try {
  getItem(null)
} catch(e) {
  console.log(e.message)                // Error - Cannot destructure property `item` of 'undefined' or 'null'.
}

Or even set a default value for the item property if the input object doesn't contain the property

const getItem = ({ item = "default" } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem({ foo: "bar" }))    // "default"

A: const { item } = Object(content)

A: const content = undefined
const { item } = content ?? {}
console.log(item)   // undefined

A: There is recently added: Nullish coalescing operator (??).
Which basically returns right-side value, if the left-side value is null or undefined (our case with undefined instead of an object).
const { item } = undefined or null
// Uncaught TypeError: Cannot destructure property 'item' of 'null' as it is  null.

const { item } = content ?? {}
console.log(item)   // undefined

So consider using the operator.
Also, as mentioned before in the answers, there is || (or) operator.
For us, there is no significant difference in this particular case.
That's just a matter of taste, in our team, we have an agreement: we use ?? for defining default object if the target object is null or undefined, and in other cases we use || operator.

A: Destructuring the nested object is clean and short but sucks when source property is null or undefined in right side object
let say we have
const {
  loading,
  data: { getPosts },
} = useQuery(FETCH_POSTS_QUERY);

Solution 1
if we have data object but no getPosts then we can use:
(Setting default at each level)
const {
  loading,
  data: { getPosts = [] } = { getPosts: [] },
} = useQuery(FETCH_POSTS_QUERY);

Solution 2:
if event data is undefined then:
const {
  loading,
  data: { getPosts } = { getPosts: [] },
} = useQuery(FETCH_POSTS_QUERY);

A: accepted answer does not work for truely undefined values which were not set by const content = undefined. in such cases this will work:
const { item } = (typeof content !== 'undefined' && content) || {}
console.log(item)

A: I'll just add that for the OP's use case, it is also possible to use the Optional chaining operator:
const item = content?.item
console.log(item)

If content is null or undefined, then content.item will not be accessed and item will be undefined.


text:
Q: Is there a way I can get the media type of the ads shown on my website? I'm working on a website hosted in WordPress and there are 2 ads, from different ad providers, that overlaps when both are showing video ads. Is there a way to get the media type of both ads and prevent the other from showing on the website when they are both showing video ads?
The website I'm working on isn't mine, this task is given to me by my supervisor. I have no knowledge with regards to inserting ads on a website. I also, wasn't the one who inserted the ads on the website.


text:
Q: dictations, improving spelling I'm looking for a website that would propose free dictations in English, so that I could listen and then type what I hear and at the end to see if I made any mistakes. I was searching in the Internet, but I didn't find anything close enough. May be someone knows and wouldn't mind to share ?
Thanks!

A: Check this link on meta ELL.
This meta post on ELL lists many resources, one of which relates to pronunciations. The other resources are quite useful as well.

A: The Writer's Almanac is a daily radio segment/podcast which features Garrison Keillor in 5 minutes of talk and poetry.  There is not a literal transcript for the entire program, but there is a "set of notes", so to speak, which can used to help interpret what is said, and there is an exact copy of the poem featured in each segment.
Keillor is a good source for pronunciations and diction as he has a clear and near-perfect Midwestern accent, and I only very rarely detect what I would consider a mispronunciation.  (Though some episodes in the summer of 2013 were done by poet Billy Collins, who notably cannot pronounce "poem" correctly.)