text:
Q: Confused about C++ memory deallocation So in C++ if I create an object useing new I should always deallocate it using delete
For example
Segment::Segment(float length)
{
    segmentLength = length;

    angle = 0.0f;
    x = Rand::randFloat(1.0f, 1.5f);
    y = Rand::randFloat(1.0f, 1.5f);

    vx = Rand::randFloat(0.0f, 1.0f);
    vy = Rand::randFloat(0.0f, 1.0f);
    prevX = Rand::randFloat(0.0f, 1.0f);
    prevX = Rand::randFloat(0.0f, 1.0f);
};

And lets say I use it like this in another class such as,
this._segmentObject = Segment(2.0f);
this._segmentPointer = new Segment(2.0f);

In the destructor of that class, I know I should call delete on the this._segmentPointer, however how do I make sure memory is deallocated for the other one?

A:
however how do I make sure memory is deallocated for the other one?

It is automatically. This is why this type of storage is called automatic. Automatic storage is released at the end of the storage's life cycle, and the objects' destructors called.
The object life-cycle ends when the program control leaves the scope where the object has been allocated.

A: Things not allocated with new, new[] or the malloc family should be destructed and "freed" when the object goes out of scope.
Often this simply means that that the code has reached the end of the block it was declared it or that the object that it was in was destructed (one way or another).
To see this in action, you can do something like this:
struct C {
    C()  { std::cout << "C()" << std::endl; }
    ~C() { std::cout << "~C()" << std::endl; }
};

struct B {
    B()  { std::cout << "B()" << std::endl; }
    ~B() { std::cout << "~B()" << std::endl; }
private:
    C c_;
};

struct A {
    A()  { std::cout << "A()" << std::endl; }
    ~A() { std::cout << "~A()" << std::endl; }
};

int main() {
    B *b = new B; // prints "B()", also constructs the member c_ printing "C()"
    { // starts a new block
        A a; // prints "A()";
    } // end of block and a's scope, prints "~A()"

    delete b; // prints "~B()", also destructs member c_, printing "~C()"
}

Note: that if we did not do delete b, the "~B()" and "~C()" would never print. Likewise, if c_ were a pointer allocated with new, it would need to be delete'd in order to print "~C()"

A: The memory for this._segmentObject is part of the memory of the containing object, and will be released when the containing object is destroyed.
this._segmentObject is assigned from a temporary object that is created on the stack and deleted when it goes out of scope.

A: Not only that, You should only allocate with new and deallocate with delete in Constructors or Destructors, otherwise your program can leak if an exception is thrown.

A: The destructors for all class-type member objects are called at the time of the destruction of the primary class.  So your this object, which is allocated on the stack, will have it's destructor called when it goes out-of-scope.  At that time, any class-type member objects of your this object will have their own destructors called in addition to the destructor for your this object which will call delete on the member pointer.
For instance, take the following code sample:
#include <iostream>

using namespace std;

class A
{
        public:
                A() {}
                ~A() { cout << "Destructor for class A called" << endl; }
};

class B
{
        private:
                A a;

        public:
                B() {}
                ~B() { cout << "Destructor for class B called" << endl; }
};

int main()
{
        B b;
        return 0;
}

When run, the output becomes the following:
Destructor for class B called
Destructor for class A called

So you can see that when b, which is allocated on the stack, goes out-of-scope at the end of main, the destrutor for class B is called, which in-turn, after executing the body of the destructor function, calls the destructors for any of its class-type member data objects, which in this case would mean the destructor for class A.  Therefore in your case, the pointer would have delete called on it in the destructor for your this class, and then the destructor for _segmentObject would be called after the destructor for this had completed execution of the body of its destructor.  Then once all the destructors for the non-static data-member objects had been called, the destructor for this then returns.

A: The _segmentObject is allocated automatically on the stack.
The object destructor will be called automatically when the variable gets out of scope.

A: As others have said, you don't need to explicitly do anything to reclaim the memory used by this._segmentObject. As soon as it goes out of scope, the memory will be reclaimed.
It's not clear why you would use Segment in both ways. You should try to ensure you use the Resource Acquisition Is Initialization idiom, as it removes much of the need for checking new / delete pairs. That is, just use the this._segmentObject version, not the pointer.
Your application may not allow it, though.


text:
Q: Flask, Python: File is not saving in the folder "images" I am trying to create new folder with name "images" and save the file [Which is coming from upload.html] in the "images" folder. My issue is, folder is generating but file is not saving into the folder. Please see the attached code below.
upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Convert csv to JSON</title>
</head>
<body>
<form action="{{url_for('upload')}}" method="post" enctype="multipart/form-data">
<input type="file" name="upload" accept="image/"/>
<input type="submit" /></form>

</body>
</html>

on the console out put is:
E:/images
<FileStorage: u'I-94.pdf' ('application/pdf')>
('Accept incoming file:', u'I-94.pdf')
E:/images/I-94.pdf

  File "E:\datamining\tryproject\convert.py", line 32, in upload
    upload.save(destination)
AttributeError: 'function' object has no attribute 'save'

python code is shown below
convert.py

import os

from flask import Flask, request, render_template, send_from_directory

__author__ = 'praveen'

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    return render_template("upload.html")

@app.route("/upload", methods=["POST"])
def upload():

    target = os.path.join(APP_ROOT, '/images')
    print(target)
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("upload"):
        print(file)

        filename = file.filename
        destination = "/".join([target, filename])
        print("Accept incoming file:", filename)
        print(destination)
        upload.save(destination)

if __name__ == "__main__":
    app.run(port=4555, debug=True)

A: convert.py

import os

from flask import Flask, request, render_template, send_from_directory

__author__ = 'praveen'

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    return render_template("upload.html")

@app.route("/upload", methods=["POST"])
def upload():

    target = os.path.join(APP_ROOT, '/images')
    print(target)
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("upload"):
        print(file)

        filename = file.filename
        destination = "/".join([target, filename])
        print("Accept incoming file:", filename)
        print(destination)
        file.save(destination)   //i made change here

if __name__ == "__main__":
    app.run(port=4555, debug=True)

A: Remove a slash from this:
target = os.path.join(APP_ROOT, '/images')

So it's going to be:
target = os.path.join(APP_ROOT, 'images')

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Segmentation fault std::array I have approx. 2 GB of free DRAM on my computer. Compiling either a std::array or the standard array:
#include <iostream>
#include <array>

int main(int argc, char *argv[]){

    // int* a = new int[500000000];
    std::array<int, 2000000> a;

}

with:
$ g++ -std=c++11 main.cpp -o main
./main

works for both arrays. Changing the size of the std::array to:
// ceteris paribus
std::array<int, 2095300> a;

leads to:
$ ./main
Segmentation fault (core dumped)

honestly, I am not sure whether or not this issue has already been addressed somewhere.
From my understanding, the std::array is created on the stack, and the int * ... array on the heap. Now my guess was that maybe my stack is simply not larger then the ~8mb, which compared to the 2 GB heap sounded disproportionate. Thus I also tried out:
//int a[2096000];

which also causes a segmentation fault. So my question is, what causes the Segmentation fault?
Thank you in advance.

A: You're putting a large array on the stack, causing the stack to overflow.
You can set how large the stack is: Change stack size for a C++ application in Linux during compilation with GNU compiler. A better option is probably to use the heap, however.

It just sounded a bit disproportionate that the stack is so much smaller then [sic] the heap.

The stack is memory that's actually allocated, which means you don't want it to be larger than you really need, because if memory is used for the stack then it won't be available for other uses. The heap, on the other hand, doesn't take up memory unless it's actually requested, so allowing the heap to  potentially take up a large proportion of the address space is fine.
The stack also generally doesn't need to be very large because the maximum depth of function calls usually isn't that high. A few megabytes is almost always more than enough.


text:
Q: Kongregate API (Unity WebGL C#): What happens with the user data if the player is not using an account? I am interested solely in what happens with the userinfo if a player is not signed into their Kongregate, I need to check for this as I will be saving game progress on a server and of course I don't want to be writing random save records into my database that will never actually be used.
My code is as follows
public void OnKongregateAPILoaded(string userInfoString)
{
    var info = userInfoString.Split('|');
    var userId = System.Convert.ToInt32(info[0]);
    var username = info[1];
    var gameAuthToken = info[2];
    Debug.Log("Kongregate User Info: " + username + ", userId: " + userId);
}

More specifically what I'm asking for is, will something such as username return null? Or something in general that I can check for?

A: Username changes to: "Guest"
Id changes to: 0


text:
Q: Using jQuery UI: How do I add an image to the dialog? I am using jQuery UI and I want to add an icon within the dialog box.
The dialog works fine, but I'd like to add a picture to be more attractive. I will appreciate any help.
Code:

<meta charset="utf-8" />
<title>jQuery UI Dialog - Modal message</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Your files have downloaded successfully into the My Downloads folder.

Currently using 36% of your storage space.

Sed vel diam id libero rutrum convallis. Donec aliquet leo vel magna. Phasellus rhoncus faucibus ante. Etiam bibendum, enim faucibus aliquet rhoncus, arcu felis ultricies neque, sit amet auctor elit eros a lectus.

A: There's nothing special about putting anything in a dialog; it's just an ordinary HTML DIV.
The problem is that you're not using correct HTML for your image. Change this line:

to:

img is not an attribute of a , it's an element of its own.

A: All that jQueryUI's dialog() does is (1) hide the specified div upon document.ready, then (2) display it with some fancy css formatting when the .dialog('open') method (or just the dialog({ //options go here }) method) is called.
Therefore, if your div contains the image WITHOUT the jQUI dialog being instantiated, then it will contain the image AFTER the jQUI dialog method is used.
Your problem is likely the syntax error where you are missing the closing angle bracket for the  element, and the opening angle bracket for the  element. Also, the attributes that you desire for the  element seem to be attached to the input element.
Removing your in-line CSS (for simplicity), this will work:


text:
Q: hadoop job output files I currently have one hadoop oozie job running. The output files are automatically generated. The expected number of output files is just ONE; however, there are two output files called part-r-00000 and part-r-00001. Sometimes, the first one(part-r-00000) has data, and the second one (part-r-00001) doesn't.  Sometimes, the second one has, and the first one doesn't. Can anyone tell me why? Also, How to set the output file to part-r-00000?

A: The number of files output is dependent on the number of mappers and reducers. In your case, the number of files and names of files indicates that your output came from 2 reducers.
To limit the number of mappers or reducers is dependent on your language (Hive, Java, etc), but each has a property that you can set to limit these. See here for Java MapReduce jobs.
Files can be empty if that particular mapper or reducer task had no resulting data on the given data node.
Finally, I don't think you want to limit your mappers and reducers. This will defeat the point of using Hadoop. If you're aiming to read all files as one, make sure they are consolidated in a given directory and pass the directory as the file name. The files will be treated as one.

A: In Hadoop, the output files are a product of the Reducers (or Mappers if it's a map-side only job, in which case it will be a part-m-xxxxx file). If your job uses two reducers, that means that after each has finished with its portion, it will write to the output directory in the form of part-r-xxxxx, where the numbers denote which reducer wrote it out.
That said, you cannot specify a single output file, but only the directory. To get all of the files from the output directory into a single file, use:
hdfs dfs -getmerge <src> <localdst> [addnl]

Or if you're using an older version of hadoop:
hadoop fs -getmerge <src> <localdst> [addnl]

See the shell guide for more info.
As to why one of your output files is empty, data is passed from Mappers to Reducers based on the grouping comparator. If you specify two reducers, but there is only one group (as identified by the grouping comparator), data will not be written from one reducer. Alternatively, if some logic within the reducer prevents a writing operation, that's another reason data may not be written from one reducer.

A: The output files are by default named part-x-yyyyy where:

*

*x is either 'm' or 'r', depending on whether this file was generated by a map  or reduce task

*yyyyy is the mapper or reducer task number (zero based)

The number of tasks has nothing to do with the number of physical nodes in the cluster. For map task output the number of tasks is given by the input splits. Usually the reducer task are set with job.setNumReduceTasks() or passed as input parameter.
A job which has 100 reducers will have files named part-r-00000 to part-r-00100, one for each reducer task.
A map only job with 100 input splits will have files named part-m-00000 to part-m-00100, one for each reducer task.


text:
Q: Creating an md5 object in python with an initial value I have some code that needs to hash certain data, then later on, in another process, continue the hash with more data.
Is there a way to create an object, either from the md5 or hashlib modules, which has a different initial value than 'd41d8cd98f00b204e9800998ecf8427e'?
What I mean is something similar to:
x = md5.from_digest('0123456789abcdef')
x.update(new_data)

Note: the less desirable approach would be to save the original md5 object and restore it later, but afaik HASH objects are non-pickleable.

A: They(@jon-clements, @itai, @delnan) are right. Until now , you can't , unless you implement one. There are some examples :
http://equi4.com/md5/pymd5.py
http://rosettacode.org/wiki/MD5/Implementation


text:
Q: Will NpgsqlConnection.Open throw an error if the port is closed? I wrote a test and at the time it seemed that if I had
NpgsqlConnection connection = new NpgsqlConnection(<valid string with port #>);
connection.Open();
...

with the corresponding network port closed, then connection.Open() would throw an exception. Now the code is
using (NpgsqlConnection connection = new NpgsqlConnection(builder.ConnectionString))
{
    connection.Open();
    ...

and I am getting feedback that this code may actually continue even if the port is closed. What is the behavior of NpgsqlConnection - is it guaranteed that connection.Open() will throw if the specified port is not opened?
I tried examining NpgsqlConnection.cs and NpgsqlConnector.cs but couldn't pin it down. Any help would be appreciated

A: Yes, NpgsqlConnection.Open() will throw an exception if PostgreSQL isn't running on the potty specified ("connection refused").
Adding a using does nothing more than dispose the connection at the end of the block, after the exception has already been thrown.


text:
Q: It has no method the_method Suppose liste is a certain list of objects.
let rec sum liste any_method = match liste with
    | [] -> 0
    | obj::r -> obj#any_methode + sum r any_method

if I use sum my_list_of_objects the_method, I'll get This expression has type int list. It has no method the_method.
Is there a workaround to manage that issue?
UPDATE
Here is a simple case
 class point =
    object
      val mutable x = 1
      method getx = x
      method move d = (x <- x + d)
  end;;

Suppose liste_pointsa list of objects point.
let func liste methode = map (fun obj -> obj#methode 5) liste;;
func liste_points move;;

The above little code occurred the error bellow :
Error: This expression has type point list
       but an expression was expected of type
         (< methode : int -> 'b; .. > as 'a) list
       Type point = < getx : int; move : int -> unit >
       is not compatible with type < methode : int -> 'b; .. > as 'a
       The first object type has no method methode

How can I make this work?

A: New Answer
Here's a little class whose instances contain two different integers:
class intx2 = object
    val mutable a : int = 0
    val mutable b : int = 0
    method set_a v = a <- v
    method get_a = a
    method set_b v = b <- v
    method get_b = b
end

let get_a_fn obj = obj#get_a
let get_b_fn obj = obj#get_b

let rec sum getter = function
    | [] -> 0
    | obj :: rest -> getter obj + sum getter rest

You can sum up the a values of a list of such objects like this:
sum get_a_fn list_of_objs

You can sum up the b values like this:
sum get_b_fn list_of_objs


text:
Q: How to get bounding box coordinates for canvas content? I have a canvas with a map. In that canvas the user is able to draw (in red) and the final result will  be:

After the user as painted whatever he wants I need to calculate the bounding box coordinates of all the content so I could ultimately have:

Now I can loop through every pixel of the canvas and calculate the bounding box based on every non-empty pixel but this is quite a heavy operation. Any idea of a better logic to achieve the intended results?

A: You can track what is being drawn and the diameter of the points. Then min/max that for the boundary.
One way to do this is to track position and radius (brush) or boundary (irregular shape) of what is being drawn, then merge that with current min/max bound to update the new bound if needed in effect "pushing" the bounds to always match the interior.
Example

var ctx = c.getContext("2d"),
    div = document.querySelector("div > div"),

    // keep track of min/max for each axis
    minX = Number.MAX_SAFE_INTEGER,
    minY = Number.MAX_SAFE_INTEGER,
    maxX = Number.MIN_SAFE_INTEGER,
    maxY = Number.MIN_SAFE_INTEGER,

    // brush/draw stuff for demo
    radius = 10,
    rect = c.getBoundingClientRect(),
    isDown = false;

ctx.fillText("Draw something here..", 10, 10);
ctx.fillStyle = "red";
c.onmousedown = function() {isDown = true};
window.onmouseup = function() {isDown = false};
window.onmousemove = function(e) {
  if (isDown) {
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;

    // When something is drawn, calculate its impact (position and radius)
    var _minX = x - radius;
    var _minY = y - radius;
    var _maxX = x + radius;
    var _maxY = y + radius;

    // calc new min/max boundary
    if (_minX < minX) minX = _minX > 0 ? _minX : 0;
    if (_minY < minY) minY = _minY > 0 ? _minY : 0;
    if (_maxX > maxX) maxX = _maxX < c.width  ? _maxX : c.width;
    if (_maxY > maxY) maxY = _maxY < c.height ? _maxY : c.height;

    // show new bounds
    showBounds();

    // draw something
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 6.28);
    ctx.fill();
  }
};

function showBounds() {
  // for demo, using bounds for display purposes (inclusive bound)
  div.style.cssText =
    "left:" + minX + "px;top:" + minY +
    "px;width:" + (maxX-minX-1) + "px;height:" + (maxY-minY-1) +
    "px;border:1px solid blue";
}
div {position:relative}
div > div {position:absolute;pointer-events:none}

  <canvas id=c width=600 height=600></canvas>


text:
Q: Replacing HTML with Javascript in a way that is executable in a browser I have no Javascript experience at all. What I want is to replace a single instance of a block of text in a page's HTML - how can I do this?
30 minutes of reading around has brought me this:
javascript:document.body.innerHTML = document.body.innerHTML.replace("this","that");

Am I even close?

A: With no experiance at all I recommend you take a look at jQuery. With jQuery you can do:
Given:

block of text

jQuery:
$('p').text("some other block of text");

A: javascript:document.body.innerHTML = "that"

A: 1) If it is part of a URL, such as , then you need
javascript:void(document.body.innerHTML = document.body.innerHTML.replace("this","that"));
2) If it is part of an event, such as <button onClick="...">, then you need
document.body.innerHTML = document.body.innerHTML.replace("this","that");
3) If you are trying to replace ALL instances of "this" with "that", and not just the first, then you need
... .replace(/this/g,"that")

A: You cannot just execute that script in the address bar. It needs to operate on a document, but there is nothing to replace there. Executing javascript from the address bar will give you a new empty document on which that code operates.
Even if you try to load a document from javascript, the rest of your script gets executed first. Try this:
javascript:window.location='http://www.google.com';alert(document.innerHTML);

You'll see that the alert pops up before the page is loaded, and it shows 'undefined'.
Even when you try binding to the onload event of the document or the window it won't work. Probably because they are reset afterwards.
javascript:window.location='http://www.google.com';window.onload=function(){alert(document.innerHTML);};

And it makes sense; if this would work, you could manipulate the next page when jumping to that page, thus making it possible to inject javascript in a page you link to. That would be a big security issue, so it's a good thing this doesn't work.


text:
Q: PHP MySQL updates without having a right value I'm pretty new with MySQL and I have a problem. I have a database etc. that works perfectly fine. I can update emails but it doesn't recognize if there isn't a value to update.
php
if (isset($_POST['updateemail'])) {
    $sname = mysqli_real_escape_string($conn, $_POST['sname']);
    $fname = mysqli_real_escape_string($conn, $_POST['fname']);
    $email = mysqli_real_escape_string($conn, $_POST['useremail']);

    if($sname == "" && $fname == ""){
        echo "
 Name can not be empty";
} else {

    $sql = "UPDATE table SET email = '$email' WHERE surename = '$sname' OR firstname = '$fname'";
    $result = mysqli_query($conn, $sql);

    if ($result) {
        echo "
 Email updated!";
    } else {
        echo "
 Email update not succesful.";
        echo "
 Error: " . $sql . "
" . mysqli_error($conn);
        }
    }
}

Does anyone know what the problem is? Thanks in advance.
I also have another code which is somewhat similar to this one but it doesn't have the "or" and it also doesn't recognize if there isn't a name what I've typed..

A: if (isset($_POST['updateemail'])) {
    $sname = mysqli_real_escape_string($conn, $_POST['sname']);
    $fname = mysqli_real_escape_string($conn, $_POST['fname']);
    $email = mysqli_real_escape_string($conn, $_POST['useremail']);

    if($sname == "" && $fname == ""){
        echo "
 Name can not be empty";
} else {
    // Search for valid user
    $sql = "SELECT table WHERE surename = '$sname' AND firstname = '$fname'";
    $found = mysqli_query($conn, $sql) or die("Can't search for user: "  . mysqli_error($conn));
    if(mysqli_num_rows($found) == 1) {
        // User found, let's update
        $sql = "UPDATE table SET email = '$email' WHERE surename = '$sname' AND firstname = '$fname'";
        $result = mysqli_query($conn, $sql);

        if ($result) {
            echo "
 Email updated!";
        } else {
            echo "
 Email update not succesful.";
            echo "
 Error: " . $sql . "
" . mysqli_error($conn);
        }
    } else {
        echo "
 User not found!";
    }
}

A: Use mysqli_affected_rows($conn)
Change your
if ($result) {
        echo "
 Email updated!";
    }

To this
if (mysqli_affected_rows($conn) > 0) {
            echo "
 Email updated!";
        }


text:
Q: How to Calculate Total Miles Travel from the Curent loaction to some another location Location Listener? Hi Can anybody tell me how can i calculate Total Miles Travel from the Curent location to another location? e.g. like i start walking from point A and reached at point B. how can i find the total distance travel from point A to B. Please help me!!!

A: Assume, you have Location start_location and finish_location.
So you can use start_location.distanceTo(finish_location)
Please See , Location in Android

A: Criteria c=new Criteria()
c.setAccuracy(Criteria.ACCURACY_FINE);
String providerName=locMgr.getBestProvider(c,true);

                         Location startLocation = new Location(providerName);
                         startLocation.setLatitude(PrevLatitude);
                         startLocation.setLongitude(PrevLongitude);
                         startLocation.set(startLocation);

                         Location _myLoc = new Location(providerName);
                         _myLoc.setLatitude(Double.valueOf(nf.format(location.getLatitude())));
                         _myLoc.setLongitude(Double.valueOf(nf.format(location.getLongitude())));
                         _myLoc.set(_myLoc);

                         double meters = _myLoc.distanceTo(startLocation);
                         double miles = (meters*0.000621371192237334);

A: I have solved this exact problem in my open source Gps Tracker. The full working android project is here:
https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android
and the class that does the tracking is below. You want to take a look at the variable called totalDistanceInMeters.
package com.websmithing.gpstracker;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class LocationService extends Service implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = "LocationService";

    // use the websmithing defaultUploadWebsite for testing and then check your
    // location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
    private String defaultUploadWebsite;

    private boolean currentlyProcessingLocation = false;
    private LocationRequest locationRequest;
    private LocationClient locationClient;

    @Override
    public void onCreate() {
        super.onCreate();

        defaultUploadWebsite = getString(R.string.default_upload_website);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // if we are currently trying to get a location and the alarm manager has called this again,
        // no need to start processing a new location.
        if (!currentlyProcessingLocation) {
            currentlyProcessingLocation = true;
            startTracking();
        }

        return START_NOT_STICKY;
    }

    private void startTracking() {
        Log.d(TAG, "startTracking");

        if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
            locationClient = new LocationClient(this,this,this);

            if (!locationClient.isConnected() || !locationClient.isConnecting()) {
                locationClient.connect();
            }
        } else {
            Log.e(TAG, "unable to connect to google play services.");
        }
    }

    protected void sendLocationDataToWebsite(Location location) {
        // formatted for mysql datetime format
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getDefault());
        Date date = new Date(location.getTime());

        SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        float totalDistanceInMeters = sharedPreferences.getFloat("totalDistanceInMeters", 0f);

        boolean firstTimeGettingPosition = sharedPreferences.getBoolean("firstTimeGettingPosition", true);

        if (firstTimeGettingPosition) {
            editor.putBoolean("firstTimeGettingPosition", false);
        } else {
            Location previousLocation = new Location("");
            previousLocation.setLatitude(sharedPreferences.getFloat("previousLatitude", 0f));
            previousLocation.setLongitude(sharedPreferences.getFloat("previousLongitude", 0f));

            float distance = location.distanceTo(previousLocation);
            totalDistanceInMeters += distance;
            editor.putFloat("totalDistanceInMeters", totalDistanceInMeters);
        }

        editor.putFloat("previousLatitude", (float)location.getLatitude());
        editor.putFloat("previousLongitude", (float)location.getLongitude());
        editor.apply();

        final RequestParams requestParams = new RequestParams();
        requestParams.put("latitude", Double.toString(location.getLatitude()));
        requestParams.put("longitude", Double.toString(location.getLongitude()));

        Double speedInMilesPerHour = location.getSpeed()* 2.2369;
        requestParams.put("speed",  Integer.toString(speedInMilesPerHour.intValue()));

        try {
            requestParams.put("date", URLEncoder.encode(dateFormat.format(date), "UTF-8"));
        } catch (UnsupportedEncodingException e) {}

        requestParams.put("locationmethod", location.getProvider());

        if (totalDistanceInMeters > 0) {
            requestParams.put("distance", String.format("%.1f", totalDistanceInMeters / 1609)); // in miles,
        } else {
            requestParams.put("distance", "0.0"); // in miles
        }

        requestParams.put("username", sharedPreferences.getString("userName", ""));
        requestParams.put("phonenumber", sharedPreferences.getString("appID", "")); // uuid
        requestParams.put("sessionid", sharedPreferences.getString("sessionID", "")); // uuid

        Double accuracyInFeet = location.getAccuracy()* 3.28;
        requestParams.put("accuracy",  Integer.toString(accuracyInFeet.intValue()));

        Double altitudeInFeet = location.getAltitude() * 3.28;
        requestParams.put("extrainfo",  Integer.toString(altitudeInFeet.intValue()));

        requestParams.put("eventtype", "android");

        Float direction = location.getBearing();
        requestParams.put("direction",  Integer.toString(direction.intValue()));

        final String uploadWebsite = sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite);

        LoopjHttpClient.get(uploadWebsite, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody) {
                LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - success", uploadWebsite, requestParams, responseBody, headers, statusCode, null);
                stopSelf();
            }
            @Override
            public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] errorResponse, Throwable e) {
                LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - failure", uploadWebsite, requestParams, errorResponse, headers, statusCode, e);
                stopSelf();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());

            // we have our desired accuracy of 500 meters so lets quit this service,
            // onDestroy will be called and stop our location uodates
            if (location.getAccuracy() < 500.0f) {
                stopLocationUpdates();
                sendLocationDataToWebsite(location);
            }
        }
    }

    private void stopLocationUpdates() {
        if (locationClient != null && locationClient.isConnected()) {
            locationClient.removeLocationUpdates(this);
            locationClient.disconnect();
        }
    }

    /**
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected");

        locationRequest = LocationRequest.create();
        locationRequest.setInterval(1000); // milliseconds
        locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        locationClient.requestLocationUpdates(locationRequest, this);
    }

    /**
     * Called by Location Services if the connection to the
     * location client drops because of an error.
     */
    @Override
    public void onDisconnected() {
        Log.e(TAG, "onDisconnected");

        stopLocationUpdates();
        stopSelf();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "onConnectionFailed");

        stopLocationUpdates();
        stopSelf();
    }
}


text:
Q: Can different subfields have the same Minimal Polynomial? I am trying to see if different subfields (of $F(\alpha)$ containing $F$) can have the same minimal polynomial?
I'm hoping that the answer is no, so that if two subfields do have the same minimal polynomial, then they must be the same subfield!
Edited to add in the whole question:
Let $F(\alpha) : F$ be a simple algebraic extension.  Let $E_1$ and $E_2$ be intermediate fields (that is, subfields of $F(\alpha)$ containg $F$).  Prove that if $\alpha$ has the same minimal polynomial over $E_1$ and $E_2$, then $E_1 = E_2$.

A: Your question is not clear, since subfields do not have minimal polynomials. I believe that your question is something along these lines:
"Given $F(\alpha)$ and $F(\beta)$, two algebraic extension fields of $F$, and knowing that the minimal polynomial of $\alpha$ over $F$ is the same as the minimal polynomial of $\beta$ over $F$, can I conclude that $F(\alpha)=F(\beta)$?"
I believe that the answer to this question is no. Consider the following polynomial:
$$x^3-2=(x-\sqrt[3]2)(x-\sqrt[3]2\omega)(x-\sqrt[3]2\omega^2)$$
where $\omega$ in the third root of unity. Notice that none of the roots belong to $\mathbb{Q}$. Also this polynomial is irreducible in $Q[X]$ by Eisenstein criterion. Being monic, it is a minimal polynomial of $\sqrt[3]2$ and $\sqrt[3]2\omega.$ But $\mathbb{Q}[\sqrt[3]2] \neq \mathbb{Q}[\sqrt[3]2\omega]$, since one field extension contains complex numbers and the other one does not.
So,the extensions are not the same. But are they isomorphic? What do you think?

A: Yes, they can.  Example: Let p(x) be an irreducible cubic over $F$ with three roots $r_1$, $r_2$, $r_3$.  The three fields $F(r_1)$, $F(r_3)$, $F(r_3)$ will be distinct, and p(x) will be the minimal polynomial for all of them.  And they will all be common subfields of the spliting field of p(x) [$F(r_1,r_2,r_3)$, which is also representable as $F(\alpha)$ for some $\alpha$].
[note: this is a slight generalization of the answer by @Paquarian]


text:
Q: A JavaScript Popup box is working perfectly in Coda 2 but not any browser I am making a game where you have to get from one point (task) on a site to another (dest) in an iframe. Your starting and end points are chosen for you. When the url of your starting point is equal to your end point I would like a popup box saying you won. I made one and it works fine in Coda 2 but not in any browser. I am very new to JS as well as Stack Overflow so any help would be appreciated!
How I am calling the code in my index.html:
<script src="assets/victory.js"></script>

The actual code:
        function victory(){
    if(url.value.substring(29, 41) == dest.value){
    window.alert("Congratulations, You Made It To Your Destination");
}
    else(null)
}

A: Use location.href instead of url.value.
Or you can see other useful location properties in w3schools.


text:
Q: Ajax passing value to PHP I would like to pass multiple values to php via ajax (on same page), here's my code:
HTML (user_list.php):
<button type="submit" class="button button-block savebutton" name="save_changes"/>
        Save changes</button>

Javascript (user_list.php):
$(".savebutton").on("click", function (event) {
    event.preventDefault();
    var js = [];
    var i = 0;
    $('select').each(function () {
        var a = {"id": "", "permission": ""}
        a.id = $(this).val();
        a.permission = $(this).children(":selected").text();
        js.push(a);
        alert(js[i].permission + " - "+js[i].id);
        i++;
    });
    $.ajax({
        type: "POST",
        url: "user_list.php",
        data: {result: JSON.stringify(js)}
    });
    return false;
});

PHP (user_list.php):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)

    if (!empty($_POST['check_list'])) {
        foreach ($_POST['check_list'] as $id) {
            $sql = "DELETE FROM users WHERE id=$id";
            $mysqli->query($sql);
            header("Refresh:0"); //Refresh page
        }
    }

}

// Other if above works fine
elseif (isset($_POST['result'])){
    // I want to get the js array with the values here after ajax
}

else {
    // But I get here, and I don't get the js array
}
}

So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly
EDIT: I moved the php to a different page, now it's working.

A: Though your Ajax request is initiated, a "normal" submit request is also started, when you press the button. To prevent the second request (thus keeping only the Ajax request), you have to return false; at the end of your onclick callback.
Solution #1:
$(".savebutton").on("click", function () {
    var js = [];
    var i = 0;
    $('select').each(function () {
        var a = {"id": "", "permission": ""}
        a.id = $(this).val();
        a.permission = $(this).children(":selected").text();
        js.push(a);
        alert(js[i].permission + " - "+js[i].id);
        i++;
    });
    $.ajax({
        type: "POST",
        url: "user_list.php",
        data: {result: JSON.stringify(js)}
    });
    return false;
});

Solution #2 (as also suggested by @charlietfl):
$(".savebutton").on("click", function (event) {
    event.preventDefault();
    var js = [];
    var i = 0;
    $('select').each(function () {
        var a = {"id": "", "permission": ""}
        a.id = $(this).val();
        a.permission = $(this).children(":selected").text();
        js.push(a);
        alert(js[i].permission + " - "+js[i].id);
        i++;
    });
    $.ajax({
        type: "POST",
        url: "user_list.php",
        data: {result: JSON.stringify(js)}
    });
});

A: $('.savebutton').click(function (e) {
  e.preventDefault()
  var js = []
  var i = 0
  $('select').each(function (i) {
    var a = {}
    a.id = $(this).val()
    a.permission = $(this).children(':selected').text()
    js.push(a)
    alert(js[i].permission + ' - ' + js[i].id)
  })
  js = JSON.stringify(js)
  $.post('user_list.php', {result: js}
})

A: It seems that when you're submitting the POST request, the data is coming as their own POST fields. Simply check for the values of what you submitted. For example, if you had done the same, but put foo as bar and hello as world, you could check for foo and hello with something like this:
elseif (isset($_POST['foo'], $_POST['hello']) {
    # your code
}

A: Try with this
<button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>


text:
Q: List a target directory in C So I am tasked with creating a shell. I have the functions working correctly (e.g. dir, clear, quit, etc.), but I have a question about the 'dir' function. Currently 'dir' works fine. It lists the files of the directory that the program is located in. What I want to do is list the directory of another location. Is there a way to that?
I have yet to create the change directory command. I was wondering if my problem would be solved through that instead. Any help is appreciated.
Side note: The instructions state that I "will need to provide some command line parsing capability to extract the target directory for listing." I have no idea what that is, but maybe someone could enlighten me.

A: Take a look at GNU's Simple Directory Lister example code, which uses opendir().
To parse command line arguments, take a look at your main() function:
int main(int argc, char* argv[])
{
    ...
    return 0;
}

Use the argv[] pointer and argc integer value to determine the number of and character pointers of arguments.


text:
Q: Autofocus following tabindex and skip disabled fields How does the cursor automatically hops to the next possible (not disabled) input field according to tabindex?
I got that function (source: Focus Next Element In Tab Index ) but my cursor doesn't move automatically after input of 1 value: - Why?
function focusNextElement () {
//add all elements we want to include in our selection
var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
if (document.activeElement && document.activeElement.form) {
    var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
    function (element) {
        //check for visibility while always include the current activeElement
        return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
    });
    var index = focussable.indexOf(document.activeElement);
    if(index > -1) {
       var nextElement = focussable[index + 1] || focussable[0];
       nextElement.focus();
    }
}
}

Example for my input fields:

 1<input type="text" maxlength="1" oninput="focusNextElement(this)" id="a" name="a" tabeindex="1">.
 3<input type="text" maxlength="1" oninput="focusNextElement(this)" id="b" name="b" tabeindex="3" disabled>
 5<input type="text" maxlength="1" oninput="focusNextElement(this)" id="c" name="c" tabeindex="5">

 2 <input type="text" maxlength="1" oninput="focusNextElement(this)" id="d" name="d" tabeindex="2">
 4<input type="text" maxlength="1" oninput="focusNextElement(this)" id="e" name="e" tabeindex="4">
 6<input type="text" maxlength="1" oninput="focusNextElement(this)" id="f" name="f"  tabeindex="6"">

Example on: https://jsfiddle.net/rydjnzkw/4/

A: You don't most of this code, just querySelector the inputs which are not disabled, try to find the current element index in this array, and focus the next element.

const inputs = document.querySelectorAll('input:not([disabled])')

function focusNextElement (input) {
  const nextIndex = [...inputs].findIndex(i => i === input) + 1
  if (inputs[nextIndex]) {
    inputs[nextIndex].focus()
  }
}
<input type="text" maxlength="1" oninput="focusNextElement(this)" id="a" name="a">
<input type="text" maxlength="1" id="c" name="b" disabled>
<input type="text" maxlength="1" oninput="focusNextElement(this)" id="d" name="c">

UPDATE
To make it work according to tabeindex

const inputs = document.querySelectorAll('input:not([disabled])');
let focusableElement;
let maxTries = 100;
let counter = 0;
const getNextElement = (tabeindex) => {
  const element = document.querySelector(`[tabeindex="${tabeindex + 1}"]`)
  if (counter >= maxTries) {
    return;
  }
  if (element && !element.disabled) {
    counter = 0;
    focusableElement = element;
    return;
  }
  counter++
  getNextElement(tabeindex + 1)
}

function focusNextElement (input) {
  const nextIndex = [...inputs].findIndex(i => i === input) + 1
  const tabeindex= +input.getAttribute('tabeindex');
  const element = getNextElement(tabeindex)
  focusableElement.focus()
}

  1<input type="text" maxlength="1" oninput="focusNextElement(this)" id="a" name="a" tabeindex="1">
 3<input type="text" maxlength="1" oninput="focusNextElement(this)" id="b" name="b" tabeindex="3" disabled>
 5<input type="text" maxlength="1" oninput="focusNextElement(this)" id="c" name="c" tabeindex="5">

 2 <input type="text" maxlength="1" oninput="focusNextElement(this)" id="d" name="d" tabeindex="2">
 4<input type="text" maxlength="1" oninput="focusNextElement(this)" id="e" name="e" tabeindex="4">
 6<input type="text" maxlength="1" oninput="focusNextElement(this)" id="f" name="f"  tabeindex="6"">


text:
Q: How can we return string from callback function to root function in node.js? function add(post)
{
    var word = new KeyWord({ keyword: post.keyword});
    word.save(function (err, word)
    {
        if(err)
        {
            if(err.code==11000)
                return post.keyword + ' is already added.';
        }
        else
            return 'Added : ' + post.keyword;
    });
}

When I am trying to read return value of add function it returns nothing.
And also when I am trying to put message in variable and return that from outside also give null value.

A: To put it simply, you can't. To get values from functions like these, you must use a callback:
function add(post, callback) {
  var word = new KeyWord({keyword: post.keyword});
  word.save(function(err, word) {
    if (err) {
      if (err.code==11000) callback(post.keyword + ' is already added.');
      else callback('Added : ' + post.keyword);
    }
  });
}

You'd then use the function like this:
add(post, function(result) {
  // return value is here
}


text:
Q: Can I force TortoiseGit to retry to unlink file while switching branches? My primary development environment is within Windows but for Git, I try to mainly use the command line for doing most things and occasionally use TortoiseGit for others (such as viewing viewing logs or rebasing).  Usually when switching branches, there are no problems when it's removing and restoring files.  But certain programs lock these files (e.g., editing CSV files in Excel) which causes minor issues when switching branches.
If switching from the command prompt and a file is locked, it'll simply notify you that it was unable to unlink the file and ask you if you want to retry.  This will give me a chance to close the program that has the lock and let it try again.

switching from command prompt
However, if I were to switch branches through TortoiseGit, it will have the error but will act as if the response was N and finish up leaving the files in their current state.  It gets a little annoying as I have to go back and manually revert the files.  I'd rather have it wait and ask me to try again, like it usually does with other actions.

switching from TortoiseGit
Is there any way I can force TortoiseGit to halt and ask me to retry unlinking the file when switching branches?  Or is this just not a feature of TortoiseGit?

A: Up to TortoiseGit 2.2.3 the yes/no question wrapper (GIT_ASK_YESNO) was not implemented. Starting with 2.2.4 this will be supported, however, I don't know why after an "error" success is reported by git.exe.


text:
Q: FirebaseCrashlytics did not report crash to my firebase console dashboard I was updating Fabric to new Firebase, my firebase showed old fabric crash report and no Firebase report. Now my firebaseCrashlytics version is 4.3.1. I had added GoogleService-Info.plist, script phase "${PODS_ROOT}/FirebaseCrashlytics/run" and phase's input files:${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME},
$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH).
When I run my app, xcode console printed "[Firebase/Crashlytics] Version 4.3.1", no other log. I did not know what problem happened.

A: Few things you need to verify .
1- Is your crashlytics connected to your app.
Even though you initially connect your app in the setup phase to get the googleInfoPlist , you have to run it again and connect again .Select the crashlyitcs tab and you will get to click "Add SDK" which i think at this point you have completed .
After that run your app again and navigate through the app and at some point it will say that it is connected.
Another thing is you can force a crash but it wont appear in the crashlogs directly.
First you run it on the device and the stop running. Re-open the App and recreate the crash again. The Crash will not appear as long as the debugger is connected to your Emulator/Device


text:
Q: HTTP Delete send with Angular HTTP Client is fired - not received by server I am working on an App including CRUD-functionality. I use Spring for the backend implementation, Angular for the frontend. In the frontend, I use Angular's http client like this to delete an entity (The following code is shortened for the sake of brevity):
Component:
export class RecipeComponent implements OnInit {

  constructor(private recipeService : RecipeService) { }

    deleteElement (id : number) {
        this.recipeService.deleteRecipe(id).subscribe();
    }
}

Service:
export class RecipeService {

    deleteRecipe (id : number) : Observable<{}> {
      return this.http.delete('http://localhost:8080/recipe/' + id);
    }

  constructor( private http: HttpClient ) { }
}

When executing the function, I can find the http-delete request in the network tab:

The Spring Controller looks (shortend) like this:
@ControllerAdvice
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(path="/recipe")
public class RESTController {
    @Autowired
    private RecipeRepository recipeRepository;

@DeleteMapping(path="/{id}")
public @ResponseBody ResponseEntity deleteRecipe (@RequestBody Recipe deletedRecipe, @PathVariable("id") int id) {

    try {
        [...]
        }
    } catch (RecipeNotFoundException e) {
        [...]
    }
}

}

Yet, my backend does not receive the request. The strange thing is, Posts or Gets work fine.
Can anyone point me to the right direction?
Thanks and best!

A: The 400 Bad request is very likely a "body is missing" error. Remove @RequestBody Recipe deletedRecipe from the method parameters since you don't provide the entity to delete, the id is enough.


text:
Q: segfault on running gsoap application I'm using gsoap to communicate with the following webservice:
http://ws.cdyne.com/delayedstockquote/delayedstockquote.asmx?wsdl
I've run the soapcpp2 to generate the header files, here's my soapClient.c:
http://pastebin.com/Bjev3dP7
getquote:
struct _ns1__GetQuote
{
/// Element "StockSymbol" of XSD type xs:string.
    char*                                StockSymbol                    0;      ///< Optional element.
/// Element "LicenseKey" of XSD type xs:string.
    char*                                LicenseKey                     0;      ///< Optional element.
};

struct _ns1__GetQuoteResponse
{
/// Element "GetQuoteResult" of XSD type "http://ws.cdyne.com/":QuoteData.
    struct ns1__QuoteData*               GetQuoteResult                 1;      ///< Required element.
};

here's my code so far:
#include "soapH.h"
#include "DelayedStockQuoteSoap.nsmap"
#include "soapClient.c"

struct _ns1__GetQuote *ns1__GetQuote;
struct _ns1__GetQuoteResponse *response;

main() {
  struct soap *soap ;
  ns1__GetQuote->StockSymbol = "goog";
  ns1__GetQuote->LicenseKey = "0";
  if (soap_call___ns1__GetQuote(soap, NULL, NULL, ns1__GetQuote, &response) == SOAP_OK)
    printf("yay\n");
}

I get a segfault as soon as I run this code, any hints?

A: In your code there are many errors, nothing is allocated.
First you need to allocate the struct soap using:
struct soap *soap = soap_new();

Next input and output arguments of GetQuote method need to be allocated, this could be easily done storing in the stack :
struct _ns1__GetQuote ns1__GetQuote;
struct _ns1__GetQuoteResponse response;

Putting all together could give something like:
#include "soapH.h"
#include "DelayedStockQuoteSoap.nsmap"
#include "soapClient.c"

main() {
  struct soap *soap = soap_new();
  struct _ns1__GetQuote ns1__GetQuote;
  struct _ns1__GetQuoteResponse response;
  ns1__GetQuote.StockSymbol = "goog";
  ns1__GetQuote.LicenseKey = "0";
  if (soap_call___ns1__GetQuote(soap, NULL, NULL, &ns1__GetQuote, &response) == SOAP_OK)
    printf("yay\n");
}


text:
Q: Navigate SwiftUI page from WKWebView operation I am a newbie in IOS Programming and also SwiftUI. Coming from Java/Kotlin Android. I want to learn SwiftUI.
I have a WKWebView. I want to change SwiftUI page according to url changes in WKWebView. I have done a lot of work as you can see below. But I am struggled in navigation.
struct ContentView: View, Listener {
    func onFetched() {
        NavigationLink(destination: MainView()) {/* HERE this is not working.
App never goes to MainView.swift page.*/
            Text("Show Detail View")
        }
    }

    var body: some View {
        NavigationView {
            VStack {
                WebView(authListener: self)
            }.navigationBarTitle(Text("PEAKUP Velocity"))
        }
    }
}

struct WebView: UIViewRepresentable {
     var listener: Listener

     @ObservedObject var observe = observable()

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
         observe.observation = uiView.observe(\WKWebView.url, options: .new) { view, change in
             if let url = view.url {
                self.observe.loggedIn = true     // We loaded the page
                self.listener.onFetched()
                uiView.isHidden = true
            }
        }
        uiView.load("https://google.com")
    }
}

protocol Listener {
    func onFetched()
}

Update: I tried this in onFetched():
 NavigationLink(destination: MainView()) { Text("") }''''

 And I tried this piece of code:
 NavigationView {
        NavigationLink(destination: SecondView()){
            Text("Navigation Link")
        }
    }

Update 2: I tried this code also in onFetched:
self.presentation(Model(MainView(), onDismiss: nil))

Update 3: I tried this:
self.sheet(isPresented: $sayHello) {
        MainView()
    }

A: ** Disclaimer I haven't used WKWebviews in the context of SwiftUI, but I assume same would be true. **
I would recommend looking into WKNavigationDelegate. Unless your class is of type WKWebView you need to ensure to assign a delegate to handle any navigation events.
Perhaps you'll find the below article helpful: https://www.hackingwithswift.com/articles/112/the-ultimate-guide-to-wkwebview


text:
Q: How to structure two classes that "intersect" and output certain values (Mediator design pattern)? I have two classes: User and Site. User and Site have a many-to-many relationship. A Site object S has a property indicating whether or not a User U should be validated before U is added to S. To validate a User, the application retrieves validation rules from the Site and checks to see that the User's properties' values match the validation rules' values. If they all match/pass, the User is "valid" to be added to that Site.
How would you structure this relationship? My first thought is to create an intermediate class (i.e. Mediator design pattern?) that has a field of type IEnumerable<User> and Site so I can encapsulate the Site validation setting retrieval. Also, I'm thinking of adding an "IsValid" property to the User class. Is that all I need? I want to make sure things are not tightly coupled.
Thoughts?
Here's similar code I wrote up:
public class User
{
    public int _userId;
    public string _fname;
    public string _lname;

    public User(string connectionString, int id)
    {
        using (var dc = new DataContext(connectionString))
        {
            var user = dc.Users.SingleOrDefault(u => u.ID == id);
            _userId = user.ID;
            _fname = user.FName;
            _lname = user.LName;
        }
    }

    public bool IsValidUser(int siteId)
    {
        bool isValid = true;
        // logic here probably won't change
        var conditions = Site.GetConditions(_userId);
        // e.g. checks _fname, _lname
        return Site.UserMeetsConditions(_id, conditions);
    }
}

public class Site
{
    public int _siteId;
    public List<Setting> _siteSettings;

    public Site(string connectionString, int id)
    {
        using (var dc = new DataContext(connectionString))
        {
            var site = dc.Sites.SingleOrDefault(u => u.ID == id);
            _siteId = site.ID;
        }
    }

    public void SetSiteSettings(string connectionString)
    {
        using (var dc = new DataContext(connectionString))
        {
            _siteSettings = dc.SiteSettings.Select(s => s).ToList();
        }
    }

    public bool SiteRequiresValidityCheck()
    {
        return _siteSettings.Any(s => s.SettingID = 100 && s.Value == true);
    }
}

public Validator
{
    public List<User> users;
    public bool _requiresValidityCheck;

    public bool UsersAreValid(int siteId)
    {
        bool usersAreValid = true;
        if (_requiresValidityCheck)
        {
            foreach (var user in users)
            {
                if (!user.IsValid)
                {
                    usersAreValid = false;
                    break;
                }
            }
        }

        return usersAreValid;
    }
}

static void Main()
{
    string cs = myconnectionstring;
    var user1 = new User(cs, 1);
    var user2 = new User(cs, 2);
    List<User> users = new List<User>() { user1, user2 };
    var site = new Site(cs, 10);
    site.SetSiteSettings(cs);
    var validator = new Validator();
    validator.Users = users;
    validator._requiresValidityCheck = site.SiteRequiresValidityCheck();

    bool usersAreValid = validator.UsersAreValid(site._siteId);

}

A: If this is a POCO class or a MODEL you could use DataAnnotations on your class attributes.
Like user
[Required]

etc attributes for each attribute.
Data annotations also has support for cross attribute checking that you can implement those too.
take a look at them here:
https://msdn.microsoft.com/en-us/library/dd901590%28VS.95%29.aspx


text:
Q: Stack frame for signal handling in the Linux Kernel I see that the stack frame the process needs to handle signals is allocated in the function setup_rt_frame().
My question is: where it is de-allocated?
Thank you!

A: setup_rt_frame() sets stack for Real-time signals (see man 7 signal). It does 2 main things:

*

*Saves CPU context of user process (before it was interrupted) from kernel stack to user stack.
For ARM architecture it's done in setup_sigframe().

*Saves return address (where signal handler returns) to user stack.
Return address will point to rt_sigreturn() syscall (see man 2 sigreturn for details).
For ARM architecture it's done in setup_return().

As you can see, once signal handler is finished, it will automatically return to sys_rt_sigreturn() function in kernel. This function will restore kernel stack from user stack and get back to interrupted user-space process.
So, answering your question:

where it is de-allocated?

It's being restored in sys_rt_sigreturn() function.
See also:
[1] How signals work internally?
[2] Who uses POSIX realtime signals and why?
[3] Implementation of signal handling (see sections "Delivering Signals (7)" to "Delivering Signals (12)")


text:
Q: How to detect windows Store App is Online (for Sync) or Offline (to fetch data from sqlite) like javascript we use navigator.online? I need to detect app is Online or Offline.
According to network availability I can sync data to sqlite and if app is Offline run app on sqlite data.

A: public static bool IsInternet()
{
    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
    return internet;
}

See this question.


text:
Q: Get contagion chain from adjacency matrix, r, igraph Q.I have a erdos.reyni graph. I infect a vertex and want to see what sequence of vertices the disease would follow? igraph has helful functions like get.adjacency(), neighbors().
Details. This is the adjacency matrix with vertex names instead of 0,1 flags and i'm trying to get the contagion chain out of it. Like the flow/sequence of an epidemic through a graph if a certain vertex is infected. Let's not worry about infection probabilities here (assume all vertices hit are infected with probability 1).
So suppose I hit vertex 1 (which is row 1 here). We see that it has outgoing links to vertex 4,5,18,22,23,24,25. So then the next vertices will be those connected to 4,5,18...25 i.e. those values in row4, row5, row18,... row25. Then, according to the model, the disease will travel through these and so forth.
I understand that I can pass a string to order the matrix rows. My problem is, I cannot figure out how to generate that sequence.
The matrix looks like this.
    > channel
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
 [1,]    4    5   18   22   23   24   25   NA
 [2,]    6   10   11   18   25   NA   NA   NA
 [3,]    7   11   18   20   NA   NA   NA   NA
 [4,]   24   NA   NA   NA   NA   NA   NA   NA
 [5,]    1    3    9   13   14   NA   NA   NA
 [6,]    3    8    9   14   19   23   NA   NA
 [7,]    3    4    8   15   20   22   NA   NA
 [8,]    2    3   25   NA   NA   NA   NA   NA
 [9,]    3    4   11   13   20   NA   NA   NA
[10,]    4    5    8   15   19   20   21   22
[11,]    3   13   15   18   19   23   NA   NA
[12,]   11   13   16   NA   NA   NA   NA   NA
[13,]    4    6   14   15   16   17   19   21
[14,]    2    6   13   NA   NA   NA   NA   NA
[15,]    3   17   20   NA   NA   NA   NA   NA
[16,]    6   15   18   23   NA   NA   NA   NA
[17,]    2   25   NA   NA   NA   NA   NA   NA
[18,]    2    5   NA   NA   NA   NA   NA   NA
[19,]    3   11   NA   NA   NA   NA   NA   NA
[20,]    1    4    7   10   12   21   22   25
[21,]    2    4    6   13   14   16   18   NA
[22,]    1    3    4   15   23   NA   NA   NA
[23,]    1   16   24   NA   NA   NA   NA   NA
[24,]    7    8   19   20   22   NA   NA   NA
[25,]    7   12   13   17   NA   NA   NA   NA

I want to reorder this matrix based on a selection criteria as follows:
R would be most helpful (but i'm interested in the algo so any python,ruby,etc.will be great).The resulting vector will have length of 115 (8x25=200 - 85 NAs=115). and would look like this. Which is basically how the disease would spread if vertex 1, becomes infected.
4,5,18,22,23,24,25,24,1,3,9,13,14,2,5,1,3,4,15,23,1,16,24,7,8,19,20,22,7,12,13,17,7,8,19,20,22, 4,5,18,22,23,24,25,7,11,18,20...

What I know so far:
 1. R has a package **igraph** which lets me calculate neighbors(graph, vertex, "out")
 2. The same package can also generate get.adjlist(graph...), get.adjacency

A: Finding a "contagion chain" like this is equivalent to a breadth-first search through the graph, e.g.:
library(igraph)
set.seed(50)
g = erdos.renyi.game(20, 0.1)
plot(g)
order = graph.bfs(g, root=14, order=TRUE, unreachable=FALSE)$order

Output:
> order
 [1]  14   1   2  11  16  18   4  19  12  17  20   7   8  15   5  13   9 NaN NaN NaN

A: It's not clear how you define the ordering of the rows, so... just a few hints:
You can select a permutation/combination of rows by passing an index vector:
> (m <- matrix(data=1:9, nrow=3))
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> m[c(2,3,1),]
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    3    6    9
[3,]    1    4    7

The function t() transposes a matrix.
The matrix is stored in columns-first (or column-major) order:
> as.vector(m)
[1] 1 2 3 4 5 6 7 8 9

NA values can be removed by subsetting:
> qq <- c(1,2,NA,5,7,NA,3,NA,NA)
> qq[!is.na(qq)]
[1] 1 2 5 7 3

Also, graph algorithms are provided by Bioconductor's graph or CRAN's igraph packages.


text:
Q: Saving view to different schema using QGIS DB manager? When I ask to save a query to a view QGIS pops up a dialogue box asking the for a name and then saves the view in the public schema with that name.  I have tried "layers.name" but this just puts "layers." in front of the name and saves it in public.
The only way I have found to get the views created in the layers schema is to use postgres directly.
Am I missing something?

A: You can write the CREATE VIEW part into the SQL input box instead of clicking the create view button. With the button, it's always put into public. (I might have seen a ticket related to this issue somewhere ...) If CREATE VIEW is simply specified in the SQL statement, the view is created in the specified schema.


text:
Q: Hover effect on inline span goes away in between text gap In the following setup, when hovering over the actual text, the hover effect fires, all good there. But the hover effect goes away when hovering over the gap in between the lines of text. I'd like the hover event to happens always even in the gaps. I know if I set it to display block, that will fix it. But in my particular case I need it to be inline.

div {
  display: inline;
}

span {
  line-height: 40px;
}

span:hover {
  color: red;
}

    long text, needs to be display inline. long text, needs to be display inline. long text, needs to be display inline. long text, needs to be display inline. long text, needs to be display inline.
  <//span>

A: try adding padding to the span, such as padding: 15px 0px; (top and bottom, not sides) to cover the gap between the lines. this should fix it

A: Apply some padding top and bottom to span it cover gap between lines like "inline-block"


text:
Q: My app has two processes, LeakCanary2 is not working I am using LeakCanary2 in my app which has two processes. One is main process, the other is remote process.
I try to make a leak in main process, but leak canary is not detecting the leak.


text:
Q: rotate images using UICollectionview in iOS5 I have used UICollectionView (Like below Image) in IOS6 is working fine.
Now, i want this in IOS5. but "UICollectionview" is not supported by iOs5.
i have triyed using supported library  PSTCollectionView but not get success.
So, it is possible to do this in IOS5? HOW?

A: UICollectionView is iOS6 only. You can include extra code to check for iOS6 and use your custom class on iOS5. But there is no way to use an actual UICollectionView in iOS5.
have look at this question


text:
Q: Knockoutjs not updating on lastest version of Edge I have a knockoutjs app which has been running smoothly for years now. The browser receives a message via SignalR and then is rendered by Knockoutjs.
Now if you run the app in Microsoft Edge, the same fields are not updating on screen where as other fields are updating. It is always the same fields that update once, then never update again. If you inspect the DOM then you can see this being changed.
After a lot of process of elimination, I have actually discovered that the issue seems to be caused by 1 line of css
html { text-transform: uppercase; }

I have put together a small demo of this bug which you can then run in Chrome/FF/IE9/IE10 vs Edge. Run the code in Edge with the style applied, then comment it out to see the values updating.
http://jsbin.com/baqozusuge/edit?html,css,js,console,output
Link to code on github https://gist.github.com/anonymous/de7610c341e6ee737d8290eb608afb57
Anyone any idea what the heck is going on with this?! It seems as though Microsoft Edge is deciding to cache the display based on the similarity of the value currently displaying.

A: This is officially a Microsoft bug so something that cannot be "fixed" through code. https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7451374/


text:
Q: Am I correct in saying this about a battery? I recently answered this:

Q When a battery, by performing work on a charge, moves it to the higher potential, why doesn't the charge move through the battery and return to the low potential, why does it go through the circuit?

A: Simply, because the battery exerts a non-electrostatic force (due to internal chemical reactions) that force the electrons to move the opposite direction. Remember the battery does some work in doing what is not favorable therefore the energy in battery is drained after sometime.

Am I correct? Seems like some people disagree.

A: Yes, you are right. Ideally, since the ends of a battery are oppositely charged like the plates of a capacitor, they can move through the battery and make the battery fail. But the resistance of a battery is much higher for conduction of charge via an applied potential than the circuit. So the charge instead moves through the circuit.


text:
Q: AWS C++ S3 SDK PutObjectRequest unable to connect to endpoint In working with the AWS C++ SDK I ran into an issue where trying to execute a PutObjectRequest complains that it is "unable to connect to endpoint" when uploaded more than ~400KB.
Aws::Client::ClientConfiguration clientConfig;
clientConfig.scheme = Aws::Http::Scheme::HTTPS;
clientConfig.region = Aws::Region::US_EAST_1;

Aws::S3::S3Client s3Client(clientConfig);

Aws::S3::Model::PutObjectRequest putObjectRequest;
putObjectRequest.SetBucket("mybucket");
putObjectRequest.SetKey("mykey");

typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> stmbuf(compressedData, dataSize);
std::iostream *stm = new std::iostream(&stmbuf);

putObjectRequest.SetBody(std::shared_ptr<Aws::IOStream>(stm));
putObjectRequest.SetContentLength(dataSize);

Aws::S3::Model::PutObjectOutcome outcome = s3Client.PutObject(putObjectRequest);

As long as my data is less than ~400KB it gets uploaded into a file on S3 but beyond that it is unable to connect to endpoint. I should be able to upload up to 5GB in one PutObjectRequest.
Any thoughts?
Edit:
Responding to @JonathanHenson's comment, the AWS log shows this timeout error repeatedly:
[DEBUG] 2016-08-04 13:42:03 AWSClient [0x700000081000] Request Successfully signed
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] Making request to https://s3.amazonaws.com/mybucket/myfile
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] Including headers:
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] content-length: 3151261
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] content-type: binary/octet-stream
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] host: s3.amazonaws.com
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] user-agent: aws-sdk-cpp/0.13.9 Darwin/15.6.0 x86_64
[DEBUG] 2016-08-04 13:42:03 CurlHandleContainer [0x700000081000] Attempting to acquire curl connection.
[DEBUG] 2016-08-04 13:42:03 CurlHandleContainer [0x700000081000] Returning connection handle 0x10b09cc00
[DEBUG] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] Obtained connection handle 0x10b09cc00
[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000] HTTP/1.1 100 Continue

[TRACE] 2016-08-04 13:42:03 CurlHttpClient [0x700000081000]

[ERROR] 2016-08-04 13:42:06 CurlHttpClient [0x700000081000] Curl returned error code 28
[DEBUG] 2016-08-04 13:42:06 CurlHandleContainer [0x700000081000] Releasing curl handle 0x10b09cc00
[DEBUG] 2016-08-04 13:42:06 CurlHandleContainer [0x700000081000] Notifying waiting threads.
[DEBUG] 2016-08-04 13:42:06 AWSClient [0x700000081000] Request returned error. Attempting to generate appropriate error codes from response
[WARN] 2016-08-04 13:42:06 AWSClient [0x700000081000] Request failed, now waiting 12800 ms before attempting again.
[DEBUG] 2016-08-04 13:42:19 InstanceProfileCredentialsProvider [0x700000081000] Checking if latest credential pull has expired.

A: Ultimately what fixed this for me was setting the request timeout. The request time out needs to be long enough for your entire transfer to finish. If you are transferring large files on a slow internet connection make sure the request timeout is long enough to allow those files to transfer.
Aws::Client::ClientConfiguration clientConfig;
clientConfig.scheme = Aws::Http::Scheme::HTTPS;
clientConfig.region = Aws::Region::US_EAST_1;
clientConfig.connectTimeoutMs = 30000;
clientConfig.requestTimoutMs = 600000;

A: Tweak your config file to below.And see it will work.
Aws::Client::ClientConfiguration clientConfig;
clientConfig.scheme = Aws::Http::Scheme::HTTPS;
clientConfig.region = Aws::Region::US_EAST_1;
clientConfig.connectTimeoutMs = 30000;

Aws::S3::S3Client s3Client(clientConfig);

Aws::S3::Model::PutObjectRequest putObjectRequest;
putObjectRequest.SetBucket("mybucket");
putObjectRequest.SetKey("mykey");

typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> stmbuf(compressedData, dataSize);
std::iostream *stm = new std::iostream(&stmbuf);

putObjectRequest.SetBody(std::shared_ptr<Aws::IOStream>(stm));
putObjectRequest.SetContentLength(dataSize);

Aws::S3::Model::PutObjectOutcome outcome = s3Client.PutObject(putObjectRequest);


text:
Q: Talk about A more than B vs talk more about A than B Which sentence has the correct grammar?

*

*I talk about A more than B.

*I talk more about A than B.

I think the first one is correct, while my friend uses the second one.

Dr. Karp's interview may ask children if they miss their biological parents or how long it has been since they saw their parents last time, all of which would sway them toward talking more about their biological parents than do other adults in the village.

The above sentence is what my friend wrote. I think the word, do, is redundant. Am I correct? Also, which one, "talk about A more than B" or "talk more about A than B", should we use in this sentence?

A: Adverbs are pretty flexible in English. Many can be placed anywhere in the sentence to retain the same meaning. Others imply different things based on where they are placed.
Talk more about, to me, implies that the talking is at greater length.
Talk about more, to me is equal to "talk about more often."
For instance if an interviewer says "Would you talk more about your father" or "Would you talk about your father more" they are saying the same thing.
So... they can both have either meaning. Welcome to English ambiguity. :)


text:
Q: Mysql Getting Results Group by SUM + a row with the sum of descarted rows i have the following question in mysql:
from a query like this:
select Category, count(*) as C
from categories_likes
group by Category
order by C desc
limit 3

I need to get a result like this:
Category | C
Love     | 10
Sad      | 5
Angry    | 3
Other    | 50

Where other is "Other" row is the sum of counts in the other categories not needed in the result but needed to group all in one last row.
Hope Somebody can help me.
Thanks

A: Presumably, you want to group all categories other than "Love", "Sad" and "Angry" in a unique group, called "Other".
If so, you can use a case expression:
select
    case
        when category in ('Love', 'Sad', 'Angry') then category
        else 'Other'
    end new_category,
    count(*) cnt
from categories_like
group by new_category
order by (new_category = 'Other'), cnt desc

Note that the order by clause of the query puts category "Other" last.

If you want a dynamic top 3 of the categories, followed by the total count in all others categories, then it's a bit different. Assming MySQL 8.0, you can use a ranking function:
select case when rn <= 3  then category else 'Other' end new_category, sum(cnt) cnt
from (
    select category, count(*) cnt, rank() over(order by count(*) desc) rn
    from categories_like
    group by category
) t
group by new_category
order by (new_category = 'Other'), cnt desc

In earlier versions, I would suggest union all:
(
    select category new_category, count(*) cnt
    from categories_like
    group by category
    order by cnt desc
    limit 3
)
union all (
    select 'Other', sum(cnt)
    from (
        select category, count(*) cnt
        from categories_like
        group by category
        order by cnt desc
        limit 4, 1000
    ) t
)
order by (new_category = 'Other'), cnt desc

This assumes that there are not more than 1000 categories; you can increase the offset of the subquery as needed.


text:
Q: Why the loop is not breaking after first iteration .Expected answer is [1,3] I have this code:
def num(list, target):
    index = []
    for i in list:
        for x in list:
            if i + x == target:
                index.append(list.index(i))
                index.append(list.index(x))
                break
    print(index)

li = [1, 7, 11, 2, 15]
num(li, 9)

I expected to get [1,3], but the result is [1,3,3,1]. Why?


text:
Q: How do versions work and how are they measured? You see programs or games have versions displayed such as 1.2.5 (Minecraft), Version 3 Build 3000 (Sublime Text 3), or 1.9.2a0 (Python's Pygame).
How do these system work and how are they measured?

A: About the only consistent rule that people follow is that later releases have somehow higher version numbers (and even that's only a guideline).
In any case, what constitutes "higher" can often be indicative of some fatal flaw in the developers grey matter.
A common simple approach (and the one I use) is <major>.<minor>, where <minor> is increased for relatively simple changes (small improvements or bug fixes) and <major> increased (resetting <minor>) for more substantial changes such as massive new functionality.
But, as stated, that's only one possibility. IBM tends to use a VxRxMx model for version, release and mod-level, some companies (like Microsoft or Sublime Text apparently) insert build numbers, others insert different text based on the build such as -beta or .cygwin.
The number of possibilities are almost endless.

A: To be honest, they're pretty much arbitrary, and depend entirely on the whims of the developers.
However, there are several common conventions that are followed by developers, with the most popular being in the form major.minor[.build[.revision]], such the Minecraft 1.2.5 example. This convention can be used to communicate the significance of a change; for example, a major revision may break compatibility, while a minor revision might include new features, while a new build might contain bugfixes only.
Lots more info in wikipedia: https://en.wikipedia.org/wiki/Software_versioning.


text:
Q: Is there a way to load JS file without require? Is there a way to load a javascript file without require, but with fs for example?
I know that for json files I can do:
const jsonFile = JSON.Parse(fs.readFileSync("./jsonfile.json")

Is there a way to do the same for a javascript file?
The reason I am asking is because, i have a configuration file that I kinda want to detach from my app, because when I bundle it with webpack, I cant exclude the config file.
I have tries to directly read it, but I just got some raw format in a buffer:
const jsFile = fs.readFileSync("./jsFile.js")

EDIT ANSWER: I was able to do it by utilizing readFileSync and eval:
const jsFile = eval(fs.readFileSync("./jsFile.js", "utf-8"));

Keep in mind that if you are requiring other files within that file, the paths change! They will NOT be relative to jsFile.js, but relative to the file which reads the jsFile.js

A: I was able to do it by utilizing readFileSync and eval:
const jsFile = eval(fs.readFileSync("./jsFile.js", "utf-8"));

Keep in mind that if you are requiring other files within that file, the paths change! They will NOT be relative to jsFile.js, but relative to the file which reads the jsFile.js


text:
Q: Best choice when detecting whether a view's point is inside another view? So I've found 3 ways to make this happen.

*

*convertPoint:toView:
convertPoint:fromView:
convertRect:toView:
convertRect:fromView:

*Bool CGRectContainsPoint(CGRect rect, CGPoint point);

*BOOL isPointInsideView = [aView pointInside:aPoint withEvent:nil];
They all seem to do the same but I might be wrong. You check if a point is inside a certain view considering its frame then get either true or false.
Does it not matter which one of them I end up using or should I be aware of issues that might arise..?

A: You should be aware of what each method is used for:
The docs for pointInside:withEvent: say

point | A point that is in the receiver's local coordinate system (bounds).

Apart from that the method probably does simply call CGRectContainsPoint with the passed point and the bounds frame.
CGRectContainsPoint simply does the math of checking the x and y coordinates against the origin and size. Simple math, but once again both have to be in the same coordinate system since neither the rect nor the point contain any information about their respective coordinate system, they are absolute values.
The convert* functions offer you the ability to transform the CGPoint which is relative to the receiver's coordinate system into some other relative coordinate system.
To understand what each method is good for, you have to understand what the different CGRects mean, frame and bounds in particular: this answer is THE way to go for that.
After understanding what the different properties mean it should be easy to pick the correct function.
TL;DR: the convert* methods offer you the ability to transform CGPoints between coordinate systems. The other two options operate within one certain fixed coordinate system. It is your job to pick the one you need in your particular case.
For example you might have to transform a point first and then perform the hit detection.


text:
Q: using classes to in different scripts with python and pygame I have recently started to make a game with python and pygame, I have a main script that has all my other scripts imported in and then it runs them all, but I have two main problems. The first being that when I run the first script in the main script it seems to stop after that class and not continue with the other script.
what i want the game to do:
show thee pictures as the opening credits. (working)
then once the credits are finished start up a menu, at the moment this is just one play button and a Rect which will have a collision response to detect whether the player has clicked it or not. (not working)
here are my scripts:
RUN.py (main game that runs everything together):
import pygame, random, math, sys, os, time
import startUp, Menu
from pygame.locals import *
pygame.init()

#classes setup
Begin = startUp.Begin()
Menu = Menu.HUD()
while True:

    #quit button
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    #show 3 pics for the opening credits
    Begin.Run()

    #bring up the menu once the opening credits are done
    Menu.Run()

Then Menu.py (the menu for the game)
import pygame, time, random
from pygame.locals import *
pygame.init()

class HUD(object):

    def __init__(object):
        object.playButtonUp = "playButtonUp.png"
        object.playButtonUpHover = "playButtonUpHover.png"
        object.playButtonDown = "playButtonDown.png"

        object.Black = (0, 0, 0)
        object.Red = (0, 255, 0)
        object.screen = pygame.display.set_mode((1440, 720), 0, 32)

        object.playButtonUp = pygame.image.load(object.playButtonUp).convert_alpha()
        object.playButtonUpHover = pygame.image.load(object.playButtonUpHover).convert_alpha()
        object.playButtonDown = pygame.image.load(object.playButtonDown).convert_alpha()

    def Run(object):
        #object.screen.fill(object.Black)

        #creat rects
        object.playButtonRect = Rect(464, 232, 256, 128)

        #blit imagers
        object.screen.blit(object.playButtonUp, (464, 232))

there are no error message's and it seems to work but the image is not shown on the screen.
thanks for you time and help!

A: Your structure is incorrect. You have merged two different approaches.
You have a Run script that should first show the 3 pictures, and after that show the menu.
Right now, you have a while loop that calls the run function of both Begin and Menu until you close the game.
Instead the files should look like this:
import pygame, random, math, sys, os, time
import startUp, Menu
from pygame.locals import *
pygame.init()

#classes setup
Begin = startUp.Begin()
Begin.run()

Menu = Menu.HUD()
Menu.run()

Menu.py
class HUD(object):
    def run(object):
        while True:
            object.playButtonRect = Rect(464, 232, 256, 128)
            object.screen.blit(object.playButtonUp, (464, 232))
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()


text:
Q: Smooth svg polyline points animation to create dynamic financial stock chart I'm trying to create a dynamic financial stock linear chart using svg polyline.
I was able to update the chart by adding new coordinates after every one second. But I want it to animate to each coordinates instead of jumping to the new coordinates after one second
i have tried using jquery keyframes library but the animation was not what i wanted. I want the polyline to animate from the initial coordinate to the new coordinate
$.keyframe.define([{
name: 'myfirst',
  from: {
    'stroke-dashoffset': '1000'
  },
  to: {
    'stroke-dashoffset': '0'
  }

  }]);
 $("#path").css({"stroke-dasharray":'1000',"stroke-dashoffset":'1000'});

 $("#path").playKeyframe({
   name: 'myfirst',
     duration: '5s',
timingFunction: 'linear',
iterationCount: '1'

 });

HTML
<body>
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1000px" height="600px" class="logo-outline" viewBox="0 0 1000 600" enable-background="new 0 0 1000 600" xml:space="preserve">
<polyline id="path" style="fill:none;stroke:black;stroke-width:3" />

</svg></body>

JAVASCRIPT
  $(document).ready(function() {

     var x = 0;
     var y1 = 0;
     var y2 = 0;
     var y = 0;
     var point = 0+","+Math.round(Math.random()*1000);

     function upD() {
        x+=40;
        y2 = y1;
        y1=y;
        y = Math.round(Math.random()*100);
        point+=" "+x+","+y;
        document.getElementById('path').setAttribute('points',point);
        // jquery keyframe library
     $.keyframe.define([{
        name: 'myfirst',
        from: {
            'stroke-dashoffset': '80%'
        },
        to: {
           'stroke-dashoffset': '0'
        }

    }]);
    $("#path").css({"stroke-dasharray":'100%',"stroke-dashoffset":'100%'});

    $("#path").playKeyframe({
        name: 'myfirst',
        duration: '5s',
     timingFunction: 'linear',
          iterationCount: '1'

   });
   }
     window.setInterval(upD,3000);

  });

I'm aiming to make a chart with polyline animation as that of olymp trade, or binarycent trade chart or something similar like a tick chart

A: Normally this type of animation is done in CSS by animating the stroke-dashoffset property
First you need to calculate the length of your path. In this case you can get the length of the polyline using path.getTotalLength(). This should be also the initial value for #path{stroke-dasharray: 1697.5px;} This means that the polyline has dashes and gaps of equal length: 1697.5px . Also the stroke-dashoffset is 1697.5px;` This means that the path is hidden since gap between the dashes is covering the whole polyline.
The @keyframes animation begins animating the stroke-dashoffset from 1697.5px to 0, till the dash is covering the whole path.
I hope this is what you need.

svg{border:1px solid}

#path{
  stroke-dasharray: 1697.5px;
  stroke-dashoffset: 1697.5px;
  animation:test 6.5s forwards
}

@keyframes test {
  from { stroke-dashoffset: 1697.5px;}
  to   { stroke-dashoffset: 0;}
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1000px" height="600px" class="logo-outline" viewBox="0 0 1000 600" enable-background="new 0 0 1000 600" xml:space="preserve">
<polyline id="path" style="fill:none;stroke:black;stroke-width:3" points="0,518 40,68 80,2 120,63 160,17 200,42 240,75 280,99 320,44 360,59 400,34 440,28 480,56 520,68 560,54 600,26 640,74 680,78 720,27 760,9 800,45 840,72 880,73 920,70 960,13 1000,35"></polyline>
</svg>


text:
Q: Move-Item with Exclude doesn't work I have two scripts which should do the same but the first doesn't work and the second does. Why is that? I have managed to figure out it has something to do with the Execlude. It says:
Move-Item : Cannot move item because the item at 'E:\hudba\test.ps1' does not exist. At line:1 char:1 + Move-Item "E:\test\*" "E:\ ... + CategoryInfo     : InvalidOperation: (:) [Move-Item], PSInvalidOperationException   + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand

The scripts
Move-Item "E:\test\*" "E:\test2" -Exclude "*.ps1"

Get-ChildItem -Path "E:\test\*" -Recurse -Exclude "*.ps1" | Move-Item -Destination "E:\test2"

Thank you :)

A: This is a known issue, and is slated for v6 to fix
https://github.com/PowerShell/PowerShell/issues/2385


text:
Q: C - Dynamic Memory Allocation #include<stdio.h>
#include<malloc.h>

int main()
{
    char *string1;
    int length;

    scanf("%d", &length);

    string1 = (char *)malloc(sizeof(char) * length);

    printf("\n Enter the First String : ");
    fgets(string1, length, stdin);

    printf("\n The First String : %s ",string1);

    free(string1);

    return 0;
}

Can someone help me on the above code ? I trying to get the length of a string and the string as inputs. But, I am able to enter only Length of the string. After that it skips the string input part.
This is the output I am getting :
sh-4.3$ main
10

Enter the First String :
The First String :
sh-4.3$

A: *

*After typing "10<enter>" the <enter> or "\n" will remain in the
stdin buffer, so you have to use getchar() after the scanf to
remove it.

*Also you should #include <stdlib.h> instead of malloc.h.

*You malloc 1 character too less, because of the 0-terminator.
string1 = malloc(length + 1); will do the job, the cast is not
necessary and sizeof(char) is always 1.

A: If you need to use stdin for string input you can use fgetln. I edited you example and now it looks like that:
#include<stdio.h>
#include <stdlib.h>

int main()
{
    char *string1;
    size_t length;

    //scanf("%d", &length);

    //string1 = (char *)malloc(sizeof(char) * length);

    printf("\n Enter the First String : ");
    //fgets(string1, length, stdin);
    string1 = fgetln(stdin, &length);
    string1[length] = '\0';

    printf("\n The First String : %s ",string1);

    free(string1);

    return 0;
}

Note: fgetln returns not a C string, you should add a NULL character to the end.

A: The most simple answer when reading from STDIN/keyboard with the newline etc.
is to just add the "\n" to the scanf, ie:
scanf("%d\n", &length);

Solves the problem ;)
PS: Beware of all the other security/buffer overflow issues of scanf


text:
Q: Spring Boot - MockMvc result null for GET (Cucumber) I am running into an issue when trying to create a mockMvc get request, I receive a null result when requesting to get a JSON object. I have it that I can create a post fine, but struggling to receive data when invoking a GET endpoint in my controller.
AddressStepDefs.java
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= WebEnvironment.MOCK)
@Transactional
@AutoConfigureMockMvc
/**
 * Address Step Definition class to execute Scenario(s) contained in Address.feature
 * @author Lewis Jones
 *
 */
public class AddressStepDefs {

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private MockMvc mockMvc;

    private ResultActions result;

    @Autowired
    @MockBean
    private AddressRepository addressRepo;

    /**
     * Build the Controller under test
     */
    @BeforeClass
    public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new AddressController()).build();
    }

    /**
     * Set the mock server up
     */
    @Before
    public void serverSetup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    /**
     * Build the WebApplicationContext
     */
    @Given("The server is up and running")
    public void the_server_is_up_and_running() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @When("I request to view an Address with id {int} at {string}")
    public void i_request_to_view_an_Address_with_id_at(Integer id, String request) throws Exception {
        /** Build a GET request using mockMvc **/
        result = this.mockMvc.perform(get(request + id).contentType(MediaType.APPLICATION_JSON));
    }

    @Then("the response code should be OK {int} and the resulting Address object json should be:")
    public void the_response_code_should_be_OK_and_the_resulting_Address_object_json_should_be(Integer responseCode, String json) throws Exception {
        result.andExpect(status().is(responseCode));
        result.andExpect(content().string(json));
    }

*

*The Controller endpoint and the request is fine.

*There is data in the database.

*It works WITHOUT the @MockBean, but then my post actually inserts data into the database. (Which isn't what I want)

*I have tried to @InjectMocks, no luck.

Where am I going wrong? Do I have the correct annotations?

A: By mocking your bean, you'll get all its results as null.
You have 2 options,

*

*You continue to mock but you define behaviors using when/then

*You spy your bean: then it will do "the same" as normal and you can just stub the method you don't want.


text:
Q: Missing Events in Kibana due to roll out of events from .json file I'm using ELK, due to so much of logging happening, the events in .json file is rolling out to .json.1 file so, when I run my test, I am not getting all the events in kibana ( for ex, if I am having 1200 events, I will get 1100 events entries in kibana, and rest 100 will be rolled out to .json.1, once .json file is filled completely. But I have made a configuration in logstash  to read only .json file and I am missing all 100 events present in .json.1.). How to get those rolled out 100 events in kibana?

A: It seems your basic problem is too many events logged to file and logstash is not picking them up fast enough.
How are the events generated? Can you change the logger to log to rabbitmq or redis or something else? Then you can have logstash pickup these messages from rabbitmq or something else.
This approach will give you higher guarantee of delivery and lower risk of losing messages.

A: While it depends a bit on how the files are rotated, it should be fine to just list both files foo.json and foo.json.1 in the filename patterns that Logstash watches. Or, increase the interval between rotations.
Either way it requires that what you're describing only happens during rare bursts and that the overall rate of logging is significantly lower than what Logstash can process. If not you simply have to increase Logstash's performance.


text:
Q: Can we Make Approval Process Optional for Sometime? We have an approval process on one of Opportunity's child object. Approval Process is almost 6 steps approval process.
We have recently migrated to PROD and for Data Update we don't need to follow Approval process.We just need to auto update those records to approved in order to bypass validation rule.
Our client wants approval process optional till next 2 months until environment is ready completely for Business User.
We can not remove the approval process as we need it after sometime. for now we just need to auto approve it.
Is there a way to make it Optional for sometime?

A: You can create a WF Rule temporary that sets the Record Status to Approved.Create a WF Rule when you create a new record.
For Existing Records,Find out those records Via Data Loader or Workbench and Set the Status to Approved via Data loader.
When your environment is ready then you can disable those WF Rule.
Another option would be create a checkbox field and Bypass it in your validation.
Let me know if it helps.