问:
Finding the rank of a student GPA in Binary Search Tree
I've read all the posts related to this question, yet I am still having a very hard time understanding how to implement the algorithm.

I have a fully written BST with methods that recursively add, delete etc Student objects(the BST class is written for generics, though). I need to write a method that returns the rank of a student in the binary search tree based off their GPA, yet I do not understand how I should implement this. The Student class has a getGPA() method, so I know ill need to use that somehow.

Should I store the elements into an array then search for the index? If so, what's the best algorithm to accomplish this? Is there a better way to do this?

Here is the important parts of my BST class:

```<code>public int size()
    // Returns the number of elements in this BST.
    {
      return recSize(root);
    }
private int recSize(BSTNode<T> tree)
  // Returns the number of elements in tree.
  {
    if (tree == null)
      return 0;
    else
      return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
  }
private boolean recContains(T element, BSTNode<T> tree)
  // Returns true if tree contains an element e such that
  // e.compareTo(element) == 0; otherwise, returns false.
  {
    if (tree == null)
      return false;       // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recContains(element, tree.getLeft());   // Search left subtree
    else if (element.compareTo(tree.getInfo()) > 0)
      return recContains(element, tree.getRight());  // Search right subtree
    else
      return true;        // element is found
  }

  public boolean contains (T element)
  // Returns true if this BST contains an element e such that
  // e.compareTo(element) == 0; otherwise, returns false.
  {
    return recContains(element, root);
  }
private T recGet(T element, BSTNode<T> tree)
  // Returns an element e from tree such that e.compareTo(element) == 0;
  // if no such element exists, returns null.
  {
    if (tree == null)
      return null;             // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recGet(element, tree.getLeft());          // get from left subtree
    else
    if (element.compareTo(tree.getInfo()) > 0)
      return recGet(element, tree.getRight());         // get from right subtree
    else
      return tree.getInfo();  // element is found
  }

  public T get(T element)
  // Returns an element e from this BST such that e.compareTo(element) == 0;
  // if no such element exists, returns null.
  {
    return recGet(element, root);
  }

  private BSTNode<T> recAdd(T element, BSTNode<T> tree)
  // Adds element to tree; tree retains its BST property.
  {
    if (tree == null)
      // Addition place found
      tree = new BSTNode<T>(element);
    else if (element.compareTo(tree.getInfo()) <= 0)
      tree.setLeft(recAdd(element, tree.getLeft()));    // Add in left subtree
    else
      tree.setRight(recAdd(element, tree.getRight()));   // Add in right subtree
    return tree;
  }

  public void add (T element)
  // Adds element to this BST. The tree retains its BST property.
  {
    root = recAdd(element, root);
  }
private void inOrder(BSTNode<T> tree)
  // Initializes inOrderQueue with tree elements in inOrder order.
  {
    if (tree != null)
    {
      inOrder(tree.getLeft());
      inOrderQueue.enqueue(tree.getInfo());
      inOrder(tree.getRight());
    }
  }
private void preOrder(BSTNode<T> tree)
  // Initializes preOrderQueue with tree elements in preOrder order.
  {
    if (tree != null)
    {
      preOrderQueue.enqueue(tree.getInfo());
      preOrder(tree.getLeft());
      preOrder(tree.getRight());
    }
  }

  private void postOrder(BSTNode<T> tree)
  // Initializes postOrderQueue with tree elements in postOrder order.
  {
    if (tree != null)
    {
      postOrder(tree.getLeft());
      postOrder(tree.getRight());
      postOrderQueue.enqueue(tree.getInfo());
    }
  }

  public int reset(int orderType)
  // Initializes current position for an iteration through this BST
  // in orderType order. Returns current number of nodes in the BST.
  {
    int numNodes = size();

    if (orderType == INORDER)
    {
      inOrderQueue = new LinkedUnbndQueue<T>();
      inOrder(root);
    }
    else
    if (orderType == PREORDER)
    {
      preOrderQueue = new LinkedUnbndQueue<T>();
      preOrder(root);
    }
    if (orderType == POSTORDER)
    {
      postOrderQueue = new LinkedUnbndQueue<T>();
      postOrder(root);
    }
    return numNodes;
  }
</code>```

答:
After several failures, it seems I have found a workable solution. Instead of storing in a generic array with a fixed size, I decided to try an ArrayList instead. I use a recursive method to add each node inorder to the array list:

```<code>//recursive method used to copy BST to array list
    public void recArrayList(BSTNode<T> tree, ArrayList<T> list)
    {
        if (tree == null)
        {
            return;
        }
        recArrayList(tree.getLeft(), list);
        list.add(tree.getInfo());
        recArrayList(tree.getRight(), list);
    }

    //converts BST to arraylist used for finding GPA rank
    public ArrayList<T> toArrayList()
    {
        stuList = new ArrayList<T>();
        recArrayList(root, stuList);
        return stuList;
    }
</code>```

And finally in the class using the BST:

```<code>//returns the rank of student in BST based off GPA
    public int rank(Student stu)
    {
        ArrayList<Student> stuList = stuGPA.toArrayList();
        for (i = 0; i < stuList.size(); i++)
        {
            if (stuList.get(i) == stu)
            {
                return i + 1;
            }
        }
        return 0;
    }
</code>```

I dont like using == to compare references so i'm working on changing that, but for now this seems to be functioning correctly. Ty for the comments, it inspired me to go a different route.

Body:
I've read all the posts related to this question, yet I am still having a very hard time understanding how to implement the algorithm.

I have a fully written BST with methods that recursively add, delete etc Student objects(the BST class is written for generics, though). I need to write a method that returns the rank of a student in the binary search tree based off their GPA, yet I do not understand how I should implement this. The Student class has a getGPA() method, so I know ill need to use that somehow.

Should I store the elements into an array then search for the index? If so, what's the best algorithm to accomplish this? Is there a better way to do this?

Here is the important parts of my BST class:

public int size()
    // Returns the number of elements in this BST.
    {
      return recSize(root);
    }
private int recSize(BSTNode<T> tree)
  // Returns the number of elements in tree.
  {
    if (tree == null)
      return 0;
    else
      return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
  }
private boolean recContains(T element, BSTNode<T> tree)
  // Returns true if tree contains an element e such that
  // e.compareTo(element) == 0; otherwise, returns false.
  {
    if (tree == null)
      return false;       // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recContains(element, tree.getLeft());   // Search left subtree
    else if (element.compareTo(tree.getInfo()) > 0)
      return recContains(element, tree.getRight());  // Search right subtree
    else
      return true;        // element is found
  }

  public boolean contains (T element)
  // Returns true if this BST contains an element e such that
  // e.compareTo(element) == 0; otherwise, returns false.
  {
    return recContains(element, root);
  }
private T recGet(T element, BSTNode<T> tree)
  // Returns an element e from tree such that e.compareTo(element) == 0;
  // if no such element exists, returns null.
  {
    if (tree == null)
      return null;             // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recGet(element, tree.getLeft());          // get from left subtree
    else
    if (element.compareTo(tree.getInfo()) > 0)
      return recGet(element, tree.getRight());         // get from right subtree
    else
      return tree.getInfo();  // element is found
  }

  public T get(T element)
  // Returns an element e from this BST such that e.compareTo(element) == 0;
  // if no such element exists, returns null.
  {
    return recGet(element, root);
  }

  private BSTNode<T> recAdd(T element, BSTNode<T> tree)
  // Adds element to tree; tree retains its BST property.
  {
    if (tree == null)
      // Addition place found
      tree = new BSTNode<T>(element);
    else if (element.compareTo(tree.getInfo()) <= 0)
      tree.setLeft(recAdd(element, tree.getLeft()));    // Add in left subtree
    else
      tree.setRight(recAdd(element, tree.getRight()));   // Add in right subtree
    return tree;
  }

  public void add (T element)
  // Adds element to this BST. The tree retains its BST property.
  {
    root = recAdd(element, root);
  }
private void inOrder(BSTNode<T> tree)
  // Initializes inOrderQueue with tree elements in inOrder order.
  {
    if (tree != null)
    {
      inOrder(tree.getLeft());
      inOrderQueue.enqueue(tree.getInfo());
      inOrder(tree.getRight());
    }
  }
private void preOrder(BSTNode<T> tree)
  // Initializes preOrderQueue with tree elements in preOrder order.
  {
    if (tree != null)
    {
      preOrderQueue.enqueue(tree.getInfo());
      preOrder(tree.getLeft());
      preOrder(tree.getRight());
    }
  }

  private void postOrder(BSTNode<T> tree)
  // Initializes postOrderQueue with tree elements in postOrder order.
  {
    if (tree != null)
    {
      postOrder(tree.getLeft());
      postOrder(tree.getRight());
      postOrderQueue.enqueue(tree.getInfo());
    }
  }

  public int reset(int orderType)
  // Initializes current position for an iteration through this BST
  // in orderType order. Returns current number of nodes in the BST.
  {
    int numNodes = size();

    if (orderType == INORDER)
    {
      inOrderQueue = new LinkedUnbndQueue<T>();
      inOrder(root);
    }
    else
    if (orderType == PREORDER)
    {
      preOrderQueue = new LinkedUnbndQueue<T>();
      preOrder(root);
    }
    if (orderType == POSTORDER)
    {
      postOrderQueue = new LinkedUnbndQueue<T>();
      postOrder(root);
    }
    return numNodes;
  }

Body:
After several failures, it seems I have found a workable solution. Instead of storing in a generic array with a fixed size, I decided to try an ArrayList instead. I use a recursive method to add each node inorder to the array list:

//recursive method used to copy BST to array list
    public void recArrayList(BSTNode<T> tree, ArrayList<T> list)
    {
        if (tree == null)
        {
            return;
        }
        recArrayList(tree.getLeft(), list);
        list.add(tree.getInfo());
        recArrayList(tree.getRight(), list);
    }

    //converts BST to arraylist used for finding GPA rank
    public ArrayList<T> toArrayList()
    {
        stuList = new ArrayList<T>();
        recArrayList(root, stuList);
        return stuList;
    }

And finally in the class using the BST:

//returns the rank of student in BST based off GPA
    public int rank(Student stu)
    {
        ArrayList<Student> stuList = stuGPA.toArrayList();
        for (i = 0; i < stuList.size(); i++)
        {
            if (stuList.get(i) == stu)
            {
                return i + 1;
            }
        }
        return 0;
    }

I dont like using == to compare references so i'm working on changing that, but for now this seems to be functioning correctly. Ty for the comments, it inspired me to go a different route.


来源: stackexchange

问:
List<BusinessObject> or BusinessObjectCollection?
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable

IE:

```<code>public class CollectionBase : IEnumerable
</code>```

and then would derive their Business Object collections from that.

```<code>public class BusinessObjectCollection : CollectionBase
</code>```

Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:

```<code>public class BusinessObjectCollection : List<BusinessObject>
</code>```

I do this because I like to have strongly typed names instead of just passing Lists around.

What is your approach?

答:
this is the way:

return arrays, accept IEnumerable<T>

=)

OwnerDisplayName: Jonathan Holland

ContentLicense: CC BY-SA 2.5

Body:
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable

IE:

public class CollectionBase : IEnumerable

and then would derive their Business Object collections from that.

public class BusinessObjectCollection : CollectionBase

Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:

public class BusinessObjectCollection : List<BusinessObject>

I do this because I like to have strongly typed names instead of just passing Lists around.

What is your approach?

LastEditorDisplayName: Mark Biek

OwnerDisplayName: Matt Hinze


问:
How can I take more control in ASP.NET?
I'm trying to build a very, very simple "micro-webapp" which I suspect will be of interest to a few Stack Overflow'rs if I ever get it done. I'm hosting it on my C# in Depth site, which is vanilla ASP.NET 3.5 (i.e. not MVC).

The flow is very simple:

If a user enters the app with a URL which doesn't specify all the parameters (or if any of them are invalid) I want to just display the user input controls. (There are only two.)

If a user enters the app with a URL which does have all the required parameters, I want to display the results and the input controls (so they can change the parameters)

Here are my self-imposed requirements (mixture of design and implementation):

I want the submission to use GET rather than POST, mostly so users can bookmark the page easily.

I don't want the URL to end up looking silly after submission, with extraneous bits and pieces on it. Just the main URL and the real parameters please.

Ideally I'd like to avoid requiring JavaScript at all. There's no good reason for it in this app.

I want to be able to access the controls during render time and set values etc. In particular, I want to be able to set the default values of the controls to the parameter values passed in, if ASP.NET can't do this automatically for me (within the other restrictions).

I'm happy to do all the parameter validation myself, and I don't need much in the way of server side events. It's really simple to set everything on page load instead of attaching events to buttons etc.

Most of this is okay, but I haven't found any way of completely removing the viewstate and keeping the rest of the useful functionality. Using the post from this blog post I've managed to avoid getting any actual value for the viewstate - but it still ends up as a parameter on the URL, which looks really ugly.

If I make it a plain HTML form instead of an ASP.NET form (i.e. take out runat="server") then I don't get any magic viewstate - but then I can't access the controls programmatically.

I could do all of this by ignoring most of ASP.NET and building up an XML document with LINQ to XML, and implementing IHttpHandler. That feels a bit low level though.

I realise that my problems could be solved by either relaxing my constraints (e.g. using POST and not caring about the surplus parameter) or by using ASP.NET MVC, but are my requirements really unreasonable?

Maybe ASP.NET just doesn't scale down to this sort of app? There's a very likely alternative though: I'm just being stupid, and there's a perfectly simple way of doing it that I just haven't found.

Any thoughts, anyone? (Cue comments of how the mighty are fallen, etc. That's fine - I hope I've never claimed to be an ASP.NET expert, as the truth is quite the opposite...)

答:
You're definitely (IMHO) on the right track by not using runat="server" in your FORM tag. This just means you'll need to extract values from the Request.QueryString directly, though, as in this example:

In the .aspx page itself:

```<code><%@ Page Language="C#" AutoEventWireup="true"
     CodeFile="FormPage.aspx.cs" Inherits="FormPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>ASP.NET with GET requests and no viewstate</title>
</head>
<body>
    <asp:Panel ID="ResultsPanel" runat="server">
      <h1>Results:</h1>
      <asp:Literal ID="ResultLiteral" runat="server" />
      <hr />
    </asp:Panel>
    <h1>Parameters</h1>
    <form action="FormPage.aspx" method="get">
    <label for="parameter1TextBox">
      Parameter 1:</label>
    <input type="text" name="param1" id="param1TextBox" value='<asp:Literal id="Param1ValueLiteral" runat="server" />'/>
    <label for="parameter1TextBox">
      Parameter 2:</label>
    <input type="text" name="param2" id="param2TextBox"  value='<asp:Literal id="Param2ValueLiteral" runat="server" />'/>
    <input type="submit" name="verb" value="Submit" />
    </form>
</body>
</html>
</code>```

and in the code-behind:

```<code>using System;

public partial class FormPage : System.Web.UI.Page {

        private string param1;
        private string param2;

        protected void Page_Load(object sender, EventArgs e) {

            param1 = Request.QueryString["param1"];
            param2 = Request.QueryString["param2"];

            string result = GetResult(param1, param2);
            ResultsPanel.Visible = (!String.IsNullOrEmpty(result));

            Param1ValueLiteral.Text = Server.HtmlEncode(param1);
            Param2ValueLiteral.Text = Server.HtmlEncode(param2);
            ResultLiteral.Text = Server.HtmlEncode(result);
        }

        // Do something with parameters and return some result.
        private string GetResult(string param1, string param2) {
            if (String.IsNullOrEmpty(param1) && String.IsNullOrEmpty(param2)) return(String.Empty);
            return (String.Format("You supplied {0} and {1}", param1, param2));
        }
    }
</code>```

The trick here is that we're using ASP.NET Literals inside the value="" attributes of the text inputs, so the text-boxes themselves don't have to runat="server". The results are then wrapped inside an ASP:Panel, and the Visible property set on page load depending whether you want to display any results or not.

OwnerDisplayName: Jon Skeet

Title: How can I take more control in ASP.NET?

LastEditorDisplayName: Jon Skeet

Body:
You're definitely (IMHO) on the right track by not using runat="server" in your FORM tag. This just means you'll need to extract values from the Request.QueryString directly, though, as in this example:

In the .aspx page itself:

<%@ Page Language="C#" AutoEventWireup="true"
     CodeFile="FormPage.aspx.cs" Inherits="FormPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>ASP.NET with GET requests and no viewstate</title>
</head>
<body>
    <asp:Panel ID="ResultsPanel" runat="server">
      <h1>Results:</h1>
      <asp:Literal ID="ResultLiteral" runat="server" />
      <hr />
    </asp:Panel>
    <h1>Parameters</h1>
    <form action="FormPage.aspx" method="get">
    <label for="parameter1TextBox">
      Parameter 1:</label>
    <input type="text" name="param1" id="param1TextBox" value='<asp:Literal id="Param1ValueLiteral" runat="server" />'/>
    <label for="parameter1TextBox">
      Parameter 2:</label>
    <input type="text" name="param2" id="param2TextBox"  value='<asp:Literal id="Param2ValueLiteral" runat="server" />'/>
    <input type="submit" name="verb" value="Submit" />
    </form>
</body>
</html>

and in the code-behind:

using System;

public partial class FormPage : System.Web.UI.Page {

        private string param1;
        private string param2;

        protected void Page_Load(object sender, EventArgs e) {

            param1 = Request.QueryString["param1"];
            param2 = Request.QueryString["param2"];

            string result = GetResult(param1, param2);
            ResultsPanel.Visible = (!String.IsNullOrEmpty(result));

            Param1ValueLiteral.Text = Server.HtmlEncode(param1);
            Param2ValueLiteral.Text = Server.HtmlEncode(param2);
            ResultLiteral.Text = Server.HtmlEncode(result);
        }

        // Do something with parameters and return some result.
        private string GetResult(string param1, string param2) {
            if (String.IsNullOrEmpty(param1) && String.IsNullOrEmpty(param2)) return(String.Empty);
            return (String.Format("You supplied {0} and {1}", param1, param2));
        }
    }

The trick here is that we're using ASP.NET Literals inside the value="" attributes of the text inputs, so the text-boxes themselves don't have to runat="server". The results are then wrapped inside an ASP:Panel, and the Visible property set on page load depending whether you want to display any results or not.

OwnerDisplayName: Dylan Beattie


问:
Changing Static IP in Azure VM (Ubuntu OS)
Is it possible to change the static IP provisioned with a classic VM (Ubuntu OS)? If so, could you please provide the steps of how to do so?

I recently deployed CloudFlare with my infrastructure, primarily for DDOS prevention. One of the requirements is changing the server IP so that malicious vectors who know the server IP can't just bypass CloudFlare and DDOS my infrastructure. I'm using a static IP; how do I change that? Thanks in advance.

答:
IP addresses in Azure fall into two categories: dynamic and reserved. Public IP addresses managed by Azure are dynamic by default.

Is it possible to change the static IP provisioned with a classic VM
  (Ubuntu OS)?

Yes, we can use PowerShell to set/remove/add reserved VIP for Azure classic VM.

Reserved IP address  can be used only as a VIP, ensuring that the IP address for the cloud service remains the same, even as resources are shut down or stopped (deallocated).

New-AzureReservedIP –ReservedIPName MyReservedIP –Location "Central US"
Get-AzureReservedIP
set-AzureReservedIPAssociation -ReservedIPName MyReservedIP -ServiceName TestService

More information about reserved IP address, please refer to this link.

ContentLicense: CC BY-SA 3.0


问:
How to add a new audio (not mixing) into a video using ffmpeg?
I used a command like:

```<code>ffmpeg -i video.avi -i audio.mp3 -vcodec codec -acodec codec output_video.avi -newaudio
</code>```

in latest version for adding new audio track to video (not mix).

But I updated the ffmpeg to the newest version (ffmpeg version git-2012-06-16-809d71d) and now in this version the parameter -newaudio doesn't work.

Tell me please how I can add new audio to my video (not mix) using ffmpeg.

答:
Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length.
If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

```<code>private void execFFmpegBinaryShortest(final String[] command) {

            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");

            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};

            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {

                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");

                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }

        }
</code>```

Body:
I used a command like:

ffmpeg -i video.avi -i audio.mp3 -vcodec codec -acodec codec output_video.avi -newaudio

in latest version for adding new audio track to video (not mix).

But I updated the ffmpeg to the newest version (ffmpeg version git-2012-06-16-809d71d) and now in this version the parameter -newaudio doesn't work.

Tell me please how I can add new audio to my video (not mix) using ffmpeg.

Body:
Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length.
If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {

            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");

            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};

            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {

                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");

                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }

        }


问:
How may i Switch my Rails App from Mysql to Sql Server in rails 4 in Windows
How may i change my database from MYSQL to Sql server in Rails 4

 What configuration i may specify in database.yml file and what all gem i may need to add for that.Please help. :)```

答:
Add this to gemfile

```<code>gem install mysql2
</code>```

And this to database.yml

```<code>default: &default
  adapter: mysql2
  encoding: utf8
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: development_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD

test:
  <<: *default
  database: test_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD

production:
  <<: *default
  database: production_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD
</code>```

Body:
Add this to gemfile

gem install mysql2

And this to database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: development_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD

test:
  <<: *default
  database: test_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD

production:
  <<: *default
  database: production_db_name
  username: YOUR_USER_NAME
  password: YOUR_PASSWORD


问:
Github Enterprise: remote: Repository not found from cmdline, works with Github desktop
github enterprise, windows 10. email+token only works with github desktop tool. Fails in powershell, git bash, and cmd consoles.

Error - remote: Repository not found. fatal: Authentication failed for https://(enterprise hostname)/(org name)/(repo name).git

ran test scenario: created new repo on github site, path used was from clone link. used sample code to generate readme.md, git add . (success); git commit -m "notes" (success); git push -u origin master (failed)

```<code>git config --system contains "config.helper=manager" (GCM)
</code>```

The GCM popup prompts for credentials (enter email; token), connection fails, also github is not added to windows credential manager.

The GCM prompts for credentials (cancel), command line prompts for username (email) and password (token), connection fails

cmd runas admin

```<code>git config --system --unset config.helper (no effect)
git config --system config.helper=wincred (no effect)
git config --system config.helper=cache (no effect)
git config --system --list (still shows "config.helper=manager")
</code>```

tried removing origin and resetting, no effect

git exists in several locations on my machine:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git

C:\Program Files\Git

C:\Users{username}\AppData\Local\GitHub\PortableGit_f02737a78695063deace08e96d5042710d3e32db

Github desktop --> options: Able to add github enterprise login successfully:
Email or usename; token; https://(enterprise hostname)
able to "sync" successfully

I am the creator and owner of both the organization and the Repo.
All of this was working from windows 7, I just did a new install of windows 10 and generated a new token, trying to pull down my repos and get them into a usable state.

did a lot of research,  tried several things, not sure what else to try, really need commandline interface to work. Any suggestions, greatly appreciated.

答:
I ran through the following steps(below) and was able to isolate the issue to either the GCM or the way I was attempting to use it. Specifying the older tool "wincred" resolved my issue.

[Installer: Microsoft Git Credential Manager for Windows setup v 1.9.0]

Removed GCM install

Removed Git Windows Install

Remove local git directories

Removed GitHub Desktop

generated new token

installed GIT windows with GCM
ran a cloning test
    - GCM popup, entered email + token
    - auth failed
removed git for windows
re-installed without GCM
ran a cloning test (git bash)
    - cmd line prompts for use/pwd
clone suceeded
removed local repo

installed Github desktop
authenticated with email+token
cloned from remote repository into local
success
closed GitHUb Desktop, removed local repo

ran git bash
cloned remote repo
- cmd line prompts for use/pwd
clone suceeded
closed Git bash, removed local repo

installed standalone GCM
 git config --global credential.helper manager
ran git bash
cloned remote repo
(Failed)
remote: Repository not found.
fatal: Authentication failed for (clone url)

uninstalled GCM
git config --global --unset credential.helper
removed local repo

ran git bash
git config --global credential.helper wincred
cloned remote repo
- cmd line prompts for use/pwd
clone suceeded
updated readme.md
git add, git commit, git push -u origin master
(success)
noted git added to windows credentials / generic credentials in Credential manager. Address stored as git:https://(username)@github...

Since git entry is now in Credential Manager, lets give GCM another try

installed standalone GCM
git config --global credential.helper manager

made a change to readme.md
git add, git commit, git push
(failed)
remote: Repository not found.
fatal: Authentication failed for (clone url)

uninstalled GCM
git config --global --unset credential.helper

reset to wincred

git config --global credential.helper wincred
git add, git commit, git push
(success)

Looks like the problem for me was microsoft's GCM or the way I was trying to use it.

Body:
github enterprise, windows 10. email+token only works with github desktop tool. Fails in powershell, git bash, and cmd consoles.

Error - remote: Repository not found. fatal: Authentication failed for https://(enterprise hostname)/(org name)/(repo name).git

ran test scenario: created new repo on github site, path used was from clone link. used sample code to generate readme.md, git add . (success); git commit -m "notes" (success); git push -u origin master (failed)

git config --system contains "config.helper=manager" (GCM)

The GCM popup prompts for credentials (enter email; token), connection fails, also github is not added to windows credential manager.

The GCM prompts for credentials (cancel), command line prompts for username (email) and password (token), connection fails

cmd runas admin

git config --system --unset config.helper (no effect)
git config --system config.helper=wincred (no effect)
git config --system config.helper=cache (no effect)
git config --system --list (still shows "config.helper=manager")

tried removing origin and resetting, no effect

git exists in several locations on my machine:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git

C:\Program Files\Git

C:\Users{username}\AppData\Local\GitHub\PortableGit_f02737a78695063deace08e96d5042710d3e32db

Github desktop --> options: Able to add github enterprise login successfully:
Email or usename; token; https://(enterprise hostname)
able to "sync" successfully

I am the creator and owner of both the organization and the Repo.
All of this was working from windows 7, I just did a new install of windows 10 and generated a new token, trying to pull down my repos and get them into a usable state.

did a lot of research,  tried several things, not sure what else to try, really need commandline interface to work. Any suggestions, greatly appreciated.


问:
Laravel Migration pivote table give error of make

php artisan make:migration:pivote products category

There are no commands defined in the "make:migration" namespace.

Did you mean this?

make

please solve this error ? thanks in advance
laravel version 5.4

答:
Looks like you have a typo pivote instead of pivot

```<code>php artisan make:migration:pivot products category
</code>```

Body:
Looks like you have a typo pivote instead of pivot

php artisan make:migration:pivot products category


问:
How to add scss file globally which should be applied to all the components in angular2 webpack?
I can apply scss to components using syntax

```<code>styleUrls: ['./app.component.scss', '../assets/css/styles.scss']
</code>```

But this style is only visible to particular component.

I want to use '../assets/css/styles.scss' across all the components.

Though using css file globally is easy but scss file is not seem to be working that way.

To configure my webpack for sass, added following line -

```<code>{
     test: /\.scss$/,
     exclude: /node_modules/,
     loaders: ['raw-loader', 'sass-loader']
}
</code>```

答:
In your main app component where all your other modules will appear via router outlet or so, include your global scss there .For eg.
@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.styles.scss' ]
})</p>

Body:
I can apply scss to components using syntax

styleUrls: ['./app.component.scss', '../assets/css/styles.scss']

But this style is only visible to particular component.

I want to use '../assets/css/styles.scss' across all the components.

Though using css file globally is easy but scss file is not seem to be working that way.

To configure my webpack for sass, added following line -

{
     test: /\.scss$/,
     exclude: /node_modules/,
     loaders: ['raw-loader', 'sass-loader']
}


问:
Filtering in Scala
So suppose I have the following data (only the first few rows, this data covers an entire year) -

```<code>(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)
</code>```

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

```<code>error: value xxxx is not a member of (org.joda.time.DateTime, String)
</code>```

Is there another way of doing this?

答:
```<code>val dateTimeStringZero = "2014-08-12T00:05:00.000+01:00"
val dateTimeOne:DateTime = org.joda.time.format.ISODateTimeFormat.dateTime.withZoneUTC.parseDateTime(dateTimeStringZero)

import java.text.SimpleDateFormat
val df = new DateTime(new SimpleDateFormat("yyyy-MM-dd").parse("2014-08-12"))

println(dateTimeOne.getYear==df.getYear)
println(dateTimeOne.getMonthOfYear==df.getYear)
</code>```

<p>...</p>

Title: Filtering in Scala

Body:
So suppose I have the following data (only the first few rows, this data covers an entire year) -

(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

error: value xxxx is not a member of (org.joda.time.DateTime, String)

Is there another way of doing this?

Body:
val dateTimeStringZero = "2014-08-12T00:05:00.000+01:00"
val dateTimeOne:DateTime = org.joda.time.format.ISODateTimeFormat.dateTime.withZoneUTC.parseDateTime(dateTimeStringZero)

import java.text.SimpleDateFormat
val df = new DateTime(new SimpleDateFormat("yyyy-MM-dd").parse("2014-08-12"))

println(dateTimeOne.getYear==df.getYear)
println(dateTimeOne.getMonthOfYear==df.getYear)

...


问:
__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

```<code>[self performSelectorInBackground:@selector(startupStuff) withObject:sender];
</code>```

With statupStuff I have this

```<code>General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];
</code>```

The Errors happen shortly after code in the refreshDBData method.

答:
Autorelease pools are tied to threads. If you create a thread through performSelectorInBackground then you need to create and destroy an autorelease pool for yourself. So you need startupStuff to look like this:

```<code>- (void)startupStuff:(id)sender
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // ... everything else you were doing ...

    [pool drain]; //see comment below
}
</code>```

Addition: Richard below makes the point that drain is preferable to release to acknowledge that (on the desktop, not yet on iOS) you may be running with a garbage collector. Apple's specific words are (source):

In a garbage-collected environment, sending a drain message to a pool triggers garbage collection if necessary; release, however, is a no-op. In a reference-counted environment, drain has the same effect as release. Typically, therefore, you should use drain instead of release.

So I've corrected my example. Suffice to say, this specific question is to do with the iPhone and currently there is no garbage collection on that device. So the originating poster is in the "drain has the same effect as release" camp, not the "drain ... triggers garbage collection if necessary; release, however, is a no-op" camp.

Body:
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

[self performSelectorInBackground:@selector(startupStuff) withObject:sender];

With statupStuff I have this

General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];

The Errors happen shortly after code in the refreshDBData method.

Body:
Autorelease pools are tied to threads. If you create a thread through performSelectorInBackground then you need to create and destroy an autorelease pool for yourself. So you need startupStuff to look like this:

- (void)startupStuff:(id)sender
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // ... everything else you were doing ...

    [pool drain]; //see comment below
}

Addition: Richard below makes the point that drain is preferable to release to acknowledge that (on the desktop, not yet on iOS) you may be running with a garbage collector. Apple's specific words are (source):

In a garbage-collected environment, sending a drain message to a pool triggers garbage collection if necessary; release, however, is a no-op. In a reference-counted environment, drain has the same effect as release. Typically, therefore, you should use drain instead of release.

So I've corrected my example. Suffice to say, this specific question is to do with the iPhone and currently there is no garbage collection on that device. So the originating poster is in the "drain has the same effect as release" camp, not the "drain ... triggers garbage collection if necessary; release, however, is a no-op" camp.


问:
Convert a dictionary of lists into a list of dictionaries
I have the following Dictionary Object:

```<code>Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}
</code>```

Which will then result in this specific output:

```<code>output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]
</code>```

I'm not sure how I would approach this problem and any help would be appreciated.

答:
In many NoSQL engines data is generally stored in a nested way, for your case it would be:

```<code>{'ID_1':
    {
    'username':'psrr_api@auto-grid.com',
    'password': 'Everseeource2016'
    },
'ID_2':{
    'username':'ps_api1@auto-grid.com',
    'password': 'Eversource2016!'
    }
}
</code>```

This provides an efficient way to access the data through the ID's

More Examples

Here's the code for converting the format:
This code is generic - means you don't have to specify the keys, in this case: username and password,

```<code>from collections import defaultdict
data = defaultdict(dict)
for idx in range(len(Input.values()[0])):
    for key in Input.keys():
        data['ID_'+str(idx)].update({key: Input[key][idx]})
print data
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following Dictionary Object:

Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

Which will then result in this specific output:

output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]

I'm not sure how I would approach this problem and any help would be appreciated.

Body:
In many NoSQL engines data is generally stored in a nested way, for your case it would be:

{'ID_1':
    {
    'username':'psrr_api@auto-grid.com',
    'password': 'Everseeource2016'
    },
'ID_2':{
    'username':'ps_api1@auto-grid.com',
    'password': 'Eversource2016!'
    }
}

This provides an efficient way to access the data through the ID's

More Examples

Here's the code for converting the format:
This code is generic - means you don't have to specify the keys, in this case: username and password,

from collections import defaultdict
data = defaultdict(dict)
for idx in range(len(Input.values()[0])):
    for key in Input.keys():
        data['ID_'+str(idx)].update({key: Input[key][idx]})
print data


问:
Gitlab CI runner unabled to shared build sources on docker executor
I try to share the build sources on docker (and use a git fetch on it), but he always run a git clone on each run (and yes, I have configured it to use git fetch on CI/CD Pipelines settings).

I just want to run a build stage with a composer update script, and a test stage with phing (phpunit, ...). On the build stage everything works (excepted the git clone), and on the test stage, he doesn't use the same source that previously and clone the source again...

I know that I need to shared my volume with the docker container, but I don't know how to make it with gitlab CI !?

My conf: .gitlab-ci.yml

```<code>image: webdevops/php:centos-7-php7

stages:
  - build
  - test

build:
  script:
    - composer --working-dir=/builds/MyGroup/MyProject update

test:
  script:
    - php /builds/MyGroup/MyProject/vendor/bin/phing
</code>```

EDIT: after a day of search, I finally found this documentation : https://docs.gitlab.com/runner/executors/docker.html#the-persistent-storage
now it works fine.

Thanks all,

答:
In addition to the solution you found, I use Artifacts for this scenario (using shared runners in Gitlab.com). Build the src, push it to Gitlab and download the file on next build steps.

```<code>build:
  environment: production
  stage: build
  image: image_used_for_builds
  script:
    - # steps to build
  artifacts:
     name: "myapplication-${CI_BUILD_REF_NAME}-${CI_BUILD_ID}-production"
     paths:
      - vendor/src
      - run.whatever
     when: on_success

# this step will download the preivous created files to deploy them
  deploy:
   stage: deploy
   environment: production
   script:
     - run-deploy.sh
   dependencies:
     - build # this will download the artifacts
</code>```

Maybe someone finds this useful as example!

Body:
I try to share the build sources on docker (and use a git fetch on it), but he always run a git clone on each run (and yes, I have configured it to use git fetch on CI/CD Pipelines settings).

I just want to run a build stage with a composer update script, and a test stage with phing (phpunit, ...). On the build stage everything works (excepted the git clone), and on the test stage, he doesn't use the same source that previously and clone the source again...

I know that I need to shared my volume with the docker container, but I don't know how to make it with gitlab CI !?

My conf: .gitlab-ci.yml

image: webdevops/php:centos-7-php7

stages:
  - build
  - test

build:
  script:
    - composer --working-dir=/builds/MyGroup/MyProject update

test:
  script:
    - php /builds/MyGroup/MyProject/vendor/bin/phing

EDIT: after a day of search, I finally found this documentation : https://docs.gitlab.com/runner/executors/docker.html#the-persistent-storage
now it works fine.

Thanks all,

Body:
In addition to the solution you found, I use Artifacts for this scenario (using shared runners in Gitlab.com). Build the src, push it to Gitlab and download the file on next build steps.

build:
  environment: production
  stage: build
  image: image_used_for_builds
  script:
    - # steps to build
  artifacts:
     name: "myapplication-${CI_BUILD_REF_NAME}-${CI_BUILD_ID}-production"
     paths:
      - vendor/src
      - run.whatever
     when: on_success

# this step will download the preivous created files to deploy them
  deploy:
   stage: deploy
   environment: production
   script:
     - run-deploy.sh
   dependencies:
     - build # this will download the artifacts

Maybe someone finds this useful as example!


问:
Add price to price final in Prestashop
I override a big part of the front of the products with JS. I would like to be able to update my price from the "Add to cart" button. Currently the price of my product in backoffice is at 1 € and I add in JS amounts in addition. See the attached screenshot:

Except that when I click on "Add to cart" the price is at 1 €.

I award my price to the price of the product like this:

```<code>function updatePrice(tabOptions) {
// Update prices options
var format = price_format_page[tabOptions['is_format_page']];
var color = price_color_page[tabOptions['is_color_page']];
var impression = price_impression_page[tabOptions['is_impression_page']];
var paper = price_paper_page[tabOptions['is_paper_page']];
var reliure = price_reliure_page[tabOptions['is_reliure_page']];
var color_reliure = price_color_reliure_page[tabOptions['is_color_reliure_page']];
var finition = price_finition_page[tabOptions['is_finition_page']];

if (tabOptions['is_color_page'] === 'Couleur') {
    var page = price_per_page * tabOptions['page_value'];
} else {
    var page = price_per_page_nb * tabOptions['page_value'];
}

var total_options = format + color + impression + paper + reliure + color_reliure + finition + page + productPriceTaxExcluded;

/*// Get combination prices
 var combID = $('#idCombination').val();
 var combination = combinationsFromController[combID];
 if (typeof combination == 'undefined')
 return;*/

// Set product (not the combination) base price
var basePriceWithoutTax = total_options;
var basePriceWithTax = +productPriceTaxIncluded;
var priceWithGroupReductionWithoutTax = 0;
</code>```

答:
The price of a product throughout the PrestaShop is calculated by the getPriceStatic() function defined in Product.php class which calls the getSpecificPrice() function of SpecificPrice.php class

In case you want to change the price of a product on run-time, then it will be better to override the getSpecificPrice() function of SpecificPrice.php class

Title: Add price to price final in Prestashop

Body:
I override a big part of the front of the products with JS. I would like to be able to update my price from the "Add to cart" button. Currently the price of my product in backoffice is at 1 € and I add in JS amounts in addition. See the attached screenshot:

Except that when I click on "Add to cart" the price is at 1 €.

I award my price to the price of the product like this:

function updatePrice(tabOptions) {
// Update prices options
var format = price_format_page[tabOptions['is_format_page']];
var color = price_color_page[tabOptions['is_color_page']];
var impression = price_impression_page[tabOptions['is_impression_page']];
var paper = price_paper_page[tabOptions['is_paper_page']];
var reliure = price_reliure_page[tabOptions['is_reliure_page']];
var color_reliure = price_color_reliure_page[tabOptions['is_color_reliure_page']];
var finition = price_finition_page[tabOptions['is_finition_page']];

if (tabOptions['is_color_page'] === 'Couleur') {
    var page = price_per_page * tabOptions['page_value'];
} else {
    var page = price_per_page_nb * tabOptions['page_value'];
}

var total_options = format + color + impression + paper + reliure + color_reliure + finition + page + productPriceTaxExcluded;

/*// Get combination prices
 var combID = $('#idCombination').val();
 var combination = combinationsFromController[combID];
 if (typeof combination == 'undefined')
 return;*/

// Set product (not the combination) base price
var basePriceWithoutTax = total_options;
var basePriceWithTax = +productPriceTaxIncluded;
var priceWithGroupReductionWithoutTax = 0;


Title: Extracting rows between 2 dates using SQL

Body:
id    date       temp       prcp
1   2015-01-01  -27.18      0
1   2015-01-02  -25.9       1.03
1   2015-01-03  -17.89      9.44
1   2015-01-04  -17.89      9.44
1   2015-01-05  -17.89      9.44

SELECT * FROM tbl WHERE id=1 and date between '2015-01-03' and '2015-01-05'

How do I fix the SQL query above? I am trying to extract all rows between the 2 dates '2015-01-03' and '2015-01-05'

Body: Did you mean date >= '2015-01-03' and date <= '2015-01-05'?


问:
Unit Testing Visual Studio Online Selenium ChromeDriver Exception
I use Selenium ChromeDriver in a Unit Test project to test some action on a web page ...

var chromeDriver = new ChromeDriver();
 chromeDriver.Navigate().GoToUrl("https://www.google.com");

Chrome driver has been installed from nuget

Install-Package Selenium.WebDriver.ChromeDriver -Version 2.28.0.

When build my project in Visual Studio Online I receive some error:

System.InvalidOperationException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.28.455520

Any solution to solve this?

答: ChromeDriver cannot find the Chrome binary files just as the error message indicates. Please check and make sure that Chrome Browser is installed on the build agent or test machine which run the test.</p>


问:
Ruby loops style/convention
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

```<code>for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}
</code>```

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

Title: Ruby loops style/convention

Body:
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

Body:
You can do this

(0..10).each do |j|
  i = 10 - j
  ...
end

# 0, 10 -> 10, 0


问:
How can I Add images dynamically through Camera or Gallery?
I am making an Android Application where i am allowing user to click the picture through camera or add the Images through Gallery.

Only 5 images are allowed to be added in the image view . How i can add image view dynamically in the activity at the run time.

how to delete and re position the images present in the activity.

As there are 5 images so when i am deleting the 2nd image then the 3rd , 4th and 5th images should be re position to 2nd , 3rd and 4th position and it should allow me to add 5th image.

Can Anyone help me with the Source code .

This is my Code :

```<code>private static final int CAMERA_REQUEST_FIRST_IMAGE = 100;
    private static final int CAMERA_REQUEST_SECOND_IMAGE = 101;
    private static final int CAMERA_REQUEST_THIRD_IMAGE = 102;
    private static final int CAMERA_REQUEST_FOURTH_IMAGE = 103;
    private static final int CAMERA_REQUEST_FIFTH_IMAGE = 104;
    private static final int PICK_PICTURE_FIRST_IMAGE = 105;
    private static final int PICK_PICTURE_SECOND_IMAGE = 106;
    private static final int PICK_PICTURE_THIRD_IMAGE = 107;
    private static final int PICK_PICTURE_FOURTH_IMAGE = 108;
    private static final int PICK_PICTURE_FIFTH_IMAGE = 109;
    Boolean imageclick_1 = false, imageclick_2 = false, imageclick_3 = false, imageclick_4 = false, imageclick_5 = false;
    TextView textview_imagename1, textview_imagename2, textview_imagename3, textview_imagename4, textview_imagename5;
ImageView imageView1, imageView2, imageView3, imageView4, imageView5;
imageView1 = (ImageView) findViewById(R.id.imageview1);
        imageView1.setOnClickListener(this);
 imageView2 = (ImageView) findViewById(R.id.imageview2);
        imageView2.setOnClickListener(this);
 imageView3 = (ImageView) findViewById(R.id.imageview3);
        imageView3.setOnClickListener(this);
 imageView4 = (ImageView) findViewById(R.id.imageview4);
        imageView4.setOnClickListener(this);
 imageView5 = (ImageView) findViewById(R.id.imageview5);
        imageView5.setOnClickListener(this);

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_PICTURE_FIRST_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage1 = data.getData();
                    String s1 = getRealPathFromURI(selectedImage1);
                    try {
                        images1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView1.setImageURI(selectedImage1);
                    String name1 = s1.substring(s1.lastIndexOf("/") + 1);
                    textview_imagename1.setText(name1);
                    imageView2.setVisibility(View.VISIBLE);
                    imageclick_1 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_SECOND_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage2 = data.getData();
                    String s2 = getRealPathFromURI(selectedImage2);
                    try {
                        images2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView2.setImageURI(selectedImage2);
                    String name2 = s2.substring(s2.lastIndexOf("/") + 1);
                    textview_imagename2.setText(name2);
                    imageView3.setVisibility(View.VISIBLE);
                    imageclick_2 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_THIRD_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage3 = data.getData();
                    String s3 = getRealPathFromURI(selectedImage3);
                    try {
                        images3 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage3);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView3.setImageURI(selectedImage3);
                    String name3 = s3.substring(s3.lastIndexOf("/") + 1);
                    textview_imagename3.setText(name3);
                    imageView4.setVisibility(View.VISIBLE);
                    imageclick_3 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_FOURTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage4 = data.getData();
                    String s4 = getRealPathFromURI(selectedImage4);
                    try {
                        images4 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage4);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView4.setImageURI(selectedImage4);
                    String name4 = s4.substring(s4.lastIndexOf("/") + 1);
                    textview_imagename4.setText(name4);
                    imageView5.setVisibility(View.VISIBLE);
                    imageclick_4 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_FIFTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage5 = data.getData();
                    String s5 = getRealPathFromURI(selectedImage5);
                    try {
                        images5 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage5);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView5.setImageURI(selectedImage5);
                    String name5 = s5.substring(s5.lastIndexOf("/") + 1);
                    textview_imagename5.setText(name5);
                    imageclick_5 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FIRST_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo1 = (Bitmap) data.getExtras().get("data");
                    imageView1.setImageBitmap(photo1);
                    SaveImage(photo1);
                    textview_imagename1.setText(fname);
                    imageView2.setVisibility(View.VISIBLE);
                    imageclick_1 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_SECOND_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo2 = (Bitmap) data.getExtras().get("data");
                    imageView2.setImageBitmap(photo2);
                    SaveImage(photo2);
                    textview_imagename2.setText(fname);
                    imageView3.setVisibility(View.VISIBLE);
                    imageclick_2 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_THIRD_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo3 = (Bitmap) data.getExtras().get("data");
                    imageView3.setImageBitmap(photo3);
                    SaveImage(photo3);
                    textview_imagename3.setText(fname);
                    imageView4.setVisibility(View.VISIBLE);
                    imageclick_3 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FOURTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo4 = (Bitmap) data.getExtras().get("data");
                    imageView4.setImageBitmap(photo4);
                    SaveImage(photo4);
                    textview_imagename4.setText(fname);
                    imageView5.setVisibility(View.VISIBLE);
                    imageclick_4 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FIFTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo5 = (Bitmap) data.getExtras().get("data");
                    imageView5.setImageBitmap(photo5);
                    SaveImage(photo5);
                    textview_imagename5.setText(fname);
                    imageclick_5 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

private void SaveImage(Bitmap finalBitmap) {
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        fname = "Image-" + timeStamp + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageview1:
                if (imageclick_1) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView1.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else {
                    final String[] Items = {"Click Pic", "Pick Pic", "Cancel"};
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Add Photo");
                    builder.setItems(Items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (i == 0) {
                                isdialogset = "CAMERA";
                                if (imageView1.getDrawable() == null) {
                                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(takePicture, CAMERA_REQUEST_FIRST_IMAGE);
                                }
                            } else if (i == 1) {
                                isdialogset = "GALLERY";
                                Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                                pickPhoto.setDataAndType(Uri.fromFile(new File(path)))
                                startActivityForResult(pickPhoto, PICK_PICTURE_FIRST_IMAGE);
                            } else {
                                dialogInterface.dismiss();
                            }
                        }
                    });
                    builder.show();
                }
                break;
            case R.id.imageview2:
                if (imageclick_2) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView2.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView2.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_SECOND_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_SECOND_IMAGE);
                }
                break;
            case R.id.imageview3:
                if (imageclick_3) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView3.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView3.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_THIRD_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_THIRD_IMAGE);
                }
                break;
            case R.id.imageview4:
                if (imageclick_4) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView4.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView4.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_FOURTH_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_FOURTH_IMAGE);
                }
                break;
            case R.id.imageview5:
                if (imageclick_5) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView5.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView5.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_FIFTH_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_FIFTH_IMAGE);
                }
                break;
        }
    }
</code>```

答:
You can create ImageView dynamically like this :</p>

```<code> container = (LinearLayout)findViewById(R.id.container);
        for (int j = 0; j < 4; j++) {
            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePicture, CAMERA_REQUEST);
            ImageView newimageview = new ImageView(MainActivity.this);
            newimageview.setBackgroundResource(R.drawable.panama_app_logo);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,50);
            newimageview.setLayoutParams(params);
            container.addView(newimageview);
        }
</code>```

Body:
I am making an Android Application where i am allowing user to click the picture through camera or add the Images through Gallery.

Only 5 images are allowed to be added in the image view . How i can add image view dynamically in the activity at the run time.

how to delete and re position the images present in the activity.

As there are 5 images so when i am deleting the 2nd image then the 3rd , 4th and 5th images should be re position to 2nd , 3rd and 4th position and it should allow me to add 5th image.

Can Anyone help me with the Source code .

This is my Code :

private static final int CAMERA_REQUEST_FIRST_IMAGE = 100;
    private static final int CAMERA_REQUEST_SECOND_IMAGE = 101;
    private static final int CAMERA_REQUEST_THIRD_IMAGE = 102;
    private static final int CAMERA_REQUEST_FOURTH_IMAGE = 103;
    private static final int CAMERA_REQUEST_FIFTH_IMAGE = 104;
    private static final int PICK_PICTURE_FIRST_IMAGE = 105;
    private static final int PICK_PICTURE_SECOND_IMAGE = 106;
    private static final int PICK_PICTURE_THIRD_IMAGE = 107;
    private static final int PICK_PICTURE_FOURTH_IMAGE = 108;
    private static final int PICK_PICTURE_FIFTH_IMAGE = 109;
    Boolean imageclick_1 = false, imageclick_2 = false, imageclick_3 = false, imageclick_4 = false, imageclick_5 = false;
    TextView textview_imagename1, textview_imagename2, textview_imagename3, textview_imagename4, textview_imagename5;
ImageView imageView1, imageView2, imageView3, imageView4, imageView5;
imageView1 = (ImageView) findViewById(R.id.imageview1);
        imageView1.setOnClickListener(this);
 imageView2 = (ImageView) findViewById(R.id.imageview2);
        imageView2.setOnClickListener(this);
 imageView3 = (ImageView) findViewById(R.id.imageview3);
        imageView3.setOnClickListener(this);
 imageView4 = (ImageView) findViewById(R.id.imageview4);
        imageView4.setOnClickListener(this);
 imageView5 = (ImageView) findViewById(R.id.imageview5);
        imageView5.setOnClickListener(this);

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_PICTURE_FIRST_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage1 = data.getData();
                    String s1 = getRealPathFromURI(selectedImage1);
                    try {
                        images1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView1.setImageURI(selectedImage1);
                    String name1 = s1.substring(s1.lastIndexOf("/") + 1);
                    textview_imagename1.setText(name1);
                    imageView2.setVisibility(View.VISIBLE);
                    imageclick_1 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_SECOND_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage2 = data.getData();
                    String s2 = getRealPathFromURI(selectedImage2);
                    try {
                        images2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView2.setImageURI(selectedImage2);
                    String name2 = s2.substring(s2.lastIndexOf("/") + 1);
                    textview_imagename2.setText(name2);
                    imageView3.setVisibility(View.VISIBLE);
                    imageclick_2 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_THIRD_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage3 = data.getData();
                    String s3 = getRealPathFromURI(selectedImage3);
                    try {
                        images3 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage3);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView3.setImageURI(selectedImage3);
                    String name3 = s3.substring(s3.lastIndexOf("/") + 1);
                    textview_imagename3.setText(name3);
                    imageView4.setVisibility(View.VISIBLE);
                    imageclick_3 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_FOURTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage4 = data.getData();
                    String s4 = getRealPathFromURI(selectedImage4);
                    try {
                        images4 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage4);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView4.setImageURI(selectedImage4);
                    String name4 = s4.substring(s4.lastIndexOf("/") + 1);
                    textview_imagename4.setText(name4);
                    imageView5.setVisibility(View.VISIBLE);
                    imageclick_4 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case PICK_PICTURE_FIFTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    Uri selectedImage5 = data.getData();
                    String s5 = getRealPathFromURI(selectedImage5);
                    try {
                        images5 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage5);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView5.setImageURI(selectedImage5);
                    String name5 = s5.substring(s5.lastIndexOf("/") + 1);
                    textview_imagename5.setText(name5);
                    imageclick_5 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FIRST_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo1 = (Bitmap) data.getExtras().get("data");
                    imageView1.setImageBitmap(photo1);
                    SaveImage(photo1);
                    textview_imagename1.setText(fname);
                    imageView2.setVisibility(View.VISIBLE);
                    imageclick_1 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_SECOND_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo2 = (Bitmap) data.getExtras().get("data");
                    imageView2.setImageBitmap(photo2);
                    SaveImage(photo2);
                    textview_imagename2.setText(fname);
                    imageView3.setVisibility(View.VISIBLE);
                    imageclick_2 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_THIRD_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo3 = (Bitmap) data.getExtras().get("data");
                    imageView3.setImageBitmap(photo3);
                    SaveImage(photo3);
                    textview_imagename3.setText(fname);
                    imageView4.setVisibility(View.VISIBLE);
                    imageclick_3 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FOURTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo4 = (Bitmap) data.getExtras().get("data");
                    imageView4.setImageBitmap(photo4);
                    SaveImage(photo4);
                    textview_imagename4.setText(fname);
                    imageView5.setVisibility(View.VISIBLE);
                    imageclick_4 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
            case CAMERA_REQUEST_FIFTH_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    photo5 = (Bitmap) data.getExtras().get("data");
                    imageView5.setImageBitmap(photo5);
                    SaveImage(photo5);
                    textview_imagename5.setText(fname);
                    imageclick_5 = true;
                    deletebutton.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

private void SaveImage(Bitmap finalBitmap) {
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        fname = "Image-" + timeStamp + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageview1:
                if (imageclick_1) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView1.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else {
                    final String[] Items = {"Click Pic", "Pick Pic", "Cancel"};
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Add Photo");
                    builder.setItems(Items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (i == 0) {
                                isdialogset = "CAMERA";
                                if (imageView1.getDrawable() == null) {
                                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(takePicture, CAMERA_REQUEST_FIRST_IMAGE);
                                }
                            } else if (i == 1) {
                                isdialogset = "GALLERY";
                                Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                                pickPhoto.setDataAndType(Uri.fromFile(new File(path)))
                                startActivityForResult(pickPhoto, PICK_PICTURE_FIRST_IMAGE);
                            } else {
                                dialogInterface.dismiss();
                            }
                        }
                    });
                    builder.show();
                }
                break;
            case R.id.imageview2:
                if (imageclick_2) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView2.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView2.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_SECOND_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_SECOND_IMAGE);
                }
                break;
            case R.id.imageview3:
                if (imageclick_3) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView3.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView3.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_THIRD_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_THIRD_IMAGE);
                }
                break;
            case R.id.imageview4:
                if (imageclick_4) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView4.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView4.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_FOURTH_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_FOURTH_IMAGE);
                }
                break;
            case R.id.imageview5:
                if (imageclick_5) {
                    fullimageview.setVisibility(View.VISIBLE);
                    Bitmap bitmap = ((BitmapDrawable) imageView5.getDrawable()).getBitmap();
                    fullimageview.setImageBitmap(bitmap);
                } else if (isdialogset.equals("CAMERA") && imageView5.getDrawable() == null) {
                    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePicture, CAMERA_REQUEST_FIFTH_IMAGE);
                } else if (isdialogset.equals("GALLERY")) {
                    Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(pickPhoto, PICK_PICTURE_FIFTH_IMAGE);
                }
                break;
        }
    }

Body:
You can create ImageView dynamically like this :

 container = (LinearLayout)findViewById(R.id.container);
        for (int j = 0; j < 4; j++) {
            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePicture, CAMERA_REQUEST);
            ImageView newimageview = new ImageView(MainActivity.this);
            newimageview.setBackgroundResource(R.drawable.panama_app_logo);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,50);
            newimageview.setLayoutParams(params);
            container.addView(newimageview);
        }


问:
Failed to install app apk in android device
I have the app running fine in the android emulator. But when I tried to install in the device it is giving error.

In CoolPad Note - running 5.1 version - error is "Failed to install the app"
In Galaxy A7 - running 6.0 version - error is "parsing failed"

I am using sqlite db, apache csv parser lib, Square's sqldelight.

Min Sdk - 19 and Max Sdk - 25

I tried giving all the uses-permission based on this link

I unlocked developer options in the phone and enabled installing from unknown sources. Still not able to install the app. In the same phone, I can install a simple android app. So the problem is with the package or the code. Please help.

Usb with both the phones are not working. So I am sending the apk through bluetooth and then installing it with package installer in the phone. How to get the installation log from the phone.

The app is 4 forms and uses fragments. If needed I can upload the apk.

答:
If you use Galaxy A7.
You can tap *#9900# in dialer app (name is 'phone').
You can find "RUN DUMPSTATE/LOGCAT" and tap it.
Then tap "COPY TO SDCARD(INCLUDE CP RAMDUMP)".
You can find 'log' folder in MyFiles app.</p>


问:
Php -MySQL query failing - error Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean
I have following php code :

```<code><?php
    $connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
    $str = "SET @id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '@id';";
    echo $str;
    $query12 = mysqli_multi_query($connect,$str);
    echo $query12;
    while($row = $query12->fetch_assoc())
    {
        $str1 = "SET @UID := '".$row."';
         SELECT AttributeValue FROM att_value where UID=@UID;
         SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
         SELECT AttributeName FROM att_name WHERE AID=@AID;";
         echo $str1;
        $query1= mysqli_multi_query($connect,$str1);
        echo $row[0];
    }
?>
</code>```

I get the generic error but when I run the same code on MySQL then it works without error. Can someone please help me what am I missing .

I even tried exception handling but it didn't help.

NOTE : code fails in the while loop condition.

答:
The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().mysqli_multi_query() only returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.</p>

```<code>if (mysqli_multi_query($connect,$str))
 {

     do
    {
        if ($result=mysqli_store_result($connect)) {

          while ($row=mysqli_fetch_row($result))
            {
                    $str1 = "SET @UID := '".$row."';
                    SELECT AttributeValue FROM att_value where UID=@UID;
                    SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
                    SELECT AttributeName FROM att_name WHERE AID=@AID;";
                    echo $str1;
                    $query1= mysqli_multi_query($connect,$str1);
                    echo $row[0];
            }

          mysqli_free_result($result);
          }
    }
    while (mysqli_next_result($connect));
}
</code>```

Body:
I have following php code :

<?php
    $connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
    $str = "SET @id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '@id';";
    echo $str;
    $query12 = mysqli_multi_query($connect,$str);
    echo $query12;
    while($row = $query12->fetch_assoc())
    {
        $str1 = "SET @UID := '".$row."';
         SELECT AttributeValue FROM att_value where UID=@UID;
         SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
         SELECT AttributeName FROM att_name WHERE AID=@AID;";
         echo $str1;
        $query1= mysqli_multi_query($connect,$str1);
        echo $row[0];
    }
?>

I get the generic error but when I run the same code on MySQL then it works without error. Can someone please help me what am I missing .

I even tried exception handling but it didn't help.

NOTE : code fails in the while loop condition.

Body:
The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().mysqli_multi_query() only returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

if (mysqli_multi_query($connect,$str))
 {

     do
    {
        if ($result=mysqli_store_result($connect)) {

          while ($row=mysqli_fetch_row($result))
            {
                    $str1 = "SET @UID := '".$row."';
                    SELECT AttributeValue FROM att_value where UID=@UID;
                    SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
                    SELECT AttributeName FROM att_name WHERE AID=@AID;";
                    echo $str1;
                    $query1= mysqli_multi_query($connect,$str1);
                    echo $row[0];
            }

          mysqli_free_result($result);
          }
    }
    while (mysqli_next_result($connect));
}