I am using Azure Mobile Apps authentication with Facebook in my app. The log in and log out is fine. I can log in with my Facebook but I am having trouble getting additional Facebook details like my profile name and picture. How can I access it with android code?

I'm a beginner in android that's why i spent much of time to found the solution . My problem is how to save selected images from gallery in singleton because i need them in an onother activity. please someone can help me ?

I'm going to provide as much detail as I possibly can so if this gets too long, my apologies.

I built out this whole app thinking that the garbage collector handled memory cleanup just fine, which was incredibly stupid and naive of me, but hey, it was my first time every using Xamarin to build an app, and my first time ever building an app, and I had a 3 week deadline, so whats a guy to do? Every screen seems to leak memory, but the screens that leak the most are screens that have bitmaps, generating a memory dump and analyzing it in MAT, I found the following:

enter image description here

So there are 4 potential culprits, 2 are bitmaps, 2 are byte arrays. This is a heap dump for the main menu of the app, if I go into my list view activity for listing out elements, I get 5 potential leaks from bitmaps. Here is the code for the activity:

            AssetManager assets = Assets;

        Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);

        var topPanel = FindViewById<TextView>(Resource.Id.topPanel);
        topPanel.Text = service.GetLanguageValue("use recommendations - top bar heading");
        topPanel.Dispose();

        var lowerPanel = FindViewById<TextView>(Resource.Id.recommendationsPanel);
        lowerPanel.Text = service.GetLanguageValue("title upper - recommendations by variety");
        Shared.ScaleTextToOneLine(lowerPanel, lowerPanel.Text, Shared.ScaleFloatToDensityPixels(Shared.GetViewportWidthInDp()), 1.0f);
        lowerPanel.Dispose();

        // Read html file and replace it's contents with apple data
        string html = "";
        using (StreamReader sr = new StreamReader(Assets.Open("apple-variety-detail.html")))
        {
            html = sr.ReadToEnd();
        }

        html = ReplaceAppleDetailsHtml(html);
        var webview = FindViewById<WebView>(Resource.Id.recommendationsMessage);
        CleanWebView();
        webview.LoadDataWithBaseURL("file:///android_asset/",
        html,
        "text/html", "UTF-8", null);

        if (Shared.currentApple != null)
        {
            // Setup apple image
            using (var imageView = FindViewById<ImageView>(Resource.Id.recommendationsImage))
            {
                var apple = this.apples.Where(a => a.Id == Shared.currentApple.AppleId).Select(a => a).First();
                var imgName = apple.Identifier.First().ToString().ToUpper() + apple.Identifier.Substring(1);
                var fullImageName = "SF_" + imgName;

                using (var bitmap = Shared.decodeSampledBitmapFromResource(ApplicationContext.Resources,
                                          Resources.GetIdentifier(fullImageName.ToLower(), "drawable", PackageName),
                                          200, 200))
                {
                    imageView.SetImageBitmap(bitmap);
                }
            }

            // Setup apple name
            FindViewById<TextView>(Resource.Id.appleNameTextView).Text = Shared.currentApple.Name;

        }
        else
        {
            FindViewById<TextView>(Resource.Id.appleNameTextView).Text = "Not Found!";
        }




        // Setup list menu for apples
        AppleListView = FindViewById<ListView>(Resource.Id.ApplesListMenu);
        // Scale details and list to fit on the same screen if the screen size permits
        if (Shared.GetViewportWidthInDp() >= Shared.minPhoneLandscapeWidth)
        {
            var listViewParams = AppleListView.LayoutParameters;
            // Scales list view to a set width
            listViewParams.Width = Shared.ScaleFloatToDensityPixels(240);
            listViewParams.Height = Shared.ScaleFloatToDensityPixels(Shared.GetViewportHeightInDp());
            AppleListView.LayoutParameters = listViewParams;
        }
        else
        {
            // Here, we either need to hide the list view if an apple was selected, 
            // or set it to be 100% of the screen if it wasn't selected.
            if(!Shared.appleSelected)
            {
                var listViewParams = AppleListView.LayoutParameters;
                // Scales list view to a set width
                listViewParams.Width = Shared.ScaleFloatToDensityPixels(Shared.GetViewportWidthInDp());
                listViewParams.Height = Shared.ScaleFloatToDensityPixels(Shared.GetViewportHeightInDp());
                AppleListView.LayoutParameters = listViewParams;
            }
            else
            {
                var listViewParams = AppleListView.LayoutParameters;
                // Scales list view to a set width
                listViewParams.Width = Shared.ScaleFloatToDensityPixels(0);
                listViewParams.Height = Shared.ScaleFloatToDensityPixels(Shared.GetViewportHeightInDp());
                AppleListView.LayoutParameters = listViewParams;
            }
        }

        // Set listview adapter
        if(AppleListView.Adapter == null)
        {
            AppleListView.Adapter = new Adapters.AppleListAdapter(this, (List<Apple>)apples, this);
        }
        AppleListView.FastScrollEnabled = true;

        // Set the currently active view for the slide menu
        var frag = (SlideMenuFragment)FragmentManager.FindFragmentById<SlideMenuFragment>(Resource.Id.SlideMenuFragment);
        frag.SetSelectedLink(FindViewById<TextView>(Resource.Id.SlideMenuRecommendations));

        // Replace fonts for entire view
        Typeface tf = Typeface.CreateFromAsset(assets, "fonts/MuseoSansRounded-300.otf");
        FontCrawler fc = new FontCrawler(tf);
        fc.replaceFonts((ViewGroup)this.FindViewById(Android.Resource.Id.recommendationsRootLayout));
        tf.Dispose();
    }

The important part to note about this is the way this activity works is it loads an adapter, and when it displays it shows a list of items, when an item is clicked, it reloads this same activity, and it computes the screen size, shrinks down the list to show only the webview off to the side, and displays details about the item, thus simulating 2 screens, the reason I did this is because when the screen size is larger, it needs to show all of this as one single view, so on larger screens it will actually show both the listview and the webview, but still reload the activity to load new data.

The adapter code is probably what is giving me a hard time, but I'm not sure, I've tried quite a few things, but nothing seems to help, here's the adapter code:

    public class AppleListAdapter : BaseAdapter<Apple>
{

    List<Apple> items;
    Activity context;
    ApplicationService service = AgroFreshApp.Current.ApplicationService;
    private Context appContext;
    private Typeface tf;
    static AppleRowViewHolder holder = null;

    public AppleListAdapter(Activity context, List<Apple> items, Context appContext): base ()
    {
        this.context = context;
        this.items = items;
        this.appContext = appContext;
        context.FindViewById<ListView>(Resource.Id.ApplesListMenu).ChoiceMode = ChoiceMode.Single;
        tf = Typeface.CreateFromAsset(context.Assets, "fonts/MuseoSansRounded-300.otf");
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override Apple this[int position]
    {
        get { return items[position]; }
    }

    public override int Count
    {
        get
        {
            return items.Count;
        }
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {

        var item = items[position];

        var view = convertView;

        var imgName = item.Identifier.First().ToString().ToUpper() + item.Identifier.Substring(1);
        var fullImageName = "SF_" + imgName;

        if (view == null)
        {
            view = context.LayoutInflater.Inflate(Resource.Layout.appleRowView, null);
        }

        if (view != null)
        {
            holder = view.Tag as AppleRowViewHolder;
        }

        if(holder == null)
        {
            holder = new AppleRowViewHolder();
            view = context.LayoutInflater.Inflate(Resource.Layout.appleRowView, null);
            holder.AppleImage = view.FindViewById<ImageView>(Resource.Id.iconImageView);
            holder.AppleName = view.FindViewById<TextView>(Resource.Id.nameTextView);
            view.Tag = holder;
        }

        using (var bitmap = Shared.decodeSampledBitmapFromResource(context.Resources,
                                    context.Resources.GetIdentifier(fullImageName.ToLower(), "drawable", context.PackageName),
                                    25, 25))
        {
            holder.AppleImage.SetImageBitmap(bitmap);
        }

        holder.AppleName.Text = AgroFreshApp.Current.AppleDetailManager.GetAll().Where(a => a.AppleId == item.Id).Select(a => a.Name).FirstOrDefault();
        holder.AppleName.SetTypeface(tf, TypefaceStyle.Normal);

        view.Click += (object sender, EventArgs e) =>
        {
            var apple = AgroFreshApp.Current.AppleManager.Get(item.Id);
            Shared.currentApple = AgroFreshApp.Current.AppleDetailManager.GetAll().Where(a=>a.AppleId == item.Id && a.LanguageId == service.UserSettings.LanguageId).Select(a=>a).FirstOrDefault();
            Shared.appleSelected = true;

            Intent intent = new Intent(appContext, typeof(RecommendationsActivity));
            intent.SetFlags(flags: ActivityFlags.NoHistory | ActivityFlags.NewTask);
            appContext.StartActivity(intent);
        };

        return view;
    }
}

So I'm using the viewholder pattern here, and assigning click events to each list item as they get generated, with nohistory and newtask as the intent flags so that the pages refreshes properly. To clean up the bitmaps, I have been using these two methods:

This cleans the large image on the details webview:

        public void CleanBitmap()
    {
        // Clean recommendations bitmap
        ImageView imageView = (ImageView)FindViewById(Resource.Id.recommendationsImage);
        Drawable drawable = imageView.Drawable;
        if (drawable is BitmapDrawable)
        {
            BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
            if (bitmapDrawable.Bitmap != null)
            {
                Bitmap bitmap = bitmapDrawable.Bitmap;
                if (!bitmap.IsRecycled)
                {
                    imageView.SetImageBitmap(null);
                    bitmap.Recycle();
                    bitmap = null;
                }
            }

        }

        Java.Lang.JavaSystem.Gc();
    }

And this cleans the bitmaps stored in each listview item:

        public void CleanListViewBitmaps()
    {
        var parent = FindViewById<ListView>(Resource.Id.ApplesListMenu);

        // Clean listview bitmaps
        for (int i = 0; i < parent.ChildCount; i++)
        {
            var tempView = parent.GetChildAt(i);
            // If the tag is null, this no longer holds a reference to the view, so 
            // just leave it.
            if(tempView.Tag != null)
            {
                AppleRowViewHolder tempHolder = (AppleRowViewHolder)tempView.Tag;

                var imageView = tempHolder.AppleImage;
                var drawable = imageView.Drawable;

                if (drawable is BitmapDrawable)
                {

                    BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
                    if (bitmapDrawable.Bitmap != null)
                    {
                        Bitmap bitmap = bitmapDrawable.Bitmap;
                        if (!bitmap.IsRecycled)
                        {
                            imageView.SetImageBitmap(null);
                            bitmap.Recycle();
                            bitmap = null;
                        }
                    }
                }
            }
        }

        Java.Lang.JavaSystem.Gc();
    }

They then get called in the activities ondestroy method like so:

        protected override void OnDestroy()
    {
        base.OnDestroy();
        CleanBitmap();
        CleanListViewBitmaps();
        Shared.appleSelected = false;
    }

I'm also using a shared class with static variables to essentially track view states like if something was selected or no, but it only stores primitives, it doesn't store any view objects or anything like that, so I don't think that is the problem like I said it looks like bitmaps aren't getting cleaned correctly, and it seems to happen on every view, but this one in particular is bad. I also on each view load 2 fragments, one is a slide menu fragment in a frame layout, and the other is a navbar fragment that just holds 2 bitmaps for a logo and menu handle, so those could be culprits too I suppose. Here's the navbar fragment:

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

        var view = inflater.Inflate(Resource.Layout.navbar, container, false);

        var navLogo = view.FindViewById(Resource.Id.navbarLogo);
        var menuHandle = view.FindViewById(Resource.Id.menuHandle);
        var navSpacer = view.FindViewById(Resource.Id.navSpacer);

        ((ImageButton)(menuHandle)).SetMaxWidth(Shared.GenerateProportionalWidth(.25f, 50));
        ((ImageButton)(menuHandle)).SetMaxHeight(Shared.GenerateProportionalHeight(.25f, 50));

        ((ImageButton)(menuHandle)).Click += (object sender, EventArgs e) =>
        {
            var slideMenu = FragmentManager.FindFragmentById(Resource.Id.SlideMenuFragment);

            if (slideMenu.IsHidden)
            {
                FragmentManager.BeginTransaction().Show(slideMenu).Commit();
            }
            else if (!slideMenu.IsHidden)
            {
                FragmentManager.BeginTransaction().Hide(slideMenu).Commit();
            }
        };

        var navLogoParams = navLogo.LayoutParameters;
        // Account for the padding offset of the handle to center logo truly in the center of the screen
        navLogoParams.Width = global::Android.Content.Res.Resources.System.DisplayMetrics.WidthPixels - (((ImageButton)(menuHandle)).MaxWidth * 2);
        navLogoParams.Height = (Shared.GenerateProportionalHeight(.25f, 30));
        navLogo.LayoutParameters = navLogoParams;

        // Spacer puts the logo in the middle of the screen, by making it's size the same as the handle on the opposite side to force-center the logo
        ((Button)(navSpacer)).SetMaxWidth(Shared.GenerateProportionalWidth(.25f, 50));
        ((Button)(navSpacer)).SetMaxHeight(Shared.GenerateProportionalHeight(.25f, 50));

        return view;
    }

Does anyone see any obvious or stupid mistake that I'm making? I feel like it has to just be sheer inexperience that's causing me to miss something really obvious, or I'm doing something completely wrong, either way, I would seriously appreciate some help, I've been at this for close to 25 hours now.

EDIT #1:

1 of the bitmaps leaking was the menu handle button in the navigation fragment, so that drops the leak down from 300kb to 200kb, but I still need to figure out how to clean it properly.

I have an example url with a .php extension as shown below:

https://my.site.ac.uk/index.php

I have seen examples with

.html, .com & .co.uk

etc but not the .php extension.

Is it possible to use this as the URL for the webview in android? Thank you.

What is shortcut key that watch the value of string.xml at layout file on Android Studio?

I am using Android Studio on Linux.

And today I have updated it to version 2.3 stable but now I am not able to build any of my projects or even create a new project.

There is no error messages, just the building progress works for infinite time !

Edit:

I have also updated the Gradle plugin to 2.14.1 which was a recommendation message after staring Android Studio 2.3


What should i do?

Is there a way to distribute an apk through a LAN for an event without users having to configure untrusted sources on each device?

The situation is:

  • No/very limmited internet connection. Well actually, I provide WiFi for ~200 clients/hour, but with a very limited bandwidth. So I'm trying to avoid publishing on Play Store.

  • Where the event is being held I cannot fully depend on 3G/4G either.

  • Lots of people (+1000), with no ability (or not willing) to configure 'Untrusted sources' on device.

  • I already have a server, being used as proxy, firewall, access control, etc.

Does Android only trust on Google Play Store as a trusted source? If so, any way to bypass it from the network configuration? Like playing with dns maybe?

I've coded a cheat engine that cracks a famous game to get in-game contents without working hard or paying. Will google warn me or will it block my account? Has anything similar happened to you before?

We're performing a delivery from our Developer stream to the Integrated stream that we share - this process allows our build team to construct our application from the Integrated view. This is for a Java application.

There are several activities that were never delivered to the Integrated stream - old changes that were never desired by the users.

We're planning to do a deployment, and it is becoming increasingly difficult to discern which activities should and should not be deployed (we are already taking steps to improve our Activity Naming convention). So we're planning to deploy all checked-in activities, on the assumption that our current environment in DEV is an acceptable deployment for our TEST team.

I have a few questions regarding how ClearCase would handle such a delivery.

  • How does ClearCase handle two activities that are being delivered at the same time that have both made changes to the same Class object?
  • How would ClearCase handle an old activity being delivered with class chages where a newer activity has already made changes to that class and rendered it obsolete?
  • What differences between two versions of the same class would trigger a "Merge Difference"?

I've been wondering something about how we pass complex ORM objects to background workers — in my case, Django models and Celery, but this could apply to any similar background processing framework.

I usually pass model objects "by reference" using the primary key. In quick Python, this would be how I send an email for an user :

@app.task
def background_task(user_id):
    user = User.objects.get(id=user_id)
    send_email(user.first_name, user.last_name)

background_task.delay(user.id)

A coworker instead prefers to pass values directly to the task :

@app.task
def background_task(user_first_name, user_last_name):
    send_email(user_first_name, user_last_name)

background_task.delay(user.first_name, user.last_name)

I find the first method much easier to maintain :

  • We have tasks using the second paradigm taking 10+ arguments coming from a single object, and these are quite hard to read and reuse because one needs to make sure that all the arguments are accounted for.

  • Adding more information to the task means that you need to add more arguments, and make sure that they are also added to all the places that use this task, which is time-consuming and error-prone.

The second method has the following advantages :

  • You do not run the risk of using the wrong information. For instance, with the first method, a model could be updated twice before the task can run, resulting in the first update not being processed.
  • You also do not run a second query when the task runs since task arguments are stored along with the task, which could lighten the load on the database.

I am rather biased towards the first method, but neither of us were able to reach a conclusion on this.

  • Are there advantages/inconvenients that I did not list?
  • Can you think of some projects using either of these that we could use as examples?
  • How should we handle this?

I want to be able to have a (pretty) large FSM where I can debug it by jumping to a point and watching the execution.

For example, lets say I'm making a FSM that uses some probability on whether I go left or right at a junction. Maybe I have a bunch of things like "people I've seen go left" and "people I've seen go right".

Suppose the simple code above looks like this:

if (somethingA()) {
    if (somethingB()) {
        if (somethingX() && somethingY()) {
            // ...
        } else {
            // ...
        }
    } else if (somethingC()) {
        // ...
    }
} else {
    // ...
}

Further, assume that all the something...() functions are probability based!

The above code is ugly, but just for illustration.

Is there any kind of design that would allow me to go arbitrarily deep in a tree? Since it would be spread over multiple functions (again this is no trivially-sized FSM), could a design pattern help me here?

Ideally I'd like to probe how it works by jumping right to the point before somethingX() && somethingY() if I change some probability parameters to see how it reacts after, and see how it works going from there. For example if I have 10 nested functions like the above, I'd like to jump to layer 8, adjust the probability of one of the calls to see how it runs, and then split off a bunch of calls from that.

By this I mean jump to the point above, run a simulation, but call this simulation maybe 1000 times from that point (and I'd want to run this as quickly as possible and multithread it).

The only solution I can think of is to add some kind of POD (this is C++) and set it beforehand so I can jump exactly to where I want, like:

if (myStruct.jumpThroughA || somethingA()) {
    if (myStruct.jumpThroughB || somethingB()) {
        if (myStruct.jumpThroughXY || (somethingX() && somethingY())) {
            // ...
        } else {
            // ...
        }
    } else if (myStruct.jumpThroughC || somethingC()) {
        // ...
    }
} else {
    // ...
}

However I'm worried I'll be making clusterfuck code by doing this (but it may be my only option). I really want to avoid such code unless my back is against the wall.

Plus such a thing would be great for unit testing something specific, especially since randomness will play a role in these things and I'd like to test this by forcing it down some branches (my idea of a predictable PRNG for testing may or may not make it still a pain in the ass).

UPDATE:

  • I need to avoid making the function calls since I need code to be fast, so evaluating them beforehand as per here isn't feasible

  • Assume the something...() functions have side effects which are designed to aid in increasing computation speed (ex: somethingC() should not be calculated if somethingB() returns true since it would invoke a very costly function)

  • The arrow head antipattern also does not solve my "branching into" mess of having to add more booleans at each level to quickly descend on a branch of choice

Background

I'm about to build a LOB application that resembles an e-commerce solution (without paying and being open to the public). It will be used to receive orders for fulfillment purposes based on fulfillment contracts with one or more companies.

The UI will be MVC, and it's a going to be a pretty simple site. Most orders that are placed on the site will be fulfilled by our company, however there are orders that will be sent to an off-site fulfillment center (not owned by us). Simply put, there will be multiple order processing workflows. There will also likely be different requirements for calculating inventory on hand on a per-customer basis.

All that being said, I'm more of a front-end UI/UX guy and I want to confirm that the way I'm planning on handling this is reasonable.

If any of the verbiage I'm using below is incorrect, please correct me. Additionally, this is my first time using asyc/await also, so don't be shy about correcting my implementation.

Setup

Note: My boss prefers architectural patters that are as simple as we can make them without sacrificing long-term software viability.

For the sake of this question, we're only going to be dealing with the order object.

My solution currently looks like this:

enter image description here

First I created an interface called IOrderRepository:

public interface IOrderRepositoy
{
    Task<Model.Order> CreateOrderAsync(Model.Order order);
    Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders);
}

Then I created a partial Business.Order class which implements IOrderRepository and inherits Model.Order from entity framework:

namespace AdventureWorks.Business
{
    internal partial class Order : Model.Order, IOrderRepositoy
    {
        public virtual async Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders)
        {
            var db = new AWEntities();
            db.Orders.AddRange(orders);
            await db.SaveChangesAsync();

            return orders;
        }

        public virtual async Task<Model.Order> CreateOrderAsync(Model.Order order)
        {
            var db = new AWEntities();
            db.Orders.Add(order);
            await db.SaveChangesAsync();

            return order;
        }
    }
}

Next, I created a class to house the custom logic for a specific customer called GAC_Order. If custom logic is required, I override the CreateOrderAsync method(s) found in the partial Order class. In the example below, I chose to call base.CreateOrderAsync() as well, but there will likely be cases where base.CreateOrderAsync() does not get called.

namespace AdventureWorks.Business.Repositories
{
    internal class GAC_Order : Business.Order
    {
        public async override Task<Model.Order> CreateOrderAsync(Model.Order order)
        {
            // Custom code to override or add to base funcionality.
            // Can be run before or after base code
            // Add 5 days to required time field
            order.RequiredDate = DateTime.Now.AddDays(5);

            // Run base create order functionality
            await base.CreateOrderAsync(order);

            // Run custom functionality
            return order;
        }

        public async override Task<IEnumerable<Model.Order>> CreateOrderAsync(IEnumerable<Model.Order> orders)
        {
            // Run base create order functionality
            await base.CreateOrderAsync(orders);

            // Run custom functionality
            return orders;
        }
    }
}

Finally, I created a repository factory to determine which implementation of the IOrderRepository would be returned to me:

namespace AdventureWorks.Business
{
    public static class RepositoryFactory
    {
        public static IOrderRepositoy GetRepository(Model.Customer customer, Type repoType)
        {
            if (repoType == typeof(Business.IOrderRepositoy))
            {
                if (customer.OrderRepository == null || String.IsNullOrEmpty(customer.OrderRepository))
                {
                    return new Business.Order();
                }
                else
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    var type = assembly.GetTypes().First(t => t.Name == customer.OrderRepository);

                    return Activator.CreateInstance(type) as IOrderRepositoy;
                }
            }
            else
            {
                // TODO: Used if/else and type passing to prepare for additional custom logic
            }
        }
    }
}

When I need to create an order, I call it like this:

// Create Order object
Model.Order order = new Model.Order();
order.ShipPostalCode = "30189";
order.OrderDate = DateTime.Now;

// NOTE: This would come from DB in real-world
Model.Customer customer = new Model.Customer();
customer.OrderRepository = "GAC_Order";

// Get order repository
Business.IOrderRepositoy orderRepository = Business.RepositoryFactory.GetRepository(customer, typeof(Business.IOrderRepositoy));

// Create order
orderRepository.CreateOrderAsync(order);

Questions

  • Is this a valid way to account allow for a default workflow, but also allow for other workflows on a per-customer basis?
  • Are their other solutions that would provide similar functionality that I should be using instead?
  • Am I correct in assuming that this is a simple repository pattern (i.e., am I using the correct terminology here?)?

I have searched a lot about this topic, and only I get is articles written in 2015 about Project Astoria. But this project has now been dropped and won't work anymore. Any other way to do so?

I have square UIScrollView with UIImageView(not square) inside. I need crop image. CGImage cropping correctly only vertical images.

Example my code:

class SelectImageViewController: UIViewController{
    //ScrollView
    IBOutlet weak var imageScrollView: CustomScrollView!  

    //UIImage content mode - AspectFit
    var cropArea:CGRect{
        get{
            let factor = self.imageScrollView.imageView.image!.size.width/self.imageScrollView.frame.width
            let scale = 1/self.imageScrollView.zoomScale
            let imageFrame = self.imageScrollView.imageView.imageFrame()
            let x = (self.imageScrollView.contentOffset.x + imageFrame.origin.x) * scale * factor
            let y = (self.imageScrollView.contentOffset.y + imageFrame.origin.y) * scale * factor
            let width = self.imageScrollView.frame.size.width * scale * factor
            let height = self.imageScrollView.frame.size.height * scale * factor

            print("x:\(x)   y:\(y)   width:\(width)   height:\(height)")

            return CGRect(x: x, y: y, width: width, height: height)
        }
    }

    //crop image and check size
    func checkCropImage() {

        let croppedCGImage = self.imageScrollView.imageView.image?.cgImage?.cropping(to: cropArea)
        let croppedImage = UIImage(cgImage: croppedCGImage!)
        self.imageScrollView.zoomScale = 1

        print("croppedImage width:\(croppedImage.size.width)  croppeedImage height:\(croppedImage.size.height)")

    }

}

extension UIImageView{
    func imageFrame()->CGRect{
        let imageViewSize = self.frame.size
        guard let imageSize = self.image?.size else{return CGRect.zero}
        let imageRatio = imageSize.width / imageSize.height
        let imageViewRatio = imageViewSize.width / imageViewSize.height

        print("imageRatio: \(imageRatio)   imageViewRatio: \(imageViewRatio)")

        if imageRatio < imageViewRatio {
            let scaleFactor = imageViewSize.height / imageSize.height
            let width = imageSize.width * scaleFactor
            let topLeftX = (imageViewSize.width - width) * 0.5
            return CGRect(x: topLeftX, y: 0, width: width, height: imageViewSize.height)
        }else{
            let scalFactor = imageViewSize.width / imageSize.width
            let height = imageSize.height * scalFactor
            let topLeftY = (imageViewSize.height - height) * 0.5
            return CGRect(x: 0, y: topLeftY, width: imageViewSize.width, height: height)
        }
  }

My logs if I crop vertical image:

 x:188.5   y:424.0   width:320.0   height:320.0 // cropArea 
    croppedImage width:321.0  croppeedImage height:321.0 // checkCropImage

If horizontal image:

x:490.575   y:444.708   width:1276.29   height:1276.29 // <- Height 1276
croppedImage width:1277.0  croppeedImage height:1092.0 // <- Height 1092

I am writing a note taking app. Unfortunately, it has several performance issues. What I need to achieve: several pages inside a UITableView (or any other scrollable container). User can draw with finger or stylus and scroll with two fingers from page to page. On the screenshot you may see a big gap between first two touches. It makes such broken lines. The following touches work well and make no trouble.

Issues

I tried subclassing UITableView and setting some properties but it didn't help. As a CanvasView I originally used Apple's approach. Here are my pieces of code gist.

Any ideas on how to fix it?

I successfuly built on codename one my app and tried it on Android and it works well (good work guys !).

But then I tried on my iPhone 4's :

  • I created the certificate, a team, added my iPhone with UDID
  • Use the certificate wizard (very useful) and overwrite all
  • I can build a dev version, no problems.

But when I scanned the QR code on the codename's one dashboard and tried to install the app, my phone just tell me the installation failed.

I tried to drag'n'drop on iTunes : same error.

I double checked my App id (prefix.package), the UDID, tried to add ios.debug.archs=armv7 ...

I don't know if I forget something, but I already lost a couple of hours :/

Please, help me !

Thanks a lot !

I want to clean up my touchesBegan(..) in SKScene. I wanted to make a case statement instead of my if .. else chain. However, I get errors when implementing, which suggests that I don't know how equality is done under the hood.

Before code:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if self.nodeAtPoint(location) === playLabel {
            buildLevelSelect()
        } else if self.nodeAtPoint(location) === aboutLabel {
            createAboutView()
        } else if self.nodeAtPoint(location) === storeLabel {
            createStore()
        }
    }
}

After code: After clicking around, some label clicks work, but some others raise a Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0) error:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        switch(self.nodeAtPoint(location)){
        case playLabel :
            buildLevelSelect()
        case aboutLabel :
            createAboutView()
        case storeLabel :
            createStore()
        default : break
    }
}

do i need to pass the argument configuration when i am using -showbuildsettings in the xcodebuild command line?

looking at this page :http://www.manpagez.com/man/1/xcodebuild/ i wonder if its also need to pass a configuration, such debug or release to the command line, and will make a diference? or doesnt matter and the only thing i need to specify is the scheme?

wonder if there a diference between the variables that exports depeding on the configuration?

thanks guys.

I've been trying unsuccessfully to parse this json:

[{"op":"replace","path":"/pending_coins","value":20}]

I want the value of 20 so I can do

int quantity = jsonValue; //20 

Here's what I currently have:

    NSArray *patch =[NSJSONSerialization JSONObjectWithData:anEvent.data options:NSJSONReadingMutableContainers error:&e];

    NSDictionary *dict = patch[0];

    NSLog(@"patch: %@", dict);

    NSInteger quantity = (NSInteger)[dict valueForKey:@"value"];
    NSLog(@"quantity: %ld",(long)quantity);

    if (quantity > 0) {
        NSLog(@"You earned %ld coins!",(long)quantity);
    }

I've tried both objectForKey and valueForKey and neither seems to get me what I'm looking for.

If I do [NSString stringWithFormat:@"%@",[patch valueForKey:@"value"]] I get a value of 20 as a String, but intValue and integerValue on that don't seem to net me what I want.

Right now, the logs show this: quantity: -5764607523034234845

Any ideas where I'm going wrong? I can't control the JSON or I'd just nix the outer array around the object.

Hey everyone of been working on this problem for weeks and cant find the answer so bare with me here. Also please do not mark as duplicate because this solution which you probably would lead me here is not the answers im looking for. So I am trying to figure out how to take the SCNCameraCase. Which is the main outter node. That is housing the SCNCameraNode which has the none physically SCNCamera in it. Then make it litearly move its ".position" around an object like the VISUALS in one of the answers here. Now the reason none of these answers in the question I linked work for me is because the all try to change the camera's rotation and the never touch its "camera.postion". I need the Camera Case to litearly circle an object like as if it were in Orbit around that object. With the Pan Gesture

Im coding in Swift 3

So here below my CameraCase's rotational ability is already being used by this piece of code:

 func lookGestureRecognized(_ gesture: UIPanGestureRecognizer) {

    let translation = gesture.translation(in: self)
    let xTranslation = acos(Float(translation.x) / 130) - Float(M_PI_2)
    let yTranslation = acos(Float(translation.y) / 130) - Float(M_PI_2)

    HorizontalAngle = max(-Float.infinity, min(Float.infinity,    HorizontalAngle + xTranslation))
    cameraCase.rotation = SCNVector4(x: 0, y: 1, z: 0, w:  HorizontalAngle + Float(cameraSpawnRotation.y))

    VerticalAngle = max(-Float.infinity, min(Float.infinity, VerticalAngle + yTranslation))
    cameraNode.rotation = SCNVector4(x: 1, y: 0, z: 0, w:  VerticalAngle + Float(cameraSpawnRotation.x))


    gesture.setTranslation(CGPoint.zero, in: self)
}

So basically this code allows the users Camera to move up and down and left and right. as the CameraCase handles the Horizontal movements and the CameraNode which is placed in side the CameraCase handles the Vertical movement. So now what I need is the SCNCameraCase to change it position with the pan gesture as you scroll/pan. Not its rotation because its rotation is already being used by this. I need the SCNCameraCase to move in a circluar motion around an object or SCNVector(x: 0, y: 0, z: 0, w: 0). Visual Example here, And here

My camera is setup i like this:

    let camera = SCNCamera()
    var cameraCase = SCNNode()
    var cameraNode = SCNNode()

    // the rotation in which the camera spawns in at
    var cameraSpawnRotation = SCNVector4(x: 0, y: Float(-M_PI_2), z: 0, w: Float(M_PI_2))

    cameraCase.position = SCNVector3Make(UserPlayer.position.x - 15 , UserPlayer.position.y + 12.0 , UserPlayer.position.z + 3.0)
    cameraCase.rotation = cameraSpawnRotation

    camera.zNear = 1.0 
    camera.zFar = 1000 
    camera.yFov = 100
    camera.xFov = 100
    camera.focalDistance = 1
    camera.focalSize = 1.0
    camera.usesOrthographicProjection = false
    camera.orthographicScale = 0

    cameraNode.camera = camera
    cameraNode.position = SCNVector3(x: 0, y: 0, z: 0)
    scnView.pointOfView = cameraNode

    cameraCase.addChildNode(cameraNode)  
    scnView.scene!.rootNode.addChildNode(cameraCase)

Any help would be greatly appreciated. Also if you have any better solutions that would be good to Thanks.

I'm creating an object that uses an NSFetchedResultsController to group objects in a database entity by propertyA into sections:

let fetchRequest = NSFetchRequest<MyCustomFetchRequestResult>(entityName: MyEntityName)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "propertyA", ascending: true)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                      managedObjectContext: moc,
                                                      sectionNameKeyPath: "propertyA",
                                                      cacheName: nil)

Now, I want fetchedResultsController.sections to return a list of MyCustomSectionInfo objects (objects that implement the NSFetchedResultsSectionInfo protocol).

How can I accomplish this?

For example, if I want fetchedResultsController.fetchedObjects to return a list of MyCustomFetchRequestResult objects, I make MyCustomFetchRequestResult extend the NSFetchRequestResult protocol, and then I declare the NSFetchedResultsController specifying my custom protocol, like this:

var fetchedResultsController: NSFetchedResultsController<MyCustomFetchRequestResult>

And then on instantiation, I make sure the NSFetchRequest that I give to the fetchedResultsController conforms to MyCustomFetchRequestResult (like my code above).

So, now my fetched results controller returns objects that conform to MyCustomFetchRequestResult protocol when I call fetchedResultsController.fetchedObjects. This makes dealing with the types very easy because I don't have to cast like fetchedResultsController.fetchedObjects as? [MyCustomFetchRequestResult] every time I access the fetched objects. I just call .fetchedObjects and this already returns [MyCustomFetchRequestResult] because of how I setup the fetched results controller.

So my question is this: Is there some way to setup the fetched results controller to automatically return my own custom section objects when I call .sections?

I already looked at this SO question and this example from Apple's documentation, but neither answered my question.