Q: How to get the list of all children in Firebase android? I have this model below in Firebase

I am trying to get all the values from child node posts using below code
  databasePostsReference =
  FirebaseDatabase.getInstance().getReference().child("posts");

 final List<UserPostPOJO> list = Collections.EMPTY_LIST;

  databasePostsReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: entered list adding");
                UserPostPOJO post = snapshot.getValue(UserPostPOJO.class);
                list.add(post);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

but I am getting error java.lang.UnsupportedOperationException.
in the above scenario i know that error is because list is declared final and i am trying to assign value in onDataChangeMethod so is throwing error but if i am not declaring the list variable final then i cant access list variable from within the onDataChange() method how to solve this
  public class UserPostPOJO {
    String uid;
    Double elevation;
    String uri;
    String feel;

    public UserPostPOJO() {
    }

    public UserPostPOJO(String uid, Double elevation, String uri, String feel) {
        this.uid = uid;
        this.elevation = elevation;
        this.uri = uri;
        this.feel = feel;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public Double getElevation() {
        return elevation;
    }

    public void setElevation(Double elevation) {
        this.elevation = elevation;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getFeel() {
        return feel;
    }

    public void setFeel(String feel) {
        this.feel = feel;
    }
    }

Error Log:
  05-08 22:19:49.706 6421-6421/redeyes17.com.abhi.android.iamat
    D/recentfragment: onDataChange: entered list adding
   05-08 22:19:49.726 6421-6421/redeyes17.com.abhi.android.iamat
    E/AndroidRuntime: FATAL EXCEPTION: main

   Process: redeyes17.com.abhi.android.iamat, PID: 6421

   java.lang.UnsupportedOperationException

   at java.util.AbstractList.add(AbstractList.java:404)

   at java.util.AbstractList.add(AbstractList.java:425)

   at redeyes17.com.abhi.android.iamat.UI.tabs
  .RecentFragment$1.onDataChange(RecentFragment.java:78)

  at com.google.android.gms.internal.zzbpx.zza(Unknown Source)

  at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)

  at com.google.android.gms.internal.zzbra$1.run(Unknown Source)

   at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

  at android.os.Looper.loop(Looper.java:158)

  at android.app.ActivityThread.main(ActivityThread.java:7230)

  at java.lang.reflect.Method.invoke(Native Method)

 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller
 .run(ZygoteInit.java:1230)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: To get all those values please use this code:
    databasePostsReference = FirebaseDatabase.getInstance().getReference().child("posts").child(postId);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           List<UserPostPOJO> list = new ArrayList<>();

           String elevation = (String) dataSnapshot.child("elevation").getValue();
           String feel = (String) dataSnapshot.child("feel").getValue();
           String uid = (String) dataSnapshot.child("uid").getValue();
           String uri = (String) dataSnapshot.child("uri").getValue();

          UserPostPOJO userPostPOJO = new UserPostPOJO();
          userPostPOJO.setElevation(elevation);
          userPostPOJO.setFeel(feel);
          userPostPOJO.setUid(uid);
          userPostPOJO.setUri(uri);

          list.add(userPostPOJO);
    }

          @Override
          public void onCancelled(DatabaseError databaseError) {}
};
databasePostsReference.addListenerForSingleValueEvent(eventListener);

In which postId is the unique id generated by the push() method. And notice, that the declaration of your list must be inside the onDataChange() method, otherwise, you'll get null.
Hope it helps.


Q: Using an varray type in a select statement I am trying to use an varray-type in a select statement:
CREATE OR REPLACE PROCEDURE ARRAYTEST IS
  type array_t is varray(2) of int;
  array_test array_t := array_t(10,11);
BEGIN
  select * from STATISTIK where abschluss1 in array_test;
END;

But it is giving me an error:
PLS-00428: an INTO clause is expected in this SELECT statement
PLS-00642: local collection types not allowed in SQL statement

The first Exception seems to be misleading, I don't want to select something into a variable I want an aquivalent of:
select * from STATISTIK where abschluss1 in (10,12);

But (10,12) substituted by an array (varray).
Is it possible to convert the varray to be used in a select-statement?

A: It is possible but your type must be global
create type array_t is varray(2) of int;

Then use array as a table (open p for only for compiling)
 declare
    array_test array_t := array_t(10,11);
p sys_refcursor;
    begin
open p for
       select * from STATISTIK where abschluss1 in (select column_value from table(array_test ));
    end;


Q: html5 validate form with required="true" and custom check What I'm looking for: way to have innate html 5 form validation using the required="true", where if the user clicks the "Submit" button, the first thing that happens is the automatic html 5 validation where it checks to see if "username" is provided by the user.  If it's not, then it displays the ugly error bubble.
If it is provided, however, I then have my own custom validation for checking against the db if the username exists.  If it does, then return true (allow submission), false otherwise.  What's happening: the form is getting submitted.  It's like it does not wait for the success callback to return true/false on whether or not it should be submitted.
I hope that's clear enough!  Code below:
html:
<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>

js:
$("form").submit(function() {
  $.ajax({
      url: 'usernamechecker.php?username=' + $("#username").val(),
      success: function(resp) {
        if (!resp.UsernameExists) {
          return true; // allow form submission
        }
        return false; // do not allow form submission
      }
    });
});

A: You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.
Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever).  There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.

A: You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.
$("form").submit(function(event) {
  $.ajax({
      async: false,
      url: 'usernamechecker.php?username=' + $("#username").val(),
      timeout: 1000,
      success: function(resp) {
        if (resp.UsernameExists) {
          event.preventDefault(); // do not allow form submission
        },
      error: function() {
          //fall back code when there's an error or timeout
      },
    });
});


Q: Firebase Google Analytics Console weird behavior. Events are logged but don't show up on User Snapshot I'm using Firebase Analytics and I'm still exploring the Google Analytics Console.
I think there's something wrong with my data, or the way I'm logging it. I have a Single Page App built with React + Firebase.
Since my app is all client side routes, for every page that it renders, I'm firing the following effect to log the screen_view event:
useEffect(() => {
  firebase.analytics().logEvent("screen_view", {
    screen_name: window.location.pathname,
    page_title: "My Page Title"
  });
},[firebase]);

So far, so good. It runs without any errors, and it seems to be logging the event (or at least, I can see the events in some parts of the console).
Here is the test I did that came back with weird results.
Note: I'm monitoring through the Realtime tab over on Google Analytics Console.

I accessed my website, and click on 5 different links. After each page loaded, the screen_view event was fired and I could see this number for total events going from 20 to 25. I.e: my effects were fired and my events were logged!

When you click on "Trending" you open up a window with the count per event type in the last minutes, and I could see the screen_view events going from 12 to 17, which is all correct, so far.

But since this is a new website and I'm currently the only user, I was able to click on "View user snapshot" and see my own activity in the report, and it's supposed to be in real time.

But the weird thing is that my screen_view events don't show up in the snapshot AT ALL. Not on real time and it's not a delay issue. They just don't appear in my user activity.

QUESTION
What is going on here? Am I doing something wrong? Weren't my events supposed to appear in my user's snapshot timeline on Real Time (or even with some delay)? This is getting really difficult to learn and test if I can't see the results of my code logged on screen.
Is there a better way to test this? I mean, I need to update my code and be able to see the changes in the events a user triggers.


Q: Electron (Windows) How does manual distribution work? I am trying to follow the instructions on this page: https://electronjs.org/docs/tutorial/application-distribution#manual-distribution however it is very vague and unclear.
I am trying to build an app that is simply an index.html with some static assets (JS, CSS, images.) There are no calls to server-side APIs from the client side.
The docs say to use this layout:
electron/resources/app
- package.json
- main.js
- index.html

But it's not working for me.
What is main.js? I assume this is the electron script that should create the main browser window and set the url to my local index.html, not something that is run within the webview window.
Why does it say index.html has to be there? I would think the URL to index.html is specified in main.js? (I have all client assets in a "public" folder.)
Why does it need a package.json? I have no scripts and don't use any additional npm modules.
I have tried a number of layouts but all that happens when I double-click electron.exe is that it exits immediately without any errors. From what I can tell it never executes my main.js script.
I can't find any additional resources on setting up a simple manual distribution.

A: I got it working after expanding the default_app.asar distributed with the Electron build. The instructions on the page linked above neglected to mention that the package.json should contain something like:
{
  "name": "electron",
  "productName": "Electron",
  "main": "main.js"
}

The only file that needs to be in resources/app is the package.json file. You can set main to the location of your your app's entry point script and you can put any other files wherever you want.


Q: What access modifier to use Suppose I have a base class:
public class A {
    public float someValue;

    <Access Modifier Here> float SomeValue {
        get {
            return someValue;
        }
    }
}

And I want to derive from it:
public class B : A {
    public float SomeProperty {
        get {
            return SomeValue;
        }
    }
}

What access modifier would I use if I want to make the SomeValue property only available to the deriving class and not anywhere else?

A: for only derived classes.. use protected
Protected means that access is limited to the containing class or types derived from the containing class.


Q: How to set hard coded HTML in UWP WebView I have some hard coded html:
string myHtml = "<html>some html</html>"

How can I set it as my WebView source? Something like this:
webView.HtmlSource = myHtml;

A: In general, we use WebView.NavigateToString(htmlstring); to load and display html string. For source of WebView, only apply for Uri parameters. But you can create an attached property like HtmlSource for WebView and when it changes to call NavigateToString to load.
public class MyWebViewExtention
{
    public static readonly DependencyProperty HtmlSourceProperty =
           DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
    public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
    public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
    private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        WebView webView = d as WebView;
        if (webView != null)
        {
            webView.NavigateToString((string)e.NewValue);
        }
    }
 }

.xaml:
<WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>

For more details, you can refer to Binding HTML to a WebView with Attached Properties.


Q: The type arguments for method cannot be inferred from the usage. (c#, lambda) Firstly, I am a complete beginner to advanced level programming. All I have done are tutorials to C++ found on the web. I'm facing this problem at work. I have seen similar queries but nothing has helped me understand.
Please note: I am terrible at terminologies like method, object, interface, etc. So I might have made a mistake somewhere further. I'm slowly learning.
Code Block 1:
public static class DummyClassName
{
    public static T DummyTemplateFunc<T>(DummyInterfaceName aaa1, Func<T> action)
    {
        T DummyVal = action();
        // blah blah code
        // blah blah code

        return val;
    }
}

Code Block 2:
public class ClassName2 : blah1 , blah2, blah3
{
    public void Method1(string DummyString)
     {
         DummyClassName.DummyTemplateFunc(_aaa1, ()=>Function1(_arg1, arg2));
     }
}

I'll try to explain what's happening to the best of my ability. The second bit of code is used over and over in the program with different Functions (or methods?) in place of Function1. (These functions come from a C++ program linked with this one. I don't know how)
If these functions are of any return type EXCEPT void, the program runs fine.
If a void-return-type function is used, I get the error
"The type arguments for method '****.****.DummyClassName.DummyTemplateName<T>
(****.****.DummyInterfaceName, System.Func<T>)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.'

From what I understand, this is because when a void function is passed it takes the place of T in the first block of code and tries returning 'val'. That's why an error is thrown.
Can somebody help me find a workaround to this? I don't mind defining a completely different class/method specifically to handle void functions. I know which functions are of return type void.

A: Create another overload, taking Action instead of Func<T>:
public static class DummyClassName
{
    public static void DummyTemplateFunc(DummyInterfaceName aaa1, Action action)
    {
        // you cannot assign result to variable, because it returns void
        action();

        // I also changed method to return void, so you can't return anything
        // return something;

        // ofc you can make it return something instead
    }
}


Q: Retain Cycle in Class Causing Potential Memory Leak So using the graph debugger tool and instruments I have noticed that there is a memory leak in my app. After many hours I have or the graph debugger has tracked it down to this function.
override func didUpdate(to object: Any) {
    comment = object as? CommentGrabbed
}

Which is contained in this bigger class
import UIKit
import IGListKit
import Foundation
import Firebase

protocol CommentsSectionDelegate: class {
    func CommentSectionUpdared(sectionController: CommentsSectionController)
}
class CommentsSectionController: ListSectionController,CommentCellDelegate {
    weak var delegate: CommentsSectionDelegate? = nil
   weak var comment: CommentGrabbed?
    let userProfileController = ProfileeViewController(collectionViewLayout: UICollectionViewFlowLayout())
    var eventKey: String?
    var dummyCell: CommentCell?
    override init() {
        super.init()
        // supplementaryViewSource = self
        //sets the spacing between items in a specfic section controller
        inset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
    }
    // MARK: IGListSectionController Overrides
    override func numberOfItems() -> Int {
        return 1
    }
    override func sizeForItem(at index: Int) -> CGSize {
        let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
        dummyCell = CommentCell(frame: frame)
        dummyCell?.comment = comment
        dummyCell?.layoutIfNeeded()
        let targetSize =  CGSize(width: collectionContext!.containerSize.width, height: 55)
        let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
        let height = max(40+8+8, (estimatedSize?.height)!)
        return  CGSize(width: collectionContext!.containerSize.width, height: height)

    }

    override var minimumLineSpacing: CGFloat {
        get {
            return 0.0
        }
        set {
            self.minimumLineSpacing = 0.0
        }
    }

    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let cell = collectionContext?.dequeueReusableCell(of: CommentCell.self, for: self, at: index) as? CommentCell else {
            fatalError()
        }
        //  print(comment)
        cell.comment = comment
        cell.delegate = self
        return cell
    }
    override func didUpdate(to object: Any) {
        comment = object as? CommentGrabbed
    }
    override func didSelectItem(at index: Int){
    }

    func optionsButtonTapped(cell: CommentCell){
        print("like")

        let comment = self.comment
        _ = comment?.uid

        // 3
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        // 4
        if comment?.uid != User.current.uid {
            let flagAction = UIAlertAction(title: "Report as Inappropriate", style: .default) { _ in
                ChatService.flag(comment!)

                let okAlert = UIAlertController(title: nil, message: "The post has been flagged.", preferredStyle: .alert)
                okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
                self.viewController?.present(okAlert, animated: true, completion: nil)
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            let replyAction = UIAlertAction(title: "Reply to Comment", style: .default, handler: { (_) in
                //do something here later to facilitate reply comment functionality
                print("Attempting to reply to user \(comment?.user.username) comment")

            })
            alertController.addAction(replyAction)
            alertController.addAction(cancelAction)
            alertController.addAction(flagAction)
        }else{
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            let deleteAction = UIAlertAction(title: "Delete Comment", style: .default, handler: { _ in
                ChatService.deleteComment(comment!, (comment?.eventKey)!)
                let okAlert = UIAlertController(title: nil, message: "Comment Has Been Deleted", preferredStyle: .alert)
                okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
                self.viewController?.present(okAlert, animated: true, completion: nil)
                self.onItemDeleted()

            })
            alertController.addAction(cancelAction)
            alertController.addAction(deleteAction)

        }
        self.viewController?.present(alertController, animated: true, completion: nil)

    }
    func onItemDeleted() {
        delegate?.CommentSectionUpdared(sectionController: self)
    }
    func handleProfileTransition(tapGesture: UITapGestureRecognizer){
        userProfileController.user = comment?.user
        if Auth.auth().currentUser?.uid != comment?.uid{
                    self.viewController?.present(userProfileController, animated: true, completion: nil)
        }else{
            //do nothing

        }

    }

    deinit {
        print("CommentSectionController class removed from memory")
    }

}

The CommentGrabbed class looks like this
import Foundation
import  IGListKit

class CommentGrabbed {
    let content: String
    let uid: String
    let user: User
    let creationDate: Date
    var commentID: String? = ""
    let eventKey:String

    init(user: User, dictionary: [String:Any]) {
        self.content = dictionary["content"] as? String ?? ""
        self.uid = dictionary["uid"] as? String ?? ""
        self.eventKey = dictionary["eventKey"] as? String ?? ""
        self.user = user
        let secondsFrom1970 = dictionary["timestamp"] as? Double ?? 0
        self.creationDate = Date(timeIntervalSince1970: secondsFrom1970)
    }

}

extension CommentGrabbed: Equatable{
    static public func  ==(rhs: CommentGrabbed, lhs: CommentGrabbed) ->Bool{
        return rhs.commentID == lhs.commentID
    }
}

extension CommentGrabbed: ListDiffable{
    public func diffIdentifier() -> NSObjectProtocol {
        return commentID! as NSObjectProtocol
    }
    public func isEqual(toDiffableObject object: ListDiffable?) ->Bool{
        guard let object = object as? CommentGrabbed else {
            return false
        }
        return  self.commentID==object.commentID
    }
}

Are there any retain cycles being created here that I don't noice?
This controller is ultimately in control of displaying all the comments and it has a UserService method which works through this code base
static func show(forUID uid: String, completion: @escaping (User?) -> Void) {
    let ref = Database.database().reference().child("users").child(uid)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let user = User(snapshot: snapshot) else {
            return completion(nil)

        }

        completion(user)
    })
}

The User model object looks like this
import Foundation
import FirebaseDatabase.FIRDataSnapshot

class User : NSObject {
    //User variables
    let uid : String
    let username : String?
    let profilePic: String?
    var isFollowed = false
    var dictValue: [String : Any] {
        return ["username" : username as Any,
                "profilePic" : profilePic as Any]
    }
    //Standard User init()
    init(uid: String, username: String, profilePic: String) {
        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        super.init()
    }
    //User init using Firebase snapshots
    init?(snapshot: DataSnapshot) {
        guard let dict = snapshot.value as? [String : Any],
            let username = dict["username"] as? String,
            let profilePic = dict["profilePic"] as? String
            else { return nil }
        self.uid = snapshot.key
        self.username = username
        self.profilePic = profilePic
    }
    //UserDefaults
    required init?(coder aDecoder: NSCoder) {
        guard let uid = aDecoder.decodeObject(forKey: "uid") as? String,
            let username = aDecoder.decodeObject(forKey: "username") as? String,
            let profilePic = aDecoder.decodeObject(forKey: "profilePic") as? String            else { return nil }
        self.uid = uid
        self.username = username
        self.profilePic = profilePic
        super.init()
    }
    init?(key: String, postDictionary: [String : Any]) {
        //var dict : [String : Any]
        //print(postDictionary as? [String:])
        let dict = postDictionary
        //print(dict)
        let profilePic = dict["profilePic"] as? String ?? ""
        let username = dict["username"] as? String ?? ""
        self.uid = key
        self.profilePic = profilePic
        self.username = username
    }
    //User singleton for currently logged user
    private static var _current: User?
    static var current: User {
        guard let currentUser = _current else {
            fatalError("Error: current user doesn't exist")
        }
        return currentUser
    }

    class func setCurrent(_ user: User, writeToUserDefaults: Bool = true) {
        //print(user)
       // print("")
        if writeToUserDefaults {
            let data = NSKeyedArchiver.archivedData(withRootObject: user)

            UserDefaults.standard.set(data, forKey: "currentUser")
            UserDefaults.standard.synchronize()
        }
        _current = user
        //print(_current ?? "")
    }
}

extension User: NSCoding {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(username, forKey: "username")
        aCoder.encode(profilePic, forKey: "profilePic")
    }
}

When I change user in commentGrabbed class to weak my code begins to crash if it has to deal with anything related to a user like so
 weak var comment: CommentGrabbed?{
        didSet{
            guard let comment = comment else{
                return
            }
          //  print("apples")
            // textLabel.text = comment.content
            //shawn was also here
            profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
            //  print(comment.user.username)
            let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])

            attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))

            attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
            let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
            attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))

            textView.attributedText = attributedText

        }
    }

Code block where commentGrabbed is init
 UserService.show(forUID: uid, completion: { [weak self](user) in
                    if let user = user {
                        let commentFetched = CommentGrabbed(user: user, dictionary: commentDictionary)
                        commentFetched.commentID = snapshot.key
                        let filteredArr = self?.comments.filter { (comment) -> Bool in
                            return comment.commentID == commentFetched.commentID
                        }
                        if filteredArr?.count == 0 {
                            self?.comments.append(commentFetched)

                        }
                        self?.adapter.performUpdates(animated: true)
                    }else{
                        print("user is null")

                    }
                    self?.comments.sort(by: { (comment1, comment2) -> Bool in
                        return comment1.creationDate.compare(comment2.creationDate) == .orderedAscending
                    })
                    self?.comments.forEach({ (comments) in
                    })
                })

            })

This is what I see in debugger tool. If I comment out that line nothing loads btw for those who are wondering why not just comment it out

Code for CommentCell as requested
import Foundation
import UIKit
import Firebase

protocol CommentCellDelegate: class {
    func optionsButtonTapped(cell: CommentCell)
    func handleProfileTransition(tapGesture: UITapGestureRecognizer)
}
class CommentCell: UICollectionViewCell {
    weak var delegate: CommentCellDelegate? = nil
    override var reuseIdentifier : String {
        get {
            return "cellID"
        }
        set {
            // nothing, because only red is allowed
        }
    }
    var didTapOptionsButtonForCell: ((CommentCell) -> Void)?

    weak var comment: CommentGrabbed?{
        didSet{
            guard let comment = comment else{
                return
            }
          //  print("apples")
            // textLabel.text = comment.content
            //shawn was also here
            profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
            //  print(comment.user.username)
            let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])

            attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))

            attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
            let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
            attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))

            textView.attributedText = attributedText

        }
    }

    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.isScrollEnabled = false
        textView.textContainer.maximumNumberOfLines = 0
        textView.textContainer.lineBreakMode = .byCharWrapping
        textView.isEditable = false
        return textView
    }()

    lazy var profileImageView: CustomImageView = {
        let iv = CustomImageView()
        iv.clipsToBounds = true
        iv.isUserInteractionEnabled = true
        iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleProfileTransition)))
        iv.contentMode = .scaleAspectFill
        return iv
    }()

    lazy var flagButton: UIButton = {
        let flagButton = UIButton(type: .system)
        flagButton.setImage(#imageLiteral(resourceName: "icons8-Info-64"), for: .normal)
        flagButton.addTarget(self, action: #selector(optionsButtonTapped), for: .touchUpInside)
        return flagButton
    }()

    @objc func optionsButtonTapped (){
        didTapOptionsButtonForCell?(self)
    }

    @objc func onOptionsTapped() {
        delegate?.optionsButtonTapped(cell: self)
    }
    @objc func handleProfileTransition(tapGesture: UITapGestureRecognizer){
        delegate?.handleProfileTransition(tapGesture: tapGesture)
      //  print("Tapped image")
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(textView)
        addSubview(profileImageView)
        addSubview(flagButton)
        textView.anchor(top: topAnchor, left: profileImageView.rightAnchor, bottom: bottomAnchor, right: flagButton.leftAnchor, paddingTop: 4, paddingLeft: 4, paddingBottom: 4, paddingRight: 4, width: 0, height: 0)
        profileImageView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 40, height: 40)
        profileImageView.layer.cornerRadius = 40/2
        flagButton.anchor(top: topAnchor, left: nil, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 40, height: 40)
        flagButton.addTarget(self, action: #selector(CommentCell.onOptionsTapped), for: .touchUpInside)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

sizeForItem
override func sizeForItem(at index: Int) -> CGSize {
    let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
      weak var dummyCell = CommentCell(frame: frame)
    dummyCell?.comment = comment
    dummyCell?.layoutIfNeeded()
    let targetSize =  CGSize(width: collectionContext!.containerSize.width, height: 55)
    let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
    let height = max(40+8+8, (estimatedSize?.height)!)
    return  CGSize(width: collectionContext!.containerSize.width, height: height)

}


Q: Still having Java install problems Please review my script, all I want to do is check to see if a particular Java Verison is installed (latest version) if it is not installed, then to go to the install command...
Having problems with the For /F command though.
PLease see what I have so far:
@echo On
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME="BrowserJavaVersion"

FOR /F "usebackq skip=1 tokens=3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueValue=%%A
)
if defined ValueValue (
@echo the current Java runtime is %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found

This is the key I am trying to interrogate from within the Windows Registry (BrowserJavaVersion):
!http://i393.photobucket.com/albums/pp11/Mikoyan_2008/Screenshot.jpg
If the version doesnt match latest Java version to then:
if "%ValueValue%"=="Latest Java Version" ( goto eof ) ELSE ( goto Install )
Can anyone please provide assistance?


Q: How to trace where Xcode program crash I'm getting an error in debugger. In Thread my app crash on line:
0x37265f78:  ldr    r3, [r4, #8]

with:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x50000008)

How to find out where app actually crash? There is a something like "call stack"?

A: http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Best tutorial for trace the error.

A: Run your app under the debugger, then when your app crashes you will have access to the call stack.
Furthermore, if you display the console window, you will get more textual information (including a call stack) at the moment of the crash.
If you are using Xcode 4, have a look at the attached picture.

A: You have to set Exception Breakpoint
Go to the Breakpoints navigator, click the + button at the bottom, and add an Exception Breakpoint.
Now you will know the exact line where any of your exception will occur (e.g. line of crash). best of luck!!


Q: admob impressions is half then request please guide what is the issue also rewarded ads not showing with real id in test is it works Hello I am working with admob but i dont know in my account their is no ads limit but still number of impressions is less then request

Please help me out what is issue why i am getting impressions less then request
second question is in my app rewarded ads are not loading i dont know why in test it works fine but when i put live id its not work and didnot shows ads


Q: Avoid changing the background of Status Bar on iOS in Ionic I'm doing a mobile app using Ionic 6.1.4 and Capacitor 3.5.1.
Android, looks good by default, black background and white icons on any screen.

iOS, always has whatever the background color I have in the ion-content with black icons. Is always like this on any screen. In my app, I have 2 screens with a dark background and the ion-content with the attribute fullscreen.

iOS, as I said, I have two screen with a very dark background, let's replicate it using a black background. See how the icons are not visible anymore?

Component:
<ion-header class="ion-no-border">
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button color="white"></ion-menu-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
</ion-content>

Style:
ion-toolbar {
  --background: transparent;
}

ion-content {
  --background: black;
}

How can I change iOS Status Bar to always have a style just like Android?
or even better, how can I leave the Status Bar untouched on iOS (app not modifying the Status Bar at all)?
I have tried:
.ios {

  ion-header {
    margin-top: var(--ion-safe-area-top);
  }

  ion-toolbar {
    margin-top: var(--ion-safe-area-top);
    --padding-top: var(--ion-safe-area-top);
    padding-top: var(--ion-safe-area-top);
  }

}

But this just moves all the content down and Status Bar is keeping the background color of my app.
I was thinking to use the plugin called @capacitor/status-bar to change the Status Bar style just on iOS, but it's not so simple in my case. Since I have 2 screens with dark background, I will need to make the Status Bar Dark when enter, and when onDestroy is called, make it back to Light so my other screens which have white background looks good too. I think this is a tedious process. I think there must be a way to avoid this.
My goal is to keep the Status Bar on iOS always the same and with a color that makes the icons visible. I would prefer leaving the Status Bar untouched just like Android do.

A: Well, I suggest trying one of the followings:

*

*If you are using Cordova, use the cordova-status-bar plugin and try setting the statusBar color in the config.xml:

<preference name="StatusBarBackgroundColor" value="#000000" />
    or
<preference name="StatusBarBackgroundColor" value="#ffffff" />

setting it to a value in hex color, probably you want it black, and then setting the text and icons to light or lightcontent as you did in Android by using:

<preference name="StatusBarStyle" value="lightcontent" />

*If you are using Capacitor, install the Capacitor plugin

npm install @capacitor/status-bar
npx cap sync

and then set the color of the background and text using
import { StatusBar, Style } from '@capacitor/status-bar';

// iOS only
window.addEventListener('statusTap', function () {
  console.log('statusbar tapped');
});

const setStatusBarStyleDark = async () => {
  await StatusBar.setStyle({ style: Style.Dark });
};

*Finally, if none of that works, or you just want to change it on iOS try setting it in the global.scss as you were doing but also changing the backgound color and the color:

.ios {
  ion-header {
    margin-top: var(--ion-safe-area-top);
    background-color: black;
    color: white;
  }

  ion-toolbar {
    margin-top: var(--ion-safe-area-top);
    --padding-top: var(--ion-safe-area-top);
    padding-top: var(--ion-safe-area-top);
    background-color: black;
    color: white;
  }
}

A: I don't know about Capacitor, but I know that on Cordova for iOS, you need to include viewport-fit=cover in the <meta name="viewport" content="..."> tag of your index.html to do this, e.g.
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">

This works for me when using the cordova-plugin-statusbar plugin, anyway.


Q: Qt creator - The process "/usr/bin/make" exited with code 2 default project I installed QT Creator 4.0 on OS X 10.11, when I try to build any project template I get the following: Error output screenshot.
Any idea what causes this issue? Thank you!


Q: Converting a working code from double-precision to quadruple-precision: How to read quadruple-precision numbers in FORTRAN from an input file I have a big, old, FORTRAN 77 code that has worked for many, many years with no problems.
Double-precision is not enough anymore, so to convert to quadruple-precision I have:

*

*Replaced all occurrences of REAL*8 to REAL*16

*Replaced all functions like DCOS() into functions like COS()

*Replaced all built-in numbers like 0.d0 to 0.q0 , and 1D+01 to 1Q+01

The program compiles with no errors or warnings with the gcc-4.6 compiler on

*

*operating system: openSUSE 11.3 x86_64 (a 64-bit operating system)

*hardware: Intel Xeon E5-2650 (Sandy Bridge)

My LD_LIBRARY_PATH variable is set to the 64-bit library folder:
/gcc-4.6/lib64
The program reads an input file that has numbers in it.
Those numbers used to be of the form 1.234D+02 (for the double-precision version of the code, which works).
I have changed them so now that number is 1.234Q+02 , however I get the runtime error:
Bad real number in item 1 of list input
Indicating that the subroutine that reads in the data from the input file (called read.f) does not find the first number in the inputfile, to be compatible with what it expected.
Strangely, the quadruple-precision version of the code does not complain when the input file contains numbers like 1.234D+02 or 123.4 (which, based on the output seems to automatically be converted to the form 1.234D+02 rather than Q+02), it just does not like the Q+02 , so it seems that gcc-4.6 does not allow quadruple-precision numbers to be read in from input files in scientific notation !
Has anyone ever been able to read from an input file a quadruple-precision number in scientific notation (ie, like 1234Q+02) in FORTRAN with a gcc compiler, and if so how did you get it to work ? (or did you need a different compiler/operating system/hardware to get it to work ?)

A: Almost all of this is already in comments by @IanH and @Vladimi.
I suggest mixing in a little Fortran 90 into your FORTRAN 77 code.
Write all of your numbers with "E".   Change your other program to write the data this way.  Don't bother with "D" and don't try to use the infrequently supported "Q".  (Using "Q" in constants in source code is an extension of gfortran -- see 6.1.8 in manual.)
Since you want the same source code to support two precisions, at the top of the program, have:
use ISO_FORTRAN_ENV
WP = real128

or
use ISO_FORTRAN_ENV
WP = real64

as the variation that changes whether your code is using double or quadruple precision.  This is using the ISO Fortran Environment to select the types by their number of bits.  (use needs to between program and implicit none; the assignment statement after implicit none.)
Then declare your real variables via:
real (WP) :: MyVar

In source code, write real constants as 1.23456789012345E+12_WP.  The _type is the Fortran 90 way of specifying the type of a constant.  This way you can go back and forth between double and quadruple precision by only changing the single line defining WP
WP == Working Precision.
Just use "E" in input files.   Fortran will read according to the type of the variable.
Why not write a tiny test program to try it out?


Q: POST and PUT methods are not working in Postman but working in Swagger So the documentation is required from me on Postman. The problem is my APIs requires authentication so I can't use Swagger to test them. When I remove authorization from my controller and use Swagger it works, but using Postman it returns the following error.

Postman headers for the request:

A: Set header Content-Type: application/json.

A: Set header Content-Type: application/json.


Q: Getting the list of available languages How can I get the list of available languages (the short symbol to be passed when calling a method that represents the language) for CodeRay syntax highlighter?
I tried
require "coderay"
CodeRay::Scanners.constants

but that doesn't seem to give the information. (Even if I were able to get the constants that correspond to the languages, I still need another step to get the symbols that correspond to them.)

A related question is, I can do something like:
CodeRay::Scanners::Ruby # => CodeRay::Scanners::Ruby

but CodeRay::Scanners.constants doesn't include that. Why is that?

A: Method you are looking for is:
CodeRay::Scanners.list
#=> [:c, :clojure, :cpp, :css, :debug, :delphi, :diff, :erb, :go, :groovy,
#    :haml, :html, :java, :java_script, :json, :lua, :php, :python, :raydebug,
#    :ruby, :sass, :scanner, :sql, :taskpaper, :text, :xml, :yaml]


Q: Drupal escaping url in dynamically created meta tags I am trying to add open graph meta tags dynamically to drupal 8 using the the page_attachments hook.
The meta tags are generated correctly however image and the website urls are being encoded by drupal and the result is broken links.
function module_page_attachments(array &$page)
{
  $tags = [
    ["name" => "twitter:card", "content" => "summary"],
    ["name" => "og:url", "content" => "https://example.net/index.php?param1=1&param2=2&param3=3"],
    ["name" => "og:title", "content" => "My title"],
    ["name" => "og:description", "content" => "My description"],
    ["name" => "og:image", "content" => "https://example.net/images?id=1&size=400"],
  ];

  foreach ($tags as $tag) {

    $headerTag = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => $tag['name'],
        'content' => $tag['content'],
      ),
    );
    $page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
  }
}

The result is the following
<html>
<head>
    <meta charset="utf-8" />
    <meta property="twitter:card" content="summary" />
    <meta property="og:url"
        content="https://example.com/index.php?param1=1&param2=2&param3=3" />
    <meta property="og:title" content="My title" />
    <meta property="og:description"
        content="My description" />
    <meta property="og:image"
        content="https://example.net/images?id=1&size=400" />

</head>
<body>
</body>
</html>

All the & characters have been encoded and transformed into &. How can I prevent Drupal from encoding the characters?

A: DrupalCoreRenderMarkup should do the trick:
<?php
use Drupal\Core\Render\Markup;

function module_page_attachments(array &$page)
{
  $tags = [
    ["name" => "twitter:card", "content" => "summary"],
    ["name" => "og:url", "content" => Markup::create("https://example.net/index.php?param1=1&param2=2&param3=3")],
    ["name" => "og:title", "content" => "My title"],
    ["name" => "og:description", "content" => "My description"],
    ["name" => "og:image", "content" => Markup::create("https://example.net/images?id=1&size=400")],
  ];

  foreach ($tags as $tag) {

    $headerTag = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => $tag['name'],
        'content' => $tag['content'],
      ),
    );
    $page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
  }
}

A: There is an open ticket for issue with the status needs work on drupal's website.
The issue can be found here:
www.drupal.org/project/drupal/issues/2968558
A work around to solve the issue is to intercept the page and alter its template in the module file like the example here below shows:
file name: example.module
/**
 * Drupal bug caused the application to escape links. Therefore the og:image and og:url
 * were not working. Drupal kept converting `&` to `&`
 * The solution here below converts the tags into inline templates
 */
function spa_seo_page_attachments_alter(array &$attachments)
{
  if (isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {

      $property = !empty($item[0]['#attributes']['property']) ? $item[0]['#attributes']['property'] : '';

      if ($property == "og:url" || $property == "og:image") {
        $content = $item[0]['#attributes']['content'];
        $property = $item[0]['#attributes']['property'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          '#template' => "{{ meta|raw }}",
          '#context' => [
            'meta' => '<meta property="' . $property . '" content="' . $content . '" />',
          ]
        ];
      }
    }
  }
}

Note
Please note that DrupalCoreRenderMarkupdoes not solve the issue as this is a bug.


Q: How to show an Eclipse view like an intro I am having an eclipse view which I am trying to display as an intro page.
I am now opening the view with maximize but still the toolbars are visible.
So is there any way to make the view opening same as intro  page in eclipse.
I am not using intro as I want to make my own welcome page so I am not sure about the attitude of intro as it is mentioned that intro is basically for internal.
Please correct me if I am wrong anywhere.

A: I would still use IIntroPart (or have a look to CustomizableIntroPart):

The intro part is a visual component within the workbench responsible for introducing the product to new users. The intro part is typically shown the first time a product is started up.
The intro part implementation is contributed to the workbench via the org.eclipse.ui.intro extension point.

(See this thread as an example).

There can be several intro part implementations, and associations between intro part implementations and products.
The workbench will only make use of the intro part implementation for the current product (as given by Platform.getProduct().
There is at most one intro part instance in the entire workbench, and it resides in exactly one workbench window at a time.

See "[Eclipse Intro] Make my own welcome page." as an example.
If you don't use it, at least have a look at the code of IIntroPart to see how it


Q: webformmailer.php not sending user text entries So I can't find anything about why my form isn't sending the text the users are entering. Its only submitting blank fields using webformmailer.php and can't find any help on godaddy site either. I know I'm using the same id for the name and email fields so if that is really the problem I'll change it but I wouldn't think it is. Heres my code.
        <form id="contact-form" action="/webformmailer.php" method="POST" >

            <textarea id="textarea" placeholder="Message Here"></textarea>
            <input type="text"  id="username" name="Firstname" placeholder="Full Name" />
            <input type="text"  id="username" name="email" placeholder="Email"  />
            <input type="submit" name ="submit" value="Submit" />

        </form>

the file is generated from godaddy.com but heres the code. I also have a simple form with no textarea for messages that seems to work fine.
<?php

if ( !isset($_SERVER['SPI'])) {
    die();
}

if (!isset($_SERVER['DOCUMENT_ROOT'])) {
    echo("CRITICAL: we seem to be running outside of the norm.\n");
    header("Location: http://".$_SERVER["HTTP_HOST"]."/");
    die("CRITICAL: Document root unavailable.\n");
}

$request_method = $_SERVER["REQUEST_METHOD"];
if($request_method == "GET") {
    $query_vars = $_GET;
}
elseif ($request_method == "POST") {
    $query_vars = $_POST;
}

reset($query_vars);
function customsort($a,$b) {
    // $a is array for form vars, $b is comma seperated case sensitive field order
    // this is case sensitive -- good idea to hrc that.
    $data = array();
    if ( strstr($b,',') == FALSE )  {
            $b = $b.",";
    }
    $ordering = split(',',$b);
    foreach ($ordering as $orderitem) {
            if ( ($orderitem != null) && ($orderitem != "") ) {
                    if (isset($a[$orderitem])) {
                            $data[$orderitem] = $a[$orderitem];
                    }
            }
    }
    foreach ($a as $key=>$val) {
            $data[$key] = $a[$key];
    }
    return $data;
}

  function xmlentities($string) {
    return str_replace ( array('&', '"', "'", '<', '>'), array('&', '"',                    ''', '<', '>'), $string);
    }

   $t = date("U");

  $formhomedir = preg_replace('/.*\/home\/content/','',$_SERVER['DOCUMENT_ROOT']);
  $formhomedir = explode('/',$formhomedir);
  if (count($formhomedir) <= 4) {
    $formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/data/";
  }
  else {
            $formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/".$formhomedir[3]."/".$form     homedir[4]."/data/";
}

 $file_order = ".default";
 $file_format = ".text";
 $file_interval = ".15m";
 $field_order = "";

if (isset($query_vars['form_order'])) {
    if ($query_vars['form_order'] != "alpha") {
            $field_order=$query_vars['form_order'];
            $file_order=".custom";
            $query_vars = customsort($query_vars,$field_order);
    }
    else {
            switch ($query_vars['form_order']) {
                    case "alpha":
                            uksort($query_vars,'strnatcasecmp');
                            $file_order=".alpha";
                    break;
                    default:
                            $file_order=".default";
                    break;
            }
    }
  }

if (isset($query_vars['form_format'])) {
    switch ($query_vars['form_format']) {
            case "csv":
                    $file_format = ".csv";
            break;
            case "html":
                    $file_format = ".html";
            break;
            case "xml":
                    $file_format = ".xml";
            break;
            case "text":
            case "default":
            default:
                    $file_format = ".text";
            break;
    }
}

if (isset($query_vars['form_delivery'])) {
    switch ($query_vars['form_delivery']) {
            case "hourly":
                    $file_interval = ".60m";
            break;
            case "hourly_digest":
                    $file_interval = ".60mc";
            break;
            case "daily":
                    $file_interval = ".24h";
            break;
            case "daily_digest":
                    $file_interval = ".24hc";
            break;
            case "digest":
                    $file_interval = ".15mc";
            break;
            case "default":
            default:
                    $file_interval = ".15m";
            break;
    }
}

$file = $formhome."form_".$t.$file_order.$file_format.$file_interval;
$fp = fopen($file,"w");

reset($query_vars);
switch ($file_format) {
    case ".csv":
            $csvkeys = "";
            $csvvals= "";
            $firsttime = "";
            while (list ($key, $val) = each ($query_vars)) {
                    if ( ($key == "form_order") ||
                            ($key == "form_format") ||
                            ($key == "form_delivery") ||
                            ($key == "redirect") ) {
                    }
                    else {
                            if ($csvkeys != "") {
                                    $firsttime=",";
                            }
                            $tmpkey=escapeshellcmd($key);
                            $csvkeys = $csvkeys.$firsttime."'".$tmpkey."'";
                            $tmpval=escapeshellcmd($val);
                            $csvvals = $csvvals.$firsttime."'".$tmpval."'";
                    }
            }
            fputs($fp,"$csvkeys\n");
            fputs($fp,"$csvvals\n");
    break;
    case ".html":
            fputs($fp,"
\n");
    break;
    case ".xml":
            fputs($fp,"<form>\n");
    break;
}

  reset($query_vars);
  while (list ($key, $val) = each ($query_vars)) {
    if ($key == "redirect") {
            $landing_page = $val;
    }
    if ( ($key == "form_order") ||
            ($key == "form_format") ||
            ($key == "form_delivery") ||
            ($key == "redirect") ) {

    }
    else {
            switch ($file_format) {
                    case ".html":
                            fputs($fp,"\t
\n");
                            fputs($fp,"\t\t$key	\n");
                            fputs($fp,"\t\t$val	\n");
                            fputs($fp,"\t
\n");

                    break;
                    case ".csv":
                            // content is already output
                    break;
                    case ".xml":
                       fputs($fp,"\t<field>\n");
                       fputs($fp,"\t\t<fieldname>".xmlentities($key)."
  </fieldname>\n");
                       fputs($fp,"\t\t<fieldvalue>".xmlentities($val)
  </fieldvalue>\n");
                            fputs($fp,"\t</field>\n");
                    break;
                    case ".text":
                    default:
                            fputs($fp,$key.": ".$val."\n");
                    break;
            }
    }
}

switch ($file_format) {
    case ".html":
            fputs($fp,"
\n");
    break;
    case ".xml":
            fputs($fp,"</form>\n");
    break;
}

fclose($fp);

if ($landing_page != "") {
    header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
}
else {
    header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}

?>

A: *

*Your <textarea> doesn't have a name, so it can't be a successful control.

*You never attempt to access $_POST['Firstname'] (or $query_vars['Firstname] for that matter)

*Ditto $_POST['email']

Also your HTML is invalid (use a validator) and you are abusing the placeholder attribute as a label.


Q: EF 5 & MVC 4: unable to get tables with no reference in Controller using Databse first I am using MVC 4, EF 5 and Database first approach. I have added 2 new tables(UserDetails and UserAddress) with no reference in existing database. I am able to see all tables including these 2 new table in EDMX file and created model also. But when im trying to get the tables in controller, its showing all Models except UserDetails and UserAddress - in following way.
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
  private DbRestaurantEntities db = new DbRestaurantEntities();

   public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    var userId = WebSecurity.GetUserId(User.Identity.Name);
                    //db.UserDetails -- Not showing
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
            return View(model);
        }
}

Am i missing something?

A: WebSecurity uses different dbContext
, you need to use the same dbContext, which is used to create the database tables. you can check it out in the web.config file for the connectionstring.. and use the exact dbContext
Add this in AuthConfig.cs
WebSecurity.InitializeDatabaseConnection(
        "specifyTheDbContextHere",
        "UserProfile",
        "UserId",
        "UserName",
        autoCreateTables: true
    );


Q: how to implement PHP file_get_contents() function in JSP(java)? In PHP we can use file_get_contents() like this:
<?php

  $data = file_get_contents('php://input');
  echo file_put_contents("image.jpg", $data);

?>

How can I implement this in Java (JSP)?

A: Here's a function I created in Java a while back that returns a String of the file contents. Hope it helps.
There might be some issues with \n and \r but it should get you started at least.
// Converts a file to a string
private String fileToString(String filename) throws IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    StringBuilder builder = new StringBuilder();
    String line;

    // For every line in the file, append it to the string builder
    while((line = reader.readLine()) != null)
    {
        builder.append(line);
    }

    reader.close();
    return builder.toString();
}

A: This will read a file from an URL and write it to a local file. Just add try/catch and imports as needed.
   byte buf[] = new byte[4096];
   URL url = new URL("http://path.to.file");
   BufferedInputStream bis = new BufferedInputStream(url.openStream());
   FileOutputStream fos = new FileOutputStream(target_filename);

   int bytesRead = 0;

   while((bytesRead = bis.read(buf)) != -1) {
       fos.write(buf, 0, bytesRead);
   }

   fos.flush();
   fos.close();
   bis.close();


Q: Invalid Argument Running Google Go Binary in Linux I’ve written a very small application in Go, and configured an AWS Linux AMI to host. The application is a very simple web server. I’ve installed Go on the Linux VM by following the instructions in the official documentation to the letter. My application runs as expected when invoked with the “go run main.go” command.
However, I receive an “Invalid argument” error when I attempt to manually launch the binary file generated as a result of running “go install”. Instead, if I run “go build” (which I understand to be essentially the same thing, with a few exceptions) and then invoke the resulting binary, the application launches as expected.
I’m invoking the file from within the $GOPATH/bin/ folder as follows:
./myapp

I’ve also added $GOPATH/bin to the $PATH variable.
I have also moved the binary from $GOPATH/bin/ to the src folder, and successfully run it from there.
The Linux instance is a 64-bit instance, and I have installed the corresponding Go 64-bit installation.

A: go build builds everything (that is, all dependent packages), then produces the resulting executable files and then discards the intermediate results (see this for an alternative take; also consider carefully reading outputs of go help build and go help install).
go install, on the contrary, uses precompiled versions of the dependent packages, if it finds them; otherwise it builds them as well, and installs under $PATH/pkg. Hence I might suggest that go install sees some outdated packages which screw the resulting build.
Consider running go install ./... in your $GOPATH/src.
Or may be just selective go install uri/of/the/package for each dependent package, and then retry building the executable.


Q: Docker run on sub domains My goal is to deploy multiple webapps and access them through sub-domains, I'm currently running them on different ports, I have nginx on the server and the containers are running apache.
docker run -p 8001:80 -d apache-test1
docker run -p 8002:80 -d apache-test2

and I'm able to access them by going to
http://example.com:8001

or
    http://example.com:8002
But I like to access them through sub-domains instead
http://example.com:8001 -> http://test1.example.com
http://example.com:8002 -> http://test2.example.com

I have nginx running on the server with the following server settings
server {
    server_name test1.anomamedia.com;
    location / {
        proxy_redirect off;
        proxy_set_header Host $host ;
        proxy_set_header X-Real-IP $remote_addr ;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
        proxy_pass http://localhost:8001;
    }
}

server {
    server_name test2.anomamedia.com;
    location / {
        proxy_redirect off;
        proxy_set_header Host $host ;
        proxy_set_header X-Real-IP $remote_addr ;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
        proxy_pass http://localhost:8002;
    }
}

If its of any help this is my Dockerfile
FROM ubuntu

RUN apt-get update
RUN apt-get -y upgrade

RUN sudo apt-get -y install apache2 php5 libapache2-mod-php5

# Install apache, PHP, and supplimentary programs. curl and lynx-cur are for debugging the container.
RUN DEBIAN_FRONTEND=noninteractive apt-get -y install apache2 libapache2-mod-php5 php5-mysql php5-gd php-pear php-apc php5-curl curl lynx-cur

# Enable apache mods.
RUN a2enmod php5
RUN a2enmod rewrite

EXPOSE 80

# Copy site into place.
ADD html /var/www/html

# Update the default apache site with the config we created.
ADD apache-config.conf /etc/apache2/sites-enabled/000-default.conf

# By default, simply start apache.
CMD /usr/sbin/apache2ctl -D FOREGROUND

A: I have similar problems. Also I often need to add and remove containers, so I don't whant to edit nginx conf everytime. My solution was using jwilder/nginx-proxy.
then you just start containers with exposed port (--expose 80, not -p 80:80) and add env variables:
-e VIRTUAL_HOST=foo.bar.com

Don't forget to transfer with your main nginx traffic with right headers:
server {
    listen       80;# default_server;
    #send all subdomains to nginx-proxy
    server_name  *.bar.com;

    #proxy to docker nginx reverse proxy
    location / {
        proxy_set_header   X-Real-IP $remote_addr; #for some reason nginx
        proxy_set_header   Host      $http_host;   #doesn't pass these by default
        proxy_pass         http://127.0.0.1:5100;
    }

}

A: Have a look at the nginx-proxy project (https://github.com/jwilder/nginx-proxy). I wrote a tutorial in my blog which demonstrates exactly what you want to achieve using it: https://blog.florianlopes.io/host-multiple-websites-on-single-host-docker
This tool automatically forwards requests to the appropriate container (based on subdomain via the VIRTUAL_HOST container environment variable).
For example, if you want to access your container through test1.example.com, simply set the VIRTUAL_HOST container environment variable to test1.example.com.


Q: How to improve look and feel of JAVA swing GUI? I am working on a project that uses Java Swing. The default look and feel of the Java Swing GUI is very boring. Is there any way I can use a better look and feel? Something like on web pages...

A: You can set the look and feel to reflect the platform:
try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
    e.printStackTrace();
}

If this is not nice enough for you, take a look at SWT for Eclipse.

A: if you're good with Photo shop you could declare the JFrame as undecorated and create your own image that will server as your custom GUI.
in this example refer to the JFrame as frame.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
//If you want full screen enter frame.setExtendedState(JFrame.MAXIMIZE_BOTH);
frame.setUndecorated(true);

now that the JFrame has its own border and custom GUI, if you defined your own custom buttons for minimize, maximize, and exit you need to lay a JPanel over the buttons and declare what those buttons will do in a action listener function(lol sorry...I don't know if it's called function like c++ or class...)
for example we will refer to the JPanel as panel and we will set up a exit button.
panel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.exit(JFrame.EXIT_ON_CLOSE);
});
}


Q: smoothing between pixels of imagesc\imshow in matlab like the matplotlib imshow When I use matplotlib's imshow() in python to represent a small matrix, it produces a some sort if smoothing between pixels. Is there any way to have this in Matlab when using imshow or imagesc?
For example, using matplotlib this is the output of the identity matrix imshow(eye(3)):

while in matlab,  imagesc(eye(3)):

A solution I can think of is to extrapolate and smooth using some filter, but that won't be relevant for the single pixel levels. I've also tried myaa and export_fig, but they are not satisfactory. Myaa is taking all GUI usabily after being applied, so I can't zoom in or out, and export_fig makes me save the figure to a file and then operate on that file, too cumbersome. So, is there a way to tell the figure engine of matlab (java or what not) to do this smoothing while keeping the nice usability of the figure GUI?

A: It is due to the default interpolation which is set to 'bilinear'. I think 'none' would be a more intuitive default. You can change the default interpolation method (eg interpolation=None) with:
mpl.rcParams['image.interpolation'] = 'none'

More information about customising Matplotlib can be found on the website
The code below will give you an overview of all interpolation methods:
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', \
           'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']

grid = np.random.rand(4,4)

fig, ax = plt.subplots(3,6,figsize=(12,6), subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(hspace=0.3, wspace=0.05)

ax = ax.ravel()

for n, interp in enumerate(methods):
    ax[n].imshow(grid, interpolation=interp)
    ax[n].set_title(interp)


Q: Why java ThreadPoolExecutor kill thread when RuntimeException occurs? Why the unhanded exception is rethrown in worker when calling execute method ? As result new Thread will be created on next execution to maximize threads count

A:
Why java ThreadPoolExecutor kill thread when RuntimeException occurs?

I can only guess that the reason why ThreadPoolExecutor.execute(...) has the thread call runnable.run() directly and not wrap it in a FutureTask is so you would not incur the overhead of the FutureTask if you didn't care about the result.
If your thread throws a RuntimeException, which is hopefully a rare thing, and there is no mechanism to return the exception to the caller then why pay for the wrapping class?  So worst case, the thread is killed and will be reaped and restarted by the thread-pool.

A: There is no way to handle exception properly. Exception can't be propagated to caller thread and can't be simply swallowed.
Unhandled exception is thrown in thread is delegated to ThreadGroup.uncaughtException method, which prints output to System.err.print, until desired behavior is overridden for ThreadGroup.
So this is expected behavior, it can be compared with throwing unhanded exception in main method. In this case, JVM terminates execution and prints exception to the output.
But I'm not sure, why ThreadPoolExecutor does not handle it itself, ThreadPoolExecutor can log it itself. Creating new Thread is not so cheap.
Maybe there is an assumption, that some resources (native, threadLocal, threadStack, etc) associated with Thread should be released.


Q: Array Compatiblilty java These are my instructions:

Two arrays are said to be compatible if they are of the same size and
  if the ith element in the first array is greater than or equal to the
  ith element in the second array for all elements. If the array size is
  zero or less then display the message "Invalid array size". Write a Java
  program to find whether 2 arrays are compatible or not. If the arrays
  are compatible display the message as "Arrays are Compatible", if not
  then display the message as "Arrays are Not Compatible".

My solution is as follows:
class CompaibleArrays {
    public static void main(String []args){
        int n1=0;
        int n2=0;
        int flag=0;
        int []a1 = new int[20];
        int []a2 = new int[20];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size for First array:");
        n1 = sc.nextInt();
        if(n1<1){
            System.out.println("Invalid array size");
        }
        else{
            System.out.println("Enter the elements for First array:");
            for(int i=0 ; i<n1 ; i++){
                a1[i] = sc.nextInt();
            }

            System.out.println("Enter the size for Second array:");
            n2 = sc.nextInt();
            if(n1<1){
                System.out.println("Invalid array size");
            }
            else{
                System.out.println("Enter the elements for Second array:");
                for(int j=0 ; j<n2 ; j++){
                    a2[j] = sc.nextInt();
                }
            }
        }
        if(n1==n2){
            System.out.println("Arrays are Not Compatible");
        }
        else{
            for(int x=0 ; x<n1 ; x++){
                if(a1[x]>=a2[x]){
                    flag++;
                }
            }
            if(flag==n1){
                System.out.println("Arrays are Compatible");
            }
            else{
                System.out.println("Arrays are Not Compatible");
            }
        }

    }
}

Sample Input 1 :
 Enter the size for First array:
 5
 Enter the elements for First array:
 5
 14
 17
 19
 15
 Enter the size for Second array:
 5
 Enter the elements for Second array:
 2
 5
 9
 15
 7
 Sample Output 1:
 Arrays are Compatible

Sample Input 2 :
 Enter the size for First array:
 3
 Enter the elements for First array:
 1
 4
 7
 Enter the size for Second array:
 5
 Enter the elements for Second array:
 2
 5
 9
 5
 7
 Sample Output 2:
 Arrays are Not Compatible

Sample Input 3 :
 Enter the size for First array:
 -2
 Sample Output 3:
 Invalid array size

** Help me out **

A: There are a few issues in your code.

*

*In your else block, you need to replace (n1<1) with (n2<1).

*Replace if(n1==n2) with if(n1!=n2)

*You do not need to iterate through all the elements. If at any point you find the index elements of both the arrays do not satisfy the condition, you should break the loop. Use a boolean flag for this.

public class CompaibleArrays {
    public static void main(String []args){
        int n1=0;
        int n2=0;
        boolean flag=true;
        int []a1 = new int[20];
        int []a2 = new int[20];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size for First array:");
        n1 = sc.nextInt();
        if(n1<1){
            System.out.println("Invalid array size");
        }
        else{
            System.out.println("Enter the elements for First array:");
            for(int i=0 ; i<n1 ; i++){
                a1[i] = sc.nextInt();
            }

            System.out.println("Enter the size for Second array:");
            n2 = sc.nextInt();
            if(n2<1){
                System.out.println("Invalid array size");
            }
            else{
                System.out.println("Enter the elements for Second array:");
                for(int j=0 ; j<n2 ; j++){
                    a2[j] = sc.nextInt();
                }
            }
        }
        if(n1!=n2){
            System.out.println("Arrays are Not Compatible");
        }
        else{
            for(int x=0 ; x<n1 ; x++){
                if(a1[x]<a2[x]){
                    flag = false;
                    break;
                }
            }
            if(flag==true){
                System.out.println("Arrays are Compatible");
            }
            else{
                System.out.println("Arrays are Not Compatible");
            }
        }

    }
}


Q: Use LIKE for strings in sql server 2008 I want to make a function that search in a table and returns rows that contain a certain word that I Insert like below. But when I use LIKE it give me an error: Incorrect syntax near '@perberesi'
CREATE FUNCTION perberesit7
(@perberesi varchar(100))
RETURNS @menu_rest TABLE
(emri_hotelit varchar(50),
emri_menuse varchar(50),
perberesit varchar(255))
AS
Begin
   insert into @menu_rest
   Select  dbo.RESTORANTET.Emri_Rest, dbo.MENU.Emri_Pjatës, dbo.MENU.Pershkrimi
   From RESTORANTET, MENU
   Where dbo.MENU.Rest_ID=dbo.RESTORANTET.ID_Rest and
          dbo.MENU.Pershkrimi LIKE %@perberesi%

   return

End

Pleae help me...How can I use LIKE in this case

A: try using:
'%' + @perberesi + '%'
instead of:
%@perberesi%
Some Examples

A: Ok, I just realized that you are creating a function, which means that you can't use INSERT. You should also really take Gordon's advice and use explicit joins and table aliases.
CREATE FUNCTION perberesit7(@perberesi varchar(100))
RETURNS @menu_rest TABLE (  emri_hotelit varchar(50),
                            emri_menuse varchar(50),
                            perberesit varchar(255))
AS
Begin
   return(
   Select  R.Emri_Rest, M.Emri_Pjatës, M.Pershkrimi
   From RESTORANTET R
   INNER JOIN MENU M
        ON M.Rest_ID = R.ID_Rest
   Where M.Pershkrimi LIKE '%' + @perberesi + '%')
End

A: Why do you have to define the return table?
The following is a inline table variable function that performs better than a multi-line table.  I wrote one to return columns that have the two letters 'id'.  Just modify for your own case.
See article from Wayne Sheffield.
http://blog.waynesheffield.com/wayne/archive/2012/02/comparing-inline-and-multistatement-table-valued-functions/
-- Use tempdb
use tempdb;
go

-- Simple ITVF
create function search_columns (@name varchar(128))
returns TABLE
return
(
select * from sys.columns where name like '%' + @name + '%'
)
go

-- Call the function
select * from search_columns('id');
go

However, since you have a '%' in the like clause at the front of the expression, a full table or index scan is likely.  You might want to look at full text indexing if you data is large.
http://craftydba.com/?p=1629


Q: Can Multiple WSO2 API manager integrate with single WSO2IS-KM 5.7.0? We have installed WSO2 IS-KM version 5.7.0 and we want to integrate Multiple WSO2 API Manager version 2.6.0 with WSO2 IS-KM.
 Requesting you to please suggest and share the link to configure multiple WSO2 API manager with WSO2 IS-KM version 5.7.0

A: Please find a simple set of configurations on setting up multiple API Manager nodes with a single IS as Key Manager. It is required to front the API Manager nodes with a load balancer (with sticky sessions enabled & data-sources are shared among all the nodes) and configure the API Manager nodes as follows
API Manager Nodes: api-manager.xml (assumption IS-KM port offset 1, therefore 9444)
<AuthManager>
  <!-- Server URL of the Authentication service -->
  <ServerURL>https://localhost:9444/services/</ServerURL>
  ...
</AuthManager>
...
<APIKeyValidator>
  <!-- Server URL of the API key manager -->
  <ServerURL>https://localhost:9444/services/</ServerURL>
  ...
</APIKeyValidator>

IS Key Manager Node: api-manager.xml
<APIGateway>
  <Environments>
    <Environment type="hybrid" api-console="true">
      ...
      <!-- Server URL of the API gateway -->
      <ServerURL>https://loadbalancer/services/</ServerURL>
      ...
</APIGateway>

Sample NGINX
upstream mgtnode {
  server localhost:9443; # api manager node 01
  server localhost:9443; # api manager node 02
}

server {
  listen 443;
  server_name mgtgw.am.wso2.com;
  proxy_set_header X-Forwarded-Port 443;
  ...
  location / {
    ...
    proxy_pass https://mgtnode;
  }
}

References

*

*Configuring IS as Key Manager


Q: Tensorflow did not save the required models I ask tensorflow to save models every 100 iterations in every epoch, the following is my code. But after 900 iterations, only trained models for the 500th, 600th, 700th, 800th, 900th iterations were saved.
with tf.Session(config = tf.ConfigProto(log_device_placement = True)) as sess:

    sess.run(init_op)

    for i in range(args.num_epochs):
        start_time = time.time()
        k = 0
        acc_train = 0
        # initialize the iterator to train_dataset
        sess.run(train_init_op)
        while True:
            try:
                accu, l, _ = sess.run([accuracy, loss, optimizer], feed_dict = {training: True})
                k += 1
                acc_train += accu
                if k % 100 == 0:
                    print('Epoch: {}, step: {}, training loss: {:.3f}, training accuracy: {:.2f}%'.format(i, k, l, accu * 100))
                    saver.save(sess, args.saved_model_path, global_step = (i+1) * k)
            except tf.errors.OutOfRangeError:
                break

The following is the training accuracies:
Epoch: 0, step: 100, training loss: 0.669, training accuracy: 59.38%
Epoch: 0, step: 200, training loss: 0.806, training accuracy: 54.69%
Epoch: 0, step: 300, training loss: 0.781, training accuracy: 57.81%
Epoch: 0, step: 400, training loss: 0.725, training accuracy: 64.06%
Epoch: 0, step: 500, training loss: 0.347, training accuracy: 89.06%
Epoch: 0, step: 600, training loss: 0.193, training accuracy: 89.06%
Epoch: 0, step: 700, training loss: 0.003, training accuracy: 100.00%
Epoch: 0, step: 800, training loss: 0.190, training accuracy: 98.44%
Epoch: 0, step: 900, training loss: 0.009, training accuracy: 100.00%
My question is why tensorflow did not saved models for the 100th, 200th, 300th, 400th iterations? Thank you!

A: It did, but I'm guessing the Saver instance you created had the default max_keep value of 5, so it overwrote them as the last 5 were created. To keep 10, change your saver creation line to
saver = tf.train.Saver(max_keep=10)

You might also want to play with the keep_checkpoint_every_n_hours argument if you don't want to save -every- one.


Q: Embedding Loops with 2 Variables Dim rng As Range, cell As Range, copyToCell As Range

For j = 9 To 23

         For i = 2 To 23
                 Set rng = ThisWorkbook.Sheets("Sheet A").Range(Cells(3, j), Cells(11, j))
                 Set copyToCell = ThisWorkbook.Sheets("Sheet B").Cells(3, i)

                  For Each cell In rng
                    If cell.Value <> vbNullString Then
                    copyToCell.Value = cell.Value
                    Set copyToCell = copyToCell.Offset(1, 0)
                    End If
                  Next cell

         i = i + 2
        Next i

j = j + 2
Next j

I'm trying to copy an array of cells from one sheet and have them pasted to another. The code I wrote places the values that are copied from "Sheet A" to "Sheet B" correctly, however, the values are incorrect.

The pic above is Sheet A. I'm trying to copy values from Range I3:Ill (Sheet A) and then have them pasted to the following Sheet B Range B3:B11 and so on for each plan listed.

I created a loop so that the values under Plan 2 and so on in Sheet A will transfer those values under Plan 2 and so on in Sheet B.
When I run my code it results in all 0's in each plan on Sheet B instead of 5,5,4 (under Plan 1) and 5 (under plan 2). Any ideas or another way around it besides having to use 2 variables in a loop?

A: Why the loop? Just put the loop values in the Range statements:

  Dim rng As Range, cell As Range, copyToCell As Range

  Set rng = ThisWorkbook.Sheets("Sheet1").Range(Cells(9, "j"), Cells(23, "j"))
  Set copyToCell = ThisWorkbook.Sheets("Sheet2").Cells(3, "i")

  rng.Copy copyToCell

End Sub

HTH


Q: Angular directive - update parent scope when another directive as also isolated scope I have written an angular directive that needs to update the parent scope.
angular.module('app').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attributes, model) {

              $scope.property1 = 'some val';
              $scope.property2 = 'another val';
              $scope.$apply();

    };
});

But in my controller I do this:
MyCtrl = function($scope){
$scope.doSave = function(){
   // do some logic
   console.log($scope.property1);
   console.log($scope.property2);

}

}
When doSave runs, I'm getting undefined values in my console. How can I get it applied to the parents scope WITHOUT isolating the scope. I don't have this option because another directive on the same element isolates the scope.

A: It should work. By default if you don't specify scope in your directive it uses the parent scope so property1 and property2 should be set. try setting the scope in your directive to false. As a side note is not a good practice what you are doing. It will be better isolate the scope and add the property as attributes. This way you will have good encapsulation.
for example
angular.module('app').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            property1: '=',
            property2: '='
        }
        link: function ($scope, element, attributes, model) {

            //here you have access to property 1 and 2

    };
});

function MyCtrl($scope) {
    $scope.property1 = null;
    $scope.property2 = null;

    $scope.doSave = function(){
   // do some logic
       console.log($scope.property1);
       console.log($scope.property2);
    }
}

And your html

A: I don't know what you are doing wrong, because it seems to work: http://jsfiddle.net/HB7LU/2865/
var myApp = angular.module('myApp',[]);
angular.module('myApp').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attributes, model) {

              $scope.property1 = 'some val';
              $scope.property2 = 'another val';
              $scope.$apply();

    }
}
});

    angular.module('myApp').controller('MyCtrl', MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.doSave = function(){
   // do some logic
   console.log($scope.property1);
   console.log($scope.property2);

}
}


Q: Use API v2 to work with Customer Group Prices We are using a tool to integrate our financial software with Magento.
Does anyone know a way to write and read the Customer Group Prices with API v2?
Each customer has a different agreed price for products in Dynamics GP and we need to match this price in Magento.
This way, when a Customer logs into the Magento site, their agreed price will be displayed in all simple products.


Q: Instance variable to stop a running thread Header :
@interface CodeTest : NSObject {
BOOL cancelThread;
}

-(void) testCode;
-(void) stopRunning;
-(void) startRunning;

@property (assign) BOOL cancelThread;
@end

Implementation :
-(void)stopRunning{
    self.cancelThread = YES;
}

-(void)startRunning{
    self.cancelThread = NO;

    [NSThread detachNewThreadSelector:@selector(testCode) toTarget:self withObject:nil];

}
-(void)testCode{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"STARTED");
    /* Std C99 code */
    while( conditions ){
            if(self.cancelThread){
                 conditions = NO;
            }
            ...
            ...
    }
    /* end of C code */
    [pool release];
}

As you can see, it tires to execute testCode on a separate thread and using the cancelThread BOOL as a stop execution flag in the separate thread.
I have the following issue :

*

*The compiler signals that self.cancelThread in the middle of the std c code is not valid (self is not defined). I think, it tries to interpret that statement as c code but this is obj-c.

There is something missing ?
UPDATE : It's not related to missing {}'s as one of you suggested... The code works perfectly without the if(self.cancelThread){ conditions = NO; }.

A:
-[CodeTest setCancelThread:]: unrecognized selector.

Means that you don't have a setter defined for the cancelThread property. You're missing
@synthesize cancelThread;

(in your @implementation section)

A: What do you mean by "    /* Std C99 code */"?
If that code is really being compiled as C99 code, then self.cancelThread is problematic because it is an Objective-C expression.  First, it is the equivalent of [self cancelThread], a method call and, secondly, it requiresself` which wouldn't be present in the body of a C99 function.
However, given that the code you showed has it in a method, the comment doesn't make sense.


Q: Obfuscating Android library projects I'm using AndEngine and two AndEngine extensions, for a total of 3 library projects. I really wish that I could obfuscate and optimize these library projects to improve application size, but I haven't seen anywhere how to do that with library projects.
Does anyone know what the Proguard configuration to do this is?

A: When Application is compiled, all *.java files in references Library Projects are compiled into Application's bin/classes folder. And obfuscation step is done using .class files in this folder. This means that all referenced Library Projects are automatically obfuscated when you obfuscate your application.


Q: MySqlException: Unable to connect to any of the specified MySQL hosts. MySql.Data.MySqlClient.NativeDriver.Open() Here is the code that connects to MySql and attemps to query data, and these are the errors i'm getting:

An unhandled exception occurred while processing the request.
  MySqlException: Timeout expired. The timeout period elapsed prior to
  completion of the operation or the server is not responding.
  MySql.Data.Common.StreamCreator.GetTcpStream(MySqlConnectionStringBuilder
  settings)
MySqlException: Unable to connect to any of the specified MySQL hosts.
  MySql.Data.MySqlClient.NativeDriver.Open()

public async Task<List<Store>> getStores(double lat, double lng)
    {
        List<Store> stores = new List<Store>();
        using (MySqlConnection connection = GetConnection())
        {
            await connection.OpenAsync();   // the code blows up here from time to time

            // request to return nearby stores
            MySqlCommand cmd = new MySqlCommand("SELECT * FROM Stores WHERE ABS(latitude- @latitude) < 0.006 AND ABS(longitude - @longtitude) < 0.006", connection);
            cmd.Parameters.Add(new MySqlParameter("@latitude", lat));
            cmd.Parameters.Add(new MySqlParameter("@longtitude", lng));
            cmd.CommandTimeout = 120;
            // MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    stores.Add(new Store()
                    {
                        id = Convert.ToInt32(reader["id"]),
                        address = reader["address"].ToString(),
                        latitude = Convert.ToDouble(reader["latitude"]),
                        longtitude = Convert.ToDouble(reader["longitude"])
                    });
                }
            }
        }

        return stores;
    }


Q: HighCharts: align rotated multiline label I'm trying to align axis labels in HighCharts
Labels should not be trimed, so ellipsis is not allowed
How it looks now:

How I want it to be:

Code: https://jsfiddle.net/9xw6dL3f/25/
{
  "chart": {
    "width": 500,
    "height": 300,
    "type": "column"
  },
  "title": {
    "text": null
  },
  "xAxis": {
    "type": "category",
    "labels": {
      "rotation": -90,
      "style": {
        "textOverflow": "none"
      }
    }
  },
  "series": [
    {
      "name": "",
      "data": [

        { "name": "Follow me into my theatre of lunacy", "y": -10, "color": "#ABC" },
        { "name": "1", "y": 1, "color": "#000" },
        { "name": "2", "y": 2, "color": "#000" },
        { "name": "3", "y": 3, "color": "#000" },
        { "name": "4", "y": 4, "color": "#000" },
        { "name": "5", "y": 5, "color": "#000" },

      ]
    }
  ]
}

A: It is possible to move label depending on it's rows count
Add render function to the chart object
{
  "chart": {
    ...
    events: {
      render() {
        for (let i = 0; i < this.xAxis[0].names.length; i++) {
          const label = this.xAxis[0].ticks[i].label;
          const rows = (label.element.innerHTML.match(/<\/tspan>/g) || []).length;
          label.translate(-8 * rows, 0);
        }
      }
    }

where 8 is half of row size in px
https://jsfiddle.net/kLz1uoga/5/


Q: Why syntax error when import my own modules in Python I created my own python package with "python setup.py bdist_wheel" and "pip install /path/to/dist/my_own_package.wheel".  After installing it, when importing it, there is error of "SyntaxError: invalid syntax". Could you help? thanks.
>>> import my-modules
  File "<stdin>", line 1
    import my-modules
             ^
SyntaxError: invalid syntax

But there is module installed in Continuum\anaconda3\Lib\site-packages

A: Your module has a minus symbol in the title. That's the reason. Sometimes (nearly never) the underline symbol may be the fault. If you name your module like "myModules" or "modules", there would be no error.
WRONG:
>>> import my-modules

  File "<stdin>", line 1
    import my-modules
             ^
SyntaxError: invalid syntax

VALID:
>>> import myModules

#No error


Q: How do you pull certain substrings(ip addresses) out of strings(Wireshark Output)? I am reading the contents of a wireshark dump from a text file, line by line.  One of the things I can pick out easily is the protocol used in that specific line of the wireshark output(as shown in the code below).  The problem I'm running into is pulling out the ip addressess from the line.  As you can see in the sample output below, and my code, it was fairly easy to pull out the protocol because it was always capitialized and there was a space on either side of it.  The ip addresses however, aren't as uniform and I'm not quite sure how to pull them out as well.  This is mostly due to the fact that I'm not quite sure how all the parts of the re.match() work.  Can somebody help me out in this, and possibly explain how the re.match() parameters work?
file = open('tcpdump.txt', 'r');
     for line in file:
          matchObj = re.match(r'(.*) TCP (.*?) .*', line, re.M)

Sample Wireshark Output:
604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0

A: The first regex group is greedy (.*) and is matching everything, you can make it non-greedy by adding ?, i.e.:
file = open('tcpdump.txt', 'r');
     for line in file:
          matchObj = re.match(r"->\s(.*?)\s(\w+)\s(.*?)\s", line, re.M)

The above example is will capture 3 groups containing the remote address 114.113.226.43, protocol TCP and port 54 respectively.

Regex101 Demo

A: Start by look at the regex documentation, for python it is here:
https://docs.python.org/3/library/re.html
There are also many sites that have good tutorials, samples and interactive testers such as:
http://regexr.com/
I don't know the output format of wireshark, but I would imagine it is documented somewhere.
This should get your ip addresses:
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b

A: As people have already responded, regex is the way to go. A sample code for the purpose
import unittest
import re
from collections import namedtuple

protocol = namedtuple('Protocol', ['source', 'destination', 'protocol'])

def parse_wireshark(input):
  pat = re.findall(r"(\d+\.\d+\.\d+\.\d+) -> (\d+\.\d+\.\d+\.\d+) (\w+)", input)[0]
  return protocol(source=pat[0], destination=pat[1], protocol=pat[2])

class TestWireShark(unittest.TestCase):

  def test_sample(self):
    self.assertEqual(parse_wireshark("604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0"),
                     protocol(source='10.200.59.77',
                              destination='114.113.226.43',
                              protocol='TCP'))
if __name__ == '__main__':
   unittest.main()


Q: Merge two Arraylist & retains all the value in Java I have 2 arrayList of PresentErrorList & PastErrorList both having 3 fields errorCode,presentErrorCount & pastErrorCount .
presentErrorList
[errorCode=1000,presentErrorCount=10,pastErrorCount =0]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]

pastErrorList
[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]
[errorCode=1000,presentErrorCount=0,pastErrorCount =12]

While calculating for Present, pastErrorCount =0 and viceversa . My finalArrayList should be
[errorCode=1000,presentErrorCount=10,**pastErrorCount =12**]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]
[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]`

As you can see in the final list for errorCode=1000 as it is duplicate in past so there will be only 1 object with both present & past error count .

A: So there was not easy to find a way but a the end that's what I do :
public static void main(String[] args) {
    List<ErrorCodeModel> presentErrorList = new ArrayList<>();
    presentErrorList.add(new ErrorCodeModel("1000", 10, 0));
    presentErrorList.add(new ErrorCodeModel("1100", 2, 0));

    List<ErrorCodeModel> pastErrorList = new ArrayList<>();
    pastErrorList.add(new ErrorCodeModel("1003", 0, 10));
    pastErrorList.add(new ErrorCodeModel("1104", 0, 12));
    pastErrorList.add(new ErrorCodeModel("1000", 0, 12));

    Map<String, ErrorCodeModel> map = Stream.of(presentErrorList, pastErrorList)
                .flatMap(Collection::stream)
                .collect(Collectors.toMap(ErrorCodeModel::getErrorCode,
                      Function.identity(),
                      (oldValue, newValue)
                      -> new ErrorCodeModel(oldValue.getErrorCode(),
                           oldValue.getPresentErrorCount()+newValue.getPresentErrorCount(),
                           oldValue.getPastErrorCount()+newValue.getPastErrorCount())));

    List<ErrorCodeModel> errorList = new ArrayList<>(map.values());

    errorList.sort((err1, err2) //line 20*
                -> Integer.compare(Integer.parseInt(err1.getErrorCode()),
                                   Integer.parseInt(err2.getErrorCode())));

    System.out.println(errorList.toString());

    //*line 20 : Optionnal, if you want to sort by errorCode
    //(need to parse to int to avoir alphabetical order
}

So after add your elements, this is what is done :

*

*A stream of each 2 List is done

*the goal is to add them in a Map :  (object's code, object)

*the (oldValue,newValue) lambda-exp is used is the key is always in the map, I tell it to add a new Object which has the sum of previous and the new to add

*after the map, a List is generated from the values which represents the ErrorCodeModel as you ask


Q: 315 error when tryin to connect to ADS Database
This error occurs when i try to connect to a remote ads data dictionary. When researching the error code 315 results only came up for error code 314.

A: Fixed this issue by installing aceapi and setting the path of the vendor lib to the syswow path of ace32.dll in FDDrivers.ini