Q:

Javascript Math.floor function blunder or implementation mystery?

    document.writeln(Math.floor(43.9));

produces 43 in the browser.
document.writeln(Math.floor(43.9999));

produces 43
 document.writeln(Math.floor(43.999999999999));

again 43
However,
    document.writeln(Math.floor(43.99999999999999));

produces 44.
The magic number of 9's after the decimal point seems to be 15*.
Why is this?
Furthermore, Does the Math.floor function accept the number as a number object, or a number value?

A:

The IEEE 754 double-precision binary floating-point format (which is what JavaScript uses for its Number type) gives you a precision of 15 - 17 significant decimal digits.

This gives from 15 - 17 significant decimal digits precision. If a
  decimal string with at most 15 significant decimal is converted to
  IEEE 754 double precision and then converted back to the same number
  of significant decimal, then the final string should match the
  original; and if an IEEE 754 double precision is converted to a
  decimal string with at least 17 significant decimal and then converted
  back to double, then the final number must match the original [1].

Source: http://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64

A:

Double-precision floating point numbers (a.k.a. doubles) are capable of storing a very wide range of values but only with limited precision—15–17 significant digits. If you do the following, you'll see what happens:
var x = 43.99999999999999;
var y = 43.999999999999999;

document.writeln(x); // 43.99999999999999
document.writeln(y); // 44
document.writeln(Math.floor(x)); // 43
document.writeln(Math.floor(y)); // 44

You'll see the same in other languages as well. For example, PHP:
echo floor(43.99999999999999); // 43
echo floor(43.999999999999999); // 44


Q:

Python rglob pattern for directory search

I try to get the name of subdirectories with Python3 script on Windows10.
Thus, I wrote code as follows:
from pathlib2 import Path
p = "./path/to/target/dir"
[str(item) for item in Path(p).rglob(".")]
# obtained only subdirectories path names including target directory itself.

It is good for me to get this result, but I don't know why the pattern of rglob argument returns this reuslt.
Can someone explain this?
Thanks.

A:

Every directory in a posix-style filesystem features two files from the get go: .., which refers to the parent directory, and ., which refers to the current directory:
$ mkdir tmp; cd tmp
tmp$ ls -a
. ..
tmp$ cd .
tmp$  # <-- still in the same directory

- with the notable exception of /.., which refers to the root itself since the root has not parent.
A Path object from python's pathlib is, when it is created, just a wrapper around a string that is assumed to point somewhere into the filesystem. It will only refer to something tangible when it is resolved:
>>> Path('.')
PosixPath('.')  # just a fancy string
>>> Path('.').resolve()
PosixPath('/current/working/dir')  # an actual point in your filesystem

The bottom line is that

the paths /current/working/dir and /current/working/dir/. are, from the filesystem's point of view, completely equivalent, and
a pathlib.Path will also reflect that as soon as it is resolved.

By matching the glob call to ., you found all links pointing to the current directories below the initial directory. The results from glob get resolved on return, so the . doesn't appear in there any more.
As a source for this behavior, see this section of PEP428 (which serves as the specification for pathlib), where it briefly mentions path equivalence.


Q:

ExpressionEngine Display Section Title Once if Channel Entries Present

I'm wondering if there a simpler way to achieve this, that cuts down on the number of queries submitted to the server:
I have a section on the home page where users can purchase tickets to an event. I don't have ticketed events that often, so I only want that section to display when tickets are available.
The way I've been doing it is like this:
{exp:channel:entries channel="ticketed_events" limit=1}

Purchase Tickets

{/exp:channel:entries}
{exp:channel:entries channel="ticketed_events"}
{event_title} - {ticket_price}
{/exp:channel:entries}

I have to do it twice so that the title only displays the one time, instead of once per entry. That seems a little awkward, having to send two queries to the server like that. Is that really the only way to do it?
ty

A:

{exp:channel:entries channel="ticketed_events"}
{if count == 1}
Purchase Tickets
{/if}
{event_title} - {ticket_price}
{/exp:channel:entries}

Without trying that should do it, otherwise try {if {count} == 1}


Q:

Driver for Wireless 7260

I just installed Ubuntu 16.04 on a laptop with Intel Wireless 7260, but the kernel does not recognize wifi. The laptop does not have ethernet, and wifi is my only way to connect to the internet.
As I searched, many people have this problem.
One issue that I see is that the intel driver for kernel 4.3+ should be iwlwifi-7260-17.ucode, but Ubuntu uses iwlwifi-7260-13.ucode.
In /lib/firmware, iwlwifi-7260-16.ucode is available. I downloaded iwlwifi-7260-16.ucode and iwlwifi-7260-17.ucode from Intel website, but still no success.

A:

After one day of struggling, I found it has nothing to do with driver.
If anyone has this problem, the solution is
echo "blacklist acer-wmi"  >>  /etc/modprobe.d/blacklist.conf

I don't know what is this problem, but I believe it should be permanently fixed.


Q:

Uploading image with Almofire 4 swift 3

i want to upload photo into server with almofire i'm using this code right now but i'm getting timeout
let imageData = UIImageJPEGRepresentation(croppedImage, 1)

let urlRequest = self.urlRequestWithComponents(url, imageData: imageData!)
self.alamofire.upload(urlRequest.1, to: urlRequest.0 as! URLConvertible).responseJSON { response in
    guard response.result.isSuccess else {
        self.showError()
        return
    }

    guard let data = response.result.value else {
        self.showError()
        return
    }

    let json = JSON(data)
}

func urlRequestWithComponents(_ urlString:String, imageData:Data) -> (URLRequestConvertible, Data) {
    var urlRequest = URLRequest(url: URL(string: urlString)!)
    urlRequest.httpMethod = HTTPMethod.post.rawValue
    let boundary = generateBoundaryString()
    let contentType = "multipart/form-data;boundary=" + boundary
    urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

    let uploadData = NSMutableData()

    uploadData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    uploadData.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!)
    uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
    uploadData.append(imageData)
    uploadData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

    return try! (Alamofire.URLEncoding.default.encode(urlRequest, with: nil), uploadData as Data)
}

Is there any solution about this issue ?

A:

Try this in swift 3
Alamofire.upload(multipartFormData: { (multipartFormData) in
    multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
    }, to:"http://server1/upload_img.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (Progress) in
            print("Upload Progress: \(Progress.fractionCompleted)")
        })

        upload.responseJSON { response in
            //self.delegate?.showSuccessAlert()
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
            //                        self.showSuccesAlert()
            //self.removeImage("frame", fileExtension: "txt")
            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
        }

    case .failure(let encodingError):
        //self.delegate?.showFailAlert()
        print(encodingError)
    }

}


Q:

Why is my javascript argument not passed "by reference"?

I'm sure I'm missing something obvious here, but I'd expect the argument to the changeMe method to be passed "by reference" - in other words, that changes to the parameter inside the function will change the variable outside the function.
The following was run in jsfiddle, using Chrome's F12 developer tools to show the console output. http://jsfiddle.net/fzEpa/
var object1 = { Property1: 'Value1' };
changeMe(object1);
console.log(object1);

function changeMe(refToObject) {
    console.log(refToObject);
    refToObject = { Property1: 'Value2' };
    console.log(refToObject);
}

A:

It is passed by reference, but it is a reference to the object, not to the object1 variable (which is also a reference to the object).
You are overwriting the reference to the object with a reference to a new object.
This leaves the original reference to the original object intact.
To modify the object, you would do something like this:
function changeMe(refToObject) {
    refToObject.Property1 = 'Value2';
}

A:

A reference to the object is passed as the argument value. However:
refToObject = { Property1: 'Value2' };

At this point you lose the reference to the object formerly referenced by refToObject as you're assigning this variable to reference a different object.
Now if you were to edit the refToObject's properties instead of discarding the former object reference, your code would work as exepected (as firstly explained in @Quentin's answer).


Q:

Should one-time events always be closed as "too localized"?

How can I craft the Golden Wrench in TF2? seems like a perfectly legitimate question someone might want to Google, with an answer that won't change (with any more likelyhood than an SC2 or WoW question would).
There should be some distinction made between questions about one-off events with lasting effects and others that are meaningless after such a date (When is X coming out?) instead of just closing all questions that are somehow connected to an event.

A:

The accepted answer is: You can no longer craft it.
That seems like the kind of thing that people would want to know.  Unlike a release date (which you'll only miss if you're hiding under a rock), the desire for an in game item is not localized to the specific time it's obtainable, but continues on for years afterwards.
After all, I'd still kill someone, in front of his own mother, if it got me that damn Bug Mount


Q:

Getting an error "found conflicting getters" when trying to upload a message to a firebase database

I am using this library: https://github.com/stfalcon-studio/ChatKit to add chat to my app, i am getting this error when i try to upload a message to the firestore db:
FATAL EXCEPTION: main
                  Process: neoncore.com.onepiece, PID: 3907
                  java.lang.RuntimeException: Found conflicting getters for name getUser on class neoncore.com.onepiece.beans.chat.Message
                      at com.google.android.gms.internal.zzevb$zza.<init>(Unknown Source)
                      at com.google.android.gms.internal.zzevb.zzg(Unknown Source)
                      at com.google.android.gms.internal.zzevb.zza(Unknown Source)
                      at com.google.android.gms.internal.zzevb.zzbw(Unknown Source)
                      at com.google.firebase.firestore.zzk.zzcd(Unknown Source)
                      at com.google.firebase.firestore.CollectionReference.add(Unknown Source)
                      at neoncore.com.onepiece.activities.ChatDetail$1.onSubmit(ChatDetail.java:57)
                      at com.stfalcon.chatkit.messages.MessageInput.onSubmit(MessageInput.java:145)
                      at com.stfalcon.chatkit.messages.MessageInput.onClick(MessageInput.java:108)
                      at android.view.View.performClick(View.java:5210)
                      at android.view.View$PerformClick.run(View.java:21328)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5551)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

This is my updated message class:
public class Message implements IMessage,
        MessageContentType.Image, /*this is for default image messages implementation*/
        MessageContentType /*and this one is for custom content type (in this case - voice message)*/ {

    private String id;
    private String text;
    private Date createdAt;
    private User user;
    private Image image;
    private Voice voice;

    public Message(String id, User user, String text) {
        this(id, user, text, new Date());
    }

    public Message(String id, User user, String text, Date createdAt) {
        this.id = id;
        this.text = text;
        this.user = user;
        this.createdAt = createdAt;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getText() {
        return text;
    }

    @Override
    public Date getCreatedAt() {
        return createdAt;
    }

    @Override
    public User getUser() {
        return this.user;
    }

    @Override
    public String getImageUrl() {
        return image == null ? null : image.url;
    }

    public Voice getVoice() {
        return voice;
    }

    public String getStatus() {
        return "Sent";
    }

    public void setText(String text) {
        this.text = text;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public void setImage(Image image) {
        this.image = image;
    }

    public void setVoice(Voice voice) {
        this.voice = voice;
    }

    public static class Image {

        private String url;

        public Image(String url) {
            this.url = url;
        }
    }

    public static class Voice {

        private String url;
        private int duration;

        public Voice(String url, int duration) {
            this.url = url;
            this.duration = duration;
        }

        public String getUrl() {
            return url;
        }

        public int getDuration() {
            return duration;
        }
    }
}

and also my user class:
     [public class User implements IUser {

    private String id, name, avatar;

    public User(String id, String name, String avatar) {
        this.id = id;
        this.name = name;
        this.avatar = avatar;
    }

    public User() {
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getAvatar() {
        return avatar;
    }
}][1]

this is the point where the error occurs:
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_detail);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
        firebaseFirestore = FirebaseFirestore.getInstance();
        final Author author = new Author(currentUser.getUid(),currentUser.getDisplayName(),currentUser.getPhotoUrl().toString());
        messageMessagesListAdapter = new MessagesListAdapter<>(author.getId(),null);
        messagesList = findViewById(R.id.messagesList);

        inputView = findViewById(R.id.input);
        inputView.setInputListener(new MessageInput.InputListener() {
            @Override
            public boolean onSubmit(CharSequence input) {
                CollectionReference reference = firebaseFirestore.collection("Messages");
                final Message message = new Message(author,input.toString(), "",null,new Date());
                reference.add(message).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentReference> task) {

                        messageMessagesListAdapter.addToStart(message,true);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("MessageUPloadFailed",e.getMessage());
                    }
                });
                return true;
            }
        });

        messagesList.setAdapter(messageMessagesListAdapter);
    }

The error occurs at the point where i try to add the message to the firestore database where the add method is called.
 database image

A:

You are getting this error:
java.lang.RuntimeException: Found conflicting getters for name getUser on class Message

Because in Message class you have a getUser() method but you don't have a user field at all. You have instead an author field and the getter for this field should be:
@Override
public Author getAuthor() { //NOT getUser()
    return author;
}


Q:

Handling log and configuration files when load balancing apache

So, I am currently rebuilding my web platform from a single-machine to a cluster of machines, and I will be using Apache load balancing to do this., but I have two questions that I need a good answer to before proceeding. I have Googled and searched here in SO, but didn't find anything good.
My setup will be one Debian machine running the Apache load balancing server (i.e. Apache with mod_proxy) and then any number of "slave" machines, that are balancing members. All of these are VPS inside a VMWare machine, so setting up new slaves as needed will be trivial.
Log Files
The first question is that of log files. In order to troubleshoot my platform, I sometimes need to analyze log files, both access logs and error logs, from Apache. When the load is evenly distributed (i.e. I don't know if I'll even use sticky balancing, any host could probably handle any request at any time), so would the log files for each slave Apache instance. Is there a way to consolidate these live, meaning that my live log analyzer could see the log files from all hosts? I certainly understand that doing so while the files being on several hosts would be difficult, so is there a way to make sure that all log files are kept on one server?
I'm thinking about two things myself, but I would greatly appreciate your input.
syslogd
The first is syslogd, where in it would be possible for several hosts to write to one logging host. The problem with this is that in my current setup, each virtual host in apache, has its own log file. That could probably be fixed in some manner though. My main usage for this is for troubleshooting, not keeping separate logs for each host (albeit if both goals could be met, that would certainly be a bonus).
NFS
My next thought was about NFS, i.e. having a NFS share on the LAN where each slave can write to the same log file. I'm going to go ahead and assume that this will be difficult since slave 1 would open the log file and then slave 2 wouldn't be able to write to it.
As I said, your input is greatly appreciated since I feel I'm stuck in how to solve this.
Configuration files
This is another thing altogether. Each slave will respond to each request as if acting as one single server. That is the entire idea. But what about making changes to the apache configuration files, adding virtual hosts, setting up other parameters? What if I have ten slaves, or fifty? Is there a way to make sure that all these slaves are always in sync? I am already using a NFS export to make sure they all have the same files, but should I use the same approach with the configuration files? Or should I have these as some form of repository and then use rsync to copy them out to the slaves? One problem is that I have built an interface in my web platform that edits these configuration files (namely the file with the virtual hosts), and since that action would take place on one of the slaves, the most current copy of this file could potentially be on one slave.
I realize that this was a long and wieldy post, and I apologize. I just wanted to make sure that all the parameters of my problem were expressed.
I hope someone out there can help me, as you have before! Thank you in advance!

A:

I suggest not using NFS for logging as it can be a real performance killer. Instead use rsyslog with remote logging enabled. In you apache2.conf you can setup a LogFormat that includes the VirtualHost name and then pipe the log to rsyslog telling it to write the output to a remote host.
In apache2.conf:
LogFormat "%v %{X-FORWARDED-FOR}i %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
CustomLog "|/usr/bin/logger -t apache2 -p local7.info" vhost_combined

In rsyslog.conf on the webserver:
local7.* @<remote host ip>

In rsyslog.conf on the remote host:
local7.*    /var/log/webfrontends.log;precise

As for the Apache configuration files, we use NFS.
apache2.conf is a link to a remote file (different files for different machines if needed) and in apache2.conf we use an Include directive to read specific site configurations (different dirs for different machines if needed)
on the NFS server the NFS exported dir /NFS_EXPORT/etc/apache2/ contains:
 - webserver1_apache2.conf
 - webserver2_apache2.conf
 - webserver1_vhosts (dir)
 - webserver2_vhosts (dir)

Both webserver1_apache2.conf and webserver2_apache2.conf contain Include "/etc/apache2/vhosts"
on WebServer 1
ln -s /NFS_EXPORT/etc/apache2/webserver1_apache2.conf /etc/apache2/apache2.conf
ln -s /NFS_EXPORT/etc/apache2/webserver1_vhosts/ /etc/apache2/vhosts

on WebServer 2
ln -s /NFS_EXPORT/etc/apache2/webserver2_apache2.conf /etc/apache2/apache2.conf
ln -s /NFS_EXPORT/etc/apache2/webserver2_vhosts/ /etc/apache2/vhosts

If all your webservers are the same in terms of hardware specs and serve the same sites/applications then there is no need to differentiate the configs.
Of course you will need a script or some other mechanism to restart apache on all your server once you modify a configuration.
Also, upgrading your apache2 software can be tricky unless you have root access to your NFS exports beacause typically your package management system will complain about not being able to modify some configuration file.

A:

NFS will not help you with log files, for exactly the reasons you describe above.  You should use syslogd (or some other solution like Splunk) to centralize the logging.  It's trivial to include information about what host the log entry comes from, so you can still winnow down to per-host data when troubleshooting.
Configuration files: you need to either centralize them (a "master" copy), or have a way of distributing changes made on any server to all the others.  I recommend centralization as the simpler approach.  NFS will do the job here, or, as you suggest, a repository from which all hosts are periodically updated.  There are a lot of options here, running all the way up to version control (SVN, git, etc) or even configuration servers (Chef, etc).
Please note that moving from a single server to a cluster has many implications.  In both cases above (logging, config files), there is potential to introduce single points of failure if done naively.  Since you have that already (one server), you're not worse off, but you should try to be aware of and plan for the failure scenarios you may need to respond to.


Q:

Wordpress.com - after saving custom CSS all widths are removed

I'm working with wordpress.com along with the custom design upgrade to be able to change the CSS.  Everything was working fine yesterday, and suddenly today I have an issue with the stylesheet: when I hit the 'save' button all the widths are removed from the CSS, which causes some elements to overlap or be misplaced.  It's such a strange behaviour that I don't think I could have accidentally caused it.  Only the widths disappear, every other element/rule is there.
I posted this question at the WP forums but no luck yet.  Hopefully someone here has an idea about what could be wrong.
Thank you in advance :)
SOLVED:
Apparently is a WP issue.  I 'fixed' it with a workaround that someone suggested me by replacing 'width' with 'min-width' and 'max-width'.

A:

This was confirmed as a bug, the staff at WP already fixed it and everything is back to normal.  Here's a link to the thread in case you were affected.


Q:

Remove class after 5 second on ViewportChecker

I'm using ViewportChecker jquery plugin, script that detects if an element is in the viewport and adds or remove a class to it.
I'm trying to hold class for 5 second, means remove class .invisible after 5 second. I've made a demo, when scroll down to the element/class then it get window view and then ViewportChecker remove .invisible class then add .visible class.
See fiddle >

HTML:

New blog writers everywhere are faced with a serious dilemma when they first reach the Internet and must decide which blogging platform is best for their new website. There are actually dozens of options on the market, ranging from the basic blog settings of the social networks to the self-hosted open sources software solutions.

New blog writers everywhere are faced with a serious dilemma when they first reach the Internet and must decide which blogging platform is best for their new website. There are actually dozens of options on the market, ranging from the basic blog settings of the social networks to the self-hosted open sources software solutions.

JS:
// For Class a
$('.a').viewportChecker({
    classToAdd: 'visible', // Class to add to the elements when they are visible
    classToRemove: 'invisible', // Class to remove before adding 'classToAdd' to the elements
    offset: 2, // The offset of the elements (let them appear earlier or later). This can also be percentage based by adding a '%' at the end
    invertBottomOffset: true, // Add the offset as a negative number to the element's bottom
    repeat: false, // Add the possibility to remove the class if the elements are not visible
    callbackFunction: function(elem, action){}, // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
    scrollHorizontal: false
});

There have any way to hold to remove class for 5 second only on class .a I means ViewportChecker will remove class immediately, so i want to hold this class .invisible for 5 second only on
.

A:

removing the given classes and then adding the class after the delay inside the callbackFunction using setTimeout() will do the job: DEMO
// For Class a
$('.a').viewportChecker({
    classToAdd: 'visible', // Class to add to the elements when they are visible
    classToRemove: 'invisible', // Class to remove before adding 'classToAdd' to the elements
    offset: 2, // The offset of the elements (let them appear earlier or later). This can also be percentage based by adding a '%' at the end
    invertBottomOffset: true, // Add the offset as a negative number to the element's bottom
    repeat: false, // Add the possibility to remove the class if the elements are not visible
    callbackFunction: function(elem, action){
        $('.a.visible').addClass('invisible').removeClass('visible');
        setTimeout(function(){
            $('.a.invisible').addClass('visible').removeClass('invisible');
        },5000);
    }, // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
    scrollHorizontal: false
});

// For Class b
$('.b').viewportChecker({
    classToAdd: 'visible', // Class to add to the elements when they are visible
    classToRemove: 'invisible', // Class to remove before adding 'classToAdd' to the elements
    offset: 2, // The offset of the elements (let them appear earlier or later). This can also be percentage based by adding a '%' at the end
    invertBottomOffset: true, // Add the offset as a negative number to the element's bottom
    repeat: false, // Add the possibility to remove the class if the elements are not visible
    callbackFunction: function(elem, action){
        $('.b.visible').addClass('invisible').removeClass('visible');
        setTimeout(function(){
            $('.b.invisible').addClass('visible').removeClass('invisible');
        },5000);
    }, // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
    scrollHorizontal: false
});


Q:

How to pass a reference to a string in JavaScript?

Maybe a closure is my solution? Not exactly sure how to pull it off though.
The code is set up like so:
var globalVar = '';
var globalVar2 = '';

function func()
{
   if (condition)
     func2(globalVar)
   else
     func2(globalVar2)
}

In func2() I cache some HTML in a main container into the appropriate global variable that I pass to it. Basically I have a main container that holds different pages depending on what tab they choose. For performance I want to cache the page into global vars so I need to know what tab is active to figure out which global var to assign the HTML to.

A:

as globals are just properties of the window object in javascript, just pass "globalVar" or "globalVar2" and assign it using window[myvar] = ...


Q:

Show $\lim_{n\to \infty} 2^n-(2+\frac{1}{n})^n = -\infty$

Show:
$$\lim_{n\to \infty} a_n=-\infty, \qquad a_n=2^n-\left(2+\frac{1}{n}\right)^n$$
attempt.
$$2^n-\left(2+\frac{1}{n}\right)^n=2^n-2^n\left(1+\frac{1}{2n}\right)^n=2^n\left(1-\left(1+\frac{1}{2n}\right)^n\right)$$LEMMA: $(1+\frac{1}{2n})^n$ converges to some $\alpha >1$.
My struggle is with proving it.

A:

We don't have to fine the limit of $\left(1+\frac{1}{2n}\right)^n$.  Rather, we only need to show that there exists a number $C>1$, such that for every $n$, $\left(1+\frac{1}{2n}\right)^n>C$.  To that end, we proceed.

Using Bernoulli's Inequality, we have
$$\left(2+\frac1n\right)^n=2^n\left(1+\frac1{2n}\right)^n\ge \left(\frac32\right)\,2^n$$
Hence,
$$2^n-\left(2+\frac1n\right)^n\le -2^{n-1}$$
whence letting $n\to\infty$ yields the coveted limit.


Q:

MS Access running a funtion from scheduled task not working

I am trying to run a macro daily from the windows task scheduler (w8.1 for tesing and server 2012 in production - both have the same problem)
my .bat file:
C:\Batch\attrib.exe -r C:\...\db.mdb
rem ping 1.1.1.1 -n 1 -w 10000 > nul
"C:\Program Files (x86)\Microsoft Office 2003\OFFICE11\MSACCESS.EXE" "C:\...\db.mdb" /x "Launch"
ping 1.1.1.1 -n 1 -w 60000 > nul
C:\Batch\attrib.exe +r C:\...\db.mdb
Taskkill /F /IM MSACCESS.EXE

Launch is a macro which calls a function. The function works fine - it updates a mssql db so i can see when it has run successfully.
When the scheduled task starts i can see the ms access process start but it doesn't do anything (cpu 0%). The macro does not run. What am i doing wrong? Any help would be much appreciated - i just cant think what else to try
BTW this task used to run on windows server 2003 without issues (though i cannot say for sure if something has changed in the batch file or in the access db).

A:

When opening access i was getting security warning which required user confirmation. I changed the security level to low in tool->macros->security to make this go away and success.
On the server i had a different warning saying that the file is corrupt or badly closed. Still have not got round to fixing but shouldn't be too hard.
Conclusion:
Make sure Access can open the file with the appropriate user without warnings.


Q:

How to select a second div following any dom element?

how to give a float left attribute to the second div following the h3 ?

   this one !

A:

You can chain adjacent sibling selectors:

h3 + div + div {
  float: left;
  background: yellow;
}

h3 + div {
  display: inline-block;
}

not this

nor this

or this

but this one !

not this


Q:

Simple cryptography problem to be implemented in PHP

I need to implement a couple of functions which comply with the following:

function genKey: given a string q (this may be a MD5 or SHA hash) and a seed string, the function must generate a new string p
function checkKey: this function must return true if a string p was generated from string q (using the previous function)

In seudo-code the above would be something lie this:
p=genKey(q,seed) ; // generate string p from q and seed

checkKey(p,q)==true ; // if p was generated from q, then this must return true. False otherwise.

Does anyone know about existing algorithms that do such thing??
I can implement the algorithms myself if there are no known implementations for PHP, so what I'm really asking is for the procedure to accomplish this.

A:

It sounds like you might be trying to describe a MAC.
A message authentication code takes a message digest, a secret, and message. The secret and data are hashed together, and the result is included with the message.
A message recipient who knows the secret can perform the same digest computation, and compare his MAC to the one that accompanied the received message. If they are equal, he can trust that the message was not altered.

Given your comments, I understand now that you are working with asymmetric keys, rather than a secret key, which would be used in a MAC.
However, there's still a little confusion. Normally, a private signature key is kept secret by its owner, which in this case seems to be the client. A client can cryptographically prove that they possess a private key that corresponds to a public key without disclosing the private key.
Using digital signatures, you can do something like this:
p = genKey(pvt, seed)
checkKey(pub, p)

Here, pvt is the server's private key, pub is its public key. The seed parameter is the data that gets signed. If I understand your application (which I doubt), seed should be the client identifier. Then p is a message format that bundles seed and its signature together. Your question is confusing because q is used both generating and verifying p—like a shared secret.
However, there's nothing in this scheme (or in the MAC scheme) to stop one client from using another's value of p. All you can do with such a technique is to ensure that the message content has not been altered. For example, if the message is something like "clientID=Alice,IPAddress=192.168.1.1", you can make sure that Mallory didn't substitute his own IP address for Alice's.
But if the message is just "clientID=Alice", you can't stop Alice from giving Bob her tamper-proof message (in return for splitting the cost of a license), and you can't control whether Mallory hacks into Alice's box and steals the message.
By the way, if message integrity really is all you need, and you can easily share a secret between the sender and a receiver, MACs have some nice advantages over public-key cryptography, such as much smaller message size and faster performance.
Outline the threats you are trying to defend against. Cryptography is hard. Devising untried schemes usually ends badly.

A:

For this discussion let p == hash(q)
You could then easily use OpenSSL with php to sign 'p' with a private key and keep that signature along side 'p'.
It is then simple to use the OpenSSL verify function to check 'p' against the signature using the public key that is paired with your private key. In this case 'p' would be the data to verify.
See openssl_sign and openssl_verify for info and examples of using OpenSSL in php to sign and verify data:


Q:

ASP.NET MVC - HTML.BeginForm and SSL

I am encountering an issue with what should be a simple logon form in ASP.NET MVC 2. Essentially my form looks a little something like this:
using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm" }))

I have a RequiresHTTPS filter on the LogOn Action method but when it executes I receive the following message

The requested resource can only be
  accessed via SSL

At this point the only solution that worked was to pass in an extra action htmlattribute as follows:
 var actionURL = "https://"  + Request.Url.Host + Request.Url.PathAndQuery;
 using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm", @action = actionURL }))

While this works I wonder a) why i am seeing this issue in the first place and b) if there is a more straightforward way of posting to https from a http page?
[Edit]
I should have stated that the logon dropdown will be available on many public pages. I do not want all of my pages to be HTTPS. For instance, my hope page - which ANYONE can see - should not be HTTPS based. Essentially I need to specify the protocol in my form but have no idea how to do that, or if it is possible.
I would appreciate any advice/suggestions.
Thanks in advance
JP

A:

You could use
<form action =" <%= Url.Action(
"action",
"controller",
ViewContext.RouteData.Values,
"https"
) %>" method="post" >

A:

Use the [RequireHttps] attribute on both the action that renders the form and the one you are posting to.

A:

Update: Review the comments below about the security vulnerabilities of this approach before considering the use of this code.
I found that a hybrid of JP and Malcolm's code examples worked.
using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @action = Url.Action("Login","Account",ViewContext.RouteData.Values,"https") }))

Still felt a bit hacky though so I created a custom BeginForm helper.  The custom helper is cleaner and does not require https when running locally.
public static MvcForm BeginFormHttps(this HtmlHelper htmlHelper, string actionName, string controllerName)
    {
        TagBuilder form = new TagBuilder("form");
        UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext);

        //convert to https when deployed
        string protocol = htmlHelper.ViewContext.HttpContext.Request.IsLocal == true? "http" : "https";

        string formAction = Url.Action(actionName,controllerName,htmlHelper.ViewContext.RouteData.Values,protocol);
        form.MergeAttribute("action", formAction);

        FormMethod method = FormMethod.Post;
        form.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);

        htmlHelper.ViewContext.Writer.Write(form.ToString(TagRenderMode.StartTag));

        MvcForm mvcForm = new MvcForm(htmlHelper.ViewContext);

        return mvcForm;
    }

Example usage:
@using (Html.BeginFormHttps("Login", "Account"))


Q:

Cannot get HTML/CSS modal box to open up and display on page

Using JQuery I'm trying to let the user select an image that is displayed in on the html page using the below code. This is then displayed in the modal box via #badgeselect
At the moment the modal box is not being opened after the user clicks the image. It looks like it might be trying to place it on the actual main page and not in the modal box.
I can make the box appear successfully using
Demo Show

But I'm wondering if
$(this).width(100).height(100).appendTo('#badgeselect');

is the issue for it not working?
JQuery
$(document).ready(function() {
            $('.go img').css('cursor', 'pointer');
            $('.go').on('click', 'img', function(e) {
                $(this).width(100).height(100).appendTo('#badgeselect');

                $('#modal1').reveal({

                });
                return false;
            });
        });

Modal box

A modal

Content.

        <select id="selectFriend">
            <option>Select friend</option>
        </select>

        <textarea id="UploaderComment" rows="5" cols="30">Add a comment</textarea>

            Confirm

            Cancel

Footer

    ×

A:

I think you need to load the reveal modal to get the img in the modal popup
 $(document).ready(function() {
       $('.go img').css('cursor', 'pointer');
       $('.go').on('click', 'img', function(e) {

       $('#modal1').reveal({ }); return false;
        });
   $(this).width(100).height(100).appendTo('#badgeselect');
   });


Q:

concurrency issues with granite ds , flex

I use granite ds in my java server , but , when 100 user they're connected to flex application , granite return this error "Could not get channel id for message: flex.messaging.messages.RemotingMessage"
Thank for the help.

A:

This is not an error but just a warning issued by the AMF3Serializer class. It can happen, for example, when the server is sending data without explicitly using a declared channel.
You can safely ignore this warning: channel identification is only used in order to handle legacy (ie: old-fashion) serialization options (legacyCollection / legacyXMLDocument), see Adobe documentation about them here (the "Configuring AMF serialization on a channel" section).
It is very unlikely that you need to use these very specific serialization options. So, again, just ignore or disable this warning.


Q:

Commenting in rmarkdown/knitr to prevent R evaluation

The recommendation for commenting in .Rmd documents to use HTML commenting <!-- comment here --> is insufficient. I'd like to comment out a section of my document that includes inline evaluations:
I haven't defined `x` yet.

<!-- So when I say that `x` is `r x` in the text, I'd like to comment it out -->

Knitting this fails:
#   |.................................................................| 100%
#    inline R code fragments
#
#
#
#
# processing file: test.Rmd
# Quitting from lines 2-3 (test.Rmd)
# Error in eval(expr, envir, enclos) : object 'x' not found
# Calls: <Anonymous> ... in_dir -> inline_exec -> withVisible -> eval -> eval
# Execution halted

One option is to comment each inline section:
I haven't defined `x` yet.

So when I say that `x` is `r #x` in the text, I'd like to comment it out

But this suffers if I'd like to comment out a whole paragraph with several such inline calculations, for example. Is there a more canonical way of doing this?

A:

As @NicE said, knitr goes first to evaluate your code, in particular because there may be inline R code evaluation or other R variable dependent text, which then need to be evaluated as markdown syntax.
For instance, this included in rmarkdown:
Define if bold `r bold <- TRUE`
This text is `r ifelse(bold, "**bold**", "_italic_")`.

Gives:

Define if bold
  This text is bold.

Then, I think the only way to insert comments without evaluating them is to embed them in a chunk with eval=FALSE & echo=FALSE
```{r, eval=FALSE, echo=FALSE}
So when I say that `x` is `r x` in the text, I'd like to comment it out
```


Q:

Laravel check if updateOrCreate performed update

I have the following code in my controller:
for($i=0; $i<$number_of_tourists; $i++) {

$tourist = Tourist::updateOrCreate(['doc_number' => $request['doc_number'][$i]],
$tourist_to_update);

}

each time "updateOrCreate" works, it does 1 of 3 things:
1) updates model instanse OR
2) creates and saves a new one OR
3) leaves everything unchanged (if model with such values already exists).
I need to check if 'updateOrCreate' has done exactly 1 (updated) and then execute some code.
How can I do it?
Thank you in advance!

A:

You can figure it out like this:
$tourist = Tourist::updateOrCreate([...]);

if(!$tourist->wasRecentlyCreated && $tourist->wasChanged()){
    // updateOrCreate performed an update
}

if(!$tourist->wasRecentlyCreated && !$tourist->wasChanged()){
    // updateOrCreate performed nothing, row did not change
}

if($tourist->wasRecentlyCreated){
   // updateOrCreate performed create
}

Remarks
In Laravel 5.5 you can finally check if updates have actually taken place with the wasChanged and isDirty method.

isDirty() is true if model attribute has been changed and not saved.
wasChanged() is true if model attribute has been changed and saved.

There is also a property (not method!) wasRecentlyCreated to check if user was created or not.
$user = factory(\App\User::class)->create();

$user->wasRecentlyCreated; // true
$user->wasChanged(); // false
$user->isDirty(); // false

$user = \App\User::find($user->id);

$user->wasRecentlyCreated; // false
$user->wasChanged(); // false
$user->isDirty(); // false

$user->vorname = 'Max';

$user->wasChanged(); // false
$user->isDirty(); // true

$user->save();

$user->wasChanged(); // true
$user->isDirty(); // false

//You can also check if a specific attribute was changed:
$user->wasChanged('name');
$user->isDirty('name');

A:

It is pretty easy to determine if the function resulted in an update or an insert (check the wasRecentlyCreated property). However, when using that function, it is less easy to determine if the update actually happened (if the model exists but is not dirty, no update will be performed). I would suggest not using that function, and splitting out the functionality yourself.
This is the function definition:
public function updateOrCreate(array $attributes, array $values = [])
{
    $instance = $this->firstOrNew($attributes);

    $instance->fill($values)->save();

    return $instance;
}

To integrate this into your code, I'd suggest something like:
for ($i=0; $i<$number_of_tourists; $i++) {
    $tourist = Tourist::firstOrNew(['doc_number' => $request['doc_number'][$i]]);

    $tourist->fill($tourist_to_update);

    // if the record exists and the fill changed data, update will be performed
    $updated = $tourist->exists && $tourist->isDirty();

    // save the tourist (insert or update)
    $tourist->save();

    if ($updated) {
        // extra code
    }
}


Q:

Recognizing text as Simplified vs. Traditional Chinese

Given a block of text that's known to be Chinese and encoded in UTF-8, is there a way to determine if it's Simplified or Traditional?

A:

I don't know if this will work, but I'd try using iconv to see if it will translate between the charsets correctly, comparing the results from the same conversion with //TRANSLIT and //IGNORE. If the two results match, then the charset conversion hasn't encountered any characters that fail to translate, so you should have a match.
$test1 = iconv("UTF-8", "big5//TRANSLIT", $text);
$test2 = iconv("UTF-8", "big5//IGNORE", $text);
if ($test1 == $test2) {
   echo 'traditional';
} else {
   $test3 = iconv("UTF-8", "gb2312//TRANSLIT", $text);
   $test4 = iconv("UTF-8", "gb2312//IGNORE", $text);
   if ($test3 == $test4) {
      echo 'simplified';
   } else {
      echo 'Failed to match either traditional or simplified';
   }
}


Q:

Would cone shapes grills in front of jet engines prevent damage in case of a bird strike?

If cone shaped grills pointing forward were in front of jet engines would they make bird parts slide outside towards the back of the engine and away?

A:

No, that wouldn't work.
Kinetic energy is measured using the formula $\tfrac12mv^2$ . This means that the kinetic energy of a 4.5kg goose at 170 knots is about the same as a motorcycle at 30mph. At 400 knots that goose's kinetic energy is the same as a small car at 30mph. Remember that velocity in this case is not the speed of the goose but the speed of the airplane hitting it, any grill would have to be immensely strong to survive that kind of impact, meaning it would have to be thick and heavy. This will block airflow to the engine, which is a big problem. If the heavy, hard metal screen fails it will get sucked into the engine and cause far more damage than a soft, squishy bird.
One method for the mass production of french fries is to shoot potatoes at a mesh screen at high speed using a water cannon, when the potato hits the screen its speed forces it through, slicing the potato perfectly in a fraction of a second. A similar thing is going to happen to a bird which hits a screen in front of the engine, rather than being deflected it will simply be sliced and ingested into the engine anyway, or it could potentially be caught on the mesh of the grill and impede airflow further.


Q:

Logarithmic averages are bounded by arithmetic averages

I'm trying to prove that for a sequence $(a_n)$ of reals, we have $$\limsup_{n \to \infty} \frac{1}{\log n} \sum_{k = 1}^n \frac{a_k}{k} \leq \limsup_{n \to \infty} \frac{1}{n} \sum_{k = 1}^n a_k.$$
My attempt was to use $$\sum_{i = 1}^n \frac{1}{i} = \log n + \gamma + O \left( \frac{1}{n} \right),$$
as $n \to \infty$, but I didn't really see how I could get rid of the $a_k$'s.
Can anyone help me on that?
Thanks!

A:

Let $L = \limsup_{n\to \infty}\frac{1}{n}\sum_{k=1}^n a_k.$ Suppose $L\in \mathbb R.$ Let $\epsilon >0.$ Then there is $n_0\in \mathbb N$ such that for $n>n_0,$
$$\tag 1 \frac{1}{n}\sum_{k=1}^{n} a_k <L+\epsilon.$$
For $k=0,1,\dots,$ set $S_0=0, S_k = a_1 + \cdots + a_k, k = 1,2,\dots.$ Summing by parts, we have
$$\tag 2\sum_{k=1}^{n}\frac{a_k}{k} = \sum_{k=1}^{n}\frac{S_k-S_{k-1}}{k} = \frac{S_n}{n} + \sum_{k=1}^{n-1} \frac{S_k}{k(k+1)}.$$
For $n>n_0,$ $(1)$ then gives
$$\tag 3 \sum_{k=1}^{n} \frac{a_k}{k} = \frac{S_n}{n} + \sum_{k=1}^{n_0} \frac{S_k}{k(k+1)}+\sum_{k=n_0+1}^{n-1} \frac{S_k}{k(k+1)}$$ $$ \le L+\epsilon + \sum_{k=1}^{n_0} \frac{S_k}{k(k+1)}+(L+\epsilon)\cdot \sum_{k=n_0+1}^{n-1} \frac{1}{k+1}.$$
Now the last sum on the right is asyptotic to $\ln n$ as $n\to \infty.$ So dividing by $\ln n$ in $(3)$ and letting $n\to \infty$ gives
$$\tag 4 \limsup \frac{1}{\ln n}\sum_{k=1}^{n} \frac{a_k}{k} \le L+\epsilon.$$
Since $\epsilon$ was arbitrary, the left side of $(4)$ is $\le L$ as desired.
In the above we assumed $L\in \mathbb R.$ The case $L=\infty$ is obvious. I'll leave the case $L=-\infty$ to the reader for now.


Q:

How to convert collections to DataTable for Ado.Net SqlDataAdapter.Update?

How to finish the following function which accept three collection parameters for deleted, inserted and updated records and convert the collections to a DataTable for DataAdapter to update the table?
I found a way to convert List to DataTable at How to fill a datatable with List<T>. However, it doesn't set the insert, update and delete flags in DataTable?
void Save(
    IEnumerable<int> deleted,
    IEnumerable<Poco1> inserted,
    IEnumerable<Poco1> updated)
{
    var dt = new DataTable();
    .... // Initialize dt with deleted, inserted and update?

    using (var con = new SqlConnection(ConnectionStr))
    {
        con.Open();
        var da = new SqlDataAdapter("select * from table", con);
        da.Update(dt);
    }
}

Or is there a better way to update the database table from these three collections? (C# 3.5)

A:

First off, your going to want to also define the Insert, Update and Delete commands:
// Create the other commands.
da.InsertCommand = new SqlCommand("...how to insert");

da.UpdateCommand = new SqlCommand("...how to update");

da.DeleteCommand = new SqlCommand("...how to delete");

Alternatively you can try to use DbCommandBuilder to do it for you at runtime:
// Create the DbCommandBuilder.
DbCommandBuilder builder = factory.CreateCommandBuilder();
builder.DataAdapter = da;

// Get the insert, update and delete commands.
da.InsertCommand = builder.GetInsertCommand();
da.UpdateCommand = builder.GetUpdateCommand();
da.DeleteCommand = builder.GetDeleteCommand();

Next you need to define the DataTables to match the table you are targeting:
DataTable dt = new DataTable();
dt.Columns.Add(add your columns...)

Then you need to add rows to the DataTable, making sure to mark the row as inserted, updated or deleted.
DataRow dr = dt.NewRow();
dr["your column"] = ...
// Don't forget to add the row to the table!
dt.Rows.Add(dr);
// Once the row is added then go ahead and mark it as deleted, modified or new
dr.Delete()
// or
dr.SetAdded();
// or
dr.SetModified();


Q:

Java different return type in a function respect to the header method

I'm using ANTLR4 to parse my grammer and OWLAPI to work on ontologies. Since I'm using the Listener class I cannot modify the return type. Here an example:
public void exitSubConcept(Parser.SubConceptContext ctx) {
    OWLClassExpression first = stack.pop();
    OWLClassExpression second = stack.pop();
    OWLSubClassOfAxiom s = factory.getOWLSubClassOfAxiom(second, first);
    if(reasoner.isEntailed(s))
    {
        System.out.println(s.toString() + "is entailed");
    }
    else
    {
        System.out.println(s.toString() + "is NOT entailed");
    }
    super.exitSubConcept(ctx);
}

This is awful since the only thing I can return is a print, but I'm interested to provide a return type that is boolean (in this example), not just a print that I cannot manage.
There is no way to modify the return type void because the parser crashes, so do you have any particular suggestions to deal with this kind of situation?

A:

You can declare an instance boolean variable and use hasEntailed() to get the boolean value (I am using hasEntails for distinguish with the existing isEntailed() method)
private boolean entailed = false;

public boolean hasEntailed(){
    return entailed;
}

public void exitSubConcept(Parser.SubConceptContext ctx) {
    OWLClassExpression first = stack.pop();
    OWLClassExpression second = stack.pop();
    OWLSubClassOfAxiom s = factory.getOWLSubClassOfAxiom(second, first);
    if(reasoner.isEntailed(s))
    {
        System.out.println(s.toString() + "is entailed");
        entailed = true;
    }
    else
    {
        System.out.println(s.toString() + "is NOT entailed");
        entailed = false;
    }
    super.exitSubConcept(ctx);
}


Q:

How do I fix my while-loop and if conditionals in my guessAge(age) in Python?

Below is the description of an assignment I have. I have tried to figure out what I'm doing wrong, but every time I correctly input the number it will still say it's wrong and won't give me all six tries if I'm incorrect.
What am I doing wrong exactly?
Description:

Write a function that will have an age as a parameter and will ask the user to guess that age.
The user will have a maximum of 6 chances to guess (after the 6th try if it’s wrong let the user know he has exceeded the number of tries).
The user may quit the game whenever he wants by writing (QUIT, quit or Quit) instead of an age and you must tell him an encouraging message like: (Don't give up just because things are hard!).
If the user guesses the age correctly, tell him he did a great job and how many tries it took him to guess it.
No matter what happens, at the end of the game thank the user for playing.

Below is the code I have so far.
def guessAge(age):

    guess = input("Guess the Age") #This counts as one try.

    count = 1

    maxtries = 5

    quit = 'quit', 'QUIT', 'Quit'

    while maxtries != 0:

        if guess == age:
            count += 1
            print("Great Job! It took you", count, "try/tries to guess the age. Thank you for playing!")
            break

        if guess != age:
            count += 1
            maxtries -= 1
            fail = input("Try again. Guess the Age")

            if fail == quit:
                print("Don't give up just because things are hard! Thank  you for playing!")
            break
    print("You have exceeded the number of tries. Thank you for playing!")

A:

This is one way to do it:
def guess_age(age):
    count = 0
    max_tries = 6
    quit = ('quit', 'QUIT', 'Quit')

    while True:
        guess = input("Try to guess the age -->")
        count += 1
        max_tries -= 1

        if guess in quit:
            print("Don't give up that easy! Thank you for playing!")
            break
        elif guess == age:
            print("Great Job! It took you", count, "try/tries to guess the age. Thank you for playing!")
            break
        elif guess != age:
            print("Sorry, incorrect!")

        if max_tries == 0:
            print("You have exceeded the number of tries. Thank you for playing!")
            break

The main mistake you made is you accidentally broke (break) out of your second if statement; which should have, by the way, just been a if-elif or if-else.
EDIT: Also note how I named the "max_tries" variable. This is really just a preference thing, but "max_tries" is much more readable than "maxtries". Also, some people, like myself, prefer "guess_age", over "guessAge".


Q:

Redirect the person, who has already seen the page

I am looking for help for the following scenario:
I have a website1.com. I would like website1.com to be like a presentation page. I want every person who has seen the page to be redirected automatically to website2.com.
Another way to look at it:
Lets say the page on website1.com contains information, which would be irrelevant for the person, who has already seen it, therefore I want them to be redirect from the page to website2.com cause then i don't loose the visitor, since I own both of those sites.
From the prespective of the visitor:
I land on a website, which I have not visited yet, website1.com. However, if I have already been to website1.com in the past ( cookie registers it ) , then i am redirected to website2.com
Hope how i broke it down is clear for everybody.
Thank you in advance for the help.

A:

If you are using PHP, you could do it that way at the begining of your page:
 <?php
     if (!isset($_COOKIE['myCookie'])){
        setcookie('myCookie', true, time() + (86400 * 30));
     }
     else{
       header('Location: http://www.website2.com');
     }
 ?>

If you are not using PHP, your serverside language surely have a way to set cookie and the logic will be the same. Hope it helped


Q:

Applying diff on selected rows for comparing angles from math.atan2

I have a data frame like this that want to apply diff function on:
test = pd.DataFrame({ 'Observation' : ['0','1','2',
                         '3','4','5',
                         '6','7','8'],
                  'Value' : [30,60,170,-170,-130,-60,-30,10,20]
            })

Observation Value
0   30
1   60
2   170
3   -170
4   -130
5   -60
6   -30
7   10
8   20

The column 'Value' is in degrees. So, the difference between -170 and 170 should be 20, not -340. In other words, when d2*d1 < 0, instead of d2-d1, I'd like to get 360-(abs(d1)+abs(d2))
Here's why I try. But then I don't know how to continue it without using a for loop:
test['Value_diff_1st_attempt'] = test['Value'].diff(1)
test['sign_temp'] = test['Value'].shift()
test['Sign'] = np.sign(test['Value']*test['sign_temp'])

Here's what the result should look like:
Observation Value Delta_Value
0   30   NAN
1   60   30
2   170    110
3   -170   20
4   -130   40
5   -60    70
6   -30   30
7   10   40
8   20   10

Eventually I'd like to get just the magnitude of differences all in positive values. Thanks.
Update: So, the value results are derived from math.atan2 function. The values are from 0<theta<180 or -180<theta<0. The problem arises when we are dealing with a change of direction from 170 (upper left corner) to -170 (lower left corner) for example, where the change is really just 20 degrees. However, when we go from -30 (Lower right corner) to 10 (upper right corner), the change is really 40 degrees. I hope I explained it well.

A:

I believe this should work (took the definition from @JasonD's answer):
test["Value"].rolling(2).apply(lambda x: 180 - abs(abs(x[0] - x[1]) - 180))
Out[45]:
0      NaN
1     30.0
2    110.0
3     20.0
4     40.0
5     70.0
6     30.0
7     40.0
8     10.0
Name: Value, dtype: float64

How it works:
Based on your question, the two angles a and b are between 0 and +/-180. For 0 < d < 180 I will write d < 180 and for -180 < d < 0 I will write d < 0. There are four possibilities:

a < 180, b < 180 -> the result is simply |a - b|. And since |a - b| - 180 cannot be greater than 180, the formula will simplify to a - b if a > b and b - a if b > a.
a < 0, b < 0 - > The same logic applies here. Both negative and their absolute difference cannot be greater than 180. The result will be |a - b|.
a < 180, b < 0 - > a - b will be greater than 0 for sure. For the cases where |a - b| > 180, we should look at the other angle and this translates to 360 - |a - b|.
a < 0, b < 180 -> again, similar to the above. If the absolute difference is greater than 180, calculate 360 - absolute difference.

For the pandas part: rolling(n) creates arrays of size n. For 2: (row 0, row1), (row1, row2), ... With apply, you apply that formula to every rolling pair where x[0] is the first element (a) and x[1] is the second element.


Q:

Proof verification - Cauchy completeness of $\mathbb{R}$

Let $(x_n)$ be a Cauchy sequence in $\mathbb{R}$. We want to show that $(x_n)$ converges in $\mathbb{R}$. I'm presenting my proof below. I've used standard $\epsilon-N$ technique, triangle inequality and Bolzano-Weierstrass theorem. I think that this scheme, while keeping it intuitive, has lengthened the proof considerably. I'd appreciate if anyone checks the proof, whether or not there is any hole in it (I checked, but still) and most importantly, if you can suggest me some other scheme to attack the problem, which may give us a quick and short proof. Thank you.

Let $\epsilon>0$. Since $(x_n)$ is Cauchy, there exists $N=N(\epsilon) \in \mathbb{N}$ such that
$$m,n \geq N \implies |x_n-x_m|<\frac{\epsilon}{3}$$
In particular, choosing $m=N$, we have
$$n \geq N \implies |x_n-x_N|<\frac{\epsilon}{3}$$
It is clear that, for all $n \in \mathbb{N}$,
$$\min\{x_1,\ldots,x_{N-1},x_N-\frac{\epsilon}{3}\} \leq x_n \leq \max\{x_1,\ldots,x_{N-1},x_N+\frac{\epsilon}{3}\}$$
Hence the sequence $(x_n)$ is bounded. So we are in a position to employ the powerful Bolzano-Weierstrass theorem. There exists a subsequence $(x_{n_k})$ that converges in $\mathbb{R}$. Let $x_{n_k} \to x$ as $k \to \infty$. Hence, there exists $K_1 \in \mathbb{N}$ such that
$$k \geq K_1 \implies |x_{n_k}-x|<\frac{\epsilon}{3}$$
This gives us a point $x$ of attack, a "guesstimate" for where the sequence $(x_n)$ might converge. Now, there exists $K_2 \in \mathbb{N}$ such that
$$k \geq K_2 \implies n_k \geq N \implies |x_{n_k}-x_N|<\frac{\epsilon}{3}$$
Choose $K_0=\max\{K_1,K_2\}$. Then in particular,
$$|x_{n_{K_0}}-x|<\frac{\epsilon}{3},\,\,\,\,|x_{n_{K_0}}-x_N|<\frac{\epsilon}{3}$$
Finally, We combine all these estimates by triangle inequality to write
$$n \geq N \implies |x_n-x| \leq |x_n-x_N|+|x_N-x_{n_{K_0}}|+|x_{n_{K_0}}-x|<\frac{\epsilon}{3}+\frac{\epsilon}{3}+\frac{\epsilon}{3}=\epsilon$$
Since $\epsilon>0$ is chosen arbitrarily, the sequence $(x_n)$ converges to $x$. Hence the proof.

A:

It looks fine to me. Here's an alternative (though similar) approach, by splitting the problem into parts.

Lemma. A real Cauchy sequence is bounded.

Proof. Let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. By hypothesis, there exists $n_0 \in \mathbb{N}$ such that if $n, m \geq n_0$ then $|x_n -x_m| < 1$. Therefore,
$$
|x_n| \leq |x_n-x_{n_0}| + |x_{n_0}| \leq 1 + |x_{n_0}|
\quad (\forall n \geq n_0)
$$
so $|x_n| \leq 1 + \max_{1 \leq i \leq n_0}|x_i|$ for all $n$.

Lemma: let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. If  $\{x_n\}_{n \geq 1}$ has a convergent subsequence, it is convergent.

Proof. By hypothesis, there exists a convergent subsequence $x_{n_k} \to x$. Now, I claim that:
$$
|x_k -x| \leq |x_k - x_{n_k}| + |x_{n_k} - x| \to 0
$$
Since $x_{n_k} \to x$, we only have to note that $|x_k - x_{n_k}| \to 0$. In effect, if $\varepsilon > 0$, there exists $K \in \mathbb{N}$ such that $n,m > K$ implies $|x_n - x_m| < \varepsilon$. Now if $k \geq K$, we have that $n_k \geq  k \geq K$ and thus $|x_k - x_{n_k}| < \varepsilon$. Therefore, $x_k \to x$ as claimed.
Finally, we can prove the original statement.

Theorem: $\mathbb{R}$ is complete.

Proof. Let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. By the first lemma, the sequence is bounded. Thus, the Bolzano-Weierstraß theorem guarantees the existence of a convergent subsequence. By the second lemma, this implies that $\{x_n\}_{n \geq 1}$ itself is convergent, which completes the proof.


Q:

Sorting Poker Ranks

The Ranks of Poker are 2345..9TJQKA
Given an array of cards String s[] = {"Qh", "Jd", "2h"}.
I want to get back
s[] = {"2h", "Jd", "Qh"}
Here's my code:
         Arrays.sort(s, new Comparator<String>() {
        @Override
        public int compare (String s1, String s2) {
            int v1 = (int) s1.charAt(0);
            int v2 = (int) s2.charAt(0);
            if (v1 == 65) v1 = 100; //changes the value of A
            if (v2 == 65) v2 = 100;
            if (v1 == 75) v1 = 85; //changes the value of K
            if (v2 == 75) v2 = 85;
            if (v1 == 84) v1 = 60;
            if (v2 == 84) v2 = 60; //changes the value of T
            return v1 - v2;
        }
    }

It leaves the array unchanged.

A:

I tested your code using the following:
import java.util.*;

public class test {
   public static void main(String... args) {
      String s[] = {"Qh", "Jd", "2h"};
      Arrays.sort(s, new Comparator<String>() {
         @Override
         public int compare (String s1, String s2) {
            int v1 = (int) s1.charAt(0);
            int v2 = (int) s2.charAt(0);
            if (v1 == 65) v1 = 100; //changes the value of A
            if (v2 == 65) v2 = 100;
            if (v1 == 75) v1 = 85; //changes the value of K
            if (v2 == 75) v2 = 85;
            if (v1 == 84) v1 = 60;
            if (v2 == 84) v2 = 60; //changes the value of T
            return v1 - v2;
         }
      });
      for (String card : s) {
         System.out.println(card);
      }
   }
}

It prints:
2h
Jd
Qh

It worked for me, so maybe the problem is in the way you're invoking/using your sorting routine


Q:

Simplification of complex expressions

The other day I wanted to simplify a following expression:
a Conjugate[a]//FullSimplify

Great! The answer we receive is Abs[a]^2.
Now I tried something like this:
a b Conjugate[a]//FullSimplify (*a Conjugate[a] b will return the same output*)

Unfortunatelly it wasn't simplified. LeafCount prefers the unsimplified expression over Abs[a]^2 b. ComplexityFunction should be able to fix this:
ComplexityFunction
I used the function presented in the link above:
f[e_] := StringLength[ToString[InputForm[e]]]
FullSimplify[a Conjugate[a] b, ComplexityFunction -> f]

And I still get the unwanted form.
Is there a workaround for this?

A:

I just learned this from my question here at StackExchange. You can do it like this:
f[expr_]:=expr/.x_*Conjugate[x_]:>Abs[x]^2
Simplify[a Conjugate[a] b,TransformationFunctions->{Automatic,f},ComplexityFunction->(StringLength[ToString[InputForm[#]]]&)]

it will give b Abs[a]^2.


Q:

Android go to next page

Im new to Android and I have created an app with 2 basic pages.
I am trying to work out how to go to the second page.
I have set the listener in the XML file, but do not know the command to make it go to the next page. My code is as follows:
public class Page2 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page2);
    }

    public void sendMessage(View view) {

    }
}

A:

From one Activity to another activity you can use Intent:
Intent intent = new Intent(this, YourActivity.class);
        startActivity(intent);


Q:

Installing oracle 11g on windows 7, why getting errors?

While installing Oracle 11g on windows 7, I get these errors:
Checking operating system requirements ...
Expected result: One of 5.0,5.1,5.2,6.0
Actual Result: 6.1
Check complete. The overall result of this check is: Failed <<<<
Problem: Oracle Database 11g is not certified on the current operating system.
Recommendation: Make sure you are installing the software on the correct platform.
========================================================
Checking service pack requirements ...
Check complete. The overall result of this check is: Not executed <<<<
OUI-18001: The operating system 'Windows Vista Version 6.1' is not supported.
Recommendation: Install the recommended Service Pack.
========================================================
Checking Network Configuration requirements ...
Check complete. The overall result of this check is: Failed <<<<
Problem: The install has detected that the primary IP address of the system is DHCP-assigned.
Recommendation: Oracle supports installations on systems with DHCP-assigned IP addresses; However, before you can do this, you must configure the Microsoft LoopBack Adapter to be the primary network adapter on the system.  See the Installation Guide for more details on installing the software on systems configured with DHCP.
========================================================
Checking Oracle Home path for spaces...
Check complete. The overall result of this check is: Failed <<<<
Problem: The Oracle Home you have specified contains spaces ( ) in the path.
Recommendation: You must choose an Oracle Home path that doesn't contain any spaces.
========================================================

How can I fix these issues?

A:

It looks like the errors below are fairly clear but have added a few points below each one which may help you.

Recommendation: Make sure you are
installing the software on the correct
platform.
Recommendation: Install the
recommended Service Pack.

For both of these recommendations, make sure you have the latest service packs installed on windows 7. I also found this post which may be useful to you. It says:

Oracle 11g works like a champ on Win7.
During the install, when you get that
error regarding Windows Vista 6.1, you
will see a small check box next to the
error message. Simply check the box
next to the error. It will designate
the error as "User Verified". Then you
can continue your install.
Problem solved.

Next

Recommendation: Oracle supports
installations on systems with
DHCP-assigned IP addresses; However,
before you can do this, you must
configure the Microsoft LoopBack
Adapter to be the primary network
adapter on the system. See the
Installation Guide for more details on
installing the software on systems
configured with DHCP.

Either set a static IP address on your NIC(Control Panel->Network & sharing centre->change adapter settings->properties) or follow the advice above to setup the loopback adapter. Personally I would go for a static IP but make sure you know or find out the right IP to use otherwise there will be conflicts.

Recommendation: You must choose an
Oracle Home path that doesn't contain
any spaces.

Install it to a directory with no spaces(maybe create d:\oracle etc.) I would always try and keep oracle off the same drive as the operating system.
Good luck


Q:

What is the best way to handle errors in Combine?

I am trying to decode the downloaded JSON into a structure with the following code.
static func request(url: URL) -> AnyPublisher<SomeDecodableStruct, Error> {
    return URLSession.shared.dataTaskPublisher(for: url)
        .map { $0.data }
        .decode(type: SomeDecodableStruct.self, decoder: JSONDecoder())
        .eraseToAnyPublisher()
}

However, if processing fails, I would like you to return information on whether the request processing failed or the decoding processing failed.
Therefore, I defined the FailureReason enum that conforms to the Error protocol as follows.
enum FailureReason : Error {
    case sessionFailed(error: URLError)
    case decodingFailed
}

static func request(url: URL) -> AnyPublisher<SomeDecodableStruct, FailureReason> {
    // ???
}

How do I define a request(url:) that satisfies this FailureReason?

A:

Combine is strongly typed with respect to errors, so you must transform your errors to the correct type using mapError or be sloppy like RxSwift and decay everything to Error.
enum NetworkService {
  enum FailureReason : Error {
      case sessionFailed(error: URLError)
      case decodingFailed
      case other(Error)
  }

  static func request<SomeDecodable: Decodable>(url: URL) -> AnyPublisher<SomeDecodable, FailureReason> {
    return URLSession.shared.dataTaskPublisher(for: url)
      .map(\.data)
      .decode(type: SomeDecodable.self, decoder: JSONDecoder())
      .mapError({ error in
        switch error {
        case is Swift.DecodingError:
          return .decodingFailed
        case let urlError as URLError:
          return .sessionFailed(error: urlError)
        default:
          return .other(error)
        }
      })
      .eraseToAnyPublisher()
  }
}


Q:

Why no gui option to open a program as root?

Just wondering why there is no option in Ubuntu's desktop environment to open a program, for example Nautilus, as root. I know that I can accomplish this in the terminal, but wouldn't it benefit the Ubuntu's usability to allow this to be done by simply right clicking on a program?

A:

Because that is not the intended usage of Nautilus manager.  It is intended to manage user related files. Like your documents.
Because we do not use a "root" account and editing files with your admin account (aka. "sudo") will change the permissions and then break stuff. Famous files are .xsession-errors and .XAuthority in your home. If those change into anything else than what they currently are (rw- --- --- and owned by $USER:$USER) you can no longer log into the desktop.
Editing files you need to edit as a admin you should really do from command line. The occasional gksudo nautilus or even gksudo gedit might be useful but should not become common. It will at some point break stuff and that almost always happens when you least expect it and at the worst time.


Q:

Missing return type on function.eslint@typescript-eslint/explicit-module-boundary-types

como esta?
Tengo este pequenio error del linter, este es mi codigo:
class DataServices {
       constructor() {
  // ...
  }

     getProperty = (obj: any, key: string | number) => obj[key];

     getMessage = () => allJson;

    }

Ambas funciones me devuelve este  error del linter
No se que hacer segun la documentancion  me dice colocar un return pero me siguen dando el mismo problema

A:

No es un problema de que tengas que poner un return. Te dice que no has puesto el tipo de dato que retorna. Como no sé el que usas concretamente, voy a poner any, pero es mejor especificar para dar más robustez al código:
getProperty = (obj: any, key: string | number): any => obj[key];

getMessage = (): any => allJson;


Q:

How can I template my Pod definition with the Jenkins kubernetes plugin?

I am using the Jenkins kubernetes plugin to run pipeline builds:
pipeline {
  agent {
    kubernetes {
      label 'kind'
      defaultContainer 'jnlp'
      yaml """
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: dind
...

I want to template a particular field of the yaml with an integer between 0 and 5 that is rotated in a round robin fashion (i.e. first build is templated with 0, second build templated with 1 etc. and goes back to 0 again after 4).
How can I achieve this?

A:

You can use podTemplates next code is from https://github.com/jenkinsci/kubernetes-plugin, you can use variables to prepare any kind of pods you need.
If this is not what you need, can you provide an example of what you are trying to do?
def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(label: label, containers: [
  containerTemplate(name: 'maven', image: 'maven:3.3.9-jdk-8-alpine', ttyEnabled: true, command: 'cat'),
  containerTemplate(name: 'golang', image: 'golang:1.8.0', ttyEnabled: true, command: 'cat')
]) {

node(label) {
    stage('Get a Maven project') {
        git 'https://github.com/jenkinsci/kubernetes-plugin.git'
        container('maven') {
            stage('Build a Maven project') {
                sh 'mvn -B clean install'
            }
        }
    }

    stage('Get a Golang project') {
        git url: 'https://github.com/hashicorp/terraform.git'
        container('golang') {
            stage('Build a Go project') {
                sh """
                mkdir -p /go/src/github.com/hashicorp
                ln -s `pwd` /go/src/github.com/hashicorp/terraform
                cd /go/src/github.com/hashicorp/terraform && make core-dev
                """
            }
        }
    }

}

}


Q:

How to schedule a task,remote access and re-run of an executable

He is my dilemma, I hope someone out there has done this…
Any views or Ideas are welcome. I am new to this are so be gentle..
I have PC A that needs to have a programX (.exe) running on a regular basis every 2 Mins this checks for another file and process the file if present.
On PC B I need to be able to stop and start the program as and when on PC A remotely.
Also programX is not allowed to re-run/recheck the existence of the file until the old programX has finished.
Both PCs are running Windows 7. (This will also be used on a couple of XP machines.)
Question 1
How do I get the .exe to run every 2 Mins? (Task scheduler only does once daily and I don’t want to have 576 tasks)
Question 1.1
How do I get the .exe to start and stop remotely?
Question 1.2
How do I get the system to recognise that programX is already running and not finished?

A:

Question 1:
I think you'd better write a service (always active) that runs a method programmatically using (for example) a timer.
Question 1.1:
If app on PC A exposes a class via remoting, from PC B you can run a Start() and Stop() method directly on PC A.
Using remoting you can create a main app (called server) which exposes a class (usually using interfaces) that can be accessed remotely via TCP/UDP/Pipes from localhost or internet.
Take a look at this example: this is only the first I've found searching "C# remoting example" in Google, but you can find hundreds.
For your need, service on PC A (see question 1) could expose via remoting a class that can start/stop the other application you run on PC A.
Question 1.2:
On PC A you could use a mutex (for example)


Q:

Cross-reference to the next section, whatever it is

Some sections of my document start with a remark such as the following: "This section may be omitted at the first reading."
I'd like to add to this text a (hypertext) reference to the next section (page) number and I can do it by labeling the next section (\label{sec:next}) and make use of \ref{sec:next} and/or \pageref{sec:next}. But, because the sec:next label is hard coded, the reference could be wrong in case of changes in the order of the sections.
Hence my question: is there a way to refer to the next section, whatever it is?

A:

We have to setup a \label that will be evaluated at the next \section command.
So I patch \@sect to add a \label command to its argument #8 (which refers to the main section title), which is evaluated only if the command has been called by \section and a \nextsection command has been issued. Also \section and \subsection need to be patched, because they both use \@sect for typesetting the title. The argument to \label is automatically generated via a counter.
Note that the patches must be made before hyperref is loaded.
\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newif\if@nextsection
\newif\if@section
\newcounter{ns@count}
\newcommand{\nextsection}{%
  \global\@nextsectiontrue
  \stepcounter{ns@count}%
  \xdef\@nstemp{ns@@\thens@count}%
  \ref{ns@@\@nstemp}%
}

\patchcmd{\@sect}
  {#8}
  {#8%
   \if@section\if@nextsection
     \label{ns@@\@nstemp}\global\@nextsectionfalse
   \fi\fi}
  {}{}
\preto\section{\global\@sectiontrue}
\preto\subsection{\global\@sectionfalse}
\makeatother

%%% hyperref should go after the patch, if used
\usepackage{hyperref}

\begin{document}
\section{TL;DR}

This section is long, go to section~\nextsection.

\subsection{A}

\newpage

\section{THIS IS IT}\label{foo}

\newpage

\section{Again TL;DR}
Check if it works \ref{foo}; now go to section~\nextsection.

\newpage

\section{Another}
\end{document}

A:

This answer has been EDITED to work for the next section, the next subsection, as well as the next subsubsection.
In essence, rather that try to invoke a label in one place meant to apply to a subsequent report section, it makes more sense to me to create macros \nextsection, \nextsubsection, and \nextsubsubsection in which the next [[sub]sub]section number is computed based on the current [[sub]sub]section number.  It will, however, require you to know in advance whether the next sectioning unit entity is a section, a subsection, or a subsubsection.
\documentclass{article}
\newcounter{nextsec}
\newcommand\nextsection{%
  \setcounter{nextsec}{\thesection}%
  \stepcounter{nextsec}%
  \thenextsec%
}
\newcommand\nextsubsection{%
  \setcounter{nextsec}{\expandafter\parsesub\thesubsection\relax}%
  \stepcounter{nextsec}%
  \thesection.\thenextsec%
}
\newcommand\nextsubsubsection{%
  \edef\tmp{\thesubsubsection}%
  \setcounter{nextsec}{\expandafter\parsesubsub\tmp\relax}%
  \stepcounter{nextsec}%
  \thesubsection.\thenextsec%
}
\def\parsesub#1.#2\relax{#2}
\def\parsesubsub#1.#2.#3\relax{#3}
\begin{document}

\section{First Section\label{s:first}}

This is section \ref{s:first}.  The following section is \nextsection,\\
but the next subsection is \nextsubsection.

\subsection{A subsection\label{s:firstsub}}

This is subsection \ref{s:firstsub}.  The following subsection is \nextsubsection.

\subsection{Next subsection}

\section{Next Section}

The next subsubsection will be \nextsubsubsection.

\end{document}


Q:

How to dissect/parse 'that could not otherwise have been obtained without'?

Source: R. v. Tessling, 2004, Supreme Court of Canada, by Justice Ian Binnie

1                               On this point, as well, we part company with the U.S. Supreme Court majority in Kyllo insofar as Scalia J. declined to distinguish among types of information relating to the home.  He declares that “[i]n the home, our cases show, all details are intimate details, because the entire area is held safe from prying government eyes” (p. 37).  This view seems to be predicated on the “originalism” philosophy of Scalia J. for he writes (at pp. 34-35):

We think that obtaining by sense-enhancing technology any information regarding the interior of the home [1.] that could not otherwise have been obtained without physical “intrusion into a constitutionally protected area,” Silverman, 365 U.S., at 512, constitutes a search _ at least where (as here) the technology in question is not in general public use.

Sequences of negative words still smother my reading comprehension. So please explain and show all steps and thought processes? Do all negative words in the bolded phrase lie within each other's scope? Then, am I right to pair and eliminate instantly not and without?
Finally, can I just replace them with WITH ?
2. obtaining ...  information  ... that could not otherwise have been obtained WITH without ... intrusion
Now otherwise seems redundant? What are the similarities and differences between 2 and 3?
3. obtaining ...  information ... that could otherwise have been obtained WITH  ... intrusion

A:

To answer the title, the bolded phrase could be recast as
[4.] "that could only have otherwise been obtained with".
The meaning being conveyed is that the information in question could only be obtained in one of two ways: 1) "physical intrusion" (PI) and 2) "sense-enhancing technology" (SET).  The purpose, presumably, is to make the case that the same constitutional protections that apply to 1) should also be applied to 2), because they serve the same practical function.
Neither of your reparsings are exactly correct.  #2 is not an incorrect statement (sorry for the double negative), but is not equivalent to the original statement because it does not eliminate the possibility of there being other methods of obtaining the information in question.  That is to say, the information could be gained by PI or SET, but also by other means.
Likewise for #3, which has the same meaning as #2.  Between #2 and #3, the "otherwise" is redundant: it is implied by the fact that SET is not the same as PI.
However, "otherwise" is necessary in the original statement (and my reparsing 4 above). otherwise means 'without SET'. Without otherwise, the statement would be technically nonsensical.  It makes no sense to say (roughly):
 "obtaining information via SET that could not have been obtained without PI".
 If the information could not be obtained without PI, then there would be no other way to obtain it.
But clearly SET is another way.

A:

We think that obtaining by sense-enhancing technology any information regarding the interior of the home [1.] that could not otherwise have been obtained without physical “intrusion into a constitutionally protected area,” Silverman, 365 U.S., at 512, constitutes a search _ at least where (as here) the technology in question is not in general public use.

Simplifying the sentence
Let's make this sentence a bit easier to understand. We don't really need the phrase "We think that" here. We can also delete the reference: "Silverman, 365 U.S., at 512,". That phrase at the end, "at least where ... use", just defines some aspects of the sentence. We can delete that too. This leaves us with:

Obtaining by sense-enhancing technology any information regarding the interior of the home that could not otherwise have been obtained without physical intrusion into a constitutionally protected area constitutes a search.

To make the sentence clear it might help to identify the subject, verb and complement.

Subject: Obtaining by sense-enhancing technology any information regarding the interior of the home that could not otherwise have been obtained without physical intrusion into a constitutionally protected area
Verb: constitutes
Complement: a search.

Simplifying the Subject
We can make the subject a bit easier to understand. sense-enhancing technology is a bit long. Let's call it SET.
Information regarding the interior of the home, just means information about the inside of people's houses. Let's replace that long phrase with the short phrase home information.
The constitutionally protected area means a house. People's houses are protected by the law. They are private and the police need special procedures to go into people's private  homes. Physical intrusion means physically going into somewhere. Let's replace "physical intrusion into a constitutionally protected area" with "going into people's houses".
This gives us:

[Obtaining, by SET, home information -  that could not otherwise have been obtained without going into people's houses]  - constitutes a search.

The subject of this sentence is a clause. We can break it down like this:

Verb: Obtaining
Object: home information that could not otherwise have been obtained without going into people's houses
Adjunct: by sense-enhancing-technology

The Object is a long noun phrase. The head of the phrase is the noun information.
 There is a relative clause modifying our understanding of the information:

that could not otherwise have been obtained without going into people's houses

The greyed relative clause
This greyed relative clause is difficult to understand. It has a double negative in it. It also has the word otherwise, which introduces a conditional idea.
The double negative is cause by using the words not and without in the same phrase. If we use not without in a sentence, it has the same meaning as only with or only by. Consider the following sentence:

I can't open it without a key

This has the same meaning as :

I can only open it with a key.

Similarly the following pairs of sentences mean the same thing:

I don't drink coffee without milk =  I only drink coffee with milk.
You can't make an omelet without breaking eggs = You can only make an omelet by breaking eggs.

So the greyed relative clause here means:

that could only otherwise have been obtained by going into people's homes.

The word otherwise means "without X". There is no grammatical rule to tell us what X is in a sentence. We need to understand from the context. In this sentence X means sense-enhancing technology. The word otherwise can go after the auxiliary verb. We need to put the preposition phrase without sense-enhancing technology at the beginning or end of the clause. So the relative clause means:

that, without sense-enhancing technology, could only have been obtained by going into people's homes

The sentence
The whole sentence therefore means:

Obtaining, by SET, home information  - which without SET could only have been obtained by going into people's homes - constitutes  a search.

That bit at the front is a bit clunky. The phrase Obtaining by SET just means Using SET to get. Let's see how that reads:

Using SET to get home information - which without SET could only have been obtained by going into people's homes - constitutes  a search.

This should be a bit more straightforward to understand. The OP asks whether these three negations not, otherwise and without cancel each other out. The answer is almost, but not quite. Not not usually cancels itself out in standard English.
So I do not not drink coffee just means I do drink coffee.
However, not without still gives an extra meaning. It still gives the meaning only with.
So I don't drink coffee without milk doesn't just mean that I drink coffee with milk. It means I only drink coffee with milk. The only meaning in the original example is crucial. The authors' point  is that when the police use SET to get private information about peoples homes, this is a breach because this information can usually only be obtained by searching people's houses. Now, if there were other ways of getting this information apart from going into people's houses, then using SET in this way would not constitute a search. So the fact that a physical search is the only other method is crucial here. The otherwise is not canceled out either. It is an adjunct and does not change the polarity of the main sentence.
Hope this is helpful!


Q:

Plot time series data (wide format)

I have a merged dataframe in R Studio like follows:
head(my_df)
     Year        Month.x      val1       Month.y        val2
     2005-01     January     22.43099    January        26.3339814993271
     2005-02     February    26.62969    February       30.8841743766816
     2005-03     March       31.67926    March          27.9245803297443
     2005-04     April       23.65202    April          30.9088206490251
     2005-05     May         25.39969    May            26.494307897712
     2005-06     June        20.30036    June           18.9395527997218

The year column contains data from January 2005 - December 2015. There was one "NA" in val2 column in data frame but I fixed it with:
my_df[is.na(my_df)] <- ""

I need to plot this time series data (val1 and val2 against year) in R. Initially, I am trying to plot val1 versus year using R base graphics:
plot(my_df$Year, my_df$val1, type = "b", col = "blue", xlim=c(2005, 2015),
     lwd=1, pch = 1, cex = 0.2, xlab="Year", ylab="Value")

but I see a blank graph with this warning.
Warning message:
In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion

Can anyone help me to figure out where things are messed up? How can I resolve this problem anyways.
EDIT1:
As suggested by @Santosh, dput(my_df) is here:
structure(list(Year = c("2005-01", "2005-02", "2005-03", "2005-04",
"2005-05", "2005-06", "2005-07", "2005-08", "2005-09", "2005-10",
"2005-11", "2005-12", "2006-01", "2006-02", "2006-03", "2006-04",
"2006-05", "2006-06", "2006-07", "2006-08", "2006-09", "2006-10",
"2006-11", "2006-12", "2007-01", "2007-02", "2007-03", "2007-04",
............
"2014-11", "2014-12", "2015-01", "2015-02", "2015-03", "2015-04",
"2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10",
"2015-11", "2015-12"),  Month.x = c("January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
.............
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"), val1 = c(22.4309863561828,
26.629689578869, 31.6792564287634, 23.6520192347222, 25.3996868508065,
20.3003602638889, 20.2621707795699, 22.3685403172043, 30.7087719888889,
..........
13.8973171652778, 11.3131837150538, 13.2869582405914, 16.4443315347222,
17.5448029758065, 22.8475848819444, 15.2890522220727), Month.y = c("January",
"February", "March", "April", "May", "June", "July", "August",
............
 "July", "August", "September", "October", "November", "December"
), val2 = c("26.3339814993271", "30.8841743766816", "27.9245803297443",
"30.9088206490251", "26.494307897712", "18.9395527997218", "21.9441695597826",
..........
"18.3722117002688", "17.8116471652778", "19.684253344086", "25.0107780152778",
"20.6051117175464")), .Names = c("Year", "Month.x", "val1",
"Month.y", "val2"), row.names = c(NA, -132L), class = "data.frame"

EDIT2:
Removing xlim(2005, 2015) from plot function also yields error:
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

A:

Here is solution how you can filter out NA cases and plot your data:

Select columns you will use
Transform Year string into a date
Transform data from wide to long format
Filter out NA cases
Plot using ggplot2

tidyverse package loads all the packages you need here (e.g. dplyr or ggplot2)
library(tidyverse)

my_df %>%
    select(Year, val1, val2) %>%
    mutate(Year = as.Date(paste0(Year, "-01"))) %>%
    gather(val, value, -Year) %>%
    filter(complete.cases(.)) %>%
    ggplot(aes(Year, value, color = val)) +
        geom_line()


Q:

Stacked bar chart from JSON file - seems to be ignoring a value

Pretty new to this stuff, so any help is greatly appreciated. To start off with, here is my JSON file's contents:
[
  {
    "drg": "NONSPECIFIC CEREBROVASCULAR DISORDERS W MCC",
    "approved": 124,
    "denied": 38
  },
  {
    "drg": "SEIZURES WO MCC",
    "approved": 138,
    "denied": 26
  },
  {
    "drg": "CHRONIC OBSTRUCTIVE PULMONARY DISEASE W CC",
    "approved": 352,
    "denied": 61
  },
  {
    "drg": "CHEST PAIN",
    "approved": 246,
    "denied": 44
  },
  {
    "drg": "TRANSIENT ISCHEMIA",
    "approved": 205,
    "denied": 37
  },
  {
    "drg": "OTHER DISORDERS OF NERVOUS SYSTEM W CC",
    "approved": 133,
    "denied": 23
  },
  {
    "drg": "DIABETES W MCC",
    "approved": 151,
    "denied": 27
  },
  {
    "drg": "CARDIAC ARRHYTHMIA CONDUCTION DISORDERS W CC",
    "approved": 336,
    "denied": 55
  },
  {
    "drg": "HYPERTENSION WO MCC",
    "approved": 177,
    "denied": 29
  },
  {
    "drg": "POISONING TOXIC EFFECTS OF DRUGS WO MCC",
    "approved": 144,
    "denied": 24
  }
]

My stacked bar chart, which worked fine with a CSV file, keeps ignoring the "denied" value. I suspect the issue has something to do with my formatting of the "processed_json.push()" portion of my code. It renders the approved value stacked on top of itself. Here is the script file:

Here is what the end product should produce (screen grab from my csv version):
Correct
And here is what I'm getting from the JSON file: incorrect
Any assistance or guidance is greatly appreciated. Thanks.

A:

Have a look at highchart's stacked bar chart example. For each series, data contains the array of values for that series.
series: [{
    name: 'John',
    data: [5, 3, 4, 7, 2]
}, {
    name: 'Jane',
    data: [2, 2, 3, 2, 1]
}, {
    name: 'Joe',
    data: [3, 4, 4, 2, 5]
}]

In your case, instead of creating the processed_json array of objects, you should create separate arrays containing each series' values.
Change the loop this way:
        var xAxis = []
            , approvedCount = []
            , deniedCount = []

        for (i = 0; i < data.length; i++) {
            xAxis.push(data[i].drg);
            approvedCount.push(data[i].approved);
            deniedCount.push(data[i].denied);

Then adapt the chart's instantiation accordingly:
// (...)
xAxis: {
    categories: xAxis
},
// (...)
            series: [{
                name: 'approved',
                color: '#55B4E4',
                data: approvedCount,
            }, {
                name: 'denied',
                color: '#005079',
                data: deniedCount,
            }],
// (...)