Q:

Convert PFGeoPoint to String Error

I am tying to save a PFGeoPoint in a parse server with the following code:
var coordinates = PFGeoPoint (latitude: (newCoordinate2.latitude), longitude:(newCoordinate2.longitude))

        var aboutSpot = PFObject(className: "spotdetail")

        aboutSpot["name"] = "name"
        aboutSpot [PFGeoPoint] = coordinates
        aboutSpot.saveInBackgroundWithBlock { (succes, error) -> Void in
            print("separate name and geopoint have been saved")
        }

and I get the following message:
swift cannot convert value of type `(PFGeoPoint).type (aka 'PFGeoPoint.type`) to expected argument type 'String'

What can I change so Xcode stops thinking that I am trying to save a String?

A:

I figured it out so I added a column manually in the parse server then changed the code like this and it now works, thanks for helping out
var coordinates = PFGeoPoint (latitude: (newCoordinate2.latitude), longitude:(newCoordinate2.longitude))

var aboutSpot = PFObject(className: "spotdetail")

aboutSpot["name"] = "replaceNow"
aboutSpot ["PFGeoPoint"] = coordinates
aboutSpot.saveInBackgroundWithBlock { (succes, error) -> Void in
    print("separate name and geopoint have been saved")
}


Q:

Lenovo X1 Carbon suddenly slows when AC is attached

To avoid anyone losing time reading this all, the solution that worked twice is: Restore your PC using "System Restore" to a point in time prior to when you started experiencing this problem

Today I notice that my one year old laptop Lenovo X1 Carbon (Windows 8.1) is 2,5 times slower on everything, only when AC is attached.
As soon as I detach the AC to go on battery, performance magically goes back to normal, and as soon as I plug the AC, performance is immediately slower.
I checked with Task Manager and Process Explorer, no special process sucks my resources (both when AC is attached or not). However my CPU speed decrease significantly in Task Manager > Performance:

I tweak the Power Management Windows configuration with no success, nothing looks abnormal here. Btw, I am always on Maximum Performance plan, both when AC is attached or not.
I investigate the CPU parking stuff with no success, the CPU is not parked, I checked it both with the registry change and with Coderbag CPU core parking manager.
I tweak various BIOS Power options with no success (as explained there answers from CodePrime818 May 2015 at 10:18). They used to have always been set to default and I went back to default after experiments.
Finally I found this related post ThinkPad Windows 7 laptop is often slow but only when plugged into AC power, the answer was:
The real problem turned out to be that I was using a 90W power supply, and the thinkpad's power management mistakenly thinks this is not enough power and slows the CPUs down to save power. Using the 135W power supply fixes it. Some people have other suggestions, even a hardware hack:
I have 2 power suppliers, one bigger one smaller, both produces the issue, I don't know how many W they are here is a photo of the big one. However I haven't changed anything in the power supply, performance uses to be maximum on both, it must somehow comes from a BIOS or Windows setting change?!

Certainly this is related: This weekend the laptop was very low on battery and suddenly ran out of power. A never seen error told me that the clock didn't even have battery and indeed, the next time I restarted the machine it told me the hours with 30 minutes late for like 15 seconds, until it gets the right time automatically (from the network I guess).
I am pretty sure this is related to this issue, but have no idea what alse to do?

Info1: I have Lenovo 2 power suppliers (90W and 65W) both used to make this laptop works fine with AC attached.
Info2: I have a second Lenovo X1 Carbon, exactly same model, that works perfectly with these two power suppliers.
Info3: I just noticed that if I let the AC plugged, then close the screen to provoke sleep mode (not deep sleep mode), and then re-open the screen, push the power-on button, then the laptop is still plugged but now the CPU is back to 2.67 GHz! So at least I'll have a way to work plugged for some time, but I'd really like to fix this once for all.
Info4: Here are the Lenovo software actually installed on this Laptop (I see nothing related to Power Management)

Thanks for your help!

A:

Note: This is too long for a 'Comment' so I posted it as an 'Answer' even though it's really just some suggestions.
After giving this some more thought, doing a little research, and with the additional information you provided, here are a few things you might try. P.S.-I agree that this is probably not a hardware/AC adapter problem especially given the behavior of "info3" that you provided.
1) I found this at the Lenovo forum titled "X1 Carbon Won't Boot without AC Cord - reset switch" which states:
When servicing the system, or when storing it for an extended period of time, the battery can be electrically disconnected.  There is an option in BIOS to disconnect the battery - AC must be unplugged while doing this step.
To start up the next time, attach AC and press the power button.
If the system become hung and will not power down, or will not start even with the AC connected, try using a paper clip to press the small reset button found inside a hole in the bottom of the system.
2) Restore your PC using "System Restore" to a point in time prior to when you started experiencing this problem. You sound very tech savvy so I won't bore you with the details on how to do it.
3) If that doesn't work, you might try doing a "Refresh" of Windows. Microsoft has instructions on how to do this on a Windows 8.1 system titled "How to refresh, reset, or restore your PC".
Note: Doing this is pretty drastic since it will remove any apps you've installed from the web (not the Microsoft Store...those will automatically be reinstalled) and from CD/DVD. If the laptop came with Windows 8 installed (has a "Recovery" partition with Windows 8), the laptop will revert to Windows 8 and you will need to manually update it again to Windows 8.1.


Q:

How to record relative times between computers?

I need to independently record events on different computers and reconstruct which order those events happened relative to each other.  The solution calls for each computer to be relatively independent; they cannot directly talk to each other or a single source.
My initial solution recorded the time on each machine, but since times can be different on different machines, and can change throughout the day, this did not completely solve my problem.  I decided to share with all machines whenever a machine (1) starts the process, or (2) has its system clock change.
So from each machine I get a log full of these
public class Activity {
    DateTime TimeOccurred { get; set; }
    string Description { get; set; }
}

Whenever (1) or (2) happens above, I add an activity to the log and broadcast it to the other machines, who add the same activity to their log, with the TranslatedTime being their own time:
public class TimeSynchronization : Activity {
    string SourceMachine { get; set; }
    DateTime TranslatedTime { get; set; }
}

So machine A would have (in order):
TimeSynchronization "started" at 3:00 am.
Activity "asked a question" at 3:05 am.
TimeSynchronization from machine B at 3:05 am.
TimeSynchronization "clock changed" at 3:03 am.
Activity "received an answer" at 3:04 am.

And machine B would have (in order):
TimeSynchronization "started" at 3:05 am.
TimeSynchronization "clock changed" at 3:06

So I need to reconstruct the same order and timing of these above events, to something like:
On machine A: TimeSynchronization "started" at 0:00
On machine A: Activity "asked a question" at 0:05
On machine B: TimeSynchronization "started" at 0:05
On machine A: TimeSychronization from machine B at 0:05
On machine A: TimeSynchronization "clock changed" at 0:06
On machine B: TimeSynchronization "clock changed" at 0:06
On machine A: Activity "received an answer" at 0:07

What is the best way to take a List<Activity> from each machine and merge it into one list with the events in order?

A:

If the two machines are connected via the network your program can ask the other machine what time it is. That way your program on machine A could ask for the time on both A and B and then log both times.
You mention that the time could change during the day (presumably the user changed the time). You can detect this by using the Win32.TimeChanged event.


Q:

Setting corner radius hides UIView

I've created this extension to quickly add rounded corners to any UIView:
extension UIView {
    func setCorners(corners: UIRectCorner, radius: CGFloat) {
        print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
        let maskPath = UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
        print(self.frame) //-> (359.0, 0.0, 306.0, 37.0)
    }
}

The code I use to create the view and round its corners:
let view = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 40))) //I reposition the view later
view.setCorners(corners: [.bottomLeft, .bottomRight], radius: 8)

When commenting out the setCorners(corners:radius:), the view appears, while it stays hidden otherwise.
Any idea why this is happening?

A:

It seems, that you need use self.bounds instead self.frame in UIBezierPath(roundedRect: self.frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: 0.0))


Q:

Show that a group of order $5$ is always abelian.

Show that a group of order $5$ is always abelian.

I know that if the binary operation $*$ is defined on a group $G$ is commutative (i.e. $a*b=b*a\ \forall a,b\in G$),\ then G is called a commutative(or abelian) group.
But I don't know how to solve a group of order $5$ is abelian.
Thanks in advance!

A:

Hint: Take some non-identity element $a\in G$. Show that the set $\{a^n : n\in\mathbb N\}$ is a subgroup of $G$, and that it has $5$ elements so is the whole group $G$. Thus every element of $G$ is a power of $a$, so it is easy to show that $G$ is abelian.

A:

You say in comments that "you know" that every group of prime order is cyclic, and that every cyclic group is abelian. I do not understand how this can give you "only" the validity, but not a proof. What's "only" about it?
If you already know that a group $G$ is cyclic, then you can prove explicitly that it is abelian as follows: $G$ is cyclic means that there exists $g\in G$ such that for every $x\in G$ there exists (at least one) $n\in\mathbb{Z}$ such that $x=g^n$.
So if $x,y\in G$, then there exist $n,m\in\mathbb{Z}$ such that $x=g^n$ and $y=g^m$. Then $xy = g^ng^m = g^{n+m} = g^{m+n} = g^mg^n = yx$, which proves that $xy=yx$ for all $x,y\in G$, hence $G$ is abelian.
If you already know that every group of prime order is cyclic, then a group of order $5$ is cyclic, and by the argument above must be abelian.
If you "know" that every group of prime order is cyclic but you don't know how to prove it (in which case I would not describe it as something you "know", but that's just me), then it becomes a little trickier.  I will assume you don't know Lagrange's Theorem:

Lagrange's Theorem. If $G$ is a finite group of order $n$, and $H$ is a subgroup of order $d$, then $d$ divides $n$.

A corollary is: if $G$ is a finite group of order $n$, and $g\in G$, then the order of $g$ is a divisor of $n$.
Using Lagrange's Theorem, we have: let $G$ be a group of order $5$. Let $x\in G$, $x\neq 1$ (the identity of the group). Then the order of $x$ must divide $|G|=5$, hence $|x|=1$ or $|x|=5$. If $|x|=5$, then the cyclic subgroup generated by $x$ equals all of $G$, so $G$ is cyclic (and hence abelian as above). If $|x|=1$, then $x=1$, which we explicitly discounted. So $G=\langle x\rangle$, and we are done.
We can prove Lagrange's Theorem as follows: let $G$ be a finite group, and let $H$ be a subgroup. For every $y\in G$, let $Hy$ be the subset of $G$ given by:
$$Hy = \{hy\mid h\in H\}.$$
Claim: Let $y$ and $z$ be elements of $G$. If $Hy\cap Hz\neq\varnothing$, then $Hy=Hz$.
Proof. Let $g\in Hy\cap Hz$. Then there exist $h_1,h_2\in H$ such that $g=h_1y=h_2z$. In particular, $zy^{-1}=h_2^{-1}h_1\in H$, and $yz^{-1}=h_1^{-1}h_2\in H$.  We prove that $Hy=Hz$ by double inclusion.
Let $g\in Hz$. Then $g=hz$ for some $h\in H$. Note that $hh_1^{-1}h_2\in H$, so $(hh_2^{-1}h_1)y\in Hy$. But
$$(hh_2^{-1}h_1)y = h(h_2^{-1}h_1)y = h(zy^{-1})y = hz(y^{-1}y) = hz= g,$$
so $g\in Hy$. Thus, $Hz\subseteq Hy$. Symmetrically, if $g=hy\in Hy$, then
$$g = hy = hyz^{-1}z = h(h_1^{-1}h_2)z = (hh_1^{-1}h_2)z\in Hz,$$
so $Hy\subseteq Hz$. Thus, if $Hy\cap Hz\neq\varnothing$, then $Hy=Hz$.
Claim 2. For all $y\in G$, $y\in Hy$.
Proof. We can write $y=1y$, with $y\in H$.
Claim 3. The sets $Hy$, $y\in G$, are a partition of $G$.
Proof. Their union is everything, since $y\in Hy$ for all $y\in G$; and any two distinct sets are disjoint by Claim 1. So they form a partition.
Claim 4. If $y\in G$, then $|Hy|=|H|$.
Proof. Define $f\colon H\to Hy$ by $f(h) = hy$. This is one-to-one, since $hy=h'y$ implies, by cancellation, $h=h'$; and onto, since every element of $Hy$ is of the form $hy$ for some $h\in H$. Thus, $f$ is a bijection.
Proof of Lagrange's Theorem. Let $|G|=n$ and $|H|=d$. Let $g_1,\ldots,g_k$ be elements of $G$ such that $Hg_i\cap H{g_j}=\varnothing$ if $i\neq j$, and with $G=\cup_{i=1}^k Hg_i$. They exist since the $Hg$ form a partition of $G$ and $G$ is finite. Then
$$n=|G| = \left|\cup_{i=1}^k Hg_i\right| = \sum_{i=1}^k|Hg_i| = \sum_{i=1}^k|H| = k|H| = kd,$$
so $d$ divides $n$ as desired. $\Box$
And now you have all the ingredients.


Q:

Is there a more efficient way to disable multiple scripts while keeping some active on a single game object in Unity?

I am trying to turn off all components instead of one of them on a Game Object based off of which number is chosen as the index. The code is longer than this but I am trying to figure out if there is a more efficient way to doing so rather than calling so many GetComponents. When running this code I am getting a StackOverflowException and I think it is because of how many time I am calling GetComponent. The idea that I had was to put each GetComponent into an array and if the index matches the array number than make that component true and make the rest false. I that is the right direction can some help me in the right direction on how I create arrays out of scripts.
switch (index) {
    case 0:
        player.GetComponent<_2dxFX_HSV1>().enabled = false;
        player.GetComponent<_2dxFX_HSV2>().enabled = false;
        player.GetComponent<_2dxFX_HSV3>().enabled = false;
        player.GetComponent<_2dxFX_HSV4>().enabled = false;
        player.GetComponent<_2dxFX_Negative>().enabled = false;
        player.GetComponent<_2dxFX_Lightning>().enabled = false;
        player.GetComponent<_2dxFX_MetalFX>().enabled = false;
        player.GetComponent<_2dxFX_Pixel8bitsC64>().enabled = false;
        player.GetComponent<_2dxFX_GoldFX>().enabled = false;
        player.GetComponent<_2dxFX_Waterfall>().enabled = false;
        player.GetComponent<_2dxFX_Hologram>().enabled = false;
        player.GetComponent<_2dxFX_PlasmaRainbow>().enabled = false;

        break;

    case 1:
        player.GetComponent<_2dxFX_HSV1>().enabled = true;
        player.GetComponent<_2dxFX_HSV2>().enabled = false;
        player.GetComponent<_2dxFX_HSV3>().enabled = false;
        player.GetComponent<_2dxFX_HSV4>().enabled = false;
        player.GetComponent<_2dxFX_Negative>().enabled = false;
        player.GetComponent<_2dxFX_Lightning>().enabled = false;
        player.GetComponent<_2dxFX_MetalFX>().enabled = false;
        player.GetComponent<_2dxFX_Pixel8bitsC64>().enabled = false;
        player.GetComponent<_2dxFX_GoldFX>().enabled = false;
        player.GetComponent<_2dxFX_Waterfall>().enabled = false;
        player.GetComponent<_2dxFX_Hologram>().enabled = false;
        player.GetComponent<_2dxFX_PlasmaRainbow>().enabled = false;

        break;
    case 2:
        player.GetComponent<_2dxFX_HSV1>().enabled = false;
        player.GetComponent<_2dxFX_HSV2>().enabled = true;
        player.GetComponent<_2dxFX_HSV3>().enabled = false;
        player.GetComponent<_2dxFX_HSV4>().enabled = false;
        player.GetComponent<_2dxFX_Negative>().enabled = false;
        player.GetComponent<_2dxFX_Lightning>().enabled = false;
        player.GetComponent<_2dxFX_MetalFX>().enabled = false;
        player.GetComponent<_2dxFX_Pixel8bitsC64>().enabled = false;
        player.GetComponent<_2dxFX_GoldFX>().enabled = false;
        player.GetComponent<_2dxFX_Waterfall>().enabled = false;
        player.GetComponent<_2dxFX_Hologram>().enabled = false;
        player.GetComponent<_2dxFX_PlasmaRainbow>().enabled = false;

        break;
    }

A:

First of all, the GetComponent<> is quite costly. Don't do it in Update if you can avoid it.
Avoiding means: if these components stay the whole time, you can cache the references:
private List<GameObject>() all_components = new List<GameObject>();

And then, you may add them in Start(), and call GetComponent just once per component:
void Start()
{
    foreach(Component c in transform.children)
    {
        all_components.Add(c);
    }
    // Or even GetComponentsInChildren, where (true) includes the inactive gameobjects!
}

GetComponentsInChildren
Alternatively, only the ones you want:
all_components.Add(GetComponent<_2dxFX_HSV1>());
all_components.Add(GetComponent<_2dxFX_HSV2>());
// and so on... (but in Start - so just once per runtime :))

If you want maximum performance, e.g. even avoid this spike at start, do this:
public Gameobject[] all_components_array;

And in Inspector, drag them all in. You may need to specify the array size first. However, no need to collect them in Start() anymore :)
Now, how to disable/enable?
This disables all:
for(int i = 0; i < all_components.Count; i++)
{
    all_components[i].SetActive(false);
}

If you want to disable "all but 2" - disable all, then enable the 2 you want:
all_components[4].SetActive(true);
all_components[9].SetActive(true);

You could also activate all, then disable some. Depends on what you want in your switch-case you posted.


Q:

clarification on vim pattern matching

I want to convert the 5 space indentation in a python file to 4 space indentation. I want the command to do the following
remove a single space in all the lines which starts with a space followed by characters.
I issued the command  %s/^\ [a-zA-Z]*// which seems to work. Later i figured out that the command should actually be
remove a single space in all the lines which starts with a space followed by any number of spaces followed by characters.
However still i am not able to figure out how the command(above) is working. It should basically report error for the following stating pattern not found but still it works.
class H:
     def __init__():
         hell()

A:

It's working because * means "match zero or more of the previous atom".  In your case, it's matching zero.  You probably wanted to use \+ instead which means "match one or more of the previous atom".
In actuality, you could have just dropped the * entirely because just a space followed by a single character would have matched what you were originally searching for.  There are better regular expressions for what you're trying to accomplish, but that's not what you're asking here.
Edit (clarification):
Your regex as it stands (^\ [a-zA-Z]*) translates to:

^: From the start of the line
\: Match a space
[a-zA-Z]: Followed by a letter
*: Zero or more times (of the previous atom - a letter)


Q:

Using same jenkins job for deployment of different applications in different servers

I have six separate deployment jobs in jenkins for deploying two different applications in three different servers. Listed below are the job names.

deploy ProductApplication1 dev
deploy ProductApplication1 ppe
deploy productApplication1 prod
deploy ProductApplication2 dev
deploy ProductApplication2 ppe
deploy productApplication2 prod

In each of the jenkin job above, I could see a similar build configuration as below. As I am using jenkins for the first time I cannot really understand the shell commands written.

I would like to create a single job which could accept the environment(dev/ppe/prod) as a parameter and deploy accordingly.
What are the steps that are required to be followed for achieving this. Requesting you to explain on what changes that would be required on .yml or ansible scripts files too.

A:

This sounds like it can be solved with a simple parameterized build.
See https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Build for details
Then define 2 parameters for your jobs. Then replace occurrences of the values to the parameter variable (e.g. $APPLICATION and $SERVER)
For more details in the suggestion, you would have to expose the current solution in more detail.


Q:

Excel and pay days

Cell F2 holds the year. I'm trying to figure out how to dynamically change the days for the pay periods for a given year. We always have 26, and the next one is 12/12. But if I type a new year in f2, I wanted it to show all the fridays I am paid that year.
I have 26 cells setup for it.
Maybe a formula that uses the the first date in jan that we are paid and add f2 - 2015 with a date formula?
= date(2015,1,9) + year(f2 - 2015) but next year it is on a different day.

A:

If the year is in F2 then you can get the first pay day of any future year with this formula
=CEILING(DATE(F2,1,1)-DATE(2014,12,12),14)+DATE(2014,12,12)
Then just add 14 to that for subsequent paydays in the year, so if you have that formula in F4 then F5 should be just
=F4+14
format in required date format and copy that formula down the column as far as required


Q:

Firebase storage query if an image file exists

For each unique userID there may or may not be a directory in the Firebase storage containing an image named profile.jpg.
I'm trying to create a query that will sort all the users:

With "age": 12 and
Have a profile.jpg file in the storage under the directory named after their userId.

My database structure is:
{
  "Users" : {
    "uid1" : {
      "name" : "Josh",
      "age": 12
    },
    "uid2" : {
      "name" : "June",
      "age": 13
    }
  }
}

And my Storage structure is like:
example.appspot.com > uploads > uid1 > profile.jpg

I have managed to solve the first section that sorts the users with age 12 with the following:
Query query = FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("age").equalTo(12);

But how can I also add the second logic that is, at first after sorting the users aged 12, filter them who have a profile image in the same query.

A:

I don't believe it is possible to combine a FirebaseDatabase query with a Firebase Storage query.  I would recommend adding a node to your database, that says whether or not the user has a profile.jpg or not, and then choose which field you want to sort on.
 {
  "Users" : {
    "uid1" : {
      "name" : "Josh",
      "age": 12,
      "hasPhoto": true
    },
    "uid2" : {
      "name" : "June",
      "age": 13,
      "hasPhoto": false
    }
  }
}

Then, I think that Firebase Realtime Database does not allow sorting on more than one field, so instead you could do this:
Sort on one field ("age"), get the result, and then sort/filter through those User objects client side based on whether they have jpg or not.  Alternatively, Firestore does allow querying on more than one field.


Q:

Assign Data using Grand Central Dispatch Swift 3

I created a Networking file for downloading data, and I want to assign the data to another view controller so I can populate a map with annotations. The data download successfully, but I can't get it to assign to the view controller. I can only get it working when I include the networking code in the view controller and use DispatchQueue.main.async. I want to keep the networking file and view controller separate. Any insights would be greatly appreciated. Apologies in advance for the many lines of code.
The networking file is as follows:
import UIKit

class Networking {

static let shared = Networking()

var objects = [Any]()

func getData (_ completionHandler:@escaping (Location?) -> ()) {

    //Create the url with NSURL reuqest
    let url = URL(string: "http://localhost:3000/locations")

    let request = NSMutableURLRequest(url: url! as URL)

    //Set HTTP method as GET
    request.httpMethod = "GET"

    //HTTP Headers
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //Create dataTask using the session object to send data to the server
    URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in

        guard let data = data,
            let dataStore = String(data: data, encoding: String.Encoding.utf8) else {
                print("Could not find network")
                completionHandler(nil)
                return
        }

        guard error == nil else {
            print("Error calling GET")
            completionHandler(nil)
            return
        }

        let HTTPResponse = response as! HTTPURLResponse
        let statusCode = HTTPResponse.statusCode

        if (statusCode == 200) {
            print("Files downloaded successfully. \(dataStore)" )
        } else {
            completionHandler(nil)
            return
        }

        //Create json object from data
        do {

            let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]]
let location: [Location] = []

            if let array = json {

                for i in 0 ..< array.count {

                    if let data_object = array[i] as? [String: Any] {

                        if let _id = data_object["_id"] as? String,
                            let name = data_object["name"] as? String,
                            let imageID = data_object["imageID"] as? String,
                            let category = data_object["category"] as? String,
                            let details = data_object["details"] as? String,
                            let latitude = data_object["latitude"] as? Double,
                            let longitude = data_object["longitude"] as? Double {

                            var dictionary  = [_id, name, imageID, category, details, latitude, longitude] as [Any]

                            dictionary.append(location)

                        }
                    }
                }
             }
         }

        }.resume()
    }
}

The model is as follows:
class Location {

var _id : String
var name : String
var imageID : String
var category : String
var details : String
var latitude : Double
var longitude : Double

init?(_id: String, name: String, imageID: String, category: String, details: String, latitude: Double, longitude: Double) {

    self._id = _id
    self.name = name
    self.imageID = imageID
    self.category = category
    self.details = details
    self.latitude = latitude
    self.longitude = longitude

  }
}

The view controller is as follows:
 class MapViewController: UIViewController, MGLMapViewDelegate, UIGestureRecognizerDelegate {

 override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self

    Networking.shared.getData { (locations) in

    }

    populateMap()

}

func populateMap (){

    let point = MGLPointAnnotation()
    for location in locations {
        let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude )
        point.coordinate = coordinate
        point.title = location.name
        point.subtitle = location.category
        self.mapView.addAnnotation(point)

    }
}

A:

You are executing completion blocks only in failure cases. Execute the completion block once you have managed to parse the data and pass the array as parameter to closure/block.
import UIKit

class Networking {

static let shared = Networking()

var objects = [Any]()

func getData (_ completionHandler:@escaping ([Location]?) -> ()) {

    //Create the url with NSURL reuqest
    let url = URL(string: "http://localhost:3000/locations")

    let request = NSMutableURLRequest(url: url! as URL)

    //Set HTTP method as GET
    request.httpMethod = "GET"

    //HTTP Headers
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //Create dataTask using the session object to send data to the server
    URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in

        guard let data = data,
            let dataStore = String(data: data, encoding: String.Encoding.utf8) else {
                print("Could not find network")
                completionHandler(nil)
                return
        }

        guard error == nil else {
            print("Error calling GET")
            completionHandler(nil)
            return
        }

        let HTTPResponse = response as! HTTPURLResponse
        let statusCode = HTTPResponse.statusCode

        if (statusCode == 200) {
            print("Files downloaded successfully. \(dataStore)" )
        } else {
            completionHandler(nil)
            return
        }

        //Create json object from data
        do {

            let json = try! JSONSerialization.jsonObject(with: data , options: []) as? [[String: Any]]
let location: [Location] = []

            if let array = json {

                for i in 0 ..< array.count {

                    if let data_object = array[i] as? [String: Any] {

                        if let _id = data_object["_id"] as? String,
                            let name = data_object["name"] as? String,
                            let imageID = data_object["imageID"] as? String,
                            let category = data_object["category"] as? String,
                            let details = data_object["details"] as? String,
                            let latitude = data_object["latitude"] as? Double,
                            let longitude = data_object["longitude"] as? Double {

                            var dictionary  = [_id, name, imageID, category, details, latitude, longitude] as [Any]

                            dictionary.append(location) //am not sure of what this means test your code

                            completionHandler(location)
                        }
                    }
                }
             }
         }

        }.resume()
    }
}

Few more mistakes in your code :

Your completion block expects Location as a parameter. but in your code you are creating an array of Locations.
let location: [Location] = []

So I have modified the completion block parameters to return array of locations

In your for loop you are creating
var dictionary  = [_id, name, imageID, category, details, latitude, longitude] as [Any]

and appending it to  dictionary.append(location) I have no idea what this code is. I believe what u actually trying to do is create a location object from the data and then add it to location array
location.append(your_new_location_object)

Hope it helps


Q:

Algorithm for unique objects from an array with sub-objects?

I have a data class:
@interface Car : NSObject
{
  Engine *_engine;
}
//...

With the class:
@interface Engine : NSObject
{
  NSInteger _power;
  NSString *_name;
}
//...

And an array:
NSArray *myArray = [ // a bunch of Car objects with Engines

How would I make a new array that contains all unique items based on Engine 'power'?
For Example:
0 Car with Engine ( power = 20, name = "engine one" )
1 Car with Engine ( power = 45, name = "engine two" )
2 Car with Engine ( power = 20, name = "engine three" )
Final array would be car objects 0 and 1
Both data classes have accessors, e.g:
- (NSInteger)power;

A:

NSArray *cars = ...;
NSMutableDictionary *carsByUniqueEnginePowers = [NSMutableDictionary dictionary];
for (Car *car in cars) {
    NSNumber *enginePower = [NSNumber numberWithInteger:car.engine.power];
    [carsByUniqueEnginePowers setObject:car forKey:enginePower];
}
NSArray *carsWithUniqueEnginePowers = [carsByUniqueEnginePowers allValues];

Will pick the last item per engine power.
To get the first one replace the line
[carsByUniqueEnginePowers setObject:car forKey:enginePower];

with this:
if (![carsByUniqueEnginePowers objectForKey:power]) {
    [carsByUniqueEnginePowers setObject:car forKey:enginePower];
}


Q:

Android - Slide Up Panel (library) rounded corners

I'm developing the app that should use Navigation drawer as a menu bur for better User Experience i decided to replace navigation drawer with slide up panel.

My view is in this image

Now i want to make this menu with rounded corners i used CardView with cornerRadius attribute but didn't work properly.

This is my xml code for the sliding up panel

   <com.sothree.slidinguppanel.SlidingUpPanelLayout
        xmlns:sothree="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        sothree:umanoPanelHeight="0dp"
        sothree:umanoShadowHeight="0dp"
        android:id="@+id/SlidingUpPanel">

</com.sothree.slidinguppanel.SlidingUpPanelLayout>

The same design can be seen in Facebook messenger app:

Any idea will be welcome,Thanks in advance...
PS: The link of library that i use: Github library
Those who want all layout:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" />

<com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/SlidingUpPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoPanelHeight="0dp"
    sothree:umanoShadowHeight="0dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#345D7D" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_centerInParent="true"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY"
                    android:src="@drawable/quran_icon" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:layout_width="125dp"
                    android:layout_height="125dp"
                    android:layout_centerInParent="true"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY"
                    android:src="@drawable/qibla_compass_icon" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:id="@+id/findMyLocation"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_centerInParent="true"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY"
                    android:src="@drawable/location_icon" />

            </RelativeLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:orientation="horizontal">

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_centerInParent="true" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_centerInParent="true" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.33333">

                <ImageButton
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_centerInParent="true" />

            </RelativeLayout>
        </LinearLayout>

    </LinearLayout>

</com.sothree.slidinguppanel.SlidingUpPanelLayout>

</LinearLayout>

A:

Sliding up panel requires the attribute :

sothree:umanoOverlay="true"

In order to overlay layouts.

By means of this attribute we not only can make panel rounded (With CardView ) but also set transparent background to slideuppanel.
Reference: Github transparent background (Issues)

A:

Create a new drawable resource like
drawable_round_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:topLeftRadius="16dp"
        android:topRightRadius="16dp"/>
    <solid android:color="#FFFFFF" />
</shape>

And Set the drawable_round_background.xml as background to your sliding layout
  like:

<com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoPanelHeight="0dp"
    sothree:umanoShadowHeight="0dp"
    android:id="@+id/SlidingUpPanel">

   <!-- SLIDING LAYOUT -->
   <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/drawable_round_background">
   </LinearLayout>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>

hope this will help.


Q:

ScrollView not working in iOS7 with AutoLayout

Today I've spend a few hours but still have no answer on very simple (I think it should be so) question: how to make anything scrollable in iOS7 with auto layout feature on.
I added ScrollView into the View (I'm using Storyboard). Then I added multiline Label to this ScrollView. Then I tried all that I could found in Internet but with no luck. Text not scrolling. It's killing me, guys :(((. Help me please maybe with some simple code snippet.
Thank you!

A:

If you add constraints between ScrollView and Label, ScrollView's content size will adjust automatically and text will scroll:


Q:

What are performant, scalable ways to resolve links from http://bit.ly

Given a series of URLS from a stream where millions could be bit.ly, google or tinyurl shortened links, what is the most scalable way to resolve those to get their final url?
A Multi-threaded crawler doing HEAD requests on each short link while caching ones you've already resolved? Are there services that already provide this?
Also factor in not getting blocked from the url shortening service.
Assume the scale is 20 million shortened urls per day.

A:

Google provides an API.  So does bit.ly (and bit.ly asks to be notified of heavy use, and specify what they mean by light usage).  I am not aware of an appropriate API for tinyurl (for decoding), but there may be one.
Then you have to fetch on the order of 230 URLs per second to keep up with your desired rates.  I would measure typical latencies for each service and create one master actor and as many worker actors as you needed so the actors could block on lookup.  (I'd use Akka for this, not default Scala actors, and make sure each worker actor gets its own thread!)
You also should cache the answers locally; it's much faster to look up a known answer than it is to ask these services for one.  (The master actor should take care of that.)
After that, if you still can't keep up because of, for example, throttling by the sites, you had better either talk to the sites or you'll have to do things that are rather questionable (rent a bunch of inexpensive servers at different sites and farm out the requests to them).


Q:

ipa root certificate signing

I am trying to get my ipa certificate signed by openca and its getting rejected due to hostname.
The following hostnames were rejected because the system couldn't link them to your
account, if they are valid please verify the domains against your account.
Rejected: Certificate Authority

does any one know how to either generate the certificates manually so all the information can be included or if there is some setting I am missing that is causing this error on the initial install of the ipa server.
host is centos 6.3 I have installed ipa-server with dns

A:

Currently, there are 3 types how FreeIPA can blend in a existent certificate environment:

No blending - FreeIPA is simply installed with own PKI and self-signed CA certificate
External CA - FreeIPA is installed with own PKI, but it's CA certificate is signed with external certificate authority. This requires the external CA to allow sub CAs, which is not so common. I think this is the root cause of your problem.
CA-less installation - FreeIPA does not configure own CA, but uses signed host certificates from external CA. This should work in your case. This feature was introduced in FreeIPA 3.2.0.

Thus, my advise would be to try CA-less installation with certs signed by openca.


Q:

Whats the difference between Cases and Select?

Im trying to further my understanding of mathematica coding and came up across this question. What is the main difference between Cases and Select?
data = Table[{RandomReal[{-10, 10}], RandomReal[{-10, 10}], RandomReal[{-10, 10}]}, 10^4];
Cases[data, {a_, b_, c_} :> {a, b} /; c > 0]
Select[data, #[[3]] > 0 &][[All, ;; 2]]

Both these approaches give the same result, Im just curious about the benefits of each. When is Select superior to Cases and vice versa.

A:

Cases uses patterns, Select uses testing functions. Because of this, Select is not seldomly faster because it reduces pattern matching to the very least: Does the testing function evaluate to True or not? (Pattern matching can be a real bottleneck sometimes, inparticular if the mere check for matching enforces unpacking of arrays.)
On the other hand, Cases is much more flexible.
1.) Cases allows a level specification. (Select always operates on the first level of an expression)
2.) Cases allows to apply replacement rules immediately.


Q:

const ref and rvalue in D

Code
struct CustomReal
{
   private real value;

   this(real value)
   {
      this.value = value;
   }

   CustomReal opBinary(string op)(CustomReal rhs) if (op == "+")
   {
      return CustomReal(value + rhs.value);
   }

   bool opEquals(ref const CustomReal x) const
   {
      return value == x.value; // just for fun
   }
}

// Returns rvalue
CustomReal Create()
{
   return CustomReal(123.123456);
}

void main()
{
   CustomReal a = Create();
   assert(a == CustomReal(123.123456)); // OK. CustomReal is temporary but lvalue
   assert(a == Create());               // Compilation error (can't bind to rvalue)
   assert(a != a + a);                  // Compilation error (can't bind to rvalue)
}

Compilation error
prog.d(31): Error: function prog.CustomReal.opEquals (ref const const(CustomReal) x) const is not callable using argument types (CustomReal)
prog.d(31): Error: Create() is not an lvalue

http://ideone.com/O8wFc
Questions:

Why const ref can't bind to rvalue? Is it ok?
Do I need to return ref CustomReal or const ref CustomReal from opBinary() to fix this problem? Is it ok?
Is it correct to return a reference to local object created on stack?
ref CustomReal Create() { return CustomReal(0.0); }

A:

The only difference between ref and const ref is that const ref is const and ref is not. Both must take a variable. Neither can take a temporary. This is different from C++ where const T& will take any value of type T - including temporaries.
opBinary cannot return either ref or const ref, because there's no variable to return. It's creating a temporary. The same goes for Create. And creating a local variable with the value that you want to return doesn't help either, because you can't return a reference to a local variable. It would end up referring to a variable which didn't exist anymore.
What you need to do here is add another overload of opEquals:
bool opEquals(CustomReal x) const
{
    return value == x.value; // just for fun
}

With that, your code will compile.
I would point out though that the current situation with opEquals does need to be ironed out a bit. You'll notice that if you only have the overload for opEquals that I gave you and not the one that you currently have, the code fails to compile, and you get an error similar to this:
prog.d(15): Error: function prog.CustomReal.opEquals type signature should be const bool(ref const(CustomReal)) not const bool(CustomReal x)

The compiler is currently overly picky about the exact signature of opEquals for structs (a few other functions - such as toString - have similar issues). It's a known issue and will probably be resolved in the near future. However, for now, just declare both overloads of opEquals. If you compare a CustomReal with a variable, then the const ref version will be used, and if you compare a CustomReal with a temporary, then the other version will be used. But if you have both, you should be okay.
Now, why
assert(a == CustomReal(123.123456));

works, and
assert(a == Create());

doesn't, I'm not sure. I'd actually expect both of them to fail, given that const ref can't take a temporary, but for some reason, the compiler accepts it here - it probably has to do with how it treats opEquals special. Regardless, as I said, there are some issues with opEquals and structs which need to be ironed out, and hopefully that'll happen soon. But in the meantime, declaring both overloads of opEquals seems to do the trick.
EDIT: It appears that the reason that
assert(a == CustomReal(123.123456));

works, and
assert(a == Create());

doesn't is because of the fact (for reasons that I don't understand) a struct literal is considered an lvalue, whereas the return value of a function which is not ref is (unsurprisingly) an rvalue. There are a couple of bug reports related to it, arguing that struct literals should be rvalues, but apparently they're lvalues by design (which baffles me). In any case, that's why a function which takes const ref works with a struct literal but not with the return value of a function.

A:

#1: Yep, const ref can't bind to rvalues. Andrei thinks it was a bad idea to allow that in C++ IIRC.
http://digitalmars.com/d/archives/digitalmars/D/const_ref_rvalues_103509.html#N103514
The weird thing is struct literals count as lvalues in D2, so this works:
struct A {}
void foo(ref A a) {}
void main()
{
    foo(A());
}

while calling the following doesn't:
static A bar()
{
    return A();
}

foo(bar());


Q:

3 Injections for Hep B Vaccine

It has been suggested by my employer that i should get the Hepatitis B vaccine to protect myself.
I have had two of the three parts, but this is the first time i have had a vaccine in more than one session.
The vaccine is in 3 doses, each around a month apart, followed up by a blood test.
Why is the Hepatitis B vaccine split into 3, any what is the blood test for at the end?

A:

Why is the Hepatitis B vaccine split into 3, any what is the blood test for at the end?

The answer to this is really no different than this same question about any other vaccine that is given in multiple doses. I'll quote some good points and sources below but understanding how vaccines work in general first, and then getting information on the others questions will give you the best understanding and answer to your question.

How Vaccines Work (1)
According to the Children's Hospital of Philadelphia Vaccine Education Center, vaccines are made of dead or weakened antigens. They
  can't cause an infection, but the immune system still sees them as an
  enemy and produces antibodies in response. After the threat has
  passed, many of the antibodies will break down, but immune cells
  called memory cells remain in the body.(1)
When the body encounters that antigen again, the memory cells produce
  antibodies fast and strike down the invader before it's too late.(1)

Why is the Hepatitis B vaccine split into 3 doses?
The human body's immune system (and everyone's is different) needs to program itself at the molecular level to build antibodies for fighting off future [antigens] bugs with similiar biomolecular signatures. Medical studies suggest that it's just more efficient to give people two or three doses to ensure the body builds all it needs to at the immune system level to fight these bugs with matching signatures moving forward rather testing all that have been vaccinated to only revaccinate those found that need more than one dose.

Why Some Vaccines Require More Than One Dose(2)
Every vaccine ever created has to take many variables into
  consideration, he explained, including the individual pathogen or bug;
  how our immune systems respond to it; what parts of the bug can be
  used to generate an immune response that is protective in nature; and
  also how long that response will last. Because that equation is
  notably complex, sometimes a second (or third) dose is a good idea.(2)
"Sometimes, if you take a large group of people with one vaccination
  you might expect 90 percent [to be protected]," he said. "But if you
  give a second dose, you may get up to 98 percent." Rather than testing
  the population to find the 10 percent not protected by the first dose,
  "what is probably a more straightforward strategy is just giving two
  doses to insure you have that high level of protection," he said.(2)

What is the blood test for at the end?
Essentially, the test afterwards confirms that you indeed have the antibodies in your blood to fight off the Hepatitis B virus so your immune system will know to attack it when it's signature is matched since the vaccine programmed your immune system to do so.

How can I tell if I am protected against hepatitis B?(3)
If someone has received the hepatitis B vaccine, then a simple blood
  test can tell whether they are protected If they have responded to the
  vaccine series, the blood test will show a positive result for the
  hepatitis B surface antibody (HBsAb+). It is recommended that all
  health care workers and household members or sexual partners of an
  infected individual have their antibody levels tested one month after
  completing the vaccine series.(3)


Q:

Input field with validation crashes when typing fast in Angular 2

I have a form in Angular 2 with a simple validation using Validators.
The html template
<form role="form" #myForm="ngForm" (ngSubmit)="submit()" novalidate [ngFormModel]="form">

        name*
        <input type="text" name="name" class="form-control" ngControl="name"
               #name="ngForm" placeholder="Enter name" [(ngModel)]=user.name >

</form>

The ControlGroup for the validation
ngOnInit() {
    this.form = new ControlGroup({
      name: new Control('', Validators.compose([
        Validators.required,
        Validators.pattern("(([a-zA-Z ]|[0-9])+)*"),
        Validators.minLength(5),
        Validators.maxLength(80)
      ]))
    });
  }

When I type fast (random) characters in the input field (e.g #1KZBZKBjkndedjk@@@kjbzdzdékj!) the application crashes. This does not happen always so I have not really noticed a pattern.
This is the place where the crash happens, so I think the crash has something to do with the pattern.

A:

That's a known issue https://github.com/angular/angular/issues/7822 and will probably be fixed when this pull request lands https://github.com/angular/angular/pull/7421


Q:

Kendo UI grid filter with refresh button

I have a Kendo UI grid and a refresh button. I would like to prevent grid rebinding on filter change. I would like to collect filters into a collection instead. If the user clicks on the refresh button, the grid should be rebinded and the filters should be applied. Is this possible? Thanks.

A:

No, this is not possible out of the box. Clicking the "Filter" button of the grid filter menu would cause immediate filtering.


Q:

PowerShell Write-Host not synchronous

I'm writing a PowerShell script to check some properties of a server. When I execute the following cmdlets in order, the output is not displayed in the order I expect.
Write-Host "=== Operating System ==="
Get-WmiObject -computername $ServerName -class Win32_OperatingSystem | select Caption | ft -HideTableHeaders -AutoSize

Write-Host "=== Pagefile ==="
Get-WmiObject -ComputerName $ServerName -Class Win32_PageFileSetting

Write-Host "=== Locale ==="
Get-WmiObject -ComputerName $ServerName -class Win32_OperatingSystem | select Locale | ft -HideTableHeaders -AutoSize | Write-Output

Output:

=== Operating System ===
Microsoft Windows Server 2012 Standard
=== Pagefile ===
=== Locale ===
MaximumSize Name            Caption
  ----------- ----            -------
         4000 C:\pagefile.sys C:\ 'pagefile.sys'
0813

How does it come that the pagefile output is not displayed under its title? It seems to me that Get-WmiObject is running asynchronously and immediately writes the next title (Locale).
How can I prevent this? It works when using Write-Output, but then I cannot use colored text.

A:

Some of your text on-screen comes from objects going through the PowerShell pipeline, and some comes from Write-Host which prints to the screen immediately without touching the pipeline.
Gathering WMI information about the pagefile takes time and outputs to the pipeline, but the script has already moved on to printing the Locale message before that pipeline has finished.
This doesn't happen for (Operating System), because that pipeline finishes with ft -AutoSize (Format-Table), which pauses the script and waits for everything in the pipeline so it has as much information as possible when deciding how to size the columns. Once ft prints to the screen, then the script moves to the PageFile message.
You should use Write-Output instead to send the text through the pipeline, this way it will integrate well with other PowerShell features like redirection, collecting command output in files and variables.
Jeffrey Snover (PowerShell lead architect) has written about why Write-Host is not recommended on his blog here: http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/
Here's a link describing the behaviour of Format-Table:

Optimizing Column Width
Because the pipeline processes results in real time, PowerShell cannot know how wide of a space the column elements will occupy. As a result, it will tend to be generous in sizing columns. If you specify the -AutoSize parameter, Format-Table will collect all results first before setting the maximum width for all elements. You can optimize output, but the results will no longer be output in real time:
Master-PowerShell | With Dr. Tobias Weltner


Q:

How can I remove the last seven characters of a hash value in Perl?

I need to cut off the last seven characters of a string (a string that is stored in a hash). What is the easiest way to do that in perl? Many thanks in advance!

A:

With substr():
substr($string, 0, -7);

I suggest you read the Perldoc page on substr() (which I linked to above) before just copying and pasting this into your code. It does what you asked, but substr() is a very useful and versatile function, and I suggest you understand everything you can use it for (by reading the documentation).
Also, in the future, please consider Googling your question (or, in the case of Perl, looking it up on Perldoc) before asking it here. You can find great resources on things like this without having to ask questions here. Not to put down your question, but it's pretty simple, and I think if you tried, you could find the answer on your own.

A:

To remove the last 7 characters:
substr($str, -7) = '';

or the somewhat inelegant
substr($str, -7, length($str), '');

To get all but the last 7 characters:
substr($str, 0, -7)

A:

Use the perl substr function, but make the "length" argument negative. Example:
#!/usr/bin/perl

my $string = "string";
$short = substr($string, 0, -3);
printf $short . "\n";
This will return the string "str" with a newline, since we specified truncating the last three characters. Take a look at the Perl documentation on substr().


Q:

What to use in place of jQuery template?

Since jQuery template will become obsolete in the future, what is a good alternative to use in its place? Is JsRender mature enough to be incorporated into an enterprise level application? What are the other options?

A:

These are my preferences
Underscore.js is most straightforward solution since it's simply embedded javascript. I use it almost all my templating needs except for when I'm actually building a complete web app
Handlebars is sophisticated. It's better to use if you're going to be writing a lot of template code that depends on a good amount of logic, because that's where simply embedding javascript can lead to messy code. It's opinionated to be mostly logic-less, and while it may be counter-intuitive to not have any display logic in your view, it's cleaner and is a structure that pays off more and more as your app grows.


Q:

How can I read parent nodes with partly selected child nodes

I'm using dynaTree http://wwwendt.de/tech/dynatree/index.html in my code to show a 2 level tree. this tree is shown in selectMode = 3 with checkboxes and when user check a node checkbox, its parent turns to gray mode.
in next stage when user clicks a button I'm sending all selected nodes to server to process.
What I would like to do is send all gray mode check boxes as well.
How can I achieve this goal?
Edit:
This is all the code you need

    <link type="text/css" href="../css/ui.dynatree.css" rel="stylesheet">

    <input type="text" id="textField" value="" /><input type="button" id="button" onclick="alert($('#textField').val())" value="Send" />

When selecting Key2_1, Key2 goes to gray state and you'll see Key2_1 is added to textField text box, I would like to have Key2 in textField field too.
Note: selecting both child nodes of Key2_1 and Key2_2 will also select the parent (key_2) but not when it is in gray mode

A:

It seems dynaTree does not have a method to look for partially selected nodes.
An alternative solution is to look for class names of such nodes. by default if the class name for partially selected nodes is not changed, it will be dynatree-partsel, however a node with fully selected children has that class assigned too so we need to select nodes that does not have dynatree-selected in their classes.
A dirty solution will be change onSelect method definition to :
onSelect: function (select, node) {
    var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
        return node.data.key;
    });
    var partsel = new Array();
    $(".dynatree-partsel:not(.dynatree-selected)").each(function () {
        var node = $.ui.dynatree.getNode(this);
        partsel.push(node.data.key);
    });
    selKeys = selKeys.concat(partsel);
    $('#textField').val(selKeys.join(", "));
}


Q:

What's the difference between a POST and a PUT HTTP REQUEST?

They both seem to be sending data to the server inside the body, so what makes them different?

A:

HTTP PUT:
PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource.  If there is no file or resource there, PUT creates one. PUT is idempotent, but paradoxically PUT responses are not cacheable.
HTTP 1.1 RFC location for PUT
HTTP POST:
POST sends data to a specific URI and expects the resource at that URI to handle the request.  The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not idempotent, however POST responses are cacheable so long as the server sets the appropriate Cache-Control and Expires headers.
The official HTTP RFC specifies POST to be:

Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list,
   or similar group of articles;
Providing a block of data, such as the result of submitting a
    form, to a data-handling process;
Extending a database through an append operation.

HTTP 1.1 RFC location for POST
Difference between POST and PUT:
The RFC itself explains the core difference:

The fundamental difference between the
  POST and PUT requests is reflected in
  the different meaning of the
  Request-URI. The URI in a POST request
  identifies the resource that will
  handle the enclosed entity. That
  resource might be a data-accepting
  process, a gateway to some other
  protocol, or a separate entity that
  accepts annotations. In contrast, the
  URI in a PUT request identifies the
  entity enclosed with the request --
  the user agent knows what URI is
  intended and the server MUST NOT
  attempt to apply the request to some
  other resource. If the server desires
  that the request be applied to a
  different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make
  its own decision regarding whether or not to redirect the request.

Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),

4.3.4.  PUT
The PUT method requests that the state of the target resource be
    created or replaced with the state defined by the representation
    enclosed in the request message payload.

Using the right method, unrelated aside:
One benefit of REST ROA vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods.  So for example you would only use PUT when you want to create a resource at that exact location.  And you would never use GET to create or modify a resource.

A:

Only semantics.
An HTTP PUT is supposed to accept the body of the request, and then store that at the resource identified by the URI.
An HTTP POST is more general.  It is supposed to initiate an action on the server.  That action could be to store the request body at the resource identified by the URI, or it could be a different URI, or it could be a different action.
PUT is like a file upload.  A put to a URI affects exactly that URI.  A POST to a URI could have any effect at all.

A:

To give examples of REST-style resources:
"POST /books" with a bunch of book information might create a new book, and respond with the new URL identifying that book: "/books/5".
"PUT /books/5" would have to either create a new book with the id of 5, or replace the existing book with ID 5.
In non-resource style, POST can be used for just about anything that has a side effect. One other difference is that PUT should be idempotent - multiple PUTs of the same data to the same URL should be fine, wheras multiple POSTs might create multiple objects or whatever it is your POST action does.


Q:

Error : The local device name has a remembered connection to another network resource

I have a windows service that I built in C#. The purpose of the Windows Service is to synchronize two folders (Folder-A & Folder-B) between different servers using File System Watcher. Everything worked fine up until I moved Folder-A & Folder-B from the C drive to the D Drive.  Now I can't map the folders and on the event log I get the "The local device name has a remembered connection to another network resource" error.
Also, the folders are shared and the credentials I use have full control rights to both folders.

A:

Hi I finally fixed my issue all I had to do on my C# code I had to force the mapping of my shared folder. Its weird because the first time I used the service for the first time I didn't for it to map. But after changing the Shared folder to a different drive that's when i had this issue.
Below is the C# code to force the mapping.
oNetDrive.Force = true;
oNetDrive.Persistent = true;

oNetDrive drive is the Shared folder. Force and Persistent are the properties.


Q:

CMake generator for Visual Studio in msys2?

I'm running cmake in msys2, but it doesn't seem to find Visual Studio 2015 (missing generator option). I am launching the msys2 prompt from within Visual Studio Developer Command Prompt, so I have cl.exe, link.exe etc in the path.
This other question seems to be asking the same thing (however for Cygwin not msys2).

A:

Talked to the msys2 devs on IRC, turns out I needed to install package mingw-w64-x86_64-cmake instead of cmake. Using that fixed the problem.


Q:

ArrayIndexOutOfBounds Exception in listview

I have the following arrayadapter :
public class SmsArrayAdapter extends ArrayAdapter<String> {

    List<String> smsBody;
    List<Boolean> Status;
    List<String> time;
    List<String> SmsMessageId;

    Context context;
    private static LayoutInflater inflater = null;
    String fromNumber;

    public SmsArrayAdapter(Context context, int resource, List<String> smsBody,
            List<Boolean> Status, List<String> time, List<String> SmsMessageId,
            String fromNumber) {
        super(context, resource, smsBody);
        this.smsBody = smsBody;
        this.Status = Status;
        this.context = context;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.fromNumber = fromNumber;
        this.time = time;
        this.SmsMessageId = SmsMessageId;
    }

    public String getStr(int position) {
        return smsBody.get(position);
    }

    public String getId(int position) {
        return SmsMessageId.get(position);
    }

    public void setRead(int position, String smsMessageId) {
        Status.set(position, true);
        ContentValues values = new ContentValues();
        values.put("read", true);
        context.getContentResolver().update(Uri.parse("content://sms/inbox"),
                values, "_id=" + smsMessageId, null);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return super.getCount();
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return smsBody.get(position);
    }

    public static class ViewHolder {
        public TextView textfrom;
        public TextView text_sms;
        public TextView text_time;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if (convertView == null) {

            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
            convertView = inflater.inflate(R.layout.row_item, null);

            /****** View Holder Object to contain tabitem.xml file elements ******/

            holder = new ViewHolder();

            holder.textfrom = (TextView) convertView
                    .findViewById(R.id.textView_from);
            holder.text_sms = (TextView) convertView
                    .findViewById(R.id.textView_sms);
            holder.text_time = (TextView) convertView
                    .findViewById(R.id.textView_time);

            /************ Set holder with LayoutInflater ************/
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.textfrom.setText(" " + fromNumber);

        String smsTextToDisplay = smsBody.get(position);
        if (smsTextToDisplay.length() > 100)
            smsTextToDisplay = smsTextToDisplay.substring(0, 99) + " ...";

        holder.text_sms.setText(smsTextToDisplay);

        holder.text_time.setText(time.get(position));
        if (Status.get(position) == false) {
            convertView.setBackgroundColor(context.getResources().getColor(
                    R.color.light_blue_overlay));
        }

        return convertView;
    }

}

But when I am using this listview , the following exception i am getting .
09-22 11:27:31.161: E/AndroidRuntime(12067): java.lang.IndexOutOfBoundsException: Invalid index 13, size is 13
09-22 11:27:31.161: E/AndroidRuntime(12067):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at java.util.ArrayList.get(ArrayList.java:308)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at com.commlink.smscheck.SmsArrayAdapter.getView(SmsArrayAdapter.java:107)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.AbsListView.obtainView(AbsListView.java:2300)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.ListView.makeAndAddView(ListView.java:1816)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.ListView.fillDown(ListView.java:698)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.ListView.fillGap(ListView.java:662)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5529)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3366)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.AbsListView.onTouchMove(AbsListView.java:3802)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.widget.AbsListView.onTouchEvent(AbsListView.java:3597)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.View.dispatchTouchEvent(View.java:7790)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2316)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2013)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2322)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2027)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2322)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2027)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2322)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2027)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2322)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2027)
09-22 11:27:31.161: E/AndroidRuntime(12067):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2145)

Why I am getting this error ? How can I avoid this error ?

A:

Bad practice
List<String> smsBody;
List<Boolean> Status;
List<String> time;
List<String> SmsMessageId;

It's a best practice to manage different ArrayLists for managing data for the same object. It would be hard for you to manage different ArrayLists while making some operations like adding or removing data.
Say for example, if you would want to add data, you will have to add data for the same index in each lists.
Best practice to manage ArrayList of data
Rather best practice is to manage a single ArrayList having user-defined objects, e.g. ArrayList<SMSModel>.
Where SMSModel is a model class having all the attributes related to SMS object, like SMSBody, time, SMS message, etc. and this model class would contain getter/setter methods to get and set items from and into the object.


Q:

Multiple instances of a self hosted WCF service

We have a "worker" service running from console application in c#, for development we were always running a single instance of this service, which fetches chunks of data and performs some calculations, these chunks of data are provided by another service (which keeps track of how much data is left etc.)
Now in QA we want to run multiple instances of the "worker" service simultaneously (on the same machine).However we are get an exception as soon as the second instance is launched:

The TransportManager failed to listen on the supplied URI using the
  NetTcpPortSharing service: the URI is already registered with the
  service.

We are using netTcpBinding and the endpoint address is hardcoded into the app.config and remains the same and because of that I assume we are getting this error.
<services>
    <service behaviorConfiguration="CoreBehavior" name="WorkerService">
        <endpoint address="net.tcp://localhost:8001/WorkerAssignment" binding="netTcpBinding" contract="IWorkerService" bindingConfiguration="CoreTcpBinding"/>
    </service>
</services>
<bindings>
    <netTcpBinding>
        <binding name="CoreTcpBinding" portSharingEnabled="true">
            <security mode="None"/>
        </binding>
    </netTcpBinding>
</bindings>

Application code :
var host = new ServiceHost(typeof(WorkerService));
host.Open();

How do we provide a different URI for each instance so that atleast the port will remain the same ?
OR If there is a different way to run multiple instances of the same service?

A:

If you want to have multiple instances of the service than it is enough to have single service host - just decorate you WorkerService with ServiceBehaviorAttribute
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)]
public class WorkerService : IWorkerService
{
  //...service data
}

This will make sure that every call to the service will first create new instance of the service. Other ways of creating service class can be found here
If, however you would like to have multiple service hosts than it is impossible to have two service hosts that will host same service on completely the same url.
Another case would be if you want to have one service host hosting the same service on multiple endpoints with the same base address and custom uri's. In this case you can make use of overloaded ServiceHost constructor or investigate methods AddBaseAddress , AddServiceEndpoint. Or if you want to do it from configuration file than here's simple example with your code slightly modified
<service behaviorConfiguration="CoreBehavior" name="WorkerService">
    <endpoint address="WorkerAssignment" binding="netTcpBinding" contract="IWorkerService"/>
    <endpoint address="QAWorkerAssignment" binding="netTcpBinding" contract="IWorkerService"/>
  <host>
    <baseAddresses>
      <add baseAddress="net.tcp://localhost:8001/" />
    </baseAddresses>
  </host>
</service>

with this configuration you will have two endpoints for your service

net.tcp://localhost:8001/WorkerAssignment
net.tcp://localhost:8001/QAWorkerAssignment


Q:

What is this notation? f(x)=[x]=the greatest integer less than or equal to x.

I came across the question above. It is a function with domain all real numbers and range all integers. But is this square bracket notation used in general or did the author just use it for this particular case?

A:

I would say that the typical notation for the function you describe (also known as the floor function) is $\lfloor x\rfloor$, but $[x]$ is not uncommon either.

However, I would recommend $\lfloor x\rfloor$, because $[x]$ is sometimes (not that common) used as the "fractional" part of $x$, i.e. $[x] = x-\lfloor x\rfloor$

A:

Vinogradov uses $[x]$ for the integral part of $x$ and $\{x\}=x-[x]$ for the fractional.


Q:

How to access multiple properties with magic method(__get & __set)?

I recently studied magic methods, __get and __set, and was wondering how to actually set and get multiple properties in the class.
I know it works perfectly with only one variable or array, but I'm not sure about accessing multiple variables.
Is there anyone who could explain this to me?
class myMagic2 {
    public $data;
    public $name;
    public $age;

    public function __set($item, $value) {
        $this->item = $value;
    }

    public function __get($item){
        return $this->item;
    }
}

Is there a way to access all variables ($data, $name, $age)?

A:

When i work at projects i always have these methods:
public function __set($name, $value)
{
    //see if there exists a extra setter method: setName()
    $method = 'set' . ucfirst($name);
    if(!method_exists($this, $method))
    {
        //if there is no setter, receive all public/protected vars and set the correct one if found
        $vars = $this->vars;
        if(array_search("_" . $name, $vars) !== FALSE)
            $this->{"_" . $name} = $value;
    } else
        $this->$method($value); //call the setter with the value
}

public function __get($name)
{
    //see if there is an extra getter method: getName()
    $method = 'get' . ucfirst($name);
    if(!method_exists($this, $method))
    {
        //if there is no getter, receive all public/protected vars and return the correct one if found
        $vars = $this->vars;
        if(array_search("_" . $name, $vars) !== FALSE)
            return $this->{"_" . $name};
    } else
        return $this->$method(); //call the getter
    return null;
}

public function getVars()
{
    if(!$this->_vars)
    {
        $reflect = new ReflectionClass($this);
        $this->_vars = array();
        foreach($reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $var)
        {
            $this->_vars[] = $var->name;
        }
    }
    return $this->_vars;
}

So with them i give myself the freedom to create extra setter/getter for properties if i want to manipulate them before writing/returning. If no setter/getter exists for the property it falls back to the property itself. With the method getVars() you receive all public and protected properties from the class.
My class properties are always defined with an underscorce so you should probably change that.


Q:

JFilechooser exit on close

In my java application, there is a browse button. When browse button is clicked, popup a file chooser to select a file. When I close the file chooser by clicking cross mark at the top right corner without selecting a file, it gives an Exception saying "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException". How shall I prevent this error?
        JFileChooser chooser = new JFileChooser();

        chooser.setCurrentDirectory(new java.io.File("."));
        //chooser.setDialogTitle(choosertitle);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        //chooser.setAcceptAllFileFilterUsed(false);
        chooser.showOpenDialog(frame);

        path=chooser.getSelectedFile().getPath();

A:

If you exit the JFileChooser without selecting a file, chooser.getSelectedFile() will return null.
Therefore, on your line path=chooser.getSelectedFile().getPath(); you are getting a NullPointerException when you try to call getPath() on the null selected file, since you exited.
You will need to do some error handling, such as this:
JFileChooser chooser = new JFileChooser();

chooser.setCurrentDirectory(new java.io.File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.showOpenDialog(frame);

File selectedFile = chooser.getSelectedFile();
if (selectedFile == null) {
    System.out.println("No file selected!");
    path = "";
}
else {
    path = selectedFile.getPath();
}

In situations like this, I'd recommend reading through the Javadoc of the method you're retrieving resources from. Quite often under the "returns" section it will state if the returned object can be null, or even if it is guarenteed not to be null.
It helps me a lot when deciding when and when not to add things like null checking.


Q:

ActivityNotFoundException when opening another activity with Intent

Before you downvote: I have googled this for hour+ now and still can't understand why this isn't working. I am following the official docs.
I want to open another Activity from my main Activity with an Intent.
This is my main Activity class (MainActivity.java):
public class MainActivity extends Activity {

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

        LinearLayout l = new LinearLayout(this);
        Button b = new Button(this);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent goToActivity2 = new Intent(MainActivity.this, Activity2.class);
                MainActivity.this.startActivity(goToActivity2);
            }
        });
        l.addView(b);

        this.setContentView(l);
    }
}

And this is Activity2.java:
public class Activity2 extends Activity {

}

If I run the app I will see the main activity with a gray button. If I click on the button I get an Exception:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.testing.kaarelp.androidtest2/com.testing.kaarelp.androidtest2.Activity2}; have you declared this activity in your AndroidManifest.xml?

Why am I getting the Exception? Whats wrong here?
------------- edit1 ---------------
okay I declared the other Activity in the manifest like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.testing.kaarelp.androidtest2">

    <application>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activity2" />
    </application>

</manifest>

... and the app works now! Yet I am looking at another working code example right now that has multiple Activity-s that are not declared in the manifest and it still works. What is going on?!
------------- edit2 ---------------
Ahh I figured it out. The code example I was looking at contained multiple Fragment-s, not Activity-s

A:

You must declare the Activity in your AndroidManifest.xml file:
<activity android:name=".Activity2"/>


Q:

SQL Two duplicate tables copy data over

I have a temp storage table where data gets imported in and an exact copy of that table which is the working table.
I want to be able to copy the data from temp table --> working table, however, it should only copy data which doesn't already exist (i.e. no duplicates) and then clear the temp table
As I have to do this for quite a few tables and the tables are exactly the same, is there a way to insert the data without declaring the columns every time?
Here is an example of my select statement which selects all rows from webshop_in (the imported data table) which are not in the webshop table:
select  *
from webshop_in T2
left join [webshop] T1
on T2.[TrackingNumber] = t1.[TrackingNumber]
where t1.[TrackingNumber] is null

A:

try this,
MERGE workingtable AS target
using (select all column from temptable )) as source
on target.id=source.id
WHEN NOT MATCHED then
INSERT (col1,col2,col3......... ) --workingtable
      VALUES (mention those column from source )


Q:

How to get httrack to work with SSL on mac os x?  (libssl.so not found)

I'm trying to use httrack website copier but the program is running and reporting "no-ssl" (ie: it does not have the capability to copy secure sites).
From looking over this thread, it seems that the problem is either when I make & configure the program, or when I run the program, it is not finding the lib-ssl / open-ssl that I have installed. I think it is looking for /var/root/lib/libssl.so.1.0
The user on that forum states that he created a symlink which allowed httrack to find the ssl library in the non-default location. Perhaps that's what I need to do - but where do I create the link from and to? I'm not seeing that I have any libssl.so files installed on my system. Do I need the development package? If so, how do I install that? I used macports to install the current version of openssl that I have. I'm running OS X 10.6.
Reserch
I have run this command to try and debug:

dtruss httrack 2>&1 | grep ssl

and that outputs this:

stat64("libssl.so.1.0\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/var/root/lib/libssl.so.1.0\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/local/lib/libssl.so.1.0\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/usr/lib/libssl.so.1.0\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)       = -1 Err#2
stat64("libssl.so.1\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.1\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.1\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.1\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so.1.0.0\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.1.0.0\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.1.0.0\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.1.0.0\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so.0\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.0\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.0\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.0\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so.0.9\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/usr/lib/libssl.so.0.9\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)       = -1 Err#2
stat64("libssl.so.0.9.8p\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8p\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8p\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8p\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8o\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8o\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8o\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8o\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8n\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8n\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8n\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8n\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8m\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8m\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8m\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8m\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8l\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8l\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8l\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8l\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8k\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8k\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8k\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8k\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8j\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8j\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8j\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8j\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8g\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8g\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8g\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8g\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8b\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8b\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8b\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8b\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)        = -1 Err#2
stat64("libssl.so.0.9.8\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.8\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.8\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.8\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so.0.9.7\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.7\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.7\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.7\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so.0.9.6\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/var/root/lib/libssl.so.0.9.6\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/usr/local/lib/libssl.so.0.9.6\0", 0x7FFF5FBFF210, 0x7FFF5FBFF470)       = -1 Err#2
stat64("/usr/lib/libssl.so.0.9.6\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("libssl.so\0", 0x7FFF5FBFEE30, 0x7FFF5FBFF470)        = -1 Err#2
stat64("/var/root/lib/libssl.so\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)      = -1 Err#2
stat64("/usr/local/lib/libssl.so\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)         = -1 Err#2
stat64("/usr/lib/libssl.so\0", 0x7FFF5FBFF220, 0x7FFF5FBFF470)       = -1 Err#2

I have already used mac ports to install open-ssl:

>> port installed

The following ports are currently installed:
  beecrypt @4.2.1_2 (active)
  cpio @2.10_0 (active)
  expat @2.0.1_1 (active)
  flex @2.5.35_0 (active)
  gettext @0.18.1.1_2 (active)
  gperf @3.0.4_0 (active)
  icu @4.6_0 (active)
  libiconv @1.13.1_0 (active)
  mysql5 @5.1.53_0 (active)
  ncurses @5.9_0 (active)
  ncursesw @5.8_0 (active)
  neon @0.29.5_0 (active)
  openssl @1.0.0c_0 (active)
  perl5.8 @5.8.9_3 (active)
  popt @1.16_0 (active)
  python24 @2.4.6_7 (active)
  readline @6.1.002_0 (active)
  rpm @4.4.9_10 (active)
  sqlite3 @3.7.3_0 (active)
  zlib @1.2.5_0 (active)

Here are the install locations:

>> locate libssl

/opt/local/lib/libssl.1.0.0.dylib
/opt/local/lib/libssl.a
/opt/local/lib/libssl.dylib
/opt/local/lib/pkgconfig/libssl.pc
/opt/local/var/macports/software/openssl/1.0.0c_0/opt/local/lib/libssl.1.0.0.dylib
/opt/local/var/macports/software/openssl/1.0.0c_0/opt/local/lib/libssl.a
/opt/local/var/macports/software/openssl/1.0.0c_0/opt/local/lib/libssl.dylib
/opt/local/var/macports/software/openssl/1.0.0c_0/opt/local/lib/pkgconfig/libssl.pc
/usr/lib/libssl.0.9.7.dylib
/usr/lib/libssl.0.9.8.dylib
/usr/lib/libssl.0.9.dylib
/usr/lib/libssl.dylib
/usr/lib/pkgconfig/libssl.pc

What should I do next?
More Info
I tried the solution below:

$ DYLD_INSERT_LIBRARIES="/opt/local/lib/libssl.1.0.0.dylib" httrack

Welcome to HTTrack Website Copier (Offline Browser) 3.44-1-nossl
Copyright (C) Xavier Roche and other contributors
To see the option list, enter a blank line or try httrack --help

It is still not able to load the ssl lib:  3.44-1-nossl

A:

When httrack loads, it looks for the openssl library. Because it is designed for linux/unix, it assumes the open ssl library will be called libssl.so and when it is named something different on the mac it can't find it.
Run this command to create a symlink called libssl.so which points to the right file:

sudo ln -s /usr/lib/libssl.dylib /usr/lib/libssl.so

via


Q:

Programmatically autolayout not centering vertically

I want to use autolayout to center a view vertically and horizontally but somehow I'm having troubles doing so. I'm running on iOS8 simulator and iOS8 device. There are two versions of code which I have tried and none of them works. Below are the snippets:
First let's allocate the view we're using:
UIView *inputView = UIView.new; //Don't hate me for the dot syntax :)
inputView.translatesAutoresizingMaskIntoConstraints = NO;
inputView.backgroundColor = UIColor.redColor;

[self.view addSubview:inputView];

Attempt #1:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]; //Center the view horizontally
[self.view addConstraint:constraint];

constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]; //And make it have the same width as the view
[self.view addConstraint:constraint];

constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0f constant:260.0f]; //Force exactly 260pts view height
[inputView addConstraint:constraint]; //If I add it to self.view it's the same thing

constraint = [NSLayoutConstraint constraintWithItem:inputView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:0.5f constant:0.0f]; //And try to center it vertically - DOES NOT WORK... wtf
[self.view addConstraint:constraint];

Seems like a perfectly legitimate piece of code to me. But NOPE.
Attempt #2. It's basically the same thing with less lines of code.
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-[inputView(>=320)]-|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(inputView)];
[self.view addConstraints:constraints];

constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[inputView(260)]-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(inputView)];
[self.view addConstraints:constraints];

Now this one does not work either. I mean it does center the view horizontally but when I add the vertical constraint I do get a warning telling me that I suck at auto layout. It says its unable to satisfy all the constraints. More specifically:
(
    "<NSLayoutConstraint:0x17408be00 UIView:0x174197010.top == UIView:0x174196da0.topMargin>",
    "<NSLayoutConstraint:0x17408bdb0 V:[UIView:0x174197010(260)]>",
    "<NSLayoutConstraint:0x17408bd60 UIView:0x174196da0.bottomMargin == UIView:0x174197010.bottom>",
    "<NSLayoutConstraint:0x17008a000 'UIView-Encapsulated-Layout-Height' V:[UIView:0x174196da0(667)]>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x17408bd60 UIView:0x174196da0.bottomMargin == UIView:0x174197010.bottom>

I'm not sure how do I fix this. Below are the pictures of the results I get from attempts #1 and #2.

How can I fix it?

A:

While setting vertical constraint, you made the multiplier to 0.5f which is causing this. Make it to 1.0f as you had it for Horizontal constraint.
constraint = [NSLayoutConstraint constraintWithItem:inputView
                                          attribute:NSLayoutAttributeCenterY
                                          relatedBy:NSLayoutRelationEqual
                                             toItem:self.view
                                          attribute:NSLayoutAttributeCenterY
                                         multiplier:1.0f
                                           constant:0.0f];