问:
Could not load file or assembly 'Microsoft.IdentityModel.Clients.ActiveDirectory.Platform'
I have a Xamarin.iOS project and I want to authenticate with Azure. The end goal is to not have the user login, and to authenticate behind the scenes. When I instantiate AuththenticationContext I get this Error. "Could not load file or assembly 'Microsoft.IdentityModel.Clients.ActiveDirectory.Platform'". I installed Microsoft.IndentityModel.Clients.ActiveDirectory v3.13.9 from Nuget and the using statement is at the top of the code. The DLL is set to copy local. I don't know why this is not working. I even unintalled the Nuget Package and added the DLL's to the project and referenced them directly and got the same error. Below is the code that I am trying to make work. Again it breaks when AuthenticationContext is instantiated so I cant even test the rest of it. I have used the following two websites for guidance, https://blog.xamarin.com/authenticate-xamarin-mobile-apps-using-azure-active-directory/

I found this "bug" here, but the fix does not work, nor does it make sense to me. Im not sure where to put the code and I get the access error as well.
https://forums.xamarin.com/discussion/45425/azure-authentication-microsoft-identitymodel-clients-activedirectory-platform-no-working

```<code> var authContext = new AuthenticationContext(aadInstance);
        ClientCredential clientCredential = new ClientCredential(clientId, appKey);

            // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
                 AuthenticationResult result =  authContext.AcquireTokenAsync(AMServiceResourceId, clientCredential).Result;

            WebRequest Request =
                WebRequest.Create(
                    new Uri(@<API call to test connection>));
            Request.ContentType = "application/json";
            Request.Method = "Get";
            Request.Proxy = null;
            Request.Timeout = 5000;
            Request.Headers.Add("Authorization", "Bearer" + result.AccessToken);
</code>```

答:
When you install the ADAL library from Nuget, Nuget should install two separate DLLs into each project of your Xamarin solution.  One with the namespace Microsoft.IdentityModel.Clients.ActiveDirectory and one with Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.  The former is most of the logic for the library, while the latter is platform-specific logic for each target platform (iOS, Android, etc).  Make sure that after installing Nuget, both packages are there in each project's dependencies.  To ensure that Nuget installs the correct package, make sure each project targets the appropriate platform in the project properties/settings.

If you're saying that the DLLs are installed correctly but are not being picked up at runttime, I'm afraid I don't have an answer for you.

Body:
I have a Xamarin.iOS project and I want to authenticate with Azure. The end goal is to not have the user login, and to authenticate behind the scenes. When I instantiate AuththenticationContext I get this Error. "Could not load file or assembly 'Microsoft.IdentityModel.Clients.ActiveDirectory.Platform'". I installed Microsoft.IndentityModel.Clients.ActiveDirectory v3.13.9 from Nuget and the using statement is at the top of the code. The DLL is set to copy local. I don't know why this is not working. I even unintalled the Nuget Package and added the DLL's to the project and referenced them directly and got the same error. Below is the code that I am trying to make work. Again it breaks when AuthenticationContext is instantiated so I cant even test the rest of it. I have used the following two websites for guidance, https://blog.xamarin.com/authenticate-xamarin-mobile-apps-using-azure-active-directory/

I found this "bug" here, but the fix does not work, nor does it make sense to me. Im not sure where to put the code and I get the access error as well.
https://forums.xamarin.com/discussion/45425/azure-authentication-microsoft-identitymodel-clients-activedirectory-platform-no-working

 var authContext = new AuthenticationContext(aadInstance);
        ClientCredential clientCredential = new ClientCredential(clientId, appKey);

            // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
                 AuthenticationResult result =  authContext.AcquireTokenAsync(AMServiceResourceId, clientCredential).Result;

            WebRequest Request =
                WebRequest.Create(
                    new Uri(@<API call to test connection>));
            Request.ContentType = "application/json";
            Request.Method = "Get";
            Request.Proxy = null;
            Request.Timeout = 5000;
            Request.Headers.Add("Authorization", "Bearer" + result.AccessToken);


来源: stackexchange

问:
How to write c# service that I can also run as a winforms program?
I have a windows service written in C# that acts as a proxy for a bunch of network devices to the back end database. For testing and also to add a simulation layer to test the back end I would like to have a GUI for the test operator to be able run the simulation. Also for a striped down version to send out as a demo. The GUI and service do not have to run at the same time. What is the best way to achieve this duel operation?

Edit:
Here is my solution combing stuff from this question , Am I Running as a Service and Install a .NET windows service without InstallUtil.exe using this excellent code  by Marc Gravell

It uses the following line to test if to run the gui or run as service.

```<code> if (arg_gui || Environment.UserInteractive || Debugger.IsAttached)
</code>```

Here is the code.

```<code>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Diagnostics;

namespace Form_Service
{
   static class Program
   {
      ///
      /// The main entry point for the application.
      ///
      [STAThread]
      static int Main(string[] args)
      {
         bool arg_install =  false;
         bool arg_uninstall = false;
         bool arg_gui = false;
         bool rethrow = false;
         try
         {
            foreach (string arg in args)
            {
               switch (arg)
               {
                  case "-i":
                  case "-install":
                     arg_install = true; break;
                  case "-u":
                  case "-uninstall":
                     arg_uninstall = true; break;
                  case "-g":
                  case "-gui":
                     arg_gui = true; break;
                  default:
                     Console.Error.WriteLine("Argument not expected: " + arg);
                     break;
               }
            }
            if (arg_uninstall)
            {
               Install(true, args);
            }
            if (arg_install)
            {
               Install(false, args);
            }
            if (!(arg_install || arg_uninstall))
            {
               if (arg_gui || Environment.UserInteractive || Debugger.IsAttached)
               {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);
                  Application.Run(new Form1());
               }
               else
               {
                  rethrow = true; // so that windows sees error...
                  ServiceBase[] services = { new Service1() };
                  ServiceBase.Run(services);
                  rethrow = false;
               }
            }
            return 0;
         }
         catch (Exception ex)
         {
            if (rethrow) throw;
            Console.Error.WriteLine(ex.Message);
            return -1;
         }
      }

      static void Install(bool undo, string[] args)
      {
         try
         {
            Console.WriteLine(undo ? "uninstalling" : "installing");
            using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
            {
               IDictionary state = new Hashtable();
               inst.UseNewContext = true;
               try
               {
                  if (undo)
                  {
                     inst.Uninstall(state);
                  }
                  else
                  {
                     inst.Install(state);
                     inst.Commit(state);
                  }
               }
               catch
               {
                  try
                  {
                     inst.Rollback(state);
                  }
                  catch { }
                  throw;
               }
            }
         }
         catch (Exception ex)
         {
            Console.Error.WriteLine(ex.Message);
         }
      }
   }

   [RunInstaller(true)]
   public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
   {
      public MyServiceInstallerProcess()
      {
         this.Account = ServiceAccount.NetworkService;
      }
   }

   [RunInstaller(true)]
   public sealed class MyServiceInstaller : ServiceInstaller
   {
      public MyServiceInstaller()
      {
         this.Description = "My Service";
         this.DisplayName = "My Service";
         this.ServiceName = "My Service";
         this.StartType = System.ServiceProcess.ServiceStartMode.Manual;
      }
   }

}
</code>```

答: You can create the service to call another executable with a command line argument so it is run without the form. When that exe is called without the command line argument it shows the form and act as normal.</p>

OwnerDisplayName: Rex Logan

ContentLicense: CC BY-SA 2.5

Body:
I have a windows service written in C# that acts as a proxy for a bunch of network devices to the back end database. For testing and also to add a simulation layer to test the back end I would like to have a GUI for the test operator to be able run the simulation. Also for a striped down version to send out as a demo. The GUI and service do not have to run at the same time. What is the best way to achieve this duel operation?

Edit:
Here is my solution combing stuff from this question , Am I Running as a Service and Install a .NET windows service without InstallUtil.exe using this excellent code  by Marc Gravell

It uses the following line to test if to run the gui or run as service.

 if (arg_gui || Environment.UserInteractive || Debugger.IsAttached)

Here is the code.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Diagnostics;

namespace Form_Service
{
   static class Program
   {
      ///
      /// The main entry point for the application.
      ///
      [STAThread]
      static int Main(string[] args)
      {
         bool arg_install =  false;
         bool arg_uninstall = false;
         bool arg_gui = false;
         bool rethrow = false;
         try
         {
            foreach (string arg in args)
            {
               switch (arg)
               {
                  case "-i":
                  case "-install":
                     arg_install = true; break;
                  case "-u":
                  case "-uninstall":
                     arg_uninstall = true; break;
                  case "-g":
                  case "-gui":
                     arg_gui = true; break;
                  default:
                     Console.Error.WriteLine("Argument not expected: " + arg);
                     break;
               }
            }
            if (arg_uninstall)
            {
               Install(true, args);
            }
            if (arg_install)
            {
               Install(false, args);
            }
            if (!(arg_install || arg_uninstall))
            {
               if (arg_gui || Environment.UserInteractive || Debugger.IsAttached)
               {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);
                  Application.Run(new Form1());
               }
               else
               {
                  rethrow = true; // so that windows sees error...
                  ServiceBase[] services = { new Service1() };
                  ServiceBase.Run(services);
                  rethrow = false;
               }
            }
            return 0;
         }
         catch (Exception ex)
         {
            if (rethrow) throw;
            Console.Error.WriteLine(ex.Message);
            return -1;
         }
      }

      static void Install(bool undo, string[] args)
      {
         try
         {
            Console.WriteLine(undo ? "uninstalling" : "installing");
            using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
            {
               IDictionary state = new Hashtable();
               inst.UseNewContext = true;
               try
               {
                  if (undo)
                  {
                     inst.Uninstall(state);
                  }
                  else
                  {
                     inst.Install(state);
                     inst.Commit(state);
                  }
               }
               catch
               {
                  try
                  {
                     inst.Rollback(state);
                  }
                  catch { }
                  throw;
               }
            }
         }
         catch (Exception ex)
         {
            Console.Error.WriteLine(ex.Message);
         }
      }
   }

   [RunInstaller(true)]
   public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
   {
      public MyServiceInstallerProcess()
      {
         this.Account = ServiceAccount.NetworkService;
      }
   }

   [RunInstaller(true)]
   public sealed class MyServiceInstaller : ServiceInstaller
   {
      public MyServiceInstaller()
      {
         this.Description = "My Service";
         this.DisplayName = "My Service";
         this.ServiceName = "My Service";
         this.StartType = System.ServiceProcess.ServiceStartMode.Manual;
      }
   }

}

LastEditorDisplayName: Rex Logan

OwnerDisplayName: Jimmy Bergmark - JTB World


问:
Max File Size in roxy fileman
Is there any way to set the max file limit.
I already searched google and found this code (this code isnt working):

```<code>function addFile() {
clickFirstOnEnter('dlgAddFile');

var dialogButtons = {};
dialogButtons[t('Upload')] = function () {
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
if (!$('#fileUploads').val())
alert(t('E_SelectFiles'));
else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t('E_ActionDisabled'));
//$('#dlgAddFile').dialog('close');
}
else {
var files = $('#fileUploads')[0].files;
for (var i = 0; i < files.length; i++) {
//alert(files[i].name);
totalsize += files[i].size;
if ((files[i].size / 1024) > maxfilesize) {
fileoversize = files[i].name + '\n';
}
}

if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
}
else if (fileoversize != "") {
alert("Max total upload : "+ maxfilesize +"KB. Oversized files:\n" + fileoversize);
}
else {
document.forms['addfile'].action = RoxyFilemanConf.UPLOAD;
document.forms['addfile'].submit();
}
}
}
};
dialogButtons[t('Cancel')] = function () { $('#dlgAddFile').dialog('close'); };

$('#dlgAddFile').dialog({ title: t('T_AddFile'), modal: true, buttons: dialogButtons });
}

Adding 2 variables to conf.json
MAXTOTAL and MAXFILESIZE.
</code>```

but this doesnt work at all..
Anyone who got any suggestions/solution for this problem?

答:
As OP has already discovered, this is a configuration setting which allows for files up to 4MB, but anything higher need some special changes.  For people searching for this solution in .Net, two changes are required in the web.config for IIS 7.0+. Check the link for more complete details.

I added the elements to my root web.config.

```<code><system.web>
    <!-- Max int value of 2gb -->
    <httpRuntime maxRequestLength="2097151" appRequestQueueLimit="100000" requestLengthDiskThreshold="2097151" />
</system.web>
<system.webServer>
     <security>
        <requestFiltering>
            <!-- maxAllowedContentLength, for IIS, in bytes -->
            <requestLimits maxAllowedContentLength="104857600" ></requestLimits>
        </requestFiltering>
    </security>
</system.webServer>
</code>```

Sause:
How to increase the max upload file size in ASP.NET?

I've also updated the code to work as intended with version 1.4.5. Make sure you apply this to the main.js/main.min.js files.

```<code>function addFile() {
    clickFirstOnEnter("dlgAddFile");
    $("#uploadResult").html("");
    clearFileField();
    var a = {};
    a[t("Upload")] = {
        id: "btnUpload",
        text: t("Upload"),
        disabled: true,
        click: function () {
            if (!$("#fileUploads").val() && (!uploadFileList || uploadFileList.length == 0)) {
                alert(t("E_SelectFiles"))
            } else {
                if (!RoxyFilemanConf.UPLOAD) {
                    alert(t("E_ActionDisabled"))
                } else {
                    // start of change
                    var maxtotal = RoxyFilemanConf.MAXTOTAL;
                    var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
                    var fileoversize = "";
                    var totalsize = 0;

                    for (var i = 0; i < uploadFileList.length; i++) {
                        totalsize += uploadFileList[i].size;
                        if ((uploadFileList[i].size / 1024) > maxfilesize) {
                            fileoversize = fileoversize + uploadFileList[i].name + '\n';
                        }
                    }

                    if ((totalsize / 1024 / 1024) > maxtotal) {
                        alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
                    } else if (fileoversize != "") {
                        alert("Max total upload : " + maxfilesize + "KB. Oversized files:\n" + fileoversize);

                    } else // end of change
                    if (window.FormData && window.XMLHttpRequest && window.FileList && uploadFileList && uploadFileList.length > 0)
                    {
                        for (i = 0; i < uploadFileList.length; i++) {
                            fileUpload(uploadFileList[i], i)
                        }
                    } else {
                        document.forms.addfile.action = RoxyFilemanConf.UPLOAD;
                        document.forms.addfile.submit()
                    }
                }
            }
        }
    };
    a[t("Cancel")] = function () {
        $("#dlgAddFile").dialog("close")
    };
    $("#dlgAddFile").dialog({
        title: t("T_AddFile"),
        modal: true,
        buttons: a,
        width: 400
    })
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Max File Size in roxy fileman

Body:
Is there any way to set the max file limit.
I already searched google and found this code (this code isnt working):

function addFile() {
clickFirstOnEnter('dlgAddFile');

var dialogButtons = {};
dialogButtons[t('Upload')] = function () {
var maxtotal = RoxyFilemanConf.MAXTOTAL;
var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
var fileoversize = "";
var totalsize = 0;
if (!$('#fileUploads').val())
alert(t('E_SelectFiles'));
else {
if (!RoxyFilemanConf.UPLOAD) {
alert(t('E_ActionDisabled'));
//$('#dlgAddFile').dialog('close');
}
else {
var files = $('#fileUploads')[0].files;
for (var i = 0; i < files.length; i++) {
//alert(files[i].name);
totalsize += files[i].size;
if ((files[i].size / 1024) > maxfilesize) {
fileoversize = files[i].name + '\n';
}
}

if ((totalsize / 1024 / 1024) > maxtotal) {
alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
}
else if (fileoversize != "") {
alert("Max total upload : "+ maxfilesize +"KB. Oversized files:\n" + fileoversize);
}
else {
document.forms['addfile'].action = RoxyFilemanConf.UPLOAD;
document.forms['addfile'].submit();
}
}
}
};
dialogButtons[t('Cancel')] = function () { $('#dlgAddFile').dialog('close'); };

$('#dlgAddFile').dialog({ title: t('T_AddFile'), modal: true, buttons: dialogButtons });
}

Adding 2 variables to conf.json
MAXTOTAL and MAXFILESIZE.

but this doesnt work at all..
Anyone who got any suggestions/solution for this problem?

Body:
As OP has already discovered, this is a configuration setting which allows for files up to 4MB, but anything higher need some special changes.  For people searching for this solution in .Net, two changes are required in the web.config for IIS 7.0+. Check the link for more complete details.

I added the elements to my root web.config.

<system.web>
    <!-- Max int value of 2gb -->
    <httpRuntime maxRequestLength="2097151" appRequestQueueLimit="100000" requestLengthDiskThreshold="2097151" />
</system.web>
<system.webServer>
     <security>
        <requestFiltering>
            <!-- maxAllowedContentLength, for IIS, in bytes -->
            <requestLimits maxAllowedContentLength="104857600" ></requestLimits>
        </requestFiltering>
    </security>
</system.webServer>

Sause:
How to increase the max upload file size in ASP.NET?

I've also updated the code to work as intended with version 1.4.5. Make sure you apply this to the main.js/main.min.js files.

function addFile() {
    clickFirstOnEnter("dlgAddFile");
    $("#uploadResult").html("");
    clearFileField();
    var a = {};
    a[t("Upload")] = {
        id: "btnUpload",
        text: t("Upload"),
        disabled: true,
        click: function () {
            if (!$("#fileUploads").val() && (!uploadFileList || uploadFileList.length == 0)) {
                alert(t("E_SelectFiles"))
            } else {
                if (!RoxyFilemanConf.UPLOAD) {
                    alert(t("E_ActionDisabled"))
                } else {
                    // start of change
                    var maxtotal = RoxyFilemanConf.MAXTOTAL;
                    var maxfilesize = RoxyFilemanConf.MAXFILESIZE;
                    var fileoversize = "";
                    var totalsize = 0;

                    for (var i = 0; i < uploadFileList.length; i++) {
                        totalsize += uploadFileList[i].size;
                        if ((uploadFileList[i].size / 1024) > maxfilesize) {
                            fileoversize = fileoversize + uploadFileList[i].name + '\n';
                        }
                    }

                    if ((totalsize / 1024 / 1024) > maxtotal) {
                        alert(t('E_MAXSIZE') + ". Set to " + maxsize + "MB.");
                    } else if (fileoversize != "") {
                        alert("Max total upload : " + maxfilesize + "KB. Oversized files:\n" + fileoversize);

                    } else // end of change
                    if (window.FormData && window.XMLHttpRequest && window.FileList && uploadFileList && uploadFileList.length > 0)
                    {
                        for (i = 0; i < uploadFileList.length; i++) {
                            fileUpload(uploadFileList[i], i)
                        }
                    } else {
                        document.forms.addfile.action = RoxyFilemanConf.UPLOAD;
                        document.forms.addfile.submit()
                    }
                }
            }
        }
    };
    a[t("Cancel")] = function () {
        $("#dlgAddFile").dialog("close")
    };
    $("#dlgAddFile").dialog({
        title: t("T_AddFile"),
        modal: true,
        buttons: a,
        width: 400
    })
}

ContentLicense: CC BY-SA 4.0


问:
ruby scan method: What does ^ do?
I wrote a method to print EUR prices:

```<code>print((" " + text).scan(/\d+,\d+ EUR/).map {|m| m.reverse.chop.reverse})
</code>```

by

```<code>text = "this is 14,67 EUR"
</code>```

it works for all digits after the comma, but is missing the first digit (returns 4,67 instead of 14,67)

I found a line to solve my problem:

```<code>text.scan(/[^\d]\d,\d+ EUR/)
</code>```

But why is this working and what does the ^ do?

答:
^ when first inside the brackets is the "not" operator

/[^\d]/ means not a digit

```<code>text.scan(/[^\d]\d,\d+ EUR/)
</code>```

Says:

look for a non-digit

followed by one digit

followed by a comma

followed by one or more digits

followed by a space

followed by "EUR"

Title: ruby scan method: What does ^ do?

Body:
I wrote a method to print EUR prices:

print((" " + text).scan(/\d+,\d+ EUR/).map {|m| m.reverse.chop.reverse})

by

text = "this is 14,67 EUR"

it works for all digits after the comma, but is missing the first digit (returns 4,67 instead of 14,67)

I found a line to solve my problem:

text.scan(/[^\d]\d,\d+ EUR/)

But why is this working and what does the ^ do?

Body:
^ when first inside the brackets is the "not" operator

/[^\d]/ means not a digit

text.scan(/[^\d]\d,\d+ EUR/)

Says:

look for a non-digit

followed by one digit

followed by a comma

followed by one or more digits

followed by a space

followed by "EUR"


问:
Sorting CREATE TABLE statements, which contains references in Java
my project is about to create my own persistence implementation. Maybe it's easy but I can't find the solution. I have Classes annotated with my own annotation @Entity and in Annotation Processor I want to create SQL create table statements and save them into file and then execute them. But how do I sort these statements? I have references in tables, I have to first create the non referencing table and then table referencing on this first table</p>

答:
Ok. I will be concrete. Imagine you have for example 3 Classes: Person Department and Company. They are annotated as Entities and I want to create the SQL statements for create tables. But Company references on Department and Person references on Department, so I have to first create the Department table and then Person or Company. I am creating the statements in Annotation Processor, so I have for disposal the annotated elements. Now I am just sorting String to be written in file. But it isn't very pretty. </p>

```<code>     ArrayList<String> sortedListOfCommands = new ArrayList<>();

        for(String command: listOfCommands){
            if(!command.contains("FOREIGN"))
                sortedListOfCommands.add(command);
        }

        for(String command: listOfCommands){
            if(!sortedListOfCommands.contains(command))
                sortedListOfCommands.add(command);
        }
</code>```

Body:
Ok. I will be concrete. Imagine you have for example 3 Classes: Person Department and Company. They are annotated as Entities and I want to create the SQL statements for create tables. But Company references on Department and Person references on Department, so I have to first create the Department table and then Person or Company. I am creating the statements in Annotation Processor, so I have for disposal the annotated elements. Now I am just sorting String to be written in file. But it isn't very pretty.

     ArrayList<String> sortedListOfCommands = new ArrayList<>();

        for(String command: listOfCommands){
            if(!command.contains("FOREIGN"))
                sortedListOfCommands.add(command);
        }

        for(String command: listOfCommands){
            if(!sortedListOfCommands.contains(command))
                sortedListOfCommands.add(command);
        }


问:
Struts 2. s:property. How to get the value of a variable whose name is passed as a parameter to the jsp?
I have a class Message.java with two variables of same type Location.java called origin and destination

Message.java

```<code>public class Message{

    private Location origin;
    private Location destination;

//Getters and setters correctly defined
}
</code>```

Location.java

```<code>public class Location{

private String address;
}
</code>```

MessageAction.java

```<code> public class MessageAction {

        private Message message;
       //Getters and setters correctly defined
    }
</code>```

I want to reuse code, so I have created a common JSP and pass the name of these variables by parameter. (Of course, the code is more complex, this is only a basic example, so it really helps me to reuse code)

message.jsp

<s:push value="message">
    <s:include value="/jsp/location.jsp">
        <s:param name="variableName" value="'origin'" />
    </s:include>
    <s:include value="/jsp/location.jsp">
        <s:param name="variableName" value="'destination'" />
    </s:include>
</push>
```

<p>Here comes the problem, I don't know how to show the value of <code>%{variableName}.address</code>. I have tried several combinations and googled a while but I haven't found anything. </p>

<p><strong>location.jsp</strong></p>

<pre class="lang-jsp prettyprint-override"><code><s:set name="variableName">${param.variableName}</s:set>
<s:property value="%{%{variableName}.address}" />
</code>```

If I write directly the names of the variables, I receive their value correctly, so the Action is setting them correctly.

<s:property value="origin.address" />
<s:property value="destination.address" />
```

答:
This is just wrong OGNL expression

```<code>%{%{variableName}.address}
</code>```

if you want to reuse JSP as templete then you should use valid OGNL expression. Nevertheless passing parameter name is enormous since you will have complex OGNL to return the value of this parameter name.

You should also know that

Parameters are passed as request parameters, so use the ${param.ParamName} notation to access them. Do not use the property tag to access parameters in included files.

Body:
I have a class Message.java with two variables of same type Location.java called origin and destination

Message.java

public class Message{

    private Location origin;
    private Location destination;

//Getters and setters correctly defined
}

Location.java

public class Location{

private String address;
}

MessageAction.java

 public class MessageAction {

        private Message message;
       //Getters and setters correctly defined
    }

I want to reuse code, so I have created a common JSP and pass the name of these variables by parameter. (Of course, the code is more complex, this is only a basic example, so it really helps me to reuse code)

message.jsp

<s:push value="message">
    <s:include value="/jsp/location.jsp">
        <s:param name="variableName" value="'origin'" />
    </s:include>
    <s:include value="/jsp/location.jsp">
        <s:param name="variableName" value="'destination'" />
    </s:include>
</push>

Here comes the problem, I don't know how to show the value of %{variableName}.address. I have tried several combinations and googled a while but I haven't found anything.

location.jsp

<s:set name="variableName">${param.variableName}</s:set>
<s:property value="%{%{variableName}.address}" />

If I write directly the names of the variables, I receive their value correctly, so the Action is setting them correctly.

<s:property value="origin.address" />
<s:property value="destination.address" />

Body:
This is just wrong OGNL expression

%{%{variableName}.address}

if you want to reuse JSP as templete then you should use valid OGNL expression. Nevertheless passing parameter name is enormous since you will have complex OGNL to return the value of this parameter name.

You should also know that

Parameters are passed as request parameters, so use the ${param.ParamName} notation to access them. Do not use the property tag to access parameters in included files.


问:
File upload not working with navbar in R Shiny
I can't get the File Upload feature to work properly when using a navigation bar. Here is what I have for server.R:

```<code>library(shiny)
library(markdown)

function(input, output) {

  df <- NULL
  current_file <- NULL
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)){
  return(NULL)}
else {df <<- read.csv(inFile$datapath, header=input$header, sep=input$sep,
                     quote=input$quote)
      current_file <<- inFile$name
}

return(NULL)
  })

output$fileInfo <- renderTable({
call.me = in_data()
data.frame(current_file)
})

}
</code>```

And for ui.R I have this:

```<code>library(shiny)
library(markdown)

navbarPage('Navigation Bar',
       tabPanel('File Information', verbatimTextOutput('fileInfo'),
                sidebarLayout(
                  sidebarPanel(fileInput('file1', 'Choose CSV File',
                                         accept=c('text/csv',
                                                  'text/comma-separated-values,text/plain',
                                                  '.csv')),
                    checkboxInput('header', 'Header', TRUE),
                    radioButtons('sep', 'Separator',
                                 c(Comma=',',
                                   Semicolon=';',
                                   Tab='\t'),
                                 ','),
                    radioButtons('quote', 'Quote',
                                 c(None='',
                                   'Double Quote'='"',
                                   'Single Quote'="'"),
                                 '"'),
                    tags$hr()),
                  mainPanel()
                )))
</code>```

I eventually want to have multiple tabs in the navigation bar, and I want to be able to access the data from each tab. All I'm looking for it to do now is for it to give me the name of the file uploaded. This works great when I don't try to fit the navigation bar in. But now it looks like some sort of HTML output. Any tips? Much appreciated.

答:
It is an extremely bad idea to enlist the use of the global assignment <<- here. Your data will be globally available to the whole app if you use a reactive -- which is the way shiny is intended to be used.

Also, look into shiny::validate (example usage below) to validate inputs.

```<code>library("shiny")

options(shiny.maxRequestSize = 9*1024^2)

server <- function(input, output) {

  # the data read in by read.csv will now be accessible throughout the app
  # by calling this reactive, e.g. in_data().
  in_data <- reactive({
    shiny::validate(
      need(input$file1, "Select a file!")
    )

    read.csv(input$file1$datapath, header = input$header,
             sep = input$sep, quote = input$quote)
  })

  # an example, we're calling the reactive to access the data loaded
  output$file_info <- renderTable({
    data.frame(in_data())
  })

}

ui <- navbarPage('Navigation Bar',
  tabPanel('File Information', verbatimTextOutput('fileInfo'),
    sidebarLayout(
      sidebarPanel(
        fileInput('file1', 'Choose CSV File', accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
        checkboxInput('header', 'Header', TRUE),
        radioButtons('sep', 'Separator', c(Comma = ',', Semicolon = ';', Tab = '\t'), ','),
        radioButtons('quote', 'Quote', c(None = '', 'Double Quote'='"', 'Single Quote' = "'"),'"'),
        tags$hr()
        ),
      mainPanel(
        tableOutput("file_info")
        )
      )
    )
  )

shinyApp(ui, server)
</code>```

Body:
I can't get the File Upload feature to work properly when using a navigation bar. Here is what I have for server.R:

library(shiny)
library(markdown)

function(input, output) {

  df <- NULL
  current_file <- NULL
  in_data <- reactive({
    inFile <- input$file1
    if (is.null(inFile)){
  return(NULL)}
else {df <<- read.csv(inFile$datapath, header=input$header, sep=input$sep,
                     quote=input$quote)
      current_file <<- inFile$name
}

return(NULL)
  })

output$fileInfo <- renderTable({
call.me = in_data()
data.frame(current_file)
})

}

And for ui.R I have this:

library(shiny)
library(markdown)

navbarPage('Navigation Bar',
       tabPanel('File Information', verbatimTextOutput('fileInfo'),
                sidebarLayout(
                  sidebarPanel(fileInput('file1', 'Choose CSV File',
                                         accept=c('text/csv',
                                                  'text/comma-separated-values,text/plain',
                                                  '.csv')),
                    checkboxInput('header', 'Header', TRUE),
                    radioButtons('sep', 'Separator',
                                 c(Comma=',',
                                   Semicolon=';',
                                   Tab='\t'),
                                 ','),
                    radioButtons('quote', 'Quote',
                                 c(None='',
                                   'Double Quote'='"',
                                   'Single Quote'="'"),
                                 '"'),
                    tags$hr()),
                  mainPanel()
                )))

I eventually want to have multiple tabs in the navigation bar, and I want to be able to access the data from each tab. All I'm looking for it to do now is for it to give me the name of the file uploaded. This works great when I don't try to fit the navigation bar in. But now it looks like some sort of HTML output. Any tips? Much appreciated.

Body:
It is an extremely bad idea to enlist the use of the global assignment <<- here. Your data will be globally available to the whole app if you use a reactive -- which is the way shiny is intended to be used.

Also, look into shiny::validate (example usage below) to validate inputs.

library("shiny")

options(shiny.maxRequestSize = 9*1024^2)

server <- function(input, output) {

  # the data read in by read.csv will now be accessible throughout the app
  # by calling this reactive, e.g. in_data().
  in_data <- reactive({
    shiny::validate(
      need(input$file1, "Select a file!")
    )

    read.csv(input$file1$datapath, header = input$header,
             sep = input$sep, quote = input$quote)
  })

  # an example, we're calling the reactive to access the data loaded
  output$file_info <- renderTable({
    data.frame(in_data())
  })

}

ui <- navbarPage('Navigation Bar',
  tabPanel('File Information', verbatimTextOutput('fileInfo'),
    sidebarLayout(
      sidebarPanel(
        fileInput('file1', 'Choose CSV File', accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
        checkboxInput('header', 'Header', TRUE),
        radioButtons('sep', 'Separator', c(Comma = ',', Semicolon = ';', Tab = '\t'), ','),
        radioButtons('quote', 'Quote', c(None = '', 'Double Quote'='"', 'Single Quote' = "'"),'"'),
        tags$hr()
        ),
      mainPanel(
        tableOutput("file_info")
        )
      )
    )
  )

shinyApp(ui, server)


问:
python smallest number from list/array
Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

Example

```<code>remove_smallest([1,2,3,4,5]) = [2,3,4,5]

remove_smallest([5,3,2,1,4]) = [5,3,2,4]

remove_smallest([2,2,1,2,1]) = [2,2,2,1]
</code>```

This my code

```<code>def remove_smallest(numbers):
    if numbers == []:
        raise NotImplementedError("TODO: remove_smallest")
    numbers = list(numbers)
    numbers.remove(min(numbers))
    return numbers
</code>```

I'm having this trace back error NotImplementedError("TODO: remove_smallest")

答:
I think this is what you are looking for. Plus what ever other error checking you want to accomplish.</p>

```<code>def remove_smallest(numbers):
    if len(numbers) == 0:
        return numbers
    lowest = min(numbers)
    del numbers[numbers.index(lowest)]
    return numbers
</code>```

Title: python smallest number from list/array

Body:
Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

Example

remove_smallest([1,2,3,4,5]) = [2,3,4,5]

remove_smallest([5,3,2,1,4]) = [5,3,2,4]

remove_smallest([2,2,1,2,1]) = [2,2,2,1]

This my code

def remove_smallest(numbers):
    if numbers == []:
        raise NotImplementedError("TODO: remove_smallest")
    numbers = list(numbers)
    numbers.remove(min(numbers))
    return numbers

I'm having this trace back error NotImplementedError("TODO: remove_smallest")

Body:
I think this is what you are looking for. Plus what ever other error checking you want to accomplish.

def remove_smallest(numbers):
    if len(numbers) == 0:
        return numbers
    lowest = min(numbers)
    del numbers[numbers.index(lowest)]
    return numbers


问:
How to place widgets next to each other?
I am building a simple GUI program to manage priorities. I am having trouble placing button widgets next to each other. It is somehow logical to me that if I want three buttons (Add, Remove, Edit) to place next to each other, I should use column = 0 for Add, column = 1 for Remove and column = 2 for Edit. Anyway, this is what I get:

Here is the createWidgets function:

```<code>def createWidgets(self):

    listBox = Listbox(width = 30).grid(row=1, column = 0)

    Button(self.root,
                text = "Add",
                command = self.addItem).grid(row = 2, column = 1, sticky = W)

    Button(self.root,
           text="Remove",
           command = self.removeItem).grid(row = 2, column = 2, sticky = W)

    Button(self.root,
        text="Edit",
        command = self.editItem).grid(row = 2, column = 3, sticky = W)

    textBox = Text(height = 10, width = 30).grid(row = 3)
</code>```

答:
When you do

```<code>textBox = Text(height = 10, width = 30).grid(row = 3)
</code>```

tkinter automatically sets column = 0 and because textBox has a width of 30 the first column is stretched to a width of 30. It is possible to place textBox so that it occupies all columns by using the columnspan parameter:

```<code>textBox = Text(height = 10, width = 30).grid(row = 3, column = 0, columnspan = 3)
</code>```

Because listBox also has a width of 30, you should also use columnspan here:

```<code>listBox = Listbox(width = 30).grid(row=1, column = 0, columnspan = 3)
</code>```

A comprehensive guide for the grid method is here.

Body:
I am building a simple GUI program to manage priorities. I am having trouble placing button widgets next to each other. It is somehow logical to me that if I want three buttons (Add, Remove, Edit) to place next to each other, I should use column = 0 for Add, column = 1 for Remove and column = 2 for Edit. Anyway, this is what I get:

Here is the createWidgets function:

def createWidgets(self):

    listBox = Listbox(width = 30).grid(row=1, column = 0)

    Button(self.root,
                text = "Add",
                command = self.addItem).grid(row = 2, column = 1, sticky = W)

    Button(self.root,
           text="Remove",
           command = self.removeItem).grid(row = 2, column = 2, sticky = W)

    Button(self.root,
        text="Edit",
        command = self.editItem).grid(row = 2, column = 3, sticky = W)

    textBox = Text(height = 10, width = 30).grid(row = 3)

Body:
When you do

textBox = Text(height = 10, width = 30).grid(row = 3)

tkinter automatically sets column = 0 and because textBox has a width of 30 the first column is stretched to a width of 30. It is possible to place textBox so that it occupies all columns by using the columnspan parameter:

textBox = Text(height = 10, width = 30).grid(row = 3, column = 0, columnspan = 3)

Because listBox also has a width of 30, you should also use columnspan here:

listBox = Listbox(width = 30).grid(row=1, column = 0, columnspan = 3)

A comprehensive guide for the grid method is here.


问:
how to type value dropdown list in SSRS?
I have a dropdown list on SSRS report.
But I have many value in filter.
So I want to type value in dropdown list  parameter.
How can I do like this?

Maybe ı can do autocomplete option in parameter. but ı don't know how can ı do:(

please help me about this issue

Thanks.

答:
maybe I can use add new parameter which type is textbox
so I can show use dropdown and textbox field for one parameter in same report.
but I could not find How can I do like this
I want to have two options.

1- If users want to use dropdown list for order they should use dropdown list parameter and textbox must be invalid or
textbox must be set in dropdown value.

2 - Or if users want to type with keyboard manuelly for order, dropdown list must be invalid or dropdown must be show just type in textbox value.
I added screenshot.

Do you have some suggestions? How can I do like this?
My customers want to use dropdown list and type in manuelly in textbox for same parameter on one report.

Thanks.


问:
PowerShell select-xml xpath doesn't seem to work
I'm trying to use select-xml to root out a few things from a SharePoint solution.  I have a solution directory that contains a number of features, and rather than open each feature.xml and select names of features by hand and put them in a list, I was hoping to do the equivalent using powershell and select-xml.

My attempt went something like this:

```<code>ls -recurse -filter feature.xml | select-xml "/Feature"
</code>```

and I got nothing, so I tried this:

```<code>ls -recurse -filter feature.xml | select-xml "//*"
</code>```

which seemed to do what it was supposed to do.  I got a list of every XML node in all the feature.xml files in my solution.

I tried XPath expressions like "//Feature" and "Feature", none of which got any results.

It seems to me that my XPath expressions are right, but the behavior of select-xml is a bit bewildering.  Anyone know why this might be happening?

答:
Even a "default" namespace has to be specified to Select-Xml e.g.:</p>

```<code>$ns = @{dns = 'http://schemas.microsoft.com/sharepoint/'}
ls . -r feature.xml | Select-Xml '//dns:Feature' -Namespace $ns
</code>```

Body:
I'm trying to use select-xml to root out a few things from a SharePoint solution.  I have a solution directory that contains a number of features, and rather than open each feature.xml and select names of features by hand and put them in a list, I was hoping to do the equivalent using powershell and select-xml.

My attempt went something like this:

ls -recurse -filter feature.xml | select-xml "/Feature"

and I got nothing, so I tried this:

ls -recurse -filter feature.xml | select-xml "//*"

which seemed to do what it was supposed to do.  I got a list of every XML node in all the feature.xml files in my solution.

I tried XPath expressions like "//Feature" and "Feature", none of which got any results.

It seems to me that my XPath expressions are right, but the behavior of select-xml is a bit bewildering.  Anyone know why this might be happening?

Body:
Even a "default" namespace has to be specified to Select-Xml e.g.:

$ns = @{dns = 'http://schemas.microsoft.com/sharepoint/'}
ls . -r feature.xml | Select-Xml '//dns:Feature' -Namespace $ns


问:
Access denied when accessing the root folder of a volume
I try to access the root volume of a drive to get a list of files like this:

```<code>Directory.GetFiles(SourceFolder, FileFilter, searchOption)
</code>```

and got this error :

Additional information: Access to the path 'H:\System Volume Information' is denied.

but sub folder is okay. I try to add:

```<code><requestedExecutionLevel level="requireAdministrator" uiAccess="true" />
</code>```

to the app.manifest, and run as admin, and it still won't work.  What can I try next?

Thank you

答:
Please note while this will give you access to the folder it will likely damage your system in the process.

System Volume Information is a special folder that Windows prevents administrators from directly accessing.  In order to access this folder you will first have to open an elevated cmd prompt and run:

```<code>takeown /f "H:\System Volume Information" /R /A
</code>```

This will transfer the ownership of this folder to you.  But be careful with modifing these files as you may damage your system!

Do you require access to this folder?  Could you be more specific with what exactly you are trying to accomplish?

Body:
I try to access the root volume of a drive to get a list of files like this:

Directory.GetFiles(SourceFolder, FileFilter, searchOption)

and got this error :

Additional information: Access to the path 'H:\System Volume Information' is denied.

but sub folder is okay. I try to add:

<requestedExecutionLevel level="requireAdministrator" uiAccess="true" />

to the app.manifest, and run as admin, and it still won't work.  What can I try next?

Thank you

Body:
Please note while this will give you access to the folder it will likely damage your system in the process.

System Volume Information is a special folder that Windows prevents administrators from directly accessing.  In order to access this folder you will first have to open an elevated cmd prompt and run:

takeown /f "H:\System Volume Information" /R /A

This will transfer the ownership of this folder to you.  But be careful with modifing these files as you may damage your system!

Do you require access to this folder?  Could you be more specific with what exactly you are trying to accomplish?


问:
Sqlite Error: Expression tree is too large (maximum depth 1000)
I'm trying to do a clean export-import of a malformed sqlite file.

Using info from techblog.dorogin.com/sqliteexception-datab..., this is what I did sqlite3 oldfile:

.mode insert

.output tempfile

.dump

Then I created a new sqlite3 newfile:

.read tempfile

Error:

```<code>sqlite> .read tempfile
Error: near line 52330: Expression tree is too large (maximum depth 1000)
Error: near line 53097: Expression tree is too large (maximum depth 1000)
Error: near line 53427: Expression tree is too large (maximum depth 1000)
Error: near line 54013: Expression tree is too large (maximum depth 1000)
Error: near line 54014: Expression tree is too large (maximum depth 1000)
Error: near line 54047: Expression tree is too large (maximum depth 1000)
Error: near line 54048: Expression tree is too large (maximum depth 1000)
Error: near line 54227: Expression tree is too large (maximum depth 1000)
Error: near line 54294: Expression tree is too large (maximum depth 1000)
Error: near line 54373: Expression tree is too large (maximum depth 1000)
Error: near line 54374: Expression tree is too large (maximum depth 1000)
Error: near line 56688: Expression tree is too large (maximum depth 1000)
Error: near line 57950: Expression tree is too large (maximum depth 1000)
Error: near line 58015: Expression tree is too large (maximum depth 1000)
Error: near line 58077: Expression tree is too large (maximum depth 1000)
Error: near line 58246: Expression tree is too large (maximum depth 1000)
Error: near line 59795: Expression tree is too large (maximum depth 1000)
Error: near line 60439: Expression tree is too large (maximum depth 1000)
Error: near line 61501: Expression tree is too large (maximum depth 1000)
Error: near line 61523: Expression tree is too large (maximum depth 1000)
Error: near line 61811: Expression tree is too large (maximum depth 1000)
Error: near line 61824: Expression tree is too large (maximum depth 1000)
</code>```

In the output file, my maximum line is 35737 chars.

How can I fix this error?

What are some solutions to do a clean export-import of a malformed sqlite file?

答:
This is due to a change in version 3.18.0's sqlite3:

In the output of the ".dump" command in the CLI, quote newline and carriage-return characters using the char() function, so that they do not get eaten by end-of-line processing logic in the OS or in other command-line utilities and/or libraries.

If there are too many newline characters in a single string value, the resulting SQL expression becomes too complex.

This was fixed in version 3.19.0.
If you are still using 3.18.0, you can work around this by converting the file to use raw newlines instead:

```<code>sed -e "s/'||char(10)||'/\\n/g" < tempfile > tempfile_with_newlines
</code>```

Body:
I'm trying to do a clean export-import of a malformed sqlite file.

Using info from techblog.dorogin.com/sqliteexception-datab..., this is what I did sqlite3 oldfile:

.mode insert

.output tempfile

.dump

Then I created a new sqlite3 newfile:

.read tempfile

Error:

sqlite> .read tempfile
Error: near line 52330: Expression tree is too large (maximum depth 1000)
Error: near line 53097: Expression tree is too large (maximum depth 1000)
Error: near line 53427: Expression tree is too large (maximum depth 1000)
Error: near line 54013: Expression tree is too large (maximum depth 1000)
Error: near line 54014: Expression tree is too large (maximum depth 1000)
Error: near line 54047: Expression tree is too large (maximum depth 1000)
Error: near line 54048: Expression tree is too large (maximum depth 1000)
Error: near line 54227: Expression tree is too large (maximum depth 1000)
Error: near line 54294: Expression tree is too large (maximum depth 1000)
Error: near line 54373: Expression tree is too large (maximum depth 1000)
Error: near line 54374: Expression tree is too large (maximum depth 1000)
Error: near line 56688: Expression tree is too large (maximum depth 1000)
Error: near line 57950: Expression tree is too large (maximum depth 1000)
Error: near line 58015: Expression tree is too large (maximum depth 1000)
Error: near line 58077: Expression tree is too large (maximum depth 1000)
Error: near line 58246: Expression tree is too large (maximum depth 1000)
Error: near line 59795: Expression tree is too large (maximum depth 1000)
Error: near line 60439: Expression tree is too large (maximum depth 1000)
Error: near line 61501: Expression tree is too large (maximum depth 1000)
Error: near line 61523: Expression tree is too large (maximum depth 1000)
Error: near line 61811: Expression tree is too large (maximum depth 1000)
Error: near line 61824: Expression tree is too large (maximum depth 1000)

In the output file, my maximum line is 35737 chars.

How can I fix this error?

What are some solutions to do a clean export-import of a malformed sqlite file?

Body:
This is due to a change in version 3.18.0's sqlite3:

In the output of the ".dump" command in the CLI, quote newline and carriage-return characters using the char() function, so that they do not get eaten by end-of-line processing logic in the OS or in other command-line utilities and/or libraries.

If there are too many newline characters in a single string value, the resulting SQL expression becomes too complex.

This was fixed in version 3.19.0.
If you are still using 3.18.0, you can work around this by converting the file to use raw newlines instead:

sed -e "s/'||char(10)||'/\\n/g" < tempfile > tempfile_with_newlines


问:
$(...).DataTable is not a function even after including the js before dataTable
I have been trying to integrate a table into my website which pulls data from my database into the table on the website.
I have read all the possible solutions on the internet and couldnt fix the issue yet.

I am putting my code below to have a look.
Please point out where I'm goiing wrong in it and what can i do for it to work.

Otherwise suggest me another option to go for the same function of loading data from the database into the tables inti the HTML site.

The declarations that i have used before the code.

```<code>      <!--Import jQuery before export.js-->
<script type="text/javascript" src="//code.jquery.com/jquery.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>

<!--Data Table-->
<script type="text/javascript"  src=" //cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"  src=" //cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>

<!--Export table buttons-->
<script type="text/javascript"  src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
<script type="text/javascript"  src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>

<!--Export table button CSS-->

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">
</code>```

This is my HTML code.

```<code>        <div style="width:90%; margin:0 auto;">
        <table id="myTable">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                </tr>
            </thead>
        </table>
    </div>
</code>```

This is my Javascript code.

```<code><script>
    $(document).ready(function () {
        $('#myTable').DataTable({
            "ajax": {
                "url": "/api/medical_inventory/",
                "type": "GET",
                "datatype": "json"
            },
            "columns" : [
                    { "data": "Id", "autoWidth": true },
                    { "data": "Name", "autoWidth": true },
                ]
        });
    });
</script>
</code>```

Any help is appreciated.

Thanks in advance.

答:
You probably want to have the ajax call actually return data, and then pass that on to DataTable.  As an example:</p>

```<code>$.ajax({
    url: "/api/medical_inventory/",
    type: "GET",
    datatype: "json",
    success: function(data){
        $("#myTable").DataTable({
          data: data,
          columns : [
            { title: "Id", className: "myClass" },
            { title: "Name", className: "otherClass" },
          ]
        });
    }
});
</code>```

Body:
I have been trying to integrate a table into my website which pulls data from my database into the table on the website.
I have read all the possible solutions on the internet and couldnt fix the issue yet.

I am putting my code below to have a look.
Please point out where I'm goiing wrong in it and what can i do for it to work.

Otherwise suggest me another option to go for the same function of loading data from the database into the tables inti the HTML site.

The declarations that i have used before the code.

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">

This is my HTML code.

                    Id
                    Name

This is my Javascript code.

Any help is appreciated.

Thanks in advance.

Body:
You probably want to have the ajax call actually return data, and then pass that on to DataTable.  As an example:

$.ajax({
    url: "/api/medical_inventory/",
    type: "GET",
    datatype: "json",
    success: function(data){
        $("#myTable").DataTable({
          data: data,
          columns : [
            { title: "Id", className: "myClass" },
            { title: "Name", className: "otherClass" },
          ]
        });
    }
});


问:
How to extract a string from a cell from right to left using a specific character that occurs more than once?
Normally I would just use the RIGHT function in excel to split it by finding a specific character such as / and outputting the string that I want.

However, I am finding trouble extracting THISSTRING.txt from d/aaa/THISSTRING.txt. With only one instance of / I would just use a function such as =RIGHT(B17,LEN(B17) - FIND("/",B17))

答:
Here's one way to get the rightmost:</p>

```<code>=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",99)),99))
</code>```

Body:
Here's one way to get the rightmost:

=TRIM(RIGHT(SUBSTITUTE(A1,"/",REPT(" ",99)),99))


问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答: You could loop through all the values once, and use int.TryParse to separate them into two separate lists: one for the values where int.TryParse returned true (aka the numbers), and another list for the ones where it returned false (the non-numbers).  Then you could sort these two lists separately, and concatenate their sorted results together at the end.</p>

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.


问:
How to get part of a key in a ruby hash
How do I get 1 from a hash that looks like this?

```<code>{{1=>2} => 3}
</code>```

Title: How to get part of a key in a ruby hash

Body:
How do I get 1 from a hash that looks like this?

{{1=>2} => 3}

Body:
{{1=>2} => 3}.keys
#=> [{1=>2}]

{{1=>2} =>3 }.keys[0]
#=> {1=>2}

{{1=>2}=>3}.keys[0].keys
#=> [1]

{{1=>2}=>3}.keys[0].keys[0]
#=> 1


问:
How to dynamically create ImageButtons inside of GridView
I am trying to dynamically create ImageButtons inside of a GridView but for some reason, they are showing up as strings (as shown below). I have looked at several posts but am still unsure of the problem. I have attached my code in addition to the xml file.

Full activity:

```<code>package com.example.myname.myproject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static com.example.myname.myproject.R.id.templateGrid;

//import com.example.myname.myproject.R;

public class AdminControlTabbed extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    List<String> options = new ArrayList<String>();
    String message;
    Spinner s;
    static String [] templateIcons = {"followfacebook", "followtwitter"};
    static int [] templateResources = {R.drawable.facebookblock, R.drawable.twitterblock};
    String [] defaultIcons = {"sendtext", "sendlink", "sendphone"};
    int [] defaultResources = {R.drawable.textblock, R.drawable.linkblock, R.drawable.callblock};
    static List <ImageButton> templateIButtons = new ArrayList<ImageButton>();
    List <ImageButton> defaultIButtons = new ArrayList<ImageButton>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_control_tabbed);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("My Project");
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        List<String> channels = new ArrayList<String>();
        channels.add("Channel 1");
        channels.add("Channel 2");
        channels.add("Channel 3");
        s = (Spinner) findViewById(R.id.channelselector);
        ArrayAdapter a = new ArrayAdapter(this, android.R.layout.simple_spinner_item, channels);
        s.setAdapter(a);
        /*ImageButton linkButton = (ImageButton) findViewById(R.id.sendLink);
        linkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(2);
            }
        });
        ImageButton textButton = (ImageButton) findViewById(R.id.sendText);
        textButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(1);
            }
        });
        ImageButton callButton = (ImageButton) findViewById(R.id.sendCall);
        callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(0);
            }
        });*/
    }

    public void sendMessage(int position, String message){
        StringTokenizer t = new StringTokenizer(s.getSelectedItem().toString());
        t.nextToken();
        String channel = (t.nextToken());
        if (position == 0){
            try{new FirebaseSendMessage().execute(channel, "Phone | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 1){
            try{new FirebaseSendMessage().execute(channel, "Banner | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 2){
            try{new FirebaseSendMessage().execute(channel, "Link | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
    }

    public void showMessageInput(final int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(AdminControlTabbed.this);
        builder.setTitle("Message Information");

        final EditText input = new EditText(AdminControlTabbed.this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                message = input.getText().toString();
                sendMessage(position, message);
            }
        });
        builder.show();
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_admin_control_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);

            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            int vNum = (int) getArguments().get(ARG_SECTION_NUMBER);
            View rootView = null;

            switch (vNum) {
                case 1:
                    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                    for (int i = 0; i < templateIcons.length; i++){
                        templateIButtons.add(new ImageButton(getContext()));
                        templateIButtons.get(i).setImageResource(templateResources[i]);
                        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                        templateIButtons.get(i).setId(i);
                    }
                    break;
                case 2:
                    rootView = inflater.inflate(R.layout.fragmentdefault_admin_control_tabbed, container, false);
                    break;

                default: //
            }
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Template";
                case 1:
                    return "Default";
            }
            return null;
        }
    }
}

rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                for (int i = 0; i < templateIcons.length; i++){
                    templateIButtons.add(new ImageButton(getContext()));
                    templateIButtons.get(i).setImageResource(templateResources[i]);
                    templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                    templateIButtons.get(i).setId(i);
                }
</code>```

GridView inside XML File

```<code><GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />
</code>```

答:
Try updating your switch case 1 statement as follows:</p>

```<code>case 1:
    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);

    for (int i = 0; i < templateIcons.length; i++){
        templateIButtons.add(new ImageButton(getContext()));
        templateIButtons.get(i).setImageResource(templateResources[i]);
        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
        templateIButtons.get(i).setId(i);
    }

    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

    break;
</code>```

Body:
I am trying to dynamically create ImageButtons inside of a GridView but for some reason, they are showing up as strings (as shown below). I have looked at several posts but am still unsure of the problem. I have attached my code in addition to the xml file.

Full activity:

package com.example.myname.myproject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static com.example.myname.myproject.R.id.templateGrid;

//import com.example.myname.myproject.R;

public class AdminControlTabbed extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    List<String> options = new ArrayList<String>();
    String message;
    Spinner s;
    static String [] templateIcons = {"followfacebook", "followtwitter"};
    static int [] templateResources = {R.drawable.facebookblock, R.drawable.twitterblock};
    String [] defaultIcons = {"sendtext", "sendlink", "sendphone"};
    int [] defaultResources = {R.drawable.textblock, R.drawable.linkblock, R.drawable.callblock};
    static List <ImageButton> templateIButtons = new ArrayList<ImageButton>();
    List <ImageButton> defaultIButtons = new ArrayList<ImageButton>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_control_tabbed);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("My Project");
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        List<String> channels = new ArrayList<String>();
        channels.add("Channel 1");
        channels.add("Channel 2");
        channels.add("Channel 3");
        s = (Spinner) findViewById(R.id.channelselector);
        ArrayAdapter a = new ArrayAdapter(this, android.R.layout.simple_spinner_item, channels);
        s.setAdapter(a);
        /*ImageButton linkButton = (ImageButton) findViewById(R.id.sendLink);
        linkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(2);
            }
        });
        ImageButton textButton = (ImageButton) findViewById(R.id.sendText);
        textButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(1);
            }
        });
        ImageButton callButton = (ImageButton) findViewById(R.id.sendCall);
        callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(0);
            }
        });*/
    }

    public void sendMessage(int position, String message){
        StringTokenizer t = new StringTokenizer(s.getSelectedItem().toString());
        t.nextToken();
        String channel = (t.nextToken());
        if (position == 0){
            try{new FirebaseSendMessage().execute(channel, "Phone | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 1){
            try{new FirebaseSendMessage().execute(channel, "Banner | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 2){
            try{new FirebaseSendMessage().execute(channel, "Link | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
    }

    public void showMessageInput(final int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(AdminControlTabbed.this);
        builder.setTitle("Message Information");

        final EditText input = new EditText(AdminControlTabbed.this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                message = input.getText().toString();
                sendMessage(position, message);
            }
        });
        builder.show();
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_admin_control_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);

            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            int vNum = (int) getArguments().get(ARG_SECTION_NUMBER);
            View rootView = null;

            switch (vNum) {
                case 1:
                    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                    for (int i = 0; i < templateIcons.length; i++){
                        templateIButtons.add(new ImageButton(getContext()));
                        templateIButtons.get(i).setImageResource(templateResources[i]);
                        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                        templateIButtons.get(i).setId(i);
                    }
                    break;
                case 2:
                    rootView = inflater.inflate(R.layout.fragmentdefault_admin_control_tabbed, container, false);
                    break;

                default: //
            }
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Template";
                case 1:
                    return "Default";
            }
            return null;
        }
    }
}

rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                for (int i = 0; i < templateIcons.length; i++){
                    templateIButtons.add(new ImageButton(getContext()));
                    templateIButtons.get(i).setImageResource(templateResources[i]);
                    templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                    templateIButtons.get(i).setId(i);
                }

GridView inside XML File

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />

Body:
Try updating your switch case 1 statement as follows:

case 1:
    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);

    for (int i = 0; i < templateIcons.length; i++){
        templateIButtons.add(new ImageButton(getContext()));
        templateIButtons.get(i).setImageResource(templateResources[i]);
        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
        templateIButtons.get(i).setId(i);
    }

    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

    break;