qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | I did it with 2 lines in powershell.
```
$versionText=(Get-Item MyProgram.exe).VersionInfo.FileVersion
(Get-Content MySetup.vdproj.template).replace('${VERSION}', $($versionText)) | Set-Content MySetup.vdproj
```
Rename your existing .vdproj to be MySetup.vdproj.template and insert "${VERSION}" wherever you want to insert the version of your primary exe file.
VS will then detect the change in the vdproj file and ask you if you want to reload it. | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"
/*
* That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
* You can let the IDE make one for you with Project + Add Reference, COM tab,
* select "Microsoft Windows Installer Object Library".
*/
namespace PostBuildEventModifyMSI
{
/* Post build event fro Rename MSI file.
* $(SolutionDir)PostBuildEventModifyMSI\bin\Debug\PostBuildEventModifyMSI.exe "$(SolutionDir)TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi"
*/
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class Program
{
static void Main(string[] args)
{
#region New code.
string msiFilePath = string.Empty;
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file complete path:");
msiFilePath = Console.ReadLine();
}
else
{
Console.WriteLine("Argument Received args[0]: " + args[0]);
msiFilePath = args[0];
}
StringBuilder sb = new StringBuilder();
string[] words = msiFilePath.Split('\\');
foreach (string word in words)
{
sb.Append(word + '\\');
if (word.Contains("Debug"))
{
break;
}
else
{
}
}
// Open a view on the Property table for the Label property
//UPDATE Property set Value = '2.06.36' where Property = 'ProductVersion'
Program p = new Program();
string version = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");
string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, version);
Console.WriteLine("Original MSI File Path: " + msiFilePath);
Console.WriteLine("New MSI File Path: " + newMSIpath);
System.IO.File.Move(msiFilePath, newMSIpath);
#endregion
//Console.Read();
}
private string GetMsiVersionProperty(string msiFilePath, string property)
{
string retVal = string.Empty;
// Create an Installer instance
WindowsInstaller.Installer installer = (WindowsInstaller.Installer) new Installer();
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = db.OpenView(sql);
//View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
return retVal;
}
}
}
``` |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | Not sure whether you still require this or not but wanted answer this as we did similar kind of operation in the postbuild event. As far as the research I did this is not possible to set the file name as you want internally through setup process.
You can do this in other way by naming the output file through an external application in post build event.
Here is what you can do:
In the post build event ->
>
> [MsiRenamerAppPath]\MsiRenamer.exe "$(BuildOutputPath)"
>
>
>
Create an application which will rename the msi file with the version number from the deployment project. Following is the code used for the application. This should fulfill your requirement I guess.
Getting msi properties code is used from [alteridem article](http://www.alteridem.net/2008/05/20/read-properties-from-an-msi-file/)
```cs
class MsiRenamer
{
static void Main(string[] args)
{
string inputFile;
string productName = "[ProductName]";
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file:");
inputFile = Console.ReadLine();
}
else
{
inputFile = args[0];
}
try
{
string version;
if (inputFile.EndsWith(".msi", StringComparison.OrdinalIgnoreCase))
{
// Read the MSI property
version = GetMsiProperty(inputFile, "ProductVersion");
productName = GetMsiProperty(inputFile, "ProductName");
}
else
{
return;
}
// Edit: MarkLakata: .msi extension is added back to filename
File.Copy(inputFile, string.Format("{0} {1}.msi", productName, version));
File.Delete(inputFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static string GetMsiProperty(string msiFile, string property)
{
string retVal = string.Empty;
// Create an Installer instance
Type classType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Object installerObj = Activator.CreateInstance(classType);
Installer installer = installerObj as Installer;
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database database = installer.OpenDatabase(msiFile, 0);
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = database.OpenView(sql);
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(database);
return retVal;
}
}
``` | If you use a WIX project (as opposed to a VS Setup & Deployment project) then [this article](http://blog.tentaclesoftware.com/archive/2009/05/03/38.aspx) explains exactly how to achieve what you are after. |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | If you use a WIX project (as opposed to a VS Setup & Deployment project) then [this article](http://blog.tentaclesoftware.com/archive/2009/05/03/38.aspx) explains exactly how to achieve what you are after. | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"
/*
* That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
* You can let the IDE make one for you with Project + Add Reference, COM tab,
* select "Microsoft Windows Installer Object Library".
*/
namespace PostBuildEventModifyMSI
{
/* Post build event fro Rename MSI file.
* $(SolutionDir)PostBuildEventModifyMSI\bin\Debug\PostBuildEventModifyMSI.exe "$(SolutionDir)TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi"
*/
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class Program
{
static void Main(string[] args)
{
#region New code.
string msiFilePath = string.Empty;
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file complete path:");
msiFilePath = Console.ReadLine();
}
else
{
Console.WriteLine("Argument Received args[0]: " + args[0]);
msiFilePath = args[0];
}
StringBuilder sb = new StringBuilder();
string[] words = msiFilePath.Split('\\');
foreach (string word in words)
{
sb.Append(word + '\\');
if (word.Contains("Debug"))
{
break;
}
else
{
}
}
// Open a view on the Property table for the Label property
//UPDATE Property set Value = '2.06.36' where Property = 'ProductVersion'
Program p = new Program();
string version = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");
string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, version);
Console.WriteLine("Original MSI File Path: " + msiFilePath);
Console.WriteLine("New MSI File Path: " + newMSIpath);
System.IO.File.Move(msiFilePath, newMSIpath);
#endregion
//Console.Read();
}
private string GetMsiVersionProperty(string msiFilePath, string property)
{
string retVal = string.Empty;
// Create an Installer instance
WindowsInstaller.Installer installer = (WindowsInstaller.Installer) new Installer();
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = db.OpenView(sql);
//View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
return retVal;
}
}
}
``` |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | I didn't want to use the .exe method above and had a little time spare so I started diggind around. I'm using VS 2008 on Windows 7 64 bit. When I have a Setup project, lets call it MySetup all the details of the project can be found in the file $(ProjectDir)MySetup.vdproj.
The product version will be found on a single line in that file in the form
```
ProductVersion="8:1.0.0"
```
Now, there IS a post-build event on a setup project. If you select a setup project and hit F4 you get a completely different set of properties to when you right-click and select properties. After hitting F4 you'll see that one of the is PostBuildEvent. Again assuming that the setup project is called MySetup the following will set the name of the .msi to include the date and the version
```
set datevar=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
findstr /v PostBuildEvent $(ProjectDir)MySetup.vdproj | findstr ProductVersion >$(ProjectDir)version.txt
set /p var=<$(ProjectDir)version.txt
set var=%var:"=%
set var=%var: =%
set var=%var:.=_%
for /f "tokens=1,2 delims=:" %%i in ("%var%") do @echo %%j >$(ProjectDir)version.txt
set /p realvar=<$(ProjectDir)version.txt
rename "$(ProjectDir)$(Configuration)\MySetup.msi" "MySetup-%datevar%-%realvar%.msi"
```
I'll take you through the above.
datevar is the current date in the form YYYYMMDD.
The findstr line goes through MySetup.vdproj, removes any line with PostBuildEvent in, then returns the single line left with productVersion in, and outputs it to a file.
We then remove the quotes, spaces, turn dots into underscores.
The for line splits the remaining string on colon, and takes the second part, and outputs it to a file again.
We then set realvar to the value left in the file, and rename MySetup.msi to include the date and version.
So, given the ProductVersion above, if it was 27th March 2012 the file would be renamed to
```
MySetup-20120327-1_0_0.msi
```
Clearly using this method you could grab ANY of the variables in the vdproj file and include them in your output file name and we don't have to build any extra .exe programs to do it.
HTH | If you use a WIX project (as opposed to a VS Setup & Deployment project) then [this article](http://blog.tentaclesoftware.com/archive/2009/05/03/38.aspx) explains exactly how to achieve what you are after. |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | Not sure whether you still require this or not but wanted answer this as we did similar kind of operation in the postbuild event. As far as the research I did this is not possible to set the file name as you want internally through setup process.
You can do this in other way by naming the output file through an external application in post build event.
Here is what you can do:
In the post build event ->
>
> [MsiRenamerAppPath]\MsiRenamer.exe "$(BuildOutputPath)"
>
>
>
Create an application which will rename the msi file with the version number from the deployment project. Following is the code used for the application. This should fulfill your requirement I guess.
Getting msi properties code is used from [alteridem article](http://www.alteridem.net/2008/05/20/read-properties-from-an-msi-file/)
```cs
class MsiRenamer
{
static void Main(string[] args)
{
string inputFile;
string productName = "[ProductName]";
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file:");
inputFile = Console.ReadLine();
}
else
{
inputFile = args[0];
}
try
{
string version;
if (inputFile.EndsWith(".msi", StringComparison.OrdinalIgnoreCase))
{
// Read the MSI property
version = GetMsiProperty(inputFile, "ProductVersion");
productName = GetMsiProperty(inputFile, "ProductName");
}
else
{
return;
}
// Edit: MarkLakata: .msi extension is added back to filename
File.Copy(inputFile, string.Format("{0} {1}.msi", productName, version));
File.Delete(inputFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static string GetMsiProperty(string msiFile, string property)
{
string retVal = string.Empty;
// Create an Installer instance
Type classType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
Object installerObj = Activator.CreateInstance(classType);
Installer installer = installerObj as Installer;
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database database = installer.OpenDatabase(msiFile, 0);
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = database.OpenView(sql);
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(database);
return retVal;
}
}
``` | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"
/*
* That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
* You can let the IDE make one for you with Project + Add Reference, COM tab,
* select "Microsoft Windows Installer Object Library".
*/
namespace PostBuildEventModifyMSI
{
/* Post build event fro Rename MSI file.
* $(SolutionDir)PostBuildEventModifyMSI\bin\Debug\PostBuildEventModifyMSI.exe "$(SolutionDir)TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi"
*/
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class Program
{
static void Main(string[] args)
{
#region New code.
string msiFilePath = string.Empty;
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file complete path:");
msiFilePath = Console.ReadLine();
}
else
{
Console.WriteLine("Argument Received args[0]: " + args[0]);
msiFilePath = args[0];
}
StringBuilder sb = new StringBuilder();
string[] words = msiFilePath.Split('\\');
foreach (string word in words)
{
sb.Append(word + '\\');
if (word.Contains("Debug"))
{
break;
}
else
{
}
}
// Open a view on the Property table for the Label property
//UPDATE Property set Value = '2.06.36' where Property = 'ProductVersion'
Program p = new Program();
string version = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");
string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, version);
Console.WriteLine("Original MSI File Path: " + msiFilePath);
Console.WriteLine("New MSI File Path: " + newMSIpath);
System.IO.File.Move(msiFilePath, newMSIpath);
#endregion
//Console.Read();
}
private string GetMsiVersionProperty(string msiFilePath, string property)
{
string retVal = string.Empty;
// Create an Installer instance
WindowsInstaller.Installer installer = (WindowsInstaller.Installer) new Installer();
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = db.OpenView(sql);
//View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
return retVal;
}
}
}
``` |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | I didn't want to use the .exe method above and had a little time spare so I started diggind around. I'm using VS 2008 on Windows 7 64 bit. When I have a Setup project, lets call it MySetup all the details of the project can be found in the file $(ProjectDir)MySetup.vdproj.
The product version will be found on a single line in that file in the form
```
ProductVersion="8:1.0.0"
```
Now, there IS a post-build event on a setup project. If you select a setup project and hit F4 you get a completely different set of properties to when you right-click and select properties. After hitting F4 you'll see that one of the is PostBuildEvent. Again assuming that the setup project is called MySetup the following will set the name of the .msi to include the date and the version
```
set datevar=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
findstr /v PostBuildEvent $(ProjectDir)MySetup.vdproj | findstr ProductVersion >$(ProjectDir)version.txt
set /p var=<$(ProjectDir)version.txt
set var=%var:"=%
set var=%var: =%
set var=%var:.=_%
for /f "tokens=1,2 delims=:" %%i in ("%var%") do @echo %%j >$(ProjectDir)version.txt
set /p realvar=<$(ProjectDir)version.txt
rename "$(ProjectDir)$(Configuration)\MySetup.msi" "MySetup-%datevar%-%realvar%.msi"
```
I'll take you through the above.
datevar is the current date in the form YYYYMMDD.
The findstr line goes through MySetup.vdproj, removes any line with PostBuildEvent in, then returns the single line left with productVersion in, and outputs it to a file.
We then remove the quotes, spaces, turn dots into underscores.
The for line splits the remaining string on colon, and takes the second part, and outputs it to a file again.
We then set realvar to the value left in the file, and rename MySetup.msi to include the date and version.
So, given the ProductVersion above, if it was 27th March 2012 the file would be renamed to
```
MySetup-20120327-1_0_0.msi
```
Clearly using this method you could grab ANY of the variables in the vdproj file and include them in your output file name and we don't have to build any extra .exe programs to do it.
HTH | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"
/*
* That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
* You can let the IDE make one for you with Project + Add Reference, COM tab,
* select "Microsoft Windows Installer Object Library".
*/
namespace PostBuildEventModifyMSI
{
/* Post build event fro Rename MSI file.
* $(SolutionDir)PostBuildEventModifyMSI\bin\Debug\PostBuildEventModifyMSI.exe "$(SolutionDir)TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi"
*/
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class Program
{
static void Main(string[] args)
{
#region New code.
string msiFilePath = string.Empty;
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file complete path:");
msiFilePath = Console.ReadLine();
}
else
{
Console.WriteLine("Argument Received args[0]: " + args[0]);
msiFilePath = args[0];
}
StringBuilder sb = new StringBuilder();
string[] words = msiFilePath.Split('\\');
foreach (string word in words)
{
sb.Append(word + '\\');
if (word.Contains("Debug"))
{
break;
}
else
{
}
}
// Open a view on the Property table for the Label property
//UPDATE Property set Value = '2.06.36' where Property = 'ProductVersion'
Program p = new Program();
string version = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");
string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, version);
Console.WriteLine("Original MSI File Path: " + msiFilePath);
Console.WriteLine("New MSI File Path: " + newMSIpath);
System.IO.File.Move(msiFilePath, newMSIpath);
#endregion
//Console.Read();
}
private string GetMsiVersionProperty(string msiFilePath, string property)
{
string retVal = string.Empty;
// Create an Installer instance
WindowsInstaller.Installer installer = (WindowsInstaller.Installer) new Installer();
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = db.OpenView(sql);
//View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
return retVal;
}
}
}
``` |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | Same concept as Jim Grimmett's answer, but with less dependencies:
```
FOR /F "tokens=2 delims== " %%V IN ('FINDSTR /B /R /C:" *\"ProductVersion\"" "$(ProjectDir)MySetupProjectName.vdproj"') DO FOR %%I IN ("$(BuiltOuputPath)") DO REN "$(BuiltOuputPath)" "%%~nI-%%~nxV%%~xI"
```
### Some points of note:
`MySetupProjectName.vdproj` should be changed to the name of your project file. Forgetting to change this results in a build error: `'PostBuildEvent' failed with error code '1'` and the `Output` window shows which file `FINDSTR` could not open.
### Step by step description:
`FINDSTR /B /R /C:" *\"ProductVersion\"" $(ProjectDir)MySetupProjectName.vdproj`
* This finds the `"ProductVersion" = "8:x.y.z.etc"` line from the project file.
`FOR /F "tokens=2 delims== " %%V IN (...) DO ... %%~nxV ...`
* This is used to parse out the `x.y.z.etc` part from the above result.
`$(BuiltOuputPath)`
* This is the original output path, as per what it says in Post-build Event Command Line's "Macros".
`FOR %%I IN (...) DO ... %%~nI-%%~nxV%%~xI`
* This is used to convert the string `foo.msi` to `foo-x.y.z.etc.msi`.
`REN "$(BuiltOuputPath)" ...`
* This just renames the output path to the new name.
`FOR ... DO FOR .. DO REN ...`
* It's written on one line like this so that an error along way cleanly breaks the build. | ```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;
// cscript //nologo "$(ProjectDir)WiRunSql.vbs" "$(BuiltOuputPath)" "UPDATE `Property` SET `Property`.`Value`='4.0.0.1' WHERE `Property`='ProductVersion'"
// "SELECT `Property`.`ProductVersion` FROM `Property` WHERE `Property`.`Property` = 'ProductVersion'"
/*
* That's a .NET wrapper generated by tlbimp.exe, wrapping the ActiveX component c:\windows\system32\msi.dll.
* You can let the IDE make one for you with Project + Add Reference, COM tab,
* select "Microsoft Windows Installer Object Library".
*/
namespace PostBuildEventModifyMSI
{
/* Post build event fro Rename MSI file.
* $(SolutionDir)PostBuildEventModifyMSI\bin\Debug\PostBuildEventModifyMSI.exe "$(SolutionDir)TestWebApplicationSetup\Debug\TestWebApplicationSetup.msi"
*/
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class Program
{
static void Main(string[] args)
{
#region New code.
string msiFilePath = string.Empty;
if (args.Length == 0)
{
Console.WriteLine("Enter MSI file complete path:");
msiFilePath = Console.ReadLine();
}
else
{
Console.WriteLine("Argument Received args[0]: " + args[0]);
msiFilePath = args[0];
}
StringBuilder sb = new StringBuilder();
string[] words = msiFilePath.Split('\\');
foreach (string word in words)
{
sb.Append(word + '\\');
if (word.Contains("Debug"))
{
break;
}
else
{
}
}
// Open a view on the Property table for the Label property
//UPDATE Property set Value = '2.06.36' where Property = 'ProductVersion'
Program p = new Program();
string version = p.GetMsiVersionProperty(msiFilePath, "ProductVersion");
string productName = p.GetMsiVersionProperty(msiFilePath, "ProductName");
string newMSIpath = sb.ToString() + string.Format("{0}_{1}.msi", productName, version);
Console.WriteLine("Original MSI File Path: " + msiFilePath);
Console.WriteLine("New MSI File Path: " + newMSIpath);
System.IO.File.Move(msiFilePath, newMSIpath);
#endregion
//Console.Read();
}
private string GetMsiVersionProperty(string msiFilePath, string property)
{
string retVal = string.Empty;
// Create an Installer instance
WindowsInstaller.Installer installer = (WindowsInstaller.Installer) new Installer();
// Open the msi file for reading
// 0 - Read, 1 - Read/Write
Database db = installer.OpenDatabase(msiFilePath, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly); //// Open the MSI database in the input file
// Fetch the requested property
string sql = String.Format(
"SELECT Value FROM Property WHERE Property='{0}'", property);
View view = db.OpenView(sql);
//View vw = db.OpenView(@"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'");
view.Execute(null);
// Read in the fetched record
Record record = view.Fetch();
if (record != null)
{
retVal = record.get_StringData(1);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(record);
}
view.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(view);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
return retVal;
}
}
}
``` |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | Same concept as Jim Grimmett's answer, but with less dependencies:
```
FOR /F "tokens=2 delims== " %%V IN ('FINDSTR /B /R /C:" *\"ProductVersion\"" "$(ProjectDir)MySetupProjectName.vdproj"') DO FOR %%I IN ("$(BuiltOuputPath)") DO REN "$(BuiltOuputPath)" "%%~nI-%%~nxV%%~xI"
```
### Some points of note:
`MySetupProjectName.vdproj` should be changed to the name of your project file. Forgetting to change this results in a build error: `'PostBuildEvent' failed with error code '1'` and the `Output` window shows which file `FINDSTR` could not open.
### Step by step description:
`FINDSTR /B /R /C:" *\"ProductVersion\"" $(ProjectDir)MySetupProjectName.vdproj`
* This finds the `"ProductVersion" = "8:x.y.z.etc"` line from the project file.
`FOR /F "tokens=2 delims== " %%V IN (...) DO ... %%~nxV ...`
* This is used to parse out the `x.y.z.etc` part from the above result.
`$(BuiltOuputPath)`
* This is the original output path, as per what it says in Post-build Event Command Line's "Macros".
`FOR %%I IN (...) DO ... %%~nI-%%~nxV%%~xI`
* This is used to convert the string `foo.msi` to `foo-x.y.z.etc.msi`.
`REN "$(BuiltOuputPath)" ...`
* This just renames the output path to the new name.
`FOR ... DO FOR .. DO REN ...`
* It's written on one line like this so that an error along way cleanly breaks the build. | I did it with 2 lines in powershell.
```
$versionText=(Get-Item MyProgram.exe).VersionInfo.FileVersion
(Get-Content MySetup.vdproj.template).replace('${VERSION}', $($versionText)) | Set-Content MySetup.vdproj
```
Rename your existing .vdproj to be MySetup.vdproj.template and insert "${VERSION}" wherever you want to insert the version of your primary exe file.
VS will then detect the change in the vdproj file and ask you if you want to reload it. |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | If you use a WIX project (as opposed to a VS Setup & Deployment project) then [this article](http://blog.tentaclesoftware.com/archive/2009/05/03/38.aspx) explains exactly how to achieve what you are after. | I did it with 2 lines in powershell.
```
$versionText=(Get-Item MyProgram.exe).VersionInfo.FileVersion
(Get-Content MySetup.vdproj.template).replace('${VERSION}', $($versionText)) | Set-Content MySetup.vdproj
```
Rename your existing .vdproj to be MySetup.vdproj.template and insert "${VERSION}" wherever you want to insert the version of your primary exe file.
VS will then detect the change in the vdproj file and ask you if you want to reload it. |
3,359,974 | Is there a way to include the version number as part of the output.msi filename in a VS2008 Setup Project?
I'd like for example an output file called: "myinstaller-1.0.13.msi" where the version part is automatically set based on the version number I have put in the deployment project properties. | 2010/07/29 | [
"https://Stackoverflow.com/questions/3359974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311181/"
] | Same concept as Jim Grimmett's answer, but with less dependencies:
```
FOR /F "tokens=2 delims== " %%V IN ('FINDSTR /B /R /C:" *\"ProductVersion\"" "$(ProjectDir)MySetupProjectName.vdproj"') DO FOR %%I IN ("$(BuiltOuputPath)") DO REN "$(BuiltOuputPath)" "%%~nI-%%~nxV%%~xI"
```
### Some points of note:
`MySetupProjectName.vdproj` should be changed to the name of your project file. Forgetting to change this results in a build error: `'PostBuildEvent' failed with error code '1'` and the `Output` window shows which file `FINDSTR` could not open.
### Step by step description:
`FINDSTR /B /R /C:" *\"ProductVersion\"" $(ProjectDir)MySetupProjectName.vdproj`
* This finds the `"ProductVersion" = "8:x.y.z.etc"` line from the project file.
`FOR /F "tokens=2 delims== " %%V IN (...) DO ... %%~nxV ...`
* This is used to parse out the `x.y.z.etc` part from the above result.
`$(BuiltOuputPath)`
* This is the original output path, as per what it says in Post-build Event Command Line's "Macros".
`FOR %%I IN (...) DO ... %%~nI-%%~nxV%%~xI`
* This is used to convert the string `foo.msi` to `foo-x.y.z.etc.msi`.
`REN "$(BuiltOuputPath)" ...`
* This just renames the output path to the new name.
`FOR ... DO FOR .. DO REN ...`
* It's written on one line like this so that an error along way cleanly breaks the build. | If you use a WIX project (as opposed to a VS Setup & Deployment project) then [this article](http://blog.tentaclesoftware.com/archive/2009/05/03/38.aspx) explains exactly how to achieve what you are after. |
63,521 | Because I write many document with office word 2007 + mathtype.
I'm not request for libreoffice can edit mathtype's equations, but I want to know libreoffice can open all the office word 2007 documents or not? | 2011/09/29 | [
"https://askubuntu.com/questions/63521",
"https://askubuntu.com",
"https://askubuntu.com/users/23864/"
] | libreoffice and openoffice are just clones separated due to policy reasons. But as far as word 07 is concerned, LO or OO may sometimes may not be so faithful in reproducing the exact same effect as in Word 07.
Some formatting mismatch you can always expect. | Well, to make sure that you can use Libre Office without any problems you can easy test for it if it will work without any issues (and maybe start moving out from MS Office in to LibreOffice) using the portable version of LibreOffice.
No need for install, if it doesn't work just delete it and you are good.
You can get the portable version of LibreOffice here: <http://www.libreoffice.org/download/portable/>
Have a look and gl ;) |
63,521 | Because I write many document with office word 2007 + mathtype.
I'm not request for libreoffice can edit mathtype's equations, but I want to know libreoffice can open all the office word 2007 documents or not? | 2011/09/29 | [
"https://askubuntu.com/questions/63521",
"https://askubuntu.com",
"https://askubuntu.com/users/23864/"
] | Yes, as others have stated, you can open Word 2007 documents with LibreOffice on Ubuntu. No one addressed MathType equations though, so let me mention that...
You already realize you can't edit MathType equations on Ubuntu, so as you stated, you don't expect to. The best experience when going from Word 2007 to LibreOffice on Ubuntu though, is for the Word document to be in .doc format -- not .docx. The main differences between the 2 when they're open in LibreOffice are fonts and alignment of the MathType equations.
When you save as .doc and open in LibreOffice, the fonts should be the same as what you used on Windows (assuming, of course, these fonts are present in Ubuntu). The equations should have roughly the same vertical alignment with surrounding text as they did in Word. With .docx, the fonts may be substituted, and the equations will be shifted up so the bottom of the equation is aligned with the baseline of the text.
There may also be an issue with the fonts used in the MathType equations. If some of the symbols don't show up, there are two things to check. First, check that the font MT Extra is installed in Ubuntu. If it is, make sure it's not a version that's dated earlier than 2001. If it's an old version, delete it and replace it with the one from your Windows installation of MathType. The second thing to check is whether you've installed the Ubuntu Restricted Extras, available from the Software Center. This includes additional Microsoft fonts. | Well, to make sure that you can use Libre Office without any problems you can easy test for it if it will work without any issues (and maybe start moving out from MS Office in to LibreOffice) using the portable version of LibreOffice.
No need for install, if it doesn't work just delete it and you are good.
You can get the portable version of LibreOffice here: <http://www.libreoffice.org/download/portable/>
Have a look and gl ;) |
63,521 | Because I write many document with office word 2007 + mathtype.
I'm not request for libreoffice can edit mathtype's equations, but I want to know libreoffice can open all the office word 2007 documents or not? | 2011/09/29 | [
"https://askubuntu.com/questions/63521",
"https://askubuntu.com",
"https://askubuntu.com/users/23864/"
] | libreoffice and openoffice are just clones separated due to policy reasons. But as far as word 07 is concerned, LO or OO may sometimes may not be so faithful in reproducing the exact same effect as in Word 07.
Some formatting mismatch you can always expect. | Yes, as others have stated, you can open Word 2007 documents with LibreOffice on Ubuntu. No one addressed MathType equations though, so let me mention that...
You already realize you can't edit MathType equations on Ubuntu, so as you stated, you don't expect to. The best experience when going from Word 2007 to LibreOffice on Ubuntu though, is for the Word document to be in .doc format -- not .docx. The main differences between the 2 when they're open in LibreOffice are fonts and alignment of the MathType equations.
When you save as .doc and open in LibreOffice, the fonts should be the same as what you used on Windows (assuming, of course, these fonts are present in Ubuntu). The equations should have roughly the same vertical alignment with surrounding text as they did in Word. With .docx, the fonts may be substituted, and the equations will be shifted up so the bottom of the equation is aligned with the baseline of the text.
There may also be an issue with the fonts used in the MathType equations. If some of the symbols don't show up, there are two things to check. First, check that the font MT Extra is installed in Ubuntu. If it is, make sure it's not a version that's dated earlier than 2001. If it's an old version, delete it and replace it with the one from your Windows installation of MathType. The second thing to check is whether you've installed the Ubuntu Restricted Extras, available from the Software Center. This includes additional Microsoft fonts. |
5,894,270 | Maybe this is supposed to not work, but at least I'd like to understand why then. I am passing a simple val=somevalue in the `PUT` body but spring sends back a `400 Bad Request` as it does not seem to recognise the val parameter.
Similar request works with `POST`. Could it be *SpringMVC* is not recognizing the `PUT` request body as source for parameters?
`Content=-Type` is set correctly to application/x-www-form-urlencoded in both cases.
The method that spring refuses to call is this:
```
@RequestMapping(value = "config/{key}", method = RequestMethod.PUT)
@ResponseBody
public void configUpdateCreate(final Model model, @PathVariable final String key, @RequestParam final String val,
final HttpServletResponse response) throws IOException
{
//...
}
```
For completeness, here is the jquery ajax call. I cannot see anything wrong with that. Client is Firefox 4 or Chrome, both show the same result.
```
$.ajax({
url:url,
type:'PUT',
data:'val=' + encodeURIComponent(configValue),
success: function(data) {...}
});
```
Any ideas? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320938/"
] | I don't know of a work around at this point, but here is the bug report that is a "Won't Fix." I've been fighting the same issue
<https://jira.springsource.org/browse/SPR-7414>
Update: Here is my fix. I'm using RequestBody annotation. Then using MultiValueMap.
<http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/mvc.html#mvc-ann-requestbody>
```
@RequestMapping(value = "/{tc}", method = RequestMethod.PUT)
public void update(@PathVariable("tc") final String tc,
@RequestBody MultiValueMap<String,String> body, HttpServletResponse response) {
String name = body.getFirst("name");
// more code
}
``` | I don't have right solution for you, but in your case I try following:
* create page with `form:form method="PUT"`
* declare `HiddenHttpMethodFilter` in `web.xml`
If this will works, then
* change `type` from `PUT` to `POST` in ajax call
* add needed params which client has with `form:form` tag (something like `_method`)
In other words, as I understand Spring emulates `PUT` based on simple `POST` with special parameter. Just send to him what he wants.
See also: <http://stsmedia.net/spring-finance-part-2-spring-mvc-spring-30-rest-integration/> and related code examples there: <http://code.google.com/p/spring-finance-manager/source/browse>
HTH |
5,894,270 | Maybe this is supposed to not work, but at least I'd like to understand why then. I am passing a simple val=somevalue in the `PUT` body but spring sends back a `400 Bad Request` as it does not seem to recognise the val parameter.
Similar request works with `POST`. Could it be *SpringMVC* is not recognizing the `PUT` request body as source for parameters?
`Content=-Type` is set correctly to application/x-www-form-urlencoded in both cases.
The method that spring refuses to call is this:
```
@RequestMapping(value = "config/{key}", method = RequestMethod.PUT)
@ResponseBody
public void configUpdateCreate(final Model model, @PathVariable final String key, @RequestParam final String val,
final HttpServletResponse response) throws IOException
{
//...
}
```
For completeness, here is the jquery ajax call. I cannot see anything wrong with that. Client is Firefox 4 or Chrome, both show the same result.
```
$.ajax({
url:url,
type:'PUT',
data:'val=' + encodeURIComponent(configValue),
success: function(data) {...}
});
```
Any ideas? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320938/"
] | [Since](https://jira.springsource.org/browse/SPR-5628) Spring 3.1, this is resolved using [org.springframework.web.filter.HttpPutFormContentFilter](http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/filter/HttpPutFormContentFilter.html).
```
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>rest</servlet-name>
</filter-mapping>
``` | I don't have right solution for you, but in your case I try following:
* create page with `form:form method="PUT"`
* declare `HiddenHttpMethodFilter` in `web.xml`
If this will works, then
* change `type` from `PUT` to `POST` in ajax call
* add needed params which client has with `form:form` tag (something like `_method`)
In other words, as I understand Spring emulates `PUT` based on simple `POST` with special parameter. Just send to him what he wants.
See also: <http://stsmedia.net/spring-finance-part-2-spring-mvc-spring-30-rest-integration/> and related code examples there: <http://code.google.com/p/spring-finance-manager/source/browse>
HTH |
5,894,270 | Maybe this is supposed to not work, but at least I'd like to understand why then. I am passing a simple val=somevalue in the `PUT` body but spring sends back a `400 Bad Request` as it does not seem to recognise the val parameter.
Similar request works with `POST`. Could it be *SpringMVC* is not recognizing the `PUT` request body as source for parameters?
`Content=-Type` is set correctly to application/x-www-form-urlencoded in both cases.
The method that spring refuses to call is this:
```
@RequestMapping(value = "config/{key}", method = RequestMethod.PUT)
@ResponseBody
public void configUpdateCreate(final Model model, @PathVariable final String key, @RequestParam final String val,
final HttpServletResponse response) throws IOException
{
//...
}
```
For completeness, here is the jquery ajax call. I cannot see anything wrong with that. Client is Firefox 4 or Chrome, both show the same result.
```
$.ajax({
url:url,
type:'PUT',
data:'val=' + encodeURIComponent(configValue),
success: function(data) {...}
});
```
Any ideas? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320938/"
] | I don't know of a work around at this point, but here is the bug report that is a "Won't Fix." I've been fighting the same issue
<https://jira.springsource.org/browse/SPR-7414>
Update: Here is my fix. I'm using RequestBody annotation. Then using MultiValueMap.
<http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/mvc.html#mvc-ann-requestbody>
```
@RequestMapping(value = "/{tc}", method = RequestMethod.PUT)
public void update(@PathVariable("tc") final String tc,
@RequestBody MultiValueMap<String,String> body, HttpServletResponse response) {
String name = body.getFirst("name");
// more code
}
``` | This, as suggest above, seems to be a bug in `spring/servlet API`. In reality `PUT` requests are supposed to work on `Request Body (or payload)` and not on Request Parameters. In that sense, servlet API & spring's handling is correct.
Having said that, a better and much easier workaround is to pass no data element from your `javascript/jQuery` call and pass your parameters as part of the url itself. meaning, set parameters in the url field the way you would do in a `GET` call.
```
$.ajax({
url: "yoururl" + "?param1=param2Val&..",
type: "PUT",
data: "",
success: function(response) {
// ....
}
});
```
now this works for simple parameters, i guess, will not work for complex JSON types. Hope this helps. |
5,894,270 | Maybe this is supposed to not work, but at least I'd like to understand why then. I am passing a simple val=somevalue in the `PUT` body but spring sends back a `400 Bad Request` as it does not seem to recognise the val parameter.
Similar request works with `POST`. Could it be *SpringMVC* is not recognizing the `PUT` request body as source for parameters?
`Content=-Type` is set correctly to application/x-www-form-urlencoded in both cases.
The method that spring refuses to call is this:
```
@RequestMapping(value = "config/{key}", method = RequestMethod.PUT)
@ResponseBody
public void configUpdateCreate(final Model model, @PathVariable final String key, @RequestParam final String val,
final HttpServletResponse response) throws IOException
{
//...
}
```
For completeness, here is the jquery ajax call. I cannot see anything wrong with that. Client is Firefox 4 or Chrome, both show the same result.
```
$.ajax({
url:url,
type:'PUT',
data:'val=' + encodeURIComponent(configValue),
success: function(data) {...}
});
```
Any ideas? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320938/"
] | I don't know of a work around at this point, but here is the bug report that is a "Won't Fix." I've been fighting the same issue
<https://jira.springsource.org/browse/SPR-7414>
Update: Here is my fix. I'm using RequestBody annotation. Then using MultiValueMap.
<http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/mvc.html#mvc-ann-requestbody>
```
@RequestMapping(value = "/{tc}", method = RequestMethod.PUT)
public void update(@PathVariable("tc") final String tc,
@RequestBody MultiValueMap<String,String> body, HttpServletResponse response) {
String name = body.getFirst("name");
// more code
}
``` | [Since](https://jira.springsource.org/browse/SPR-5628) Spring 3.1, this is resolved using [org.springframework.web.filter.HttpPutFormContentFilter](http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/filter/HttpPutFormContentFilter.html).
```
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>rest</servlet-name>
</filter-mapping>
``` |
5,894,270 | Maybe this is supposed to not work, but at least I'd like to understand why then. I am passing a simple val=somevalue in the `PUT` body but spring sends back a `400 Bad Request` as it does not seem to recognise the val parameter.
Similar request works with `POST`. Could it be *SpringMVC* is not recognizing the `PUT` request body as source for parameters?
`Content=-Type` is set correctly to application/x-www-form-urlencoded in both cases.
The method that spring refuses to call is this:
```
@RequestMapping(value = "config/{key}", method = RequestMethod.PUT)
@ResponseBody
public void configUpdateCreate(final Model model, @PathVariable final String key, @RequestParam final String val,
final HttpServletResponse response) throws IOException
{
//...
}
```
For completeness, here is the jquery ajax call. I cannot see anything wrong with that. Client is Firefox 4 or Chrome, both show the same result.
```
$.ajax({
url:url,
type:'PUT',
data:'val=' + encodeURIComponent(configValue),
success: function(data) {...}
});
```
Any ideas? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5894270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/320938/"
] | [Since](https://jira.springsource.org/browse/SPR-5628) Spring 3.1, this is resolved using [org.springframework.web.filter.HttpPutFormContentFilter](http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/filter/HttpPutFormContentFilter.html).
```
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>rest</servlet-name>
</filter-mapping>
``` | This, as suggest above, seems to be a bug in `spring/servlet API`. In reality `PUT` requests are supposed to work on `Request Body (or payload)` and not on Request Parameters. In that sense, servlet API & spring's handling is correct.
Having said that, a better and much easier workaround is to pass no data element from your `javascript/jQuery` call and pass your parameters as part of the url itself. meaning, set parameters in the url field the way you would do in a `GET` call.
```
$.ajax({
url: "yoururl" + "?param1=param2Val&..",
type: "PUT",
data: "",
success: function(response) {
// ....
}
});
```
now this works for simple parameters, i guess, will not work for complex JSON types. Hope this helps. |
67,414,796 | I created a parent class Repo which has methods for insert, delete, display and delete objects in a list. Repo is a generic class. I created a child classes for Repo (like DepartmentRepo class)and pass Department, Employee, etc.. classes. I want perform insert, delete, display and delete operations on any class objects that passed to Repo class.
I need to get the return value of the method "get" which is from Generic class in java. I can only get the method name from Generic here I mention the code files
```
public class Department {
private long Id;
private String Name;
private String Location;
public Department() {
}
public Department(long id, String name, String location) {
super();
Id = id;
Name = name;
Location = location;
}
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
```
```
import java.util.ArrayList;
import java.util.List;
public class Repo<T, U> {
List<T> list = new ArrayList<T>();
public List<T> getAll() {
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) throws NoSuchMethodException, SecurityException {
for (T ele : list) {
if (ele.getClass().getMethod("getId") == id) {
return ele;
}
}
return null;
}
public void delete(U id) throws NoSuchMethodException, SecurityException {
list.remove(get(id));
}
}
```
```
public class DepartmentRepo extends Repo<Department, Long>{
}
```
```
class MainApi
{
public static void main (String[] args)
{
DepartmentRepo dept = new DepartmentRepo ();
Department ict=new Department(10001,"Dept of ICT","Town");
Department cs=new Department(10002,"Dept of Computer Science","Pampaimadu");
Department bio=new Department(10003,"Dept of Bio Science","Pampaimadu");
Department sats=new Department(10004,"Dept of Statistics","Kurumankadu");
dept.insert(ict);
dept.insert(cs);
dept.insert(bio);
dept.insert(sats);
System.out.println();
dept.getAll();
try{
dept.get(10001);
}
catch(Exception e){
}
}
}
``` | 2021/05/06 | [
"https://Stackoverflow.com/questions/67414796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15850862/"
] | Have you considered using flask\_mail extension for flask. You could send an E-Mail as easy as that:
```
from flask_mail import Message
from app import mail
def send_email(subject, sender, recipients, html_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.html = html_body
mail.send(msg)
```
You should also consider sending it as an Asynchronous call, since it can take a while. You can find detailled information on how it can be implemented under the following link:
<https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support>
And please consider using SQL expression language, instead of raw SQL to prevent SQL Injection. | You have not revealed how this is failing; I would assume that the problem is that Gmail rejects the connection because you failed to do the `ehlo()` again after `startls()`. (Yes, it's a bit crazy that they require this; but they do.)
Tangentially, you should probably update your `email` code to use the Python 3.6+ `EmailMessage` module.
```py
import smtplib
from email.message import EmailMessage
# Don't put a space before the text. Fix typos.
mail_content = '''Hello,
This is a Simple mail. There is only text, no attachments are there. The mail is sent.
Thank you.'''
#The mail addresses and password
def email_alert(receiver_address):
sender_address = 'email'
sender_pass = 'password'
# Comment out, utterly pointless
# receiver_address = receiver_address
message = EmailMessage()
message['From'] = sender_address
message['to'] = receiver_address
# Don't lie i the subject
message['Subject'] = 'A test mail sent by Python. It has no attachment.'
message.set_content(mail_content)
# Use a context manager
with smtplib.SMTP('smtp.gmail.com', 587) as session:
# EHLO is required ... twice
session.ehlo()
session.starttls()
session.ehlo()
session.login(sender_address, sender_pass)
# Prefer send_message
session.send_message(message)
# Probably don't print anything
print('Mail Sent')
``` |
18,239,617 | I am trying to make a quiz app and I am new to IOS.I want to get 3 wrong answers from an array of 6 wrong answers for a specific question and there will be 1 correct answer for each question.I want to randomize the wrong options every time the question is shown.So every time the question is shown the app will choose 3 wrong options from the array and 1 correct answer.How can I code this?I would be glad if you can help me on this.
Thank you..
```
{
int counted = [theOptions count];
int i;
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:counted];
for (i=0; i<counted; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:counted];
while ([indexes count])
{
int index = rand()%[indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
NSMutableArray* shuffledOptions = [[NSMutableArray alloc] initWithCapacity:4];
for (int i=0; i<counted; i++)
{
int randomIndex = [[shuffle objectAtIndex:i] intValue];
[shuffledOptions addObject:[theOptions objectAtIndex:randomIndex]];
UIButton* optionButton = [_optionsButtonsArray objectAtIndex:i];
optionButton.tag = randomIndex;
}
return shuffledOptions;
}
return theOptions;}
``` | 2013/08/14 | [
"https://Stackoverflow.com/questions/18239617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2498271/"
] | Pass the proper format string to `DATE_FORMAT` in your query:
```
SELECT
*,
DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS the_date
FROM mystation
```
Then the formatted date will be available in a `the_date` column when you loop through your rows.
The following formatting string ,suggested by Marty McVry below, also works:
```
DATE_FORMAT(start, '%d/%m/%Y %T')
```
Reference: [DATE\_FORMAT on MySQL manual entry](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format) | Beside the solution bellow, that *is* right: WHEN working with data - in your case passing a date using a REST-API or something - you usually don't want to apply formating. You should return the data AS RAW as possible, to allow the finally processing application to Format data as required.
use the common Format '2013-08-14 20:45:00 GMT+2' ('Year-Month-Day Hour:minute:second timezone') so every Client *is able* to refactor the data retrieved in an appropriate way.
Data should be converted *the Moment* it is presented to the user - no second earlier.
(On the *raw* data Format of a date you can perform `<`, `>`, `equals` comparissions or sorting operations, without doing anything wrong.) |
53,132,550 | I have a list of lists. This is an example of how the list looks.
```
[[7]][[8]]
Prtf_Return Quantile Date
2002-07-31 -0.08161658 8 2002-07-31
2003-07-31 0.05648458 8 2003-07-31
2004-07-30 0.24751328 8 2004-07-30
2005-07-29 0.26955881 8 2005-07-29
2006-07-31 0.08099889 8 2006-07-31
2007-07-31 0.14633871 8 2007-07-31
2008-07-31 -0.02790529 8 2008-07-31
2009-07-31 -0.17913224 8 2009-07-31
2010-07-30 0.33681922 8 2010-07-30
2011-07-29 0.23411797 8 2011-07-29
2012-07-31 0.10671685 8 2012-07-31
2013-07-31 0.19845169 8 2013-07-31
2014-07-31 0.11399025 8 2014-07-31
2015-07-31 0.10308543 8 2015-07-31
2016-07-29 0.01388617 8 2016-07-29
2017-07-31 0.03685517 8 2017-07-31
2018-07-31 0.09661410 8 2018-07-31
[[7]][[9]]
Prtf_Return Quantile Date
2002-07-31 -0.02322572 9 2002-07-31
2003-07-31 0.25252339 9 2003-07-31
2004-07-30 0.26290503 9 2004-07-30
2005-07-29 0.26407951 9 2005-07-29
2006-07-31 0.03501359 9 2006-07-31
2007-07-31 0.13907544 9 2007-07-31
2008-07-31 -0.02064978 9 2008-07-31
2009-07-31 -0.27060352 9 2009-07-31
2010-07-30 0.33156794 9 2010-07-30
2011-07-29 0.22488091 9 2011-07-29
2012-07-31 0.03268992 9 2012-07-31
2013-07-31 0.29199203 9 2013-07-31
2014-07-31 0.10818639 9 2014-07-31
2015-07-31 0.19940041 9 2015-07-31
2016-07-29 0.04085818 9 2016-07-29
2017-07-31 0.04345668 9 2017-07-31
2018-07-31 0.11842907 9 2018-07-31
```
The first part of the list indicates the start month, the second part the quantile ([["Start\_month"]][["Quantile"]]).
The question is how can I plot the Prtf\_Returns in a ggplot for every single dataframe in the list?. The following is what I got so far:
```
library(ggplot2)
p <- ggplot()
for(i in 1:10){
p <- p + geom_line(data = first_year[[1]][[i]], aes(x = Date, y = cumsum(Prtf_Return), group = Quantile, colour = Quantile)) +
scale_color_discrete(name = "Quantile", labels = rep(as.character(1:10)))
}
```
[This is how the plot looks](https://i.stack.imgur.com/i6RMg.png)
What I know so far is that the legend possibly doesn't match the lines itself, but I really don't know how I could change the code to work.
Thanks in advance | 2018/11/03 | [
"https://Stackoverflow.com/questions/53132550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9055967/"
] | The trick is to `rbind` each of the `Quantile` dataframes in the sublists. Then call a plot function in a `lapply` loop. The plot function could be an anonymous function but I have written it separately for the sake of clarity.
I also rotate the x axis labels. To do that function `rotate_x_text` from package `ggpubr` is used.
```
library(ggplot2)
library(ggpubr)
plotFun <- function(DF){
DF[["Quantile"]] <- factor(DF[["Quantile"]])
ggplot(data = DF, aes(x = Date, y = cumsum(Prtf_Return),
group = Quantile, colour = Quantile)) +
geom_line() +
rotate_x_text(angle = 45) +
scale_color_discrete(name = "Quantile",
labels = as.character(1:10))
}
first_year_rbind <- lapply(first_year, function(L) do.call(rbind, L))
p_list <- lapply(first_year_rbind, plotFun)
p_list[[1]]
```
[](https://i.stack.imgur.com/vysFb.png)
**Test data.**
This list of lists repeats the two dataframes in the question.
```
df1 <-
structure(list(Prtf_Return = c(-0.08161658, 0.05648458, 0.24751328,
0.26955881, 0.08099889, 0.14633871, -0.02790529, -0.17913224,
0.33681922, 0.23411797, 0.10671685, 0.19845169, 0.11399025, 0.10308543,
0.01388617, 0.03685517, 0.0966141), Quantile = c(8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L),
Date = structure(1:17, .Label = c("2002-07-31",
"2003-07-31", "2004-07-30", "2005-07-29", "2006-07-31", "2007-07-31",
"2008-07-31", "2009-07-31", "2010-07-30", "2011-07-29", "2012-07-31",
"2013-07-31", "2014-07-31", "2015-07-31", "2016-07-29", "2017-07-31",
"2018-07-31"), class = "factor")), class = "data.frame",
row.names = c("2002-07-31",
"2003-07-31", "2004-07-30", "2005-07-29", "2006-07-31", "2007-07-31",
"2008-07-31", "2009-07-31", "2010-07-30", "2011-07-29", "2012-07-31",
"2013-07-31", "2014-07-31", "2015-07-31", "2016-07-29", "2017-07-31",
"2018-07-31"))
df2 <-
structure(list(Prtf_Return = c(-0.02322572, 0.25252339, 0.26290503,
0.26407951, 0.03501359, 0.13907544, -0.02064978, -0.27060352,
0.33156794, 0.22488091, 0.03268992, 0.29199203, 0.10818639, 0.19940041,
0.04085818, 0.04345668, 0.11842907), Quantile = c(9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L),
Date = structure(1:17, .Label = c("2002-07-31",
"2003-07-31", "2004-07-30", "2005-07-29", "2006-07-31", "2007-07-31",
"2008-07-31", "2009-07-31", "2010-07-30", "2011-07-29", "2012-07-31",
"2013-07-31", "2014-07-31", "2015-07-31", "2016-07-29", "2017-07-31",
"2018-07-31"), class = "factor")), class = "data.frame",
row.names = c("2002-07-31",
"2003-07-31", "2004-07-30", "2005-07-29", "2006-07-31", "2007-07-31",
"2008-07-31", "2009-07-31", "2010-07-30", "2011-07-29", "2012-07-31",
"2013-07-31", "2014-07-31", "2015-07-31", "2016-07-29", "2017-07-31",
"2018-07-31"))
first_year <- list(list(df1, df2), list(df1, df2))
``` | I figured it out. Thanks to everybody that helped.
The trick was to (like Rui mentioned) create a new column with the cumsums.
```
first_year_cumsum <- lapply(first_year, function(a) lapply(a, function(b) ddply(b, .(Quantile), transform, cumsum = cumsum(Prtf_Return))))
```
With that, the function of Rui looks like:
```
plotFun <- function(DF){
DF[["Quantile"]] <- factor(DF[["Quantile"]])
ggplot(data = DF, aes(x = Date, y = cumsum,
group = Quantile, colour = Quantile)) +
geom_line() +
theme_bw() +
rotate_x_text(angle = 45) +
scale_color_discrete(name = "Quantile",
labels = as.character(1:10))
}
first_year_rbind <- lapply(first_year_cumsum, function(L) do.call(rbind, L))
p_list <- lapply(first_year_rbind, plotFun)
```
After that the plot returns a nice cumsum for each quantile
[](https://i.stack.imgur.com/c29KE.png)
Thanks again |
92,086 | Which one is correct?
>
> 1. I met my future wife on this very American traditional occasion.
> 2. I met my future wife during this very American traditional occasion.
>
>
> | 2012/11/23 | [
"https://english.stackexchange.com/questions/92086",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/31284/"
] | ***During*** is an unusual preposition in that it can only have an object that refers to a duration of [Time](http://www.umich.edu/~jlawler/3-Time.pdf) -- there are fewer than ten words in English that have exclusive time reference, and many of them come from the same root as *during*. It is also unusual in that it's almost never metaphorical. Objects of *during* will be interpreted as temporal references:
* *during the service, during dinner, during Summer, during the night*
Occasionally one must strain to interpret them that way in context:
* *during the aardvark, during B♭ Minor, during John Cassavetes, during NaOH*
That's the problem with using *during* with *occasion* as its object. Which temporal part of the "occasion" is being referred to? The dinner, the visiting, the travelling, or what? *Occasion* normally refers to a notation on a calendar -- a 2-Dimensional metaphor -- rather than something with a temporal duration of its own.
***On***, on the other hand, requires some two-dimensional surface as an object, and produces a location that is **above** and **in contact with** that surface:
* *on the sidewalk, on the lawn, on the desk[top], on the page, on the bed*
but *on* is more usually metaphorical, and will work with anything that can be [metaphorized](http://www.umich.edu/~jlawler/Metaphors.pdf) onto such a surface, which includes just about **anything**, at least if it can be printed on a sheet of paper:
* *on the subject of, on the Watson story, on the NYSE, on HBO, on Black Friday*
The last example shows how we use all three [Spatial](http://www.umich.edu/~jlawler/2-Space.pdf) dimensions to refer to Time in English. In general,
* Months and larger measures are Containers -- **3**-D: ***in*** 1949, **in** June, **in** this century
* Days are Surfaces -- **2**-D: ***on*** Thursday, **on** Thanksgiving, **on** this occasion
* Smaller measures are Points on a **1**-D line: ***at*** noon, **at** 12:03:45, **at** the moment of death.
A special case is *at night*, which refers to some indefinite moment in the dark, especially to states or events repeated on multiple nights. The dark itself is a volume: *in the night/dark*.
That's why *on* is better for *occasion*. | Both sentences are grammatical. There are two differences in usage, though slight.
**Specificity**
The first sentence is slightly ambiguous:
>
> I met my future wife **on** this very American traditional occasion
>
>
>
A traditional occasion is presumed, by definition, to be a recurring event. You may have met your future wife on the occurrence of the event, many years ago, or last month. It may have been in Omaha, just as likely as in Guam.
The second sentence,
>
> I met my future wife **during** this very American traditional occasion
>
>
>
is more readily understood as a particular instance of the occasion. Both time and location are associated with specificity. So "during this occasion", would more likely imply "last month in Guam" versus "decades ago in Omaha", for example.
**Formality**
"During" rather than "on" is a less formal way of expressing something. For example, one would say, for a formal wedding invitation,
>
> Mr. and Mrs. Blah request the pleasure of your attendance **on** the
> occasion of the marriage of their daughter, Blahbity.
>
>
>
I was surprised though, that "on" and "during" seem to be used interchangeably when I checked just now. The most common *English language* usages of "on the occasion of" were in **[Indian (Hindu, Muslim and Sikh)](http://www.regalcards.com/text_layouts.htm "Text layouts for Indian weddings Hindu Islam Sikh")** wedding invitations. There was merely one traditional Roman Catholic wedding guide that I found. It used "on the occasion of". Even a wedding announcement posted in the informal venue of the **[Yahoo! Groups Geophysics forum](http://dir.groups.yahoo.com/group/geophysics_au/message/681 "GloriousGeophysics message 681")** used "on the occasion of"! I am personally most familiar with American English, and Jewish wedding invitations. They use "on the occasion of".
Regarding more general usage of "on the occasion of", whether weddings or commemoration of formal events, **[Fatwa Online](http://www.fatwa-online.com/fataawa/marriage/maritalrelations/0051016.htm "Fatwa Marital Relations")** and **[Defender of Sunna](http://www.defenderofsunnah.com/fatwa/concise-fatwa/marriage/marital-relations/756-giving-the-wife-a-gift-on-the-occasion-of-the-wedding-anniversary "On the occasion of the wedding")** use "on the occasion of" (all English language websites). Also, Fatwa Online makes the distinction that "on the occasion of" refers to the general case of the occasion, rather than a specific instance, to which I alluded to above. |
67,846,647 | ```
import numpy as np
a = np.array([8.0,7.0,6.0],[5.0,4.0])
print(a)
```
I am trying to run this code but I get this error. (In Jupiter)
---
```
TypeError Traceback (most recent call last)
<ipython-input-3-31ad187a1d2f> in <module>
1 import numpy as np
----> 2 a = np.array([8.0,7.0,6.0],[5.0,4.0])
3 print(a)
TypeError: Field elements must be 2- or 3-tuples, got '5.0'
``` | 2021/06/05 | [
"https://Stackoverflow.com/questions/67846647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716044/"
] | It would help to know what you are trying to achieve with this code.
Assuming you are trying to create a 2D array with numpy - you need to make sure your dimensions are correct (first row with 3 element and second row with 2 element cannot make a 2D array).
And you need another [] around to make 2D array. Something like this -
```
import numpy as np
a = np.array([[8.0,7.0,6.0],[5.0,4.0,3.0]])
print(a)
``` | There are two mistakes here,
i. another element has to be inserted into the second array / removed from the first array,
ii. both of them have to be passed as first argument i.e. enclosed in braces.
Rewriting the same:
```
import numpy as np
a = np.array(([8.0,7.0,6.0],[5.0,4.0,3.0]))
print(a)
``` |
67,846,647 | ```
import numpy as np
a = np.array([8.0,7.0,6.0],[5.0,4.0])
print(a)
```
I am trying to run this code but I get this error. (In Jupiter)
---
```
TypeError Traceback (most recent call last)
<ipython-input-3-31ad187a1d2f> in <module>
1 import numpy as np
----> 2 a = np.array([8.0,7.0,6.0],[5.0,4.0])
3 print(a)
TypeError: Field elements must be 2- or 3-tuples, got '5.0'
``` | 2021/06/05 | [
"https://Stackoverflow.com/questions/67846647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716044/"
] | It would help to know what you are trying to achieve with this code.
Assuming you are trying to create a 2D array with numpy - you need to make sure your dimensions are correct (first row with 3 element and second row with 2 element cannot make a 2D array).
And you need another [] around to make 2D array. Something like this -
```
import numpy as np
a = np.array([[8.0,7.0,6.0],[5.0,4.0,3.0]])
print(a)
``` | ```
1 import numpy as np
```
----> 2 a = np.array([8.0,7.0,6.0],[5.0,4.0])
3 print(a)
ANS : you need the "[ ]" around the Data
like this below
```
1 import numpy as np
2 a = np.array( [ [8.0,7.0,6.0],[5.0,4.0] ] )
3 print(a)
``` |
67,846,647 | ```
import numpy as np
a = np.array([8.0,7.0,6.0],[5.0,4.0])
print(a)
```
I am trying to run this code but I get this error. (In Jupiter)
---
```
TypeError Traceback (most recent call last)
<ipython-input-3-31ad187a1d2f> in <module>
1 import numpy as np
----> 2 a = np.array([8.0,7.0,6.0],[5.0,4.0])
3 print(a)
TypeError: Field elements must be 2- or 3-tuples, got '5.0'
``` | 2021/06/05 | [
"https://Stackoverflow.com/questions/67846647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716044/"
] | There are two mistakes here,
i. another element has to be inserted into the second array / removed from the first array,
ii. both of them have to be passed as first argument i.e. enclosed in braces.
Rewriting the same:
```
import numpy as np
a = np.array(([8.0,7.0,6.0],[5.0,4.0,3.0]))
print(a)
``` | ```
1 import numpy as np
```
----> 2 a = np.array([8.0,7.0,6.0],[5.0,4.0])
3 print(a)
ANS : you need the "[ ]" around the Data
like this below
```
1 import numpy as np
2 a = np.array( [ [8.0,7.0,6.0],[5.0,4.0] ] )
3 print(a)
``` |
6,444,987 | Is there a better (built in?) way to mix observableArray and associative arrays?
```
viewModel = {
a: ko.observableArray(),
a_assoc: {},
add_item: function(i) {
if (typeof this.a_assoc[i] == 'undefined') {
this.a.push(i);
this.a_assoc[i]=1;
}
}
}
viewModel.add_item('bla');
``` | 2011/06/22 | [
"https://Stackoverflow.com/questions/6444987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/657866/"
] | Typically, you would do something like this in Knockout:
```
var viewModel = {
a: ko.observableArray(["a","b","c","d"]),
add_item: function() {
this.a.push("new" + this.a().length);
}
};
viewModel.a_assoc = ko.dependentObservable(function() {
var result = {};
ko.utils.arrayForEach(this.a(), function(item) {
result[item] = 1;
});
return result;
}, viewModel);
```
So, you have a dependentObservable that maps your array to an object. Note that each time that the original array is updated, the object is rebuilt. So, it is less efficient than the method in your post, but unless your object is substantially big, it is doubtful that it would cause a performance issue.
Sample here: <http://jsfiddle.net/rniemeyer/PgceN/> | I think it is best to use an associative array under the hood for performance. You also (as you alluded to) need to use an observableArray to be able to track changes (because that's how knockout works).
If you're seeking a 'knockout friendly' associative array you probably want a way to track changes to the item (and thus affect dependency chains).
<http://jsfiddle.net/rz41afLq/2/>
Here's what I came up with that suited my needs. Basically you store a key value pair in the `observableArray` and use a standard associative array to store a copy for lookup purposes.
```
// VIEW MODEL
var viewModel = {
// we have to use observable array to track changes
items: ko.observableArray([]),
// also use associative array for performance
_assoc: {},
update_item: function(key, value) {
// use a true assoc array for performance
// _assoc[key] = ko.observable(value)
if (viewModel._assoc[key])
{
// update observable (overwriting existing item)
viewModel._assoc[key].value(value);
}
else {
// Important: See how we wrap value with an observable to detect changes
this.items.push(viewModel._assoc[key] = { key: key, value: ko.observable(value) });
}
}
};
```
So you save your dogs like this:
```
update_item('dogs', ['kim', 'abbey', 'goldie', 'rover']);
update_item('dogs', ko.observableArray(['kim', 'abbey', 'goldie', 'rover']));
```
(The second is only required if you are planning on calling `pop()` or `push()` on the list of dogs and want to update the UI. You can of course call `update_item` to completely update the item at any time in which case it doesn't need to be observable)
To lookup a value, you dynamically create a computed to go fetch it :
```
var dogs = getValue('dogs');
```
Then as soon as the value indexed as 'dogs' in the associative array changes then the observable `dogs()` will update (and can be chained). This `dogs` observable can be bound to the UI of course
```
var getValue = function(key) { return ko.pureComputed(function()
{
// reevaluate when item is added or removed to list
// not necessary if the value itself changes
viewModel.items();
var item = viewModel._assoc[key];
return (item == null) ? null : item.value();
}, viewModel);
``` |
996,620 | I am using Windows 10 and just setup Offline Files for 3 folders I'm currently working from (28 sub-folders, 550 files, 185MiB). I prefer working from local copies of the files for performance reasons although our network folders perform pretty well. I also want my work to sync with the network location the files come from so I don't have different versions from the network.
When I navigate through the offline files on my computer it takes several seconds to simply change directories, its much slower than just using the mapped network folder.
I do not have any performance issues on my computer, I have tons of ram, a very modern 4 core 8 thread processor, very fast Samsung SSD, etc...
I setup offline files so that I wouldn't have to worry about sync'n files, and for performance. However, so far offline files is the worst performing method of file browsing, what's going on?
I'm trying to avoid setting up 3rd party version control or 3rd party sync apps, if possible. I am open to suggestions, however, if Offline Files is a poor solution. | 2015/11/05 | [
"https://superuser.com/questions/996620",
"https://superuser.com",
"https://superuser.com/users/396067/"
] | I too noticed that browsing the "Offline Files Folder" in Windows 10 can be extremely slow. After playing with the feature a bit, my conclusion is that you don't need it most of the time.
First, to make clear what we're talking about, if you go to the Windows 10 Sync Center, click "Manage offline files", and then click "View your offline files", it opens a folder called "Offline Files Folder". It's the browsing of this folder that can be extremely slow, and I also found that Explorer would crash quite often while browsing the folder.
The good news is that you don't really need the "Offline Files Folder" to work with offline files. Normally, you'll interact with all of your offline files at their normal online location, be that a UNC path or a mapped drive letter. That's where your applications will see the files, and that's where you browse in Explorer to select which files to make "Always available offline" (by right clicking, or in the "Easy access" menu). That's also where you can see which files have been made always available offline, by setting your Explorer view to Details and then adding the "Availability" column. Each file will be shown with an availability of "Online-only" or "Available offline". When working offline, the Online-only files will either be totally missing from the filesystem, or will be shown with a blank page icon that has a grey X at the lower left-hand corner. Access to offline files is speedy, just like with any other file on the system drive.
The "Offline Files Folder" is really only good for some specific maintenance tasks. If you right click a server, file, or folder there and then click "Delete Offline Copy", it will delete the offline copy of all sub-folders and files, *and* change the availability back to Online-only. If I was having a problem with offline files, the first thing I would try would be to delete everything in the Offline Files Folder and start over.
After using offline files for a bit, I've found the feature to be more trouble than it's worth. It often complains of sync conflicts when it shouldn't, and sometimes forgets when I have told it to work offline. I gave up on the feature and now I just copy files manually. Offline files hasn't seen any new features since Windows 8, and probably doesn't have much of a future. Microsoft is more interested in Work Folders and OneDrive these days. | Offline Files saves data in C:\Windows\CSC directory which admins do not have access to without registry changes. This is a big issue for me as I want to work with the files and directories directly.
I have chosen to try SyncToy or FreeFileSync as alternatives;
[SyncToy download page](https://www.microsoft.com/en-us/download/confirmation.aspx?id=15155)
[FreeFileSync homepage](http://www.freefilesync.org/) |
70,289,996 | So Im doing a project scraping different websites using multiple spiders. I want to make it so that the spiders run again when the user says "Yes" when asked to continue.
```
keyword = input("enter keyword: ")
page_range = input("enter page range: ")
flag = True
while flag:
process = CrawlProcess()
process.crawl(crawler1, keyword, page_range)
process.crawl(crawler2, keyword, page_range)
process.crawl(crawler3, keyword, page_range)
process.start()
isContinue = input("Do you want to continue? (y/n): ")
if isContinue == 'n':
flag = False
```
But I get an error saying reactor is not restartable.
```
Traceback (most recent call last):
File "/Users/user/Desktop/programs/eshopSpider/eshopSpider.py", line 47, in <module>
process.start()
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/scrapy/crawler.py", line 327, in start
reactor.run(installSignalHandlers=False) # blocking call
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 1317, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 1299, in startRunning
ReactorBase.startRunning(cast(ReactorBase, self))
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 843, in startRunning
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable
```
So I guess using while loop is no-go. I don't know where to even start... | 2021/12/09 | [
"https://Stackoverflow.com/questions/70289996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6363509/"
] | You can remove the `while` loop and use callbacks instead.
Edit: Example added:
```
def callback_f():
# stuff #
calling_f()
def calling_f():
answer = input("Continue? (y/n)")
if not answer == 'n':
callback_f()
callback_f()
``` | ```
from twisted.internet import reactor #only this is supposed to be here, we will be deleting the reactor after each run, using the main
configure_logging()
settings = get_project_settings()
runner = CrawlerRunner(settings)
d = runner.crawl('your spider class name')
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until all crawling jobs are finished
del sys.modules['twisted.internet.reactor'] #deleting the reactor, because we want to run a for loop, the reactor will be imported again at the top
default.install()
``` |
70,289,996 | So Im doing a project scraping different websites using multiple spiders. I want to make it so that the spiders run again when the user says "Yes" when asked to continue.
```
keyword = input("enter keyword: ")
page_range = input("enter page range: ")
flag = True
while flag:
process = CrawlProcess()
process.crawl(crawler1, keyword, page_range)
process.crawl(crawler2, keyword, page_range)
process.crawl(crawler3, keyword, page_range)
process.start()
isContinue = input("Do you want to continue? (y/n): ")
if isContinue == 'n':
flag = False
```
But I get an error saying reactor is not restartable.
```
Traceback (most recent call last):
File "/Users/user/Desktop/programs/eshopSpider/eshopSpider.py", line 47, in <module>
process.start()
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/scrapy/crawler.py", line 327, in start
reactor.run(installSignalHandlers=False) # blocking call
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 1317, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 1299, in startRunning
ReactorBase.startRunning(cast(ReactorBase, self))
File "/Users/user/opt/anaconda3/lib/python3.8/site-packages/twisted/internet/base.py", line 843, in startRunning
raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable
```
So I guess using while loop is no-go. I don't know where to even start... | 2021/12/09 | [
"https://Stackoverflow.com/questions/70289996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6363509/"
] | **Method 1:**
`scrapy` creates `Reactor` which can't be reused after `stop` but if you will run `Crawler` in separated process then new process will have to create new `Reactor`.
```
import multiprocessing
def run_crawler(keyword, page_range):
process = CrawlProcess()
process.crawl(crawler1, keyword, page_range)
process.crawl(crawler2, keyword, page_range)
process.crawl(crawler3, keyword, page_range)
process.start()
# --- main ---
keyword = input("enter keyword: ")
page_range = input("enter page range: ")
flag = True
while flag:
p = multiprocessing(target=run_crawler, args=(keyword, page_range))
p.start()
p.join()
isContinue = input("Do you want to continue? (y/n): ")
if isContinue == 'n':
flag = False
```
It will not work if you use `threading` instead of `multiprocessing` because threads share variables so new thread will use the same `Reactor` as previous thread.
---
Minimal working code (tested on Linux).
```
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
#start_urls = ['https://books.toscrape.com/']
def __init__(self, keyword, page, *args, **kwargs):
'''generate start_urls list'''
super().__init__(*args, **kwargs)
self.keyword = keyword
self.page = int(page)
self.start_urls = [f'https://books.toscrape.com/catalogue/page-{page}.html']
def parse(self, response):
print('[parse] url:', response.url)
for book in response.css('article.product_pod'):
title = book.css('h3 a::text').get()
url = book.css('img::attr(src)').get()
url = response.urljoin(url)
yield {'page': self.page, 'keyword': self.keyword, 'title': title, 'image': url}
# --- run without project and save in `output.csv` ---
import multiprocessing
from scrapy.crawler import CrawlerProcess
def run_crawler(keyword, page_range):
#from scrapy.crawler import CrawlerProcess
c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
# save in file CSV, JSON or XML
'FEEDS': {'output.csv': {'format': 'csv'}}, # new in 2.1
})
c.crawl(MySpider, keyword, page)
c.crawl(MySpider, keyword, int(page)+1)
c.crawl(MySpider, keyword, int(page)+2)
c.start()
# --- main ---
if __name__ == '__main__':
keyword = input("enter keyword: ")
page = input("enter page: ")
running = True
while running:
p = multiprocessing.Process(target=run_crawler, args=(keyword, page))
p.start()
p.join()
answer = input('Repeat [Y/n]? ').strip().lower()
if answer == 'n':
running = False
```
---
**Method 2:**
Found in Google: [Restarting a Twisted Reactor](https://www.blog.pythonlibrary.org/2016/09/14/restarting-a-twisted-reactor/).
It is old post which uses `del` to remove module `twisted` from memory and later it `imports` it again.
```
keyword = input("enter keyword: ")
page_range = input("enter page range: ")
flag = True
while flag:
process = CrawlProcess()
process.crawl(crawler1, keyword, page_range)
process.crawl(crawler2, keyword, page_range)
process.crawl(crawler3, keyword, page_range)
process.start()
isContinue = input("Do you want to continue? (y/n): ")
if isContinue == 'n':
flag = False
import sys
del sys.modules['twisted.internet.reactor']
from twisted.internet import reactor
from twisted.internet import default
default.install()
```
---
Minimal working code (tested on Linux)
```
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
#start_urls = ['https://books.toscrape.com/']
def __init__(self, keyword, page, *args, **kwargs):
'''generate start_urls list'''
super().__init__(*args, **kwargs)
self.keyword = keyword
self.page = int(page)
self.start_urls = [f'https://books.toscrape.com/catalogue/page-{page}.html']
def parse(self, response):
print('[parse] url:', response.url)
for book in response.css('article.product_pod'):
title = book.css('h3 a::text').get()
url = book.css('img::attr(src)').get()
url = response.urljoin(url)
yield {'page': self.page, 'keyword': self.keyword, 'title': title, 'image': url}
# --- run without project and save in `output.csv` ---
from scrapy.crawler import CrawlerProcess
def run_crawler(keyword, page):
c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
# save in file CSV, JSON or XML
'FEEDS': {'output.csv': {'format': 'csv'}}, # new in 2.1
})
c.crawl(MySpider, keyword, page)
c.crawl(MySpider, keyword, int(page)+1)
c.crawl(MySpider, keyword, int(page)+2)
c.start()
# --- main ---
if __name__ == '__main__':
keyword = input("enter keyword: ")
page = input("enter page: ")
running = True
while running:
run_crawler(keyword, page)
answer = input('Repeat [Y/n]? ').strip().lower()
if answer == 'n':
running = False
import sys
del sys.modules['twisted.internet.reactor']
from twisted.internet import reactor
from twisted.internet import default
default.install()
```
---
**Method 3:**
It seems you could use use [CrawlRunner](https://docs.scrapy.org/en/latest/topics/api.html#scrapy.crawler.CrawlerRunner) instead of `CrawlProcess` - but I didn't test it yet.
Base on last example in doc for [Running multiple spiders in the same process](https://docs.scrapy.org/en/latest/topics/practices.html?highlight=CrawlerRunner#running-multiple-spiders-in-the-same-process) I created code which runs `while`-loop inside reactor (so it doesn't have to stop it) but it first starts one Spider, next runs second Spider, next it asks for contiuation and it runs again first Spider, next runs second Spider. It doesn't runs both Spiders at the same time but maybe it could be somehow changed.
```
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
#start_urls = ['https://books.toscrape.com/']
def __init__(self, keyword, page, *args, **kwargs):
'''generate start_urls list'''
super().__init__(*args, **kwargs)
self.keyword = keyword
self.page = int(page)
self.start_urls = [f'https://books.toscrape.com/catalogue/page-{page}.html']
def parse(self, response):
print('[parse] url:', response.url)
for book in response.css('article.product_pod'):
title = book.css('h3 a::text').get()
url = book.css('img::attr(src)').get()
url = response.urljoin(url)
yield {'page': self.page, 'keyword': self.keyword, 'title': title, 'image': url}
# --- run without project and save in `output.csv` ---
from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
@defer.inlineCallbacks
def run_crawler():
running = True
while running:
yield runner.crawl(MySpider, keyword, page)
yield runner.crawl(MySpider, keyword, int(page)+1)
yield runner.crawl(MySpider, keyword, int(page)+2)
answer = input('Repeat [Y/n]? ').strip().lower()
if answer == 'n':
running = False
reactor.stop()
#return
# --- main ---
if __name__ == '__main__':
keyword = input("enter keyword: ")
page = input("enter page: ")
configure_logging()
runner = CrawlerRunner({
'USER_AGENT': 'Mozilla/5.0',
# save in file CSV, JSON or XML
'FEEDS': {'output.csv': {'format': 'csv'}}, # new in 2.1
})
run_crawler()
reactor.run()
```
**EDIT:**
The same but now all crawlers run at the same time
```
@defer.inlineCallbacks
def run_crawler():
running = True
while running:
runner.crawl(MySpider, keyword, page)
runner.crawl(MySpider, keyword, int(page)+1)
runner.crawl(MySpider, keyword, int(page)+2)
d = runner.join()
yield d
answer = input('Repeat [Y/n]? ').strip().lower()
if answer == 'n':
running = False
reactor.stop()
#return
``` | ```
from twisted.internet import reactor #only this is supposed to be here, we will be deleting the reactor after each run, using the main
configure_logging()
settings = get_project_settings()
runner = CrawlerRunner(settings)
d = runner.crawl('your spider class name')
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until all crawling jobs are finished
del sys.modules['twisted.internet.reactor'] #deleting the reactor, because we want to run a for loop, the reactor will be imported again at the top
default.install()
``` |
281,974 | Given a conic $\Gamma$ that has the equation $Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0$, $\Gamma$ can be represented by the symmetric matrix
$$\mathbf{C} = \begin{bmatrix}
A & B/2 & D/2\\
B/2 & C & E/2\\
D/2 & E/2 & F
\end{bmatrix}.$$
Suppose we have points $(x\_\text{c}, y\_\text{c})$, $(x\_-, y\_-)$, $(x\_+, y\_+)$ and $(x\_0, y\_0)$ that satisfy the following:
1. $\Gamma$ has center $(x\_\text{c}, y\_\text{c})$.
2. $(x\_-, y\_-), (x\_+, y\_+) \in \Gamma$.
3. The tangents at $(x\_-, y\_-)$ $(x\_+, y\_+)$ intersect at $(x\_0, y\_0)$.
Are these conditions enough to make $\Gamma$ unique, assuming that $\Gamma$ exists? I have two positional and two tangential conditions; does knowledge of the conic center count as the "fifth condition" for specifying conics?
I attempt to solve the equations formed by following [this Wikipedia article](http://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections).
From (1) we have
$$\begin{cases}
Ax\_\text{c} + B(y\_\text{c}/2) + D/2 = 0\\
B(x\_\text{c}/2) + Cy\_\text{c} + E/2 = 0.
\end{cases}$$
(2) implies that
$$\left\{\begin{split}
Ax\_-^2 + Bx\_-y\_- + Cy\_-^2 + Dx\_- + Ey\_- + F &= 0\\
Ax\_+^2 + Bx\_+y\_+ + Cy\_+^2 + Dx\_+ + Ey\_+ + F &= 0.
\end{split}\right.$$
Finally, (3) gives us
$$\begin{gather}
\begin{bmatrix}
x\_0 & y\_0 & 1
\end{bmatrix}\mathbf{C}
\begin{bmatrix}
x\_- \\ y\_- \\ 1
\end{bmatrix} = 0 =
\begin{bmatrix}
x\_0 & y\_0 & 1
\end{bmatrix}\mathbf{C}
\begin{bmatrix}
x\_+ \\ y\_+ \\ 1
\end{bmatrix}\\
\implies
\begin{cases}
Ax\_0x\_- + B(x\_0y\_- + y\_0x\_-)/2 + Cy\_0y\_- + D(x\_0 + x\_-)/2 + E(y\_0 + y\_-)/2 + F = 0\\
Ax\_0x\_+ + B(x\_0y\_+ + y\_0x\_+)/2 + Cy\_0y\_+ + D(x\_0 + x\_+)/2 + E(y\_0 + y\_+)/2 + F = 0\end{cases}
\end{gather}$$
Reorganizing the system of linear equations gives us
$$
\begin{bmatrix}
x\_\text{c} & \frac{y\_\text{c}}{2} & 0 & \frac{1}{2} & 0 & 0\\
0 & \frac{x\_\text{c}}{2} & y\_\text{c} & 0 & \frac{1}{2} & 0\\
x\_-^2 & x\_-y\_- & y\_-^2 & x\_- & y\_- & 1\\
x\_+^2 & x\_+y\_+ & y\_+^2 & x\_+ & y\_+ & 1\\
x\_0x\_- & \frac{x\_0y\_- + y\_0x\_-}{2} & y\_0y\_- & \frac{x\_0 + x\_-}{2} & \frac{y\_0 + y\_-}{2} & 1\\
x\_0x\_+ & \frac{x\_0y\_+ + y\_0x\_+}{2} & y\_0y\_+ & \frac{x\_0 + x\_+}{2} & \frac{y\_0 + y\_+}{2} & 1
\end{bmatrix}
\begin{bmatrix}
A \\ B \\ C \\ D \\ E \\ F
\end{bmatrix} = \mathbf{0}
$$
However, this means that the square matrix on the left-hand-side must be singular. How do I go about solving for one permissible solution of $\begin{bmatrix}A & B & C & D & E & F\end{bmatrix}^\intercal$? The solution vectors should all be parallel. | 2013/01/19 | [
"https://math.stackexchange.com/questions/281974",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/34473/"
] | generated by g means the set (which turns out to be a cyclic subgroup) {g, g+g, g+g+g, ...} until you get back to where you started.
so {(6,10), (12, 20), (18, 30), (24, 40), ...} and written reduced that's {(6,10), (4, 5), (2, 0), (0, 10), ...}.
A slightly easier way to do this is write out the group by 6 in Z\_8 then by 10 in Z\_15 and piece them together:
* 6, 4, 2, 0
* 10, 5, 0
since they have different periods it'll be like this:
```
6 4 2 0 6 4 2 0 6 4 2 0
10 5 0 10 5 0 10 5 0 10 5 0
```
which is exactly what's written there.
---
The group Z\_8 x Z\_10 has 80 elements (there are 80 pairs (x,y) where x is < 8 and y < 10). An element can only generate the whole group if it has the same order as the whole group. | In example 2, the subgroup is generated by $1$ element. You start by writing $(6, 15)$ and its multiples (mod 8 and 15 of course) until you get $(0, 0)$. That seems efficient enough to me.
In example 10, the group $\mathbb Z\_8 \times \mathbb Z\_{10}$ has $80$ elements. A group generated by 1 generator will have the same size as the order of the generator. Knowing that all elements have order not greater than $40$ means you cannot generate a group of order greater than $40$ with 1 element. |
71,278,176 | I have a navbar and two side menus which I use in multiple pages. But for a number of pages I don't want to have the side menu.
I have tried using v-if with $router.name, but because I was using a grid system, the layout would break. Then also it was impossible to add more than one component to not render the side menus.
This is the template:
```
<template>
<TheNavbar/>
<div class="container">
<TheLeftMenu/>
<router-view/>
<TheRightMenu/>
</div>
</template>
``` | 2022/02/26 | [
"https://Stackoverflow.com/questions/71278176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15024647/"
] | You need to mock `authenticationManager.authenticate` to throw BadCredentialsException to make it fails. | You have to mock the Authentication Manager and that can be done as below code snippet:
```
Mockito.doThrow(BadCredentialsException.class)
.when(authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword())));
```
This should work fine !! |
71,278,176 | I have a navbar and two side menus which I use in multiple pages. But for a number of pages I don't want to have the side menu.
I have tried using v-if with $router.name, but because I was using a grid system, the layout would break. Then also it was impossible to add more than one component to not render the side menus.
This is the template:
```
<template>
<TheNavbar/>
<div class="container">
<TheLeftMenu/>
<router-view/>
<TheRightMenu/>
</div>
</template>
``` | 2022/02/26 | [
"https://Stackoverflow.com/questions/71278176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15024647/"
] | You need to mock `authenticationManager.authenticate` to throw BadCredentialsException to make it fails. | It just turned out that I'm dumb and I forgot that I'm mocking the beans so there isn't actually a connection to the database.
I just ended up moving the authentication code to UserService class inside an authenticate() method that returns a boolean, then I stubbed the method and tested the controller and everything is working fine.
My test now:
```
@Test
void shouldReturnUnauthorized() throws Exception{
final LoginDto validLoginDto = new LoginDto("admin", "yesyesyes");
final String expectedMessage = "Invalid credentials";
Mockito.when(userService.authenticate(validLoginDto)).thenReturn(false);
mvc.perform(MockMvcRequestBuilders
.post("/auth/login")
.content(objectMapper.writeValueAsString(validLoginDto))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized())
.andExpect(content().string(expectedMessage));
}
``` |
1,629,685 | I have enabled the `-Wstack-protector` warning when compiling the project I'm working on (a commercial multi-platform C++ game engine, compiling on Mac OS X 10.6 with GCC 4.2).
This flag warns about functions that will not be protected against stack smashing even though `-fstack-protector` is enabled.
GCC emits some warnings when building the project:
>
> not protecting function: no buffer at least 8 bytes long
>
> not protecting local variables: variable length buffer
>
>
>
For the first warning, I found that it is possible to adjust the minimum size a buffer must have when used in a function, for this function to be protected against stack smashing: `--param ssp-buffer-size=X` can be used, where X is 8 by default and can be as low as 1.
For the second warning, I can't suppress its occurrences unless I stop using `-Wstack-protector`.
1. When should `-fstack-protector` be used? (as in, for instance, all the time during dev, or just when tracking bugs down?)
2. When should `-fstack-protector-all` be used?
3. What is `-Wstack-protector` telling me? Is it suggesting that I decrease the buffer minimum size?
4. If so, are there any downsides to putting the size to 1?
5. It appears that `-Wstack-protector` is not the kind of flag you want enabled at all times if you want a warning-free build. Is this right? | 2009/10/27 | [
"https://Stackoverflow.com/questions/1629685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123183/"
] | Stack-protection is a hardening strategy, not a debugging strategy. If your game is network-aware or otherwise has data coming from an uncontrolled source, turn it on. If it doesn't have data coming from somewhere uncontrolled, don't turn it on.
Here's how it plays out: If you have a bug and make a buffer change based on something an attacker can control, that attacker can overwrite the return address or similar portions of the stack to cause it to execute their code instead of your code. Stack protection will abort your program if it detects this happening. Your users won't be happy, but they won't be hacked either. This isn't the sort of hacking that is about cheating in the game, it's the sort of hacking that is about someone using a vulnerability in your code to create an exploit that potentially infects your user.
For debugging-oriented solutions, look at things like mudflap.
As to your specific questions:
1. Use stack protector if you get data from uncontrolled sources. The answer to this is probably yes. So use it. Even if you don't have data from uncontrolled sources, you probably will eventually or already do and don't realize it.
2. Stack protections for all buffers can be used if you want extra protection in exchange for some performance hit. From [gcc4.4.2 manual](http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Optimize-Options.html):
>
>
> >
> >
> > >
> > > ### -fstack-protector
> > >
> > >
> > > Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call alloca, and functions with buffers larger than 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits.
> > >
> > >
> > >
> > > ### -fstack-protector-all
> > >
> > >
> > > Like -fstack-protector except that all functions are protected.
> > >
> > >
> > >
> >
> >
> >
>
>
>
3. The warnings tell you what buffers the stack protection can't protect.
4. It is not necessarily suggesting you decrease your minimum buffer size, and at a size of 0/1, it is the same as stack-protector-all. It is only pointing it out to you so that you can, if you decide redesign the code so that buffer is protected.
5. No, those warnings don't represent issues, they just point out information to you. Don't use them regularly. | You indeed should not care about the warning for normal builds. It's really more of an informational message. I hope it's obvious that you do have an inherent security concern with variable-sized buffers on the stack; get the size calculation wrong and you're opening a big hole. |
35,169,218 | I am looking on how to get specific day from time given :
let's say I have 2 dates : 1 Jan 2016 until 1 Jan 2017, I will need to know how many Mondays are there, or Tuesdays or any days that I select on the input I gave.
Is there any best way to achieve this ? | 2016/02/03 | [
"https://Stackoverflow.com/questions/35169218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5677342/"
] | **UPDATED ANSWER**
```
<?php
$count = 0;
$days = array("Monday", "Friday");
foreach ($days as $day) {
$startDate = '1 Jan 2016';
$endDate = '1 Jan 2017';
$endDate = strtotime($endDate);
$i = '';
for ($i = strtotime($day, strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i)) {
echo date('l Y-m-d', $i) . '<br>';
$count++;
}
}
echo $count;
``` | Try modify this example:
```
<?php
//http://php.net/manual/en/class.dateperiod.php#109846
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
//HERE ADD YOUR CONDITIONS...
echo $date->format("Ymd") . "<br>";
}
?>
```
You can reviewer this solution [PHP create range of dates](https://stackoverflow.com/questions/6111345/php-create-range-of-dates) |
35,169,218 | I am looking on how to get specific day from time given :
let's say I have 2 dates : 1 Jan 2016 until 1 Jan 2017, I will need to know how many Mondays are there, or Tuesdays or any days that I select on the input I gave.
Is there any best way to achieve this ? | 2016/02/03 | [
"https://Stackoverflow.com/questions/35169218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5677342/"
] | **UPDATED ANSWER**
```
<?php
$count = 0;
$days = array("Monday", "Friday");
foreach ($days as $day) {
$startDate = '1 Jan 2016';
$endDate = '1 Jan 2017';
$endDate = strtotime($endDate);
$i = '';
for ($i = strtotime($day, strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i)) {
echo date('l Y-m-d', $i) . '<br>';
$count++;
}
}
echo $count;
``` | get all days and loop through them all, get the first Monday after the start date and then iterate 7 days at a time:
```
$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i =strtotime('+1 week', $i))
echo date('l Y-m-d', $i);
``` |
64,724,787 | I am trying to make a customer and employee login and register page...however whenever I try to go to localhost:8000/customer register, I get a page not found error not found error. this is my
urls.py file:
```
from django.contrib import admin
from django.urls import path
from accounts import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.register, name = 'register'),
path('customer_resgister', views.customer_register.as_view(), name = 'customer_register'),
]
```
views.py:
```
from django.shortcuts import render
from django.views.generic import CreateView
from .models import User, Customer, Employee
from .forms import CustomerSignupForm, EmployeeSignupForm
# Create your views here.
def register(request):
return render(request, 'accounts/register.html')
class customer_register(CreateView):
model = User
form_class = CustomerSignupForm
template_name = 'accounts/customer_register.html'
#def customer_register(request):
```
models.py:
```
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length = 150)
last_name = models.CharField(max_length = 150)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
Phone_no = models.CharField(max_length = 10)
location = models.CharField(max_length = 150)
class Employee(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
Phone_no = models.CharField(max_length = 10)
designation = models.CharField(max_length = 150)
```
forms.py:
```
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from .models import Customer, Employee, User
from django import forms
class CustomerSignupForm(UserCreationForm):
first_name = forms.CharField(required = True)
last_name = forms.CharField(required = True)
phone_no = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def data_save(self):
user = super().save(commit = False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.save()
customer = Customer.objects.create(user = user)
customer.phone_no = self.cleaned_data.get('phone_no')
customer.save()
return user
class EmployeeSignupForm(UserCreationForm):
first_name = forms.CharField(required = True)
last_name = forms.CharField(required = True)
designation = forms.CharField(required = True)
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def data_save(self):
user = super().save(commit = False)
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.save()
employee = Employee.objects.create(user = user)
employee.phone_no = self.cleaned_data.get('phone_no')
employee.designation = self.cleaned_data.get('designation')
customer.save()
return user
```
settings.py:
```
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'apk-h*1!*f-=^6zw^_q0q!z6att9f+exfr+k(!awfvybu^x(l%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'accounts.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'demo_register.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'demo_register.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
```
All my templates are stored in accounts/templates/accounts
I don't know what am I doing wrong here...please help. | 2020/11/07 | [
"https://Stackoverflow.com/questions/64724787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14032045/"
] | 1. Download and install Microsoft Visual Studio build tools from <https://visualstudio.microsoft.com/en/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16>
2. Reboot your computer
3. Upgrade pip with command `python -m pip install --upgrade pip`
4. Run your command `python -m pip install twint` to install the package | Upgrade your pip with: `python -m pip install --upgrade pip`
Upgrade your wheel with: `pip install --upgrade wheel`
Upgrade your setuptools with: `pip install --upgrade setuptools`
Close the terminal and try installing the package again. |
20,036,182 | What am I doing wrong?
This is my code:
```
$.ajax({
type: "POST",
url: "GetData.asmx/GetEventMembers",
data: "{'ShulID': '" + ShulID
+ "','EventID': '" + EventID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$('#tblEventMembers').dataTable({
"aaData": eval(data.d)
});
},
failure: function (msg) {
alert(msg);
}
});
```
This is my json:
```
{
"aaData": [
{
"MemberID": 22,
"FName": "hfhfh",
"LName": "fhfhfh",
"InvitationDate": null,
"Approved": false,
"Invited": 0
},
{
"MemberID": 42,
"FName": "fkfk",
"LName": "vm.,v",
"InvitationDate": null,
"Approved": false,
"Invited": 0
}
]}
```
And I'm getting this error:

Any idea?
Thank you. | 2013/11/17 | [
"https://Stackoverflow.com/questions/20036182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181421/"
] | This `(int *)arg` takes whatever type `arg` is and pretends it is a `int *`
This `*((int *)arg)` takes the above pointer and deferences it, returning an `int` | You are casting `arg` to a pointer to int which is then dereferenced.
Think of it this way:
```
void* arg;
int* ptr = (int*) arg;
int offset = *ptr;
``` |
20,036,182 | What am I doing wrong?
This is my code:
```
$.ajax({
type: "POST",
url: "GetData.asmx/GetEventMembers",
data: "{'ShulID': '" + ShulID
+ "','EventID': '" + EventID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$('#tblEventMembers').dataTable({
"aaData": eval(data.d)
});
},
failure: function (msg) {
alert(msg);
}
});
```
This is my json:
```
{
"aaData": [
{
"MemberID": 22,
"FName": "hfhfh",
"LName": "fhfhfh",
"InvitationDate": null,
"Approved": false,
"Invited": 0
},
{
"MemberID": 42,
"FName": "fkfk",
"LName": "vm.,v",
"InvitationDate": null,
"Approved": false,
"Invited": 0
}
]}
```
And I'm getting this error:

Any idea?
Thank you. | 2013/11/17 | [
"https://Stackoverflow.com/questions/20036182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181421/"
] | Let's break this down:
```
(int *)arg;
```
This takes `arg` and casts it to an `int *`. The result of this expression is, of course, an `int *`.
```
*((int *)arg);
```
We're now just dereferencing that `int *` we just came up with — the result is the integer that the pointer was pointing to.
```
int offset = *((int *)arg);
```
We assign that integer into offeset.
No multiplication is involved here. | You are casting `arg` to a pointer to int which is then dereferenced.
Think of it this way:
```
void* arg;
int* ptr = (int*) arg;
int offset = *ptr;
``` |
20,036,182 | What am I doing wrong?
This is my code:
```
$.ajax({
type: "POST",
url: "GetData.asmx/GetEventMembers",
data: "{'ShulID': '" + ShulID
+ "','EventID': '" + EventID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$('#tblEventMembers').dataTable({
"aaData": eval(data.d)
});
},
failure: function (msg) {
alert(msg);
}
});
```
This is my json:
```
{
"aaData": [
{
"MemberID": 22,
"FName": "hfhfh",
"LName": "fhfhfh",
"InvitationDate": null,
"Approved": false,
"Invited": 0
},
{
"MemberID": 42,
"FName": "fkfk",
"LName": "vm.,v",
"InvitationDate": null,
"Approved": false,
"Invited": 0
}
]}
```
And I'm getting this error:

Any idea?
Thank you. | 2013/11/17 | [
"https://Stackoverflow.com/questions/20036182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181421/"
] | This `(int *)arg` takes whatever type `arg` is and pretends it is a `int *`
This `*((int *)arg)` takes the above pointer and deferences it, returning an `int` | It's a cast followed by a dereference. Basically, you're telling the compiler, "Trust me. I know that `arg` points to an `int`, so read the `int` it's pointing to, and put it into `offset`. |
20,036,182 | What am I doing wrong?
This is my code:
```
$.ajax({
type: "POST",
url: "GetData.asmx/GetEventMembers",
data: "{'ShulID': '" + ShulID
+ "','EventID': '" + EventID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$('#tblEventMembers').dataTable({
"aaData": eval(data.d)
});
},
failure: function (msg) {
alert(msg);
}
});
```
This is my json:
```
{
"aaData": [
{
"MemberID": 22,
"FName": "hfhfh",
"LName": "fhfhfh",
"InvitationDate": null,
"Approved": false,
"Invited": 0
},
{
"MemberID": 42,
"FName": "fkfk",
"LName": "vm.,v",
"InvitationDate": null,
"Approved": false,
"Invited": 0
}
]}
```
And I'm getting this error:

Any idea?
Thank you. | 2013/11/17 | [
"https://Stackoverflow.com/questions/20036182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181421/"
] | Let's break this down:
```
(int *)arg;
```
This takes `arg` and casts it to an `int *`. The result of this expression is, of course, an `int *`.
```
*((int *)arg);
```
We're now just dereferencing that `int *` we just came up with — the result is the integer that the pointer was pointing to.
```
int offset = *((int *)arg);
```
We assign that integer into offeset.
No multiplication is involved here. | It's a cast followed by a dereference. Basically, you're telling the compiler, "Trust me. I know that `arg` points to an `int`, so read the `int` it's pointing to, and put it into `offset`. |
20,036,182 | What am I doing wrong?
This is my code:
```
$.ajax({
type: "POST",
url: "GetData.asmx/GetEventMembers",
data: "{'ShulID': '" + ShulID
+ "','EventID': '" + EventID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
$('#tblEventMembers').dataTable({
"aaData": eval(data.d)
});
},
failure: function (msg) {
alert(msg);
}
});
```
This is my json:
```
{
"aaData": [
{
"MemberID": 22,
"FName": "hfhfh",
"LName": "fhfhfh",
"InvitationDate": null,
"Approved": false,
"Invited": 0
},
{
"MemberID": 42,
"FName": "fkfk",
"LName": "vm.,v",
"InvitationDate": null,
"Approved": false,
"Invited": 0
}
]}
```
And I'm getting this error:

Any idea?
Thank you. | 2013/11/17 | [
"https://Stackoverflow.com/questions/20036182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181421/"
] | Let's break this down:
```
(int *)arg;
```
This takes `arg` and casts it to an `int *`. The result of this expression is, of course, an `int *`.
```
*((int *)arg);
```
We're now just dereferencing that `int *` we just came up with — the result is the integer that the pointer was pointing to.
```
int offset = *((int *)arg);
```
We assign that integer into offeset.
No multiplication is involved here. | This `(int *)arg` takes whatever type `arg` is and pretends it is a `int *`
This `*((int *)arg)` takes the above pointer and deferences it, returning an `int` |
1,080,173 | Let's say we have two normally distributed populations A and B, which have different means and standard deviations. We then pick one item from population A and one from population B. How could we analytically find out the probability that the item from population B is larger in value than the item from population A?
I know that this can be solved fairly easily with some Monte-Carlo simulation, but I was curious to see how this problem could be solved analytically. | 2014/12/24 | [
"https://math.stackexchange.com/questions/1080173",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/26944/"
] | Think of it as a three-dimensional anthole. If A and B are independent then this is the same as the Probability (A-B) > 0 coming from a distribution of (A-B) which has mean $\mu\_A - \mu\_B$ and $ var(A-B) = var(A)+var(B)$ Then you just have to work out the Z-score of 0 in that distribution.
For instance, Let's say A is given by $N(3,5)$ and B is given by $N(2,12)$ (I'm writing these in mean, standard deviation form) then A-B is given by $N((3-2),\sqrt{25+144}) = N(1,13)$
A-B=0 occurs with a Z-score of $\frac{-1}{13}$ which is 0.2206 or 22%. 22% of the time B will be greater than A and 78% of the time A will be greater than B. | Lets say the joint pdf of A and B is $f(a,b)$. The analytical solution is:
$\int\_{b\geq a} f(a,b) dadb$, this will just be the integral above the line $a=b$ on the domain of $f(a,b)$ |
1,077,576 | How can I prove
>
> $$\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}...}}}}=2$$
>
>
>
I don't know which method can be used for this? | 2014/12/22 | [
"https://math.stackexchange.com/questions/1077576",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/187799/"
] | We can define $x=\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}...}}}}$ as follows:
Let $x\_1 = \sqrt 2$ and $x\_{n+1} = (\sqrt 2)^{x\_{n}}$
We can show $x\_n \lt 2\ \forall n$ by induction, since if $y \lt 2$, then $(\sqrt 2)^y \lt 2$. And $x\_n$ is clearly monotonically increasing, so $x\_n \to x$.
But $$x\_{n+1} = (\sqrt 2)^{x\_{n}}$$
so taking limits, we get that $$x = (\sqrt 2)^{x}$$
Solving this, and using the fact that $x \le 2$ gives $x =2$. | Define $x\_1=\sqrt{2}$ and $x\_{n+1}=\sqrt{2}^{x\_n}$.
Prove by induction that $x\_n \leq x\_{n+1} \leq 2$. As the sequence is bounded and increasing, it is convergent, and the limit is between $x\_1=\sqrt{2}$ and $2$.
Finish the proof by observing that
$$\sqrt{2}^x=x$$
has an unique solution on the interval $[\sqrt{2}, 2]$.
For the last part, as well as for the monotony, you should study first the monotony/sign of $x-\sqrt{2}^x$ on $ [\sqrt{2}, 2]$ |
1,077,576 | How can I prove
>
> $$\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}...}}}}=2$$
>
>
>
I don't know which method can be used for this? | 2014/12/22 | [
"https://math.stackexchange.com/questions/1077576",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/187799/"
] | We can define $x=\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}...}}}}$ as follows:
Let $x\_1 = \sqrt 2$ and $x\_{n+1} = (\sqrt 2)^{x\_{n}}$
We can show $x\_n \lt 2\ \forall n$ by induction, since if $y \lt 2$, then $(\sqrt 2)^y \lt 2$. And $x\_n$ is clearly monotonically increasing, so $x\_n \to x$.
But $$x\_{n+1} = (\sqrt 2)^{x\_{n}}$$
so taking limits, we get that $$x = (\sqrt 2)^{x}$$
Solving this, and using the fact that $x \le 2$ gives $x =2$. | **Step One.** Define the recursive sequence
$$
a\_0=\sqrt{2}, \quad a\_{n+1}=\sqrt{2}^{a\_n},\,\,n\in\mathbb N.
$$
**Step Two.** Show that $\{a\_n\}$ is increasing (inductively), and upper bounded by $2$ (also inductively).
**Step Three.** Due to *Step Two* the sequence $\{a\_n\}$ is convergent. Let $a\_n\to x$. Clearly, $\sqrt{2}<x\le 2$.
But $a\_{n+1}=\sqrt{2}^{a\_n}\to x$, as well. Hence
$$
x=\lim\_{n\to\infty}a\_n=\lim\_{n\to\infty}a\_{n+1}=\lim\_{n\to\infty}\sqrt{2}^{a\_n}=\sqrt{2}^x.
$$
Thus $x$ satisfies $\sqrt{2}^x=x$.
**Step Four.** Show that $x<\sqrt{2}^x$, for all $x\in (\sqrt{2},2)$, and thus $x=2$. |
1,077,576 | How can I prove
>
> $$\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}^{\sqrt{2}...}}}}=2$$
>
>
>
I don't know which method can be used for this? | 2014/12/22 | [
"https://math.stackexchange.com/questions/1077576",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/187799/"
] | **Step One.** Define the recursive sequence
$$
a\_0=\sqrt{2}, \quad a\_{n+1}=\sqrt{2}^{a\_n},\,\,n\in\mathbb N.
$$
**Step Two.** Show that $\{a\_n\}$ is increasing (inductively), and upper bounded by $2$ (also inductively).
**Step Three.** Due to *Step Two* the sequence $\{a\_n\}$ is convergent. Let $a\_n\to x$. Clearly, $\sqrt{2}<x\le 2$.
But $a\_{n+1}=\sqrt{2}^{a\_n}\to x$, as well. Hence
$$
x=\lim\_{n\to\infty}a\_n=\lim\_{n\to\infty}a\_{n+1}=\lim\_{n\to\infty}\sqrt{2}^{a\_n}=\sqrt{2}^x.
$$
Thus $x$ satisfies $\sqrt{2}^x=x$.
**Step Four.** Show that $x<\sqrt{2}^x$, for all $x\in (\sqrt{2},2)$, and thus $x=2$. | Define $x\_1=\sqrt{2}$ and $x\_{n+1}=\sqrt{2}^{x\_n}$.
Prove by induction that $x\_n \leq x\_{n+1} \leq 2$. As the sequence is bounded and increasing, it is convergent, and the limit is between $x\_1=\sqrt{2}$ and $2$.
Finish the proof by observing that
$$\sqrt{2}^x=x$$
has an unique solution on the interval $[\sqrt{2}, 2]$.
For the last part, as well as for the monotony, you should study first the monotony/sign of $x-\sqrt{2}^x$ on $ [\sqrt{2}, 2]$ |
45,341,326 | This SP is called on by sp\_send\_dbmail, which is executed daily on a job. When this does not have any records to show on report, I do not want the section sent with '0 rows affected' I still want to report the sections that have records available.
here is my sp it actually has 15 separate select statements, but for the sake of saving space I am only showing 2
```
------------------------------------------THIS IS FOR DEPARTMENT CODE [FS - FD]
DECLARE
@Now2 DATETIME,
@EndReportDate2 DATETIME,
@StartReportDate2 DATETIME
SET @Now2 = GETDATE()
SET @EndReportDate2 = DATEADD(dd, DATEDIFF(dd, 0, @Now2), -1)
SET @StartReportDate2 = DATEADD(dd, DATEDIFF(dd, 0, @Now2), -1)
SELECT StatDate = TimeLog.EventDate
,[ID#] = a.ID
,Codes = (a.DeptCode + '-' + a.OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60 as decimal(10,0))
,[Goal%] = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/1552*100 as decimal(10,0))) + '%')
,AssociateName = (b.FirstName + ' ' + b.LastName)
FROM PTW.dbo.TimeLog a LEFT JOIN PTW.dbo.AssociateInfo b
ON a.ID = b.ID
WHERE EventDate BETWEEN @StartReportDate2 AND @EndReportDate2 AND DeptCode = 'FS' AND OpCode = 'FD'
GROUP BY a.EventDate, a.ID, a.DeptCode, a.OpCode, b.FirstName, b.LastName
ORDER BY UPH DESC
------------------------------------------THIS IS FOR DEPARTMENT CODE [FS - FT]
DECLARE
@Now3 DATETIME,
@EndReportDate3 DATETIME,
@StartReportDate3 DATETIME
SET @Now3 = GETDATE()
SET @EndReportDate3 = DATEADD(dd, DATEDIFF(dd, 0, @Now3), -1)
SET @StartReportDate3 = DATEADD(dd, DATEDIFF(dd, 0, @Now3), -1)
SELECT StatDate = a.EventDate
,[ID#] = a.ID
,Codes = (a.DeptCode + '-' + a.OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60 as decimal(10,0))
,[Goal%] = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/295*100 as decimal(10,0))) + '%')
,AssociateName = (b.FirstName + ' ' + b.LastName)
FROM PTW.dbo.TimeLog a LEFT JOIN PTW.dbo.AssociateInfo b
ON a.ID = b.ID
WHERE EventDate BETWEEN @StartReportDate3 AND @EndReportDate3 AND DeptCode = 'FS' AND OpCode = 'FT'
GROUP BY a.EventDate, a.ID, a.DeptCode, a.OpCode, b.FirstName, b.LastName
ORDER BY UPH DESC
```
Here where I call for it with sp\_send\_dbmail
```
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DBMail,
@recipients = 'me@me.com',
@subject = 'FLAT_Daily',
@query = N'EXEC PTW.dbo.SP_FLAT_Daily',
@query_attachment_filename = 'FLAT_Daily.txt'
```
Here are my results
```
StatDate ID# Codes TotalTime Units UPH Goal% AssociateName
-------- --- ----- --------- ----- --- ----- -------------
7/24/2017 1234567 FS-FD 03:40:00 0 0 0% MY NAME
(1 rows affected)
StatDate ID# Codes TotalTime Units UPH Goal% AssociateName
-------- --- ----- --------- ----- --- ----- -------------
(0 rows affected)
```
Some days I have records on both, but like the example sometimes only one portion has records. How can I send only what has records available?
-----------------------------------------------------------------------
-----------------------------------------------------------------------
Would also like to group resultset like below. Showing only same `associateName` with all department `codes` individual worked in for the specified time.
```
StatDate ID Codes TotalTime Units UPH Goal AssociateName
---------- ----------- ----- --------- ----------- ------- ------ ------------------
2017-07-26 2375935 fs-ft 03:44:00 263 70 24% Druid Druid
2017-07-26 2375935 fs-fd 04:50:00 553 114 7% Druid Druid
2017-07-26 2375935 fr-pk 04:50:00 553 114 7% Druid Druid
(3 row(s) affected)
``` | 2017/07/27 | [
"https://Stackoverflow.com/questions/45341326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8088749/"
] | Your bitwise code is incorrect.
Assume A = 0001
Assume B = 0010
A is first bit is set, B is 2nd bit is set
x & ~A doesn't mean what you think. ~A doesn't mean first bit is off, it means 1110. So x & ~A would only be true if those 3 bits are set, not just if the first bit is off.
If you want A is not set, that's ((x & A) == 0). Or if you want cleaner code, use the [Flags] modifier on the enum and then you get Enum.HasFlag(). | You need to think about what you're *trying* to do with the flags. Flags are usually not exclusive settings; they're used in combination. So let's examine your logic:
For `TR1`
```
TR1 = ~(SB1) & ~(SB2), // BIT12 - 0 BIT13 - 0
```
The result of which is:
```
0011111111111
```
Note that this has turned on every flag *except* `SB1` and `SB2`. Setting one flag should *not* affect others.
What you're really trying to do is check which flags have been set. For this, you should have either helper methods, or use `Enum.HasFlag`. It should *not* be baked into the `enum` itself, as it's impossible to represent `SB1 & !SB2` as a set of bits, while also treating them as flags.
Thus, you should have:
```
[Flags]
public enum EFlagsBmp
{
...
}
public static class EFlagsBmpHelper
{
public static bool TR1(this EFlagsBmp flags)
{
return !flags.HasFlag(EFlagsBmp.SB1) && !flags.HasFlag(EFlagsBmp.SB2);
}
public static bool TR2(this EFlagsBmp flags)
{
return flags.HasFlag(EFlagsBmp.SB1) && !flags.HasFlag(EFlagsBmp.SB2);
}
public static bool TR3(this EFlagsBmp flags)
{
return !flags.HasFlag(EFlagsBmp.SB1) && flags.HasFlag(EFlagsBmp.SB2);
}
public static bool TR4(this EFlagsBmp flags)
{
return flags.HasFlag(EFlagsBmp.SB1) && flags.HasFlag(EFlagsBmp.SB2);
}
}
```
Which you can then use as:
```
EFlagsBmp.K.TR1()
``` |
74,530,022 | The deviations of the mean should always sum up to 0.
However, when the mean has a lot of digits, maybe infinitely like this one which is 20/7, R fails to calculate it.
```
x <- c(1,2,2,3,3,4,5)
sum(x - mean(x))
[1] -4.440892e-16
```
I am quite a newbie and have not found any information about this so far, maybe I was not searching for the right terms.
Is it possible to calculate with infinitely long numbers in R?
I am asking this out of theoretical interest. | 2022/11/22 | [
"https://Stackoverflow.com/questions/74530022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19487551/"
] | In your entity, do not name properties with `id_*`. The client-Property in the Group(?) Entity should be named `$client`, not `$id_client`.
Then, in your Form, name that field excactly like the property in the Group-Entity. Doctrine (as a DBAL should do) does that behind-the-scene relating of the object by the actual id for you.
**Group1Type.php**
```php
->add('client', EntityType::class, [
'class' => Client::class,
// ...
])
```
And your **Group-Entity** (or Group1?)
```php
class Group
{
// ...
#[ORM\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]
#[ORM\JoinColumn(nullable: false)]
private $client;
// ...
}
```
>
> It is totallfy fine and correct that the Form it self submits and handles the Entity-Instance of the selected client. You almost never handle `$id` values. Thats one of the features of doctrine!
>
>
>
>
> See the [Symfony documentation](https://symfony.com/doc/current/reference/forms/types/entity.html) for more information on how to use `EntityType` fields.
>
>
>
---
>
> **Note:** From the naming you gave, **I suspect** you have the **wrong relation**, maybe it should be `OneToMany`? (Can you tell us how `Group` and `Client` is related? Does 1 Group have multiple clients or vice versa?)
>
>
>
---
>
> **Sidenote:** In rare cases, when you really need a Number related to an Entity (e.g. a textinput where user can enter a customer number which then translates to a real customer entity) you can use `DataTransformer` to translate such values. **But this is not what you want here!**
>
>
> | simple solution is to use choice type, this way you dont need the relation and when you submit you will have the id of the client. If load the form for editing (loading the entity, it will show the selected value from the submit)
```
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('client', ChoiceType::class, [
'choices'=> $this->getClients(),
])
}
public function getClients(){
$conn = $this->getEntityManager()->getConnection();
$query = "SELECT `name`, `id` FROM `clients` order by `name`";
$stmt = $conn->executeQuery($query);
return $stmt->fetchAllKeyValue();
}
```
it will generate a dropdown menu where the value is the id, and the option is the client name |
52,653 | Ecclesiastes 7:26
>
> I find more bitter than death the woman who is a snare, whose heart is a trap and whose hands are chains. The man who pleases God will escape her, but the sinner she will ensnare.
>
>
>
Solomon had many many wives and concubines. Some ensnared him. He knew this would go bad for him. | 2020/10/28 | [
"https://hermeneutics.stackexchange.com/questions/52653",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/35953/"
] | Solomon was a very complex character who was (as with all humans) full of contradictions!
* He was an astute observer of human nature (as Ecclesiastes reveals)
* He was a victim of his own carnality as his biography reveals
* He was a brilliant naturalist and amateur "scientist"
* He was capable of being the human conduit of great divine truths as Ps 72 and Proverbs shows
* He was also a brilliant poet who composed some of the most inspiring literature of all time
* He was a superb politician and statesman (1 Kings 4:20-34) who made Israel the greatest nation in his time.
Thus, much of Solomon's inspired writings in Ecclesiastes is based on both person (and very deep) experience and that of others around him. Which was inspired by which cannot now be known - just enjoy and apply the great man's wisdom. | A note about the authorship of Ecclesiastes. Scholars don't know who wrote Ecclesiastes so it would be tenuous to apply everything written to Solomon.
Here is a quote from Michael V. Fox's commentary of Ecclesiastes (or Hebrew, *Qohelet* - which can mean 'teacher to the public'):
>
> "Koheleth was traditionally identified with Solomon...since the nineteenth century, critical scholarship has not regarded Solomon as the actual author. Though modern scholars ***do not*** think that Koheleth was Solomon, almost all of them believe that the author wants us to make that identification.
>
>
>
You can check out a short video regarding who wrote Ecclesiastes, from an Old Testament scholar/professor, John Walton, [here](https://www.youtube.com/watch?v=QoZ-_MIUwZA) |
77,755 | My bike has an 8-speed nexus hub and the plastic adjustment screw broke. Now I can't adjust the cable anymore and can't use some of the gears. My question is, can I use a normal thumb shifter on my nexus 8 speed since the nexus shifter (internal gear bike in general) is very uncommon where I live and I don't want to pay for the ridiculous price of shipping fee plus tax on my old bike. | 2021/07/12 | [
"https://bicycles.stackexchange.com/questions/77755",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/57731/"
] | The ultimate marker of how durable a paint finish is is to see how easily it chips :)
You can’t really predict how durable the paint will be. Since paint is a type of coating, it is subject to a vast variety of factors such as the cleanliness of the aluminum, surface roughness, primer choice, painting technique, etc. There isn’t a highly identifiable characteristic you can judge to determine the quality of the entire process.
That said, I’ve found powder coated paint to be more durable. It seems to be less brittle than spray-on paint, chipping less, and is often thicker, so hides scratches better. Since you see white stuff (primer), your frame is sprayed, which may explain the relative ease of chipping.
To protect your paint, purchase a vinyl or (ideally) polyurethane wrap product so you can wrap entire frame tubes, not just using small decals. Some examples include 3M paint protection film, RideWrap, and AMS frame protection. Existing chips can be touched up with matching enamel paint or nail polish. I’ve even had success using artistic acrylic paint for hard-to-match colors, with clear nail polish on top for protection. | I don't think you can tell to look at a paint job whether it will be durable. Perhaps a paint specialist can. There are a lot of different paint techniques and technologies. There are paints that are basically 2-stage epoxies, paints that are basically rubber, as well as powdercoat, enamel, etc.
My most expensive bike has an enamel paint job that is beautiful but not durable. |
77,755 | My bike has an 8-speed nexus hub and the plastic adjustment screw broke. Now I can't adjust the cable anymore and can't use some of the gears. My question is, can I use a normal thumb shifter on my nexus 8 speed since the nexus shifter (internal gear bike in general) is very uncommon where I live and I don't want to pay for the ridiculous price of shipping fee plus tax on my old bike. | 2021/07/12 | [
"https://bicycles.stackexchange.com/questions/77755",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/57731/"
] | Paint damage due to locks is a perennial problem. Another option aside from those above is to better cushion your lock. I assume it's the lock itself and attached few chain links that are loose and unprotected, so why not put them in a padded pouch? I would think neoprene wetsuit material would be a good choice and easily found suitable-looking camera lens pouches [like this one](https://www.walmart.com/ip/ULTIMAXX-Lens-Pouch-Medium/613929969) (example only). | I don't think you can tell to look at a paint job whether it will be durable. Perhaps a paint specialist can. There are a lot of different paint techniques and technologies. There are paints that are basically 2-stage epoxies, paints that are basically rubber, as well as powdercoat, enamel, etc.
My most expensive bike has an enamel paint job that is beautiful but not durable. |
574,327 | Clearly, if I'm spinning, I'll feel my arms lift away from my torso. But what sets the preferred angular momentum? Is there a preferred angular momentum in a vacuum? In Newtonian mechanics, I imagine one would appeal to the ether, so I suspect the answer lies in general relativity. | 2020/08/19 | [
"https://physics.stackexchange.com/questions/574327",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/-1/"
] | If you're spinning you'll have intrinsic angular momentum, it doesn't need to have anything to do with extrinsic objects.
If you're spinning You'll feel the force proportional to the distance from the axis of rotation pulling each part of your body away from the axis of rotation, and this force will be felt everywhere except along the axis, thus also uniquely fixing it. | Einstein thought about this and coined the term [Mach’s principle](https://en.m.wikipedia.org/wiki/Mach%27s_principle). The basic idea behind Mach’s principle is that very distant stars and galaxies (or maybe, in modern cosmology, the Cosmic Microwave Background Radiation) define a preferred reference frame against which absolute rotation can be measured. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | You can have an unlimited number of apps on your developer-unlocked phone from the Windows Store, but there is a limit of 10 developer apps that can be loaded onto a dev-unlocked phone at any time. Once you have reached that limit, you must remove at least one of them from your developer phone in order to load another one onto the phone. This is a simple solution and doesn't require unregistering & reregistering your phone. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | Check applications list and uninstall all other developer application. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | I think this step worked for me. Try manually deleting all files in Bin and obj folders of your project (not just clean project in VS)
Still having some issues with registering almost everyday the device as a developer. Do you experience this issue or only the error while deploying? |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | I just ran into this, and then realized I still had my Windows 7 phone registered with the same name. I deleted that registration at <https://dev.windowsphone.com/en-us/Account/Devices>, unregistered and re-registered the Phone 8, and it now works. YMMV |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | You can have an unlimited number of apps on your developer-unlocked phone from the Windows Store, but there is a limit of 10 developer apps that can be loaded onto a dev-unlocked phone at any time. Once you have reached that limit, you must remove at least one of them from your developer phone in order to load another one onto the phone. This is a simple solution and doesn't require unregistering & reregistering your phone. | Check applications list and uninstall all other developer application. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | You can have an unlimited number of apps on your developer-unlocked phone from the Windows Store, but there is a limit of 10 developer apps that can be loaded onto a dev-unlocked phone at any time. Once you have reached that limit, you must remove at least one of them from your developer phone in order to load another one onto the phone. This is a simple solution and doesn't require unregistering & reregistering your phone. | Go to your applications list on your mobile and uninstall the developer applications, because you have limited developer apps on you phone. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | You can have an unlimited number of apps on your developer-unlocked phone from the Windows Store, but there is a limit of 10 developer apps that can be loaded onto a dev-unlocked phone at any time. Once you have reached that limit, you must remove at least one of them from your developer phone in order to load another one onto the phone. This is a simple solution and doesn't require unregistering & reregistering your phone. | I think this step worked for me. Try manually deleting all files in Bin and obj folders of your project (not just clean project in VS)
Still having some issues with registering almost everyday the device as a developer. Do you experience this issue or only the error while deploying? |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | You can have an unlimited number of apps on your developer-unlocked phone from the Windows Store, but there is a limit of 10 developer apps that can be loaded onto a dev-unlocked phone at any time. Once you have reached that limit, you must remove at least one of them from your developer phone in order to load another one onto the phone. This is a simple solution and doesn't require unregistering & reregistering your phone. | I just ran into this, and then realized I still had my Windows 7 phone registered with the same name. I deleted that registration at <https://dev.windowsphone.com/en-us/Account/Devices>, unregistered and re-registered the Phone 8, and it now works. YMMV |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | Go to your applications list on your mobile and uninstall the developer applications, because you have limited developer apps on you phone. |
16,196,318 | I started a Windows 8 phone application and am trying to use a NEW phone as the device for debugging.
>
> Unable to install application. The maximum number of developer applications on this phone has been reached. Please uninstall a developer application and try again.
>
>
>
I registered the device so I do not know what the issue is. I have read about other people having the same issue but have not found a solution yet.
([Windows Phone App Deployment Issue](http://www.kunal-chowdhury.com/2013/01/solution-to-resolve-windows-phone-app-deployment-issue.html) - see end comment)
**Just to make it clear. I have not yet installed any other apps on this phone. It is a new phone**
I also tried it on another phone of someone I know (but same type Lumia 920) and get the same error.
**Edit:** After registering on the Windows Phone Dev Center. I still get the same error even after unregistering and reregistering the phone. Strange thing is it says under my account under phones *"You haven't registered any phones."*, but I did. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16196318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834815/"
] | When you first use the Developer Registration Tool, it checks DevCenter for your permission level (there are different types of accounts that allow different amounts of unlocked devices and allowed installations).
Then, the tool unlocks the device and sets those permissions. (make sure the device is connected to the internet by itself, don't rely on the usb connection).
If you've had recent permission level changes or are changing to a new developer account, you may need to restart the phone to clear the old permissions after removing it from your DevCenter account.
To summarize:
1. Remove phone from DevCenter
2. Open Developer Registration Tool and plug in the phone. Confirm the device is no longer registered
3. Unplug and Reset the phone (Settings > About > Reset)
4. Set up the phone, connect to internet
5. Plug the phone back into the registration tool
6. Register the device again | I have brand new Lumia 620 and have the same error. The reason was in different country I set in my phone. Country of your microsoft account and the phone must be the same, I think. |
478,543 | I'm trying to install a certificate into my windows 2008 but I'm not able to do it right.
I have a .crt file and I click to install from contextual menu. It succeed to import but if I browse the certificate store (personal -> local computer) it is not there.
I searched by thumbprint on all repositories and the cert is nowhere.
What's missing here? | 2013/02/13 | [
"https://serverfault.com/questions/478543",
"https://serverfault.com",
"https://serverfault.com/users/55884/"
] | You're installing the certificate into your user account's certificate store. Use the "Import" functionality inside the Certificates MMC snap-in, targeted at the computer, to import the certificate into the computer's certificate store. | You have to import the certificate in the proper keystore. The wizard for the import has the option to chose the X509 certificates keystore.
You have to chose the proper keystore for your application.
What are you trying to import?
* A host certificate for a CRQ you submited to be signed for your host
* An exported keystore with a certificate and a private key
* A root certificate of a not yet trusted certificate authority
* A self signed host certificate |
478,543 | I'm trying to install a certificate into my windows 2008 but I'm not able to do it right.
I have a .crt file and I click to install from contextual menu. It succeed to import but if I browse the certificate store (personal -> local computer) it is not there.
I searched by thumbprint on all repositories and the cert is nowhere.
What's missing here? | 2013/02/13 | [
"https://serverfault.com/questions/478543",
"https://serverfault.com",
"https://serverfault.com/users/55884/"
] | This is what you should do if you want to import a cert into the SYSTEM account certificate store:
1. fire up MMC by executing mmc.exe
2. choose *File* / *Add/Remove Snap-in* fom the menu
3. select the *"Certificates"* snap-in to add and use the "Local computer" as the destination
4. import the certificate using the wizard and make sure you are specifying the store and not letting the wizard decide
If you simply "import" the cert using Windows Explorer it will go into the current users' personal certificate store - where you probably do not want to see it.
See also <http://technet.microsoft.com/en-US/library/cc754431.aspx> | You have to import the certificate in the proper keystore. The wizard for the import has the option to chose the X509 certificates keystore.
You have to chose the proper keystore for your application.
What are you trying to import?
* A host certificate for a CRQ you submited to be signed for your host
* An exported keystore with a certificate and a private key
* A root certificate of a not yet trusted certificate authority
* A self signed host certificate |
3,785,560 | Consider the function
I want to show that the function
$F(x,y)=\frac{xy}{x^2+y^2}$ defined to be 0 at (0,0)
Is continuous in each variable separately and then to show that the function is not continuous at 0
How do I show this topologically (inverse image of open sets)? If the denominator is not zero, then holding one variable fixed, we see that we have a rational function is continuous.
Why don’t we have continuity at 0? | 2020/08/09 | [
"https://math.stackexchange.com/questions/3785560",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/364333/"
] | I think your proof is essentially correct at this point. You should show that $f(a) = \sup f(r)$ where the sup is taken over rational numbers $r$ such that $r\leq a$. This follows from the monotonicity of $f\_n$ and taking limits. The reason we need $f(x) = \sup f(r)$ here is mostly in step (iv). We need $f(x)$ to have only a countable number of discontinuities, so defining it in this way guarantees that it is monotonically increasing and thus discontinuous at at most countably many points. | To prove part(b):
To simplify notation, suppose that there exists a continuous function
$f:\mathbb{R}\rightarrow[0,1]$ such that $f\_{n}\rightarrow f$ pointwisely.
We go to show that $f\_{n}\rightarrow f$ uniformly on each compact
subset of $\mathbb{R}$. Firstly, observe that $f$ is monotonic increasing.
Let $M>0$ be arbitrary. We go to show that $f\_{n}\rightarrow f$
uniformly on $[-M,M]$. Let $\varepsilon>0$ be given. By Cantor theorem,
$f$ is uniformly continuous on $[-M,M]$, so there exists $\delta>0$
such that $|f(x)-f(y)|<\varepsilon$ whenever $x,y\in[-M,M]$ and
$|x-y|<\delta$. Choose $N\in\mathbb{N}$ such that $\frac{2M}{N}<\delta$.
Define $x\_{i}=-M+i\cdot\frac{2M}{N}$, $i=0,1,\ldots,N$. Since $f\_{k}(x\_{i})\rightarrow f(x\_{i})$
as $k\rightarrow\infty$, there exists $K\in\mathbb{N}$ such that
$|f\_{k}(x\_{i})-f(x\_{i})|<\varepsilon$ whenever $k\geq K$ and $i=0,1,\ldots,N$.
Let $k\geq K$ and $x\in[-M,M]$ be arbitrary. If $x\in\{x\_{0},x\_{1},\ldots,x\_{N}\}$,
we clearly have $|f\_{k}(x)-f(x)|<\varepsilon$. Suppose that $x\notin\{x\_{0},x\_{1},\ldots,x\_{N}\}$,
then there exists $i$ such that $x\_{i-1}<x<x\_{i}$. Observe that
$|x-x\_{i-1}|<\delta$ and $|x-x\_{i}|<\delta$, so $|f(x)-f(x\_{i-1})|<\varepsilon$
and $|f(x)-f(x\_{i})|<\varepsilon$. We have that
\begin{eqnarray\*}
f(x)-f\_{k}(x) & \leq & f(x)-f\_{k}(x\_{i-1})\\
& \leq & f(x\_{i-1})-f\_{k}(x\_{i-1})+\varepsilon\\
& \leq & 2\varepsilon.
\end{eqnarray\*}
Moreover,
\begin{eqnarray\*}
f(x)-f\_{k}(x) & \geq & f(x)-f\_{k}(x\_{i})\\
& \geq & f(x\_{i})-f\_{k}(x\_{i})-\varepsilon\\
& \geq & -2\varepsilon.
\end{eqnarray\*}
That is,
$$
|f(x)-f\_{k}(x)|\leq2\varepsilon.
$$
Thefore, $f\_{n}\rightarrow f$ uniformly on each compact subset of
$\mathbb{R}$. |
3,785,560 | Consider the function
I want to show that the function
$F(x,y)=\frac{xy}{x^2+y^2}$ defined to be 0 at (0,0)
Is continuous in each variable separately and then to show that the function is not continuous at 0
How do I show this topologically (inverse image of open sets)? If the denominator is not zero, then holding one variable fixed, we see that we have a rational function is continuous.
Why don’t we have continuity at 0? | 2020/08/09 | [
"https://math.stackexchange.com/questions/3785560",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/364333/"
] | To prove part (a):
(A) Firstly, we show that there exists a subsequence $(f\_{n\_{k}})\_{k}$
such that $\lim\_{k\rightarrow\infty}f\_{n\_{k}}(r)$ for each $r\in\mathbb{Q}$.
The proof involves an important trick known as Cantor Diagonal Argument.
Fix an enumeration $\mathbb{Q}=\{r\_{n}\mid n\in\mathbb{N}\}$. Since
$(f\_{n}(r\_{1}))\_{n}$ is a bounded sequence in $[0,1],$ it has a
convergent subsequence. Denote such a subsequence by $(f\_{\theta(1,k)}(r\_{1}))\_{k}$.
Here, $\theta(1,k)\in\mathbb{N}$ such that $\theta(1,1)<\theta(1,2)<\ldots$
(That is, $\theta(1,k)$ is the usual $n\_{k}$ for a subsequence.).
Again, the sequence $(f\_{\theta(1,k)}(r\_{2}))\_{k}$ is a bounded,
so it has a convergent subsequece $(f\_{\theta(2,k)}(r\_{2}))\_{k}$.
Note that $\theta(2,1)<\theta(2,2)<\ldots$ and $\theta(2,k)\geq\theta(1,k)$.
Observe that $(f\_{\theta(2,k)}(r\_{1}))\_{k}$ is a subsequence of $(f\_{\theta(1,k)}(r\_{1}))\_{k}$,
so $(f\_{\theta(2,k)}(r\_{1}))\_{k}$ is also convergent. Repeat the
above argument (more accurately, by recursion theorem), we obtain
$\theta(m,k)\in\mathbb{N}$, $m,k\in\mathbb{N}$ such that:
(1) $(f\_{\theta(m,k)})\_{k}$ is a subsequence of $(f\_{\theta(m-1,k)})\_{k}$
($\theta(0,k):=k$ by convention),
(2) $(f\_{\theta(m,k)}(x))\_{k}$ is convergent for $x\in\{r\_{1},r\_{2},\ldots,r\_{m}\}$.
We assert that $(f\_{\theta(k,k)})\_{k}$ is a subsequence of $(f\_{k})\_{k}$
and for each $x\in\mathbb{Q}$, $(f\_{\theta(k,k)}(x))\_{k}$ converges.
To show that $(f\_{\theta(k,k)})\_{k}$ is a subsequence of $(f\_{k})\_{k}$,
it suffices that $\theta(1,1)<\theta(2,2)<\ldots$. Let $k\in\mathbb{N}$.
Since $(f\_{\theta(k+1,j)})\_{j}$ is a subsequence of $(f\_{\theta(k,j)})\_{j}$,
we have that $\theta(k+1,j)\geq\theta(k,j)$ for all $j$. In particular,
we have $\theta(k+1,k+1)\geq\theta(k,k+1)>\theta(k,k)$. Let $x\in\mathbb{Q}$,
then $x=r\_{k\_{0}}$ for some $k\_{0}$. Suppose that $\lim\_{j\rightarrow\infty}f\_{\theta(k\_{0},j)}(r\_{k\_{0}})=l$.
Let $\varepsilon>0$, then there exists $J$ such that $|f\_{\theta(k\_{0},j)}(r\_{k\_{0}})-l|<\varepsilon$
whenever $j\geq J$. Now, for any $j\geq\max(J,k\_{0})$, observe that
$\theta(j,j)\in\{\theta(k\_{0},J),\theta(k\_{0},J+1),\ldots\}$. For,
since $(f\_{\theta(j,l)})\_{l}$ is a subsequence of $(f\_{\theta(j-1,l)})\_{l}$,
we have that $\theta(j,l)\in\{\theta(j-1,l),\theta(j-1,l+1),\ldots\}$
for each $l$. In particular, $\theta(j,j)\in\{\theta(j-1,j),\theta(j-1,j+1),\ldots\}$.
Argue it inductively, we have
\begin{eqnarray\*}
\theta(j,j) & \in & \{\theta(j-1,j),\theta(j-1,j+1),\ldots\}\\
& \subseteq & \{\theta(j-2,j),\theta(j-2,j+1),\ldots\}\\
& \subseteq & \ldots\\
& \subseteq & \{\theta(k\_{0},j),\theta(k\_{0},j+1),\ldots\}\\
& \subseteq & \{\theta(k\_{0},J),\theta(k\_{0},J+1),\ldots\}.
\end{eqnarray\*}
Hence, $|f\_{\theta(j,j)}(r\_{k\_{0}})-l|<\varepsilon$. This show that
$\lim\_{k}f\_{\theta(k,k)}(x)$ converges for each $x\in\mathbb{Q}$.
(B) Construction of $g\_{2}$: Define $g\_{1}:\mathbb{Q}\rightarrow[0,1]$
by $g\_{1}(r)=\lim\_{k}f\_{\theta(k,k)}(r)$. For each $x,y\in\mathbb{Q}$
with $x<y$, we have $f\_{\theta(k.k)}(x)\leq f\_{\theta(k,k)}(y)$.
Letting $k\rightarrow\infty$ yields $g\_{1}(x)\leq g\_{1}(y)$. Therefore
$g\_{1}$ is montonic increasing. Define $g\_{2}:\mathbb{R}\rightarrow[0,1]$
by $g\_{2}(x)=\inf\{g\_{1}(r)\mid r\in[x,\infty)\cap\mathbb{Q}\}$.
We go to show that $g\_{2}$ is increasing and $f\_{\theta(k,k)}(x)\rightarrow g\_{2}(x)$
whenever $g\_{2}$ is continuous at $x$. Let $x,y\in\mathbb{R}$ with
$x<y$. Clearly $\{g\_{1}(r)\mid r\in[x,\infty)\cap\mathbb{Q}\}\supseteq\{g\_{1}(r)\mid r\in[y,\infty)\cap\mathbb{Q}\}$,
so $\inf\{g\_{1}(r)\mid r\geq x\}\leq\inf\{g\_{1}(r)\mid r\geq y\}$.
That is, $g\_{2}(x)\leq g\_{2}(y)$. Since $g\_{1}$ is increasing, it
is clear that $g\_{2}(r)=g\_{1}(r)$ for each $r\in\mathbb{Q}$. Let
$x\in\mathbb{R}$ such that $g\_{2}$ is continuous at $x$. Let $r\in[x,\infty)\cap\mathbb{Q}$
be arbitrary. For each $k$, we have $f\_{\theta(k,k)}(x)\leq f\_{\theta(k,k)}(r)$.
Therefore, $\limsup\_{k}f\_{\theta(k,k)}(x)\leq\limsup\_{k}f\_{\theta(k,k)}(r)=g\_{1}(r)$.
Therefore $\limsup\_{k}f\_{\theta(k,k)}(x)\leq\inf\_{r\in[x,\infty)\cap\mathbb{Q}}g\_{1}(r)=g\_{2}(x)$.
Let $\varepsilon>0$. Since $g\_2$ is continuous at $x$, there exists $r\in(-\infty,x)\cap\mathbb{Q}$
such that $|g\_{2}(x)-g\_{2}(r)|<\varepsilon$. Therefore
\begin{eqnarray\*}
g\_{2}(x) & \leq & g\_{2}(r)+\varepsilon\\
& = & g\_{1}(r)+\varepsilon\\
& = & \lim\_{k}f\_{\theta(k,k)}(r)+\varepsilon.
\end{eqnarray\*}
On the other hand, for each $k$, $f\_{\theta(k,k)}(r)\leq f\_{\theta(k,k)}(x)$,
so $\liminf\_{k}f\_{\theta(k,k)}(r)\leq\liminf\_k f\_{\theta(k,k)}(x)$.
Combining, we obtain:
\begin{eqnarray\*}
g\_{2}(x) & \leq & \varepsilon+\liminf\_{k}f\_{\theta(k,k)}(x).
\end{eqnarray\*}
Since $\varepsilon>0$ is arbitrary, we have $g\_{2}(x)\leq\liminf f\_{\theta(k,k)}(x)$.
Hence, $\limsup\_{k}f\_{\theta(k,k)}(x)\leq g\_{2}(x)\leq\liminf\_k f\_{\theta(k,k)}(x)$.
It follows that $\lim\_{k}f\_{\theta(k,k)}=g\_{2}(x)$.
(C) Since $g\_{2}$ is an increasing function, the set $A=\{x\in\mathbb{R}\mid g\_{2}$
is discontinuous at $x\}$ is countable. Starting from the sequence
$(f\_{\theta(k,k)})\_{k}$ and going through Cantor Diagonal Argument again,
we can choose a subsequence $(f\_{n\_{k}})\_{k}$ of $(f\_{\theta(k,k)})\_{k}$
such that $(f\_{n\_{k}}(x))\_{k}$ converges at each $x\in A$. For $x\in A^{c}$,
$(f\_{\theta(k,k)}(x))\_{k}$ is already convergent, so $(f\_{n\_{k}}(x))\_{k}$
is convergent too. In short $\lim\_{k}f\_{n\_{k}}(x)$ converges for
each $x\in\mathbb{R}$. | To prove part(b):
To simplify notation, suppose that there exists a continuous function
$f:\mathbb{R}\rightarrow[0,1]$ such that $f\_{n}\rightarrow f$ pointwisely.
We go to show that $f\_{n}\rightarrow f$ uniformly on each compact
subset of $\mathbb{R}$. Firstly, observe that $f$ is monotonic increasing.
Let $M>0$ be arbitrary. We go to show that $f\_{n}\rightarrow f$
uniformly on $[-M,M]$. Let $\varepsilon>0$ be given. By Cantor theorem,
$f$ is uniformly continuous on $[-M,M]$, so there exists $\delta>0$
such that $|f(x)-f(y)|<\varepsilon$ whenever $x,y\in[-M,M]$ and
$|x-y|<\delta$. Choose $N\in\mathbb{N}$ such that $\frac{2M}{N}<\delta$.
Define $x\_{i}=-M+i\cdot\frac{2M}{N}$, $i=0,1,\ldots,N$. Since $f\_{k}(x\_{i})\rightarrow f(x\_{i})$
as $k\rightarrow\infty$, there exists $K\in\mathbb{N}$ such that
$|f\_{k}(x\_{i})-f(x\_{i})|<\varepsilon$ whenever $k\geq K$ and $i=0,1,\ldots,N$.
Let $k\geq K$ and $x\in[-M,M]$ be arbitrary. If $x\in\{x\_{0},x\_{1},\ldots,x\_{N}\}$,
we clearly have $|f\_{k}(x)-f(x)|<\varepsilon$. Suppose that $x\notin\{x\_{0},x\_{1},\ldots,x\_{N}\}$,
then there exists $i$ such that $x\_{i-1}<x<x\_{i}$. Observe that
$|x-x\_{i-1}|<\delta$ and $|x-x\_{i}|<\delta$, so $|f(x)-f(x\_{i-1})|<\varepsilon$
and $|f(x)-f(x\_{i})|<\varepsilon$. We have that
\begin{eqnarray\*}
f(x)-f\_{k}(x) & \leq & f(x)-f\_{k}(x\_{i-1})\\
& \leq & f(x\_{i-1})-f\_{k}(x\_{i-1})+\varepsilon\\
& \leq & 2\varepsilon.
\end{eqnarray\*}
Moreover,
\begin{eqnarray\*}
f(x)-f\_{k}(x) & \geq & f(x)-f\_{k}(x\_{i})\\
& \geq & f(x\_{i})-f\_{k}(x\_{i})-\varepsilon\\
& \geq & -2\varepsilon.
\end{eqnarray\*}
That is,
$$
|f(x)-f\_{k}(x)|\leq2\varepsilon.
$$
Thefore, $f\_{n}\rightarrow f$ uniformly on each compact subset of
$\mathbb{R}$. |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | I guess something like this should work:
```
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
```
A bit simplified fiddle there: <http://jsfiddle.net/Daess/fukxu/> | ```
var i = 0
var plus = ++i;
```
This part means that `plus` will always be zero and `i == 1`, so your `rel` attribute always reads `0`.
```
var count = jQuery.('#button').attr('rel');
```
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the *first* matched element which will obviously not be the one you want as you want the number in the *last* element.
```
if(count=5){
```
..but it doesn't matter anyway because now you're just telling that `count` equals 5 and the `alert` will always execute. What you are looking for is the comparison operator `==`.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
```
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
```
Note that I added the `myRow` class to help identify which rows are appended and changed the `id="button"` to `class="button"`. |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | I guess something like this should work:
```
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
```
A bit simplified fiddle there: <http://jsfiddle.net/Daess/fukxu/> | When you try to compare the "count" with the number 5 you have to use == instead.
`count = 5` will set count to 5 and always return true if you use `count == 5` it will compare your variable with the number 5 and return true or false, depending on the value of the variable.
Also I think you can easily count the number of buttons by using length, sth like: `$('.button').length` should return the number of elements with the class (not ID) "button". |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | I guess something like this should work:
```
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
```
A bit simplified fiddle there: <http://jsfiddle.net/Daess/fukxu/> | Try this.
```
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});
``` |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | I guess something like this should work:
```
jQuery('#add_slider_image').click(function() {
var count = jQuery("input[name='sliderbut']").length;
if (count < 5){
jQuery('.form-table').append("<tr><td><input type='text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' /></td><tr>");
}
})
```
A bit simplified fiddle there: <http://jsfiddle.net/Daess/fukxu/> | You have to put the counter variable outside the event handler, otherwise you will be starting over from zero each time.
You should put the code that adds the elements inside the if statement, so that you either show a messare or add the elements.
There is no point in reading the value from the button that you just added, when you already have the value. Besides, an id should be unique, so you would not get the value from the last button but the first.
The comparison operator is `==`, if you use `=` you will instead assign a value to the variable, so the condition would always end up being true.
```
$(document).ready(function(){
var sliderCount = 0;
jQuery('#add_slider_image').click(function() {
if (sliderCount == 5) {
alert('Limit reached');
} else {
sliderCount++;
jQuery('.form-table').append('<tr><td><input type="text" value="" name="slider[]" /><input type="button" name="sliderbut" value="Upload" rel="'+ sliderCount +'" /></td><tr>');
}
});
});
``` |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | When you try to compare the "count" with the number 5 you have to use == instead.
`count = 5` will set count to 5 and always return true if you use `count == 5` it will compare your variable with the number 5 and return true or false, depending on the value of the variable.
Also I think you can easily count the number of buttons by using length, sth like: `$('.button').length` should return the number of elements with the class (not ID) "button". | ```
var i = 0
var plus = ++i;
```
This part means that `plus` will always be zero and `i == 1`, so your `rel` attribute always reads `0`.
```
var count = jQuery.('#button').attr('rel');
```
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the *first* matched element which will obviously not be the one you want as you want the number in the *last* element.
```
if(count=5){
```
..but it doesn't matter anyway because now you're just telling that `count` equals 5 and the `alert` will always execute. What you are looking for is the comparison operator `==`.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
```
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
```
Note that I added the `myRow` class to help identify which rows are appended and changed the `id="button"` to `class="button"`. |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | ```
var i = 0
var plus = ++i;
```
This part means that `plus` will always be zero and `i == 1`, so your `rel` attribute always reads `0`.
```
var count = jQuery.('#button').attr('rel');
```
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the *first* matched element which will obviously not be the one you want as you want the number in the *last* element.
```
if(count=5){
```
..but it doesn't matter anyway because now you're just telling that `count` equals 5 and the `alert` will always execute. What you are looking for is the comparison operator `==`.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
```
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
```
Note that I added the `myRow` class to help identify which rows are appended and changed the `id="button"` to `class="button"`. | Try this.
```
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});
``` |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | You have to put the counter variable outside the event handler, otherwise you will be starting over from zero each time.
You should put the code that adds the elements inside the if statement, so that you either show a messare or add the elements.
There is no point in reading the value from the button that you just added, when you already have the value. Besides, an id should be unique, so you would not get the value from the last button but the first.
The comparison operator is `==`, if you use `=` you will instead assign a value to the variable, so the condition would always end up being true.
```
$(document).ready(function(){
var sliderCount = 0;
jQuery('#add_slider_image').click(function() {
if (sliderCount == 5) {
alert('Limit reached');
} else {
sliderCount++;
jQuery('.form-table').append('<tr><td><input type="text" value="" name="slider[]" /><input type="button" name="sliderbut" value="Upload" rel="'+ sliderCount +'" /></td><tr>');
}
});
});
``` | ```
var i = 0
var plus = ++i;
```
This part means that `plus` will always be zero and `i == 1`, so your `rel` attribute always reads `0`.
```
var count = jQuery.('#button').attr('rel');
```
You are using an ID selector. And ID can exist only once per page. As you use an ID selector, you get only the *first* matched element which will obviously not be the one you want as you want the number in the *last* element.
```
if(count=5){
```
..but it doesn't matter anyway because now you're just telling that `count` equals 5 and the `alert` will always execute. What you are looking for is the comparison operator `==`.
Easiest way to do this is to ditch the counts and whatnots, and just check if there are already too many elements before inserting:
```
jQuery('#add_slider_image').click(function() {
if($('.form-table .myRow').length < 5) {
jQuery('.form-table').append('<tr class="myRow"><td><input type="text" name="slider[]" /><input type="button" name="sliderbut" value="Upload" class="button" /></td><tr>');
}
});
```
Note that I added the `myRow` class to help identify which rows are appended and changed the `id="button"` to `class="button"`. |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | When you try to compare the "count" with the number 5 you have to use == instead.
`count = 5` will set count to 5 and always return true if you use `count == 5` it will compare your variable with the number 5 and return true or false, depending on the value of the variable.
Also I think you can easily count the number of buttons by using length, sth like: `$('.button').length` should return the number of elements with the class (not ID) "button". | Try this.
```
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});
``` |
7,253,612 | I'm adding text fields with a onclick. What I'm trying to do is limit the amount of boxes to about 5.
I also need to increment the number to use as an ID.
my code:
```
jQuery('#add_slider_image').click(function() {
var i = 0
var plus = ++i;
jQuery('.form-table').append("<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button' rel='"+ plus +"' /></td><tr>");
var count = jQuery.('#button').attr('rel');
if(count=5){
alert('Limit reached');
}
})
```
THanks | 2011/08/31 | [
"https://Stackoverflow.com/questions/7253612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087234/"
] | You have to put the counter variable outside the event handler, otherwise you will be starting over from zero each time.
You should put the code that adds the elements inside the if statement, so that you either show a messare or add the elements.
There is no point in reading the value from the button that you just added, when you already have the value. Besides, an id should be unique, so you would not get the value from the last button but the first.
The comparison operator is `==`, if you use `=` you will instead assign a value to the variable, so the condition would always end up being true.
```
$(document).ready(function(){
var sliderCount = 0;
jQuery('#add_slider_image').click(function() {
if (sliderCount == 5) {
alert('Limit reached');
} else {
sliderCount++;
jQuery('.form-table').append('<tr><td><input type="text" value="" name="slider[]" /><input type="button" name="sliderbut" value="Upload" rel="'+ sliderCount +'" /></td><tr>');
}
});
});
``` | Try this.
```
jQuery('#add_slider_image').click(function() {
var myHTML = "";
var current_count = jQuery('.form-table tr').length();
if (current_count >= 5) return;
for (var i = current_count; i <= 5; i++) {
myHTML += "<tr><td><input type'text' value='' name='slider[]' /><input type='button' name='sliderbut' value='Upload' id='button" + plus + "' rel='" + plus + "' /></td><tr>";
}
//touch DOM once
jQuery('.form-table').append(myHTML);
});
``` |
67,064,995 | I am using Gnuplot to show the precipitation measured during the last 13 monthts. Data is read from two data files, rain.dat and snow.dat. I use impulses, but on days with both rain and snow the impulses are plotted over each other. It had been better if the impulses were stacked.
```
#!/usr/bin/gnuplot -persist
set xdata time
set timefmt "%d.%m.%Y"
set ylabel "Precipitation (mm)"
set xrange ["01.`date --date="1 year ago" +%m.%Y`":"01`date --date="1 month" +.%m.%Y`"]
set xtics "01.`date --date="1 year ago" +%m.%Y`",2800000, \
"01.`date --date="now 1 month" +%m.%Y`" offset 3,0.2
set format x "%b"
set style line 100 lt 3 lc rgb "gray" lw 0.5
set style line 101 lt 3 lc rgb "gray" lw 0.5
set grid back xtics ytics mytics ls 100, ls 100, ls 101
set terminal png size 1000,200
set output 'precipitation.png'
plot 'rain.dat' using 1:2 title 'Rain' w impulses lt rgb '#ff0000' lw 4 , \
'snow.dat' using 1:2 title 'Snow' w impulses lt rgb '#0000ff' lw 2
rain.dat:
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
snow.dat:
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
```
[](https://i.stack.imgur.com/rEVDU.png)
How can impulses be stacked with Gnuplot? | 2021/04/12 | [
"https://Stackoverflow.com/questions/67064995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12344958/"
] | As @Ethan already mentioned, `with impulses` will always start at `0`. If you don't mind some little extra effort, you can mimic "stacking" impulses if you first plot the sum of rain and snow with the "snow color", and then plot rain alone with the "rain color" on top of it.
But how do you get the sum of rain and snow?
* plot your datablocks (or files) into the temporary datablock `$Temp`.
* plot datablock `$Temp` into the datablock `$SnowAndRain` using the option `smooth frequency` which sums up snow and rain for each day. Check `help smooth`.
**Script:** (works for gnuplot>=5.2.0, Sept. 2017)
```
### "stacked" impulses
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (sprintf("%.0f",timecolumn(1,myTimeFmt))):2 w table
plot $Rain u (sprintf("%.0f",timecolumn(1,myTimeFmt))):2 w table
set table $SnowAndRain
set format x "%.0f"
plot $Temp u 1:2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain', \
### end of script
```
**Result:**
[](https://i.stack.imgur.com/JCnFG.png)
**Addition:**
A bit more cumbersome solution which seem to work with gnuplot 5.0.0 (at least with Win10). I hope somebody can simplify this.
**Script:** (tested with Win10 gnuplot 5.0.0. Same result as above)
```
### "stacked" impulses (should work with gnuplot 5.0.0)
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (t=timecolumn(1,myTimeFmt)/1e5,int(t)):2:((t-int(t))*1e5) w table
plot $Rain u (t=timecolumn(1,myTimeFmt)/1e5,int(t)):2:((t-int(t))*1e5) w table
unset table
set table $SnowAndRain
set format x "%.0f"
plot $Temp u ($1*1e5+$3):2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain'
### end of script
``` | Impulses cannot be stacked. By definition they extend from y=0 to some non-zero y value.
If the two data sets were sampled at the same set of x coordinates then you could use the stacked histogram plot mode, but that isn't the case here.
How about back-to-back impulses rather than stacked impulses?
```
$RAIN << EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$SNOW << EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
set xzeroaxis
plot $RAIN using 1:2 with impulse lw 3, \
$SNOW using 1:(-$2) with impulse lw 3
```
[](https://i.stack.imgur.com/0IJU5.png) |
67,064,995 | I am using Gnuplot to show the precipitation measured during the last 13 monthts. Data is read from two data files, rain.dat and snow.dat. I use impulses, but on days with both rain and snow the impulses are plotted over each other. It had been better if the impulses were stacked.
```
#!/usr/bin/gnuplot -persist
set xdata time
set timefmt "%d.%m.%Y"
set ylabel "Precipitation (mm)"
set xrange ["01.`date --date="1 year ago" +%m.%Y`":"01`date --date="1 month" +.%m.%Y`"]
set xtics "01.`date --date="1 year ago" +%m.%Y`",2800000, \
"01.`date --date="now 1 month" +%m.%Y`" offset 3,0.2
set format x "%b"
set style line 100 lt 3 lc rgb "gray" lw 0.5
set style line 101 lt 3 lc rgb "gray" lw 0.5
set grid back xtics ytics mytics ls 100, ls 100, ls 101
set terminal png size 1000,200
set output 'precipitation.png'
plot 'rain.dat' using 1:2 title 'Rain' w impulses lt rgb '#ff0000' lw 4 , \
'snow.dat' using 1:2 title 'Snow' w impulses lt rgb '#0000ff' lw 2
rain.dat:
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
snow.dat:
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
```
[](https://i.stack.imgur.com/rEVDU.png)
How can impulses be stacked with Gnuplot? | 2021/04/12 | [
"https://Stackoverflow.com/questions/67064995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12344958/"
] | Impulses cannot be stacked. By definition they extend from y=0 to some non-zero y value.
If the two data sets were sampled at the same set of x coordinates then you could use the stacked histogram plot mode, but that isn't the case here.
How about back-to-back impulses rather than stacked impulses?
```
$RAIN << EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$SNOW << EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
set xzeroaxis
plot $RAIN using 1:2 with impulse lw 3, \
$SNOW using 1:(-$2) with impulse lw 3
```
[](https://i.stack.imgur.com/0IJU5.png) | I have tried to make a simplification to @theozh's answer, but some of the pulses are slightly displaced in time. @theozh has a much better solution of my problem.
```
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (timecolumn(1,myTimeFmt)):2 w table
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set table $SnowAndRain
plot $Temp u 1:2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain', \
### end of code
```
**Addition:**
The rain and snow pulses are drawn on top of each other if $Rain is written to table $RainTemp using (timecolumn(1,myTimeFmt)):2 before plotting the the graph. But still the timing is bit incorrect.
```
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (timecolumn(1,myTimeFmt)):2 w table
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set table $SnowAndRain
plot $Temp u 1:2 smooth freq
unset table
set table $RainTemp
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$RainTemp u 1:2 w impulses lw 4 lc "red" title 'Rain'
``` |
67,064,995 | I am using Gnuplot to show the precipitation measured during the last 13 monthts. Data is read from two data files, rain.dat and snow.dat. I use impulses, but on days with both rain and snow the impulses are plotted over each other. It had been better if the impulses were stacked.
```
#!/usr/bin/gnuplot -persist
set xdata time
set timefmt "%d.%m.%Y"
set ylabel "Precipitation (mm)"
set xrange ["01.`date --date="1 year ago" +%m.%Y`":"01`date --date="1 month" +.%m.%Y`"]
set xtics "01.`date --date="1 year ago" +%m.%Y`",2800000, \
"01.`date --date="now 1 month" +%m.%Y`" offset 3,0.2
set format x "%b"
set style line 100 lt 3 lc rgb "gray" lw 0.5
set style line 101 lt 3 lc rgb "gray" lw 0.5
set grid back xtics ytics mytics ls 100, ls 100, ls 101
set terminal png size 1000,200
set output 'precipitation.png'
plot 'rain.dat' using 1:2 title 'Rain' w impulses lt rgb '#ff0000' lw 4 , \
'snow.dat' using 1:2 title 'Snow' w impulses lt rgb '#0000ff' lw 2
rain.dat:
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
snow.dat:
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
```
[](https://i.stack.imgur.com/rEVDU.png)
How can impulses be stacked with Gnuplot? | 2021/04/12 | [
"https://Stackoverflow.com/questions/67064995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12344958/"
] | As @Ethan already mentioned, `with impulses` will always start at `0`. If you don't mind some little extra effort, you can mimic "stacking" impulses if you first plot the sum of rain and snow with the "snow color", and then plot rain alone with the "rain color" on top of it.
But how do you get the sum of rain and snow?
* plot your datablocks (or files) into the temporary datablock `$Temp`.
* plot datablock `$Temp` into the datablock `$SnowAndRain` using the option `smooth frequency` which sums up snow and rain for each day. Check `help smooth`.
**Script:** (works for gnuplot>=5.2.0, Sept. 2017)
```
### "stacked" impulses
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (sprintf("%.0f",timecolumn(1,myTimeFmt))):2 w table
plot $Rain u (sprintf("%.0f",timecolumn(1,myTimeFmt))):2 w table
set table $SnowAndRain
set format x "%.0f"
plot $Temp u 1:2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain', \
### end of script
```
**Result:**
[](https://i.stack.imgur.com/JCnFG.png)
**Addition:**
A bit more cumbersome solution which seem to work with gnuplot 5.0.0 (at least with Win10). I hope somebody can simplify this.
**Script:** (tested with Win10 gnuplot 5.0.0. Same result as above)
```
### "stacked" impulses (should work with gnuplot 5.0.0)
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (t=timecolumn(1,myTimeFmt)/1e5,int(t)):2:((t-int(t))*1e5) w table
plot $Rain u (t=timecolumn(1,myTimeFmt)/1e5,int(t)):2:((t-int(t))*1e5) w table
unset table
set table $SnowAndRain
set format x "%.0f"
plot $Temp u ($1*1e5+$3):2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain'
### end of script
``` | I have tried to make a simplification to @theozh's answer, but some of the pulses are slightly displaced in time. @theozh has a much better solution of my problem.
```
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (timecolumn(1,myTimeFmt)):2 w table
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set table $SnowAndRain
plot $Temp u 1:2 smooth freq
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$Rain u (timecolumn(1,myTimeFmt)):2 w impulses lc "red" lw 4 title 'Rain', \
### end of code
```
**Addition:**
The rain and snow pulses are drawn on top of each other if $Rain is written to table $RainTemp using (timecolumn(1,myTimeFmt)):2 before plotting the the graph. But still the timing is bit incorrect.
```
reset session
$Rain <<EOD
16.02.2021 8
22.02.2021 6
04.03.2021 10
08.03.2021 13
14.03.2021 5
EOD
$Snow <<EOD
19.02.2021 19
22.02.2021 10
04.03.2021 14
12.03.2021 8
EOD
myTimeFmt = "%d.%m.%Y"
set table $Temp
plot $Snow u (timecolumn(1,myTimeFmt)):2 w table
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set table $SnowAndRain
plot $Temp u 1:2 smooth freq
unset table
set table $RainTemp
plot $Rain u (timecolumn(1,myTimeFmt)):2 w table
unset table
set format x "%d %b" timedate
plot $SnowAndRain u 1:2 w impulses lw 4 lc "blue" title 'Snow', \
$RainTemp u 1:2 w impulses lw 4 lc "red" title 'Rain'
``` |
21,024,186 | I've been trying to make a selling program where the customer will be asked the quantity of items he will buy. For example, if he inputs `"5"`, the next window will ask him 5 questions. My problem is, I'm required to use array, so is there any way that I can change
```
string[] arrmerch = new string[6];
```
the number is "6" in the new string with the what the user inputted? Here's the loop. The item choice is the question.
```
for (int i = 0; i <= arrmerch.Length; i++)
{
Console.Write("Item choice: ");
arrmerch[i] = Console.ReadLine();
``` | 2014/01/09 | [
"https://Stackoverflow.com/questions/21024186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3173353/"
] | Of course, just do this:
```
int userInput = Convert.ToInt32(Console.ReadLine());
string[] arrmerch = new string[userInput];
```
You will need to add input checking to ensure that what you have is an integer and not something else.
Here's an example with input checking:
```
int arraySize = 0;
if(Int32.TryParse(Console.ReadLine(), out arraySize))
{
string[] arrmerch = new string[arraySize];
//the rest of your code
//...
//.
}
else
{
//The user entered a value which cannot be parsed to an int
}
``` | Change
string[] arrmerch = new string[6];
to
```
string[] arrmerch = new string[Convert.ToInt32(Console.ReadLine())];
```
which will take the users input and create and array of that size. |
21,024,186 | I've been trying to make a selling program where the customer will be asked the quantity of items he will buy. For example, if he inputs `"5"`, the next window will ask him 5 questions. My problem is, I'm required to use array, so is there any way that I can change
```
string[] arrmerch = new string[6];
```
the number is "6" in the new string with the what the user inputted? Here's the loop. The item choice is the question.
```
for (int i = 0; i <= arrmerch.Length; i++)
{
Console.Write("Item choice: ");
arrmerch[i] = Console.ReadLine();
``` | 2014/01/09 | [
"https://Stackoverflow.com/questions/21024186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3173353/"
] | Of course, just do this:
```
int userInput = Convert.ToInt32(Console.ReadLine());
string[] arrmerch = new string[userInput];
```
You will need to add input checking to ensure that what you have is an integer and not something else.
Here's an example with input checking:
```
int arraySize = 0;
if(Int32.TryParse(Console.ReadLine(), out arraySize))
{
string[] arrmerch = new string[arraySize];
//the rest of your code
//...
//.
}
else
{
//The user entered a value which cannot be parsed to an int
}
``` | How about:
```
int numberOfQuestions = Convert.ToInt32(Console.Readline());
string[] arrmerch = new string[numberOfQuestions];
for (int i = 0; i <= arrmerch.Length; i++)
{
Console.Write("Item choice: ");
arrmerch[i] = Console.ReadLine();
```
Will need error checking though. |
21,024,186 | I've been trying to make a selling program where the customer will be asked the quantity of items he will buy. For example, if he inputs `"5"`, the next window will ask him 5 questions. My problem is, I'm required to use array, so is there any way that I can change
```
string[] arrmerch = new string[6];
```
the number is "6" in the new string with the what the user inputted? Here's the loop. The item choice is the question.
```
for (int i = 0; i <= arrmerch.Length; i++)
{
Console.Write("Item choice: ");
arrmerch[i] = Console.ReadLine();
``` | 2014/01/09 | [
"https://Stackoverflow.com/questions/21024186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3173353/"
] | Of course, just do this:
```
int userInput = Convert.ToInt32(Console.ReadLine());
string[] arrmerch = new string[userInput];
```
You will need to add input checking to ensure that what you have is an integer and not something else.
Here's an example with input checking:
```
int arraySize = 0;
if(Int32.TryParse(Console.ReadLine(), out arraySize))
{
string[] arrmerch = new string[arraySize];
//the rest of your code
//...
//.
}
else
{
//The user entered a value which cannot be parsed to an int
}
``` | Also you can use `Generic Lists`.They are more flexible, if you want to change your array lenght in the future
```
int count = Convert.ToInt32(Console.ReadLine());
var list = new List<string>();
for (int i = 0; i <= count; i++)
{
Console.Write("Item choice: ");
list.Add(Console.ReadLine());
}
``` |
59,797,191 | I have two classes that have some identical methods, the method below should access the methods of one of the two classes based on which checkbox is ticked, However I am having issues passing the objects created within the IF statements into the main body of the method. Is there way to achieve this without copying the main body of the method into both areas? Here is the code:
```
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
```
EDIT\*\*
Based on Salim's response, here is the error message I am receiving:
[](https://i.stack.imgur.com/vKEFD.png)
To confirm, the method getBusinessName() is in both supplier and deliveryCompany classes.
My apologies if this is a novice question, I am fairly new to Java, any help with this is appreciated. | 2020/01/18 | [
"https://Stackoverflow.com/questions/59797191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12287824/"
] | You have multiple beans of the same type and want to prevent `Bean2` from injecting. In some project inject `Bean1` and in others `Bean1Child`.
There are multiple options.
Override bean definition with `@Bean`
-------------------------------------
Make `Bean1Child` bean definition the same as `Bean1` has using `@Bean`
```
@Configuration
public class Config {
@Primary
@Bean
public Bean1 bean1() { //return type must be Bean1
return new Bean1Child();
}
}
```
and set the property `spring.main.allow-bean-definition-overriding=true`
Create custom `@Qualifier` annotation
-------------------------------------
```
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface BeanType {
}
@BeanType
public @interface Bean1Type {
}
@Bean1Type
@Component("bean1")
public class Bean1 implements Bean {
}
@Component("bean2")
public class Bean2 implements Bean {
}
@Component("bean3")
public class Bean3 {
private final Bean bean;
public Bean3(@Bean1Type Bean bean) {
this.bean = bean;
}
}
@Bean1Type
@Primary
@Component("bean1Child")
public class Bean1Child extends Bean1 {
}
``` | You cannot have two beans specified with the same qualified name, as the error indicates:
```
Annotation-specified bean name 'bean1' for bean class [Bean1Child]
conflicts with existing, non-compatible bean definition of same name and class [Bean1]
```
Giving a different qualifier name to Bean1Child should work.
```java
@Component("bean1child")
@Primary
public class Bean1Child extends Bean1 {
}
```
and in Bean3 , `public void setBean(@Qualifier("bean1child") final Bean bean) {` |
59,797,191 | I have two classes that have some identical methods, the method below should access the methods of one of the two classes based on which checkbox is ticked, However I am having issues passing the objects created within the IF statements into the main body of the method. Is there way to achieve this without copying the main body of the method into both areas? Here is the code:
```
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
```
EDIT\*\*
Based on Salim's response, here is the error message I am receiving:
[](https://i.stack.imgur.com/vKEFD.png)
To confirm, the method getBusinessName() is in both supplier and deliveryCompany classes.
My apologies if this is a novice question, I am fairly new to Java, any help with this is appreciated. | 2020/01/18 | [
"https://Stackoverflow.com/questions/59797191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12287824/"
] | If this is possible, you can change the way the beans are created by removing the `@Component` annotations:
In the first project, the `BeanChild3` would be refactored to get the `bean` in the constructor
```java
public class Bean3 {
private final Bean bean;
public Bean3(final Bean bean) {
this.bean = bean;
}
}
```
Then we can create the beans in a `BeansConfig` class
```java
@Configuration
class BeansConfig {
@ConditionalOnMissingBean
@Bean("bean1")
Bean bean1(){
return new Bean1();
}
@Bean("bean2")
Bean bean2(){
return new Bean2();
}
@Bean("bean3")
Bean bean3(@Autowired @Qualifier("bean1") Bean){
return new Bean3(bean);
}
}
```
The `@ConditionalOnMissingBean` allows us to provide another bean with the same name to be used instead. If no such bean exists, then the default one would be used.
You will then need to create a `beanChild1` bean in your second project and it should be picked up.
```java
@Bean("bean1")
Bean bean1(){
return new Bean1Child();
}
``` | You cannot have two beans specified with the same qualified name, as the error indicates:
```
Annotation-specified bean name 'bean1' for bean class [Bean1Child]
conflicts with existing, non-compatible bean definition of same name and class [Bean1]
```
Giving a different qualifier name to Bean1Child should work.
```java
@Component("bean1child")
@Primary
public class Bean1Child extends Bean1 {
}
```
and in Bean3 , `public void setBean(@Qualifier("bean1child") final Bean bean) {` |
59,797,191 | I have two classes that have some identical methods, the method below should access the methods of one of the two classes based on which checkbox is ticked, However I am having issues passing the objects created within the IF statements into the main body of the method. Is there way to achieve this without copying the main body of the method into both areas? Here is the code:
```
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
```
EDIT\*\*
Based on Salim's response, here is the error message I am receiving:
[](https://i.stack.imgur.com/vKEFD.png)
To confirm, the method getBusinessName() is in both supplier and deliveryCompany classes.
My apologies if this is a novice question, I am fairly new to Java, any help with this is appreciated. | 2020/01/18 | [
"https://Stackoverflow.com/questions/59797191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12287824/"
] | You can easily achieve this using `@ConditionalOnMissingBean` feature.
Modify your `Bean1` class as below
```
@Component("bean1")
@ConditionalOnMissingBean(type = "bean1")
public class Bean1 implements Bean {
}
```
modify `Bean1Child` class as below
```
@Component
@Qualifier("bean1")
@Primary
public class Bean1Child extends Bean1 {
}
```
**How it works?**
* Spring will try to load a bean named "bean1". If it doesn't find any bean by the same name that is marked as `@Primary` it will fall back to `Bean1` class and load it as "bean1".
* `Bean1Child` has to be marked as primary because spring is going to find 2 beans by the same name. We need to tell which to load. | You cannot have two beans specified with the same qualified name, as the error indicates:
```
Annotation-specified bean name 'bean1' for bean class [Bean1Child]
conflicts with existing, non-compatible bean definition of same name and class [Bean1]
```
Giving a different qualifier name to Bean1Child should work.
```java
@Component("bean1child")
@Primary
public class Bean1Child extends Bean1 {
}
```
and in Bean3 , `public void setBean(@Qualifier("bean1child") final Bean bean) {` |
59,797,191 | I have two classes that have some identical methods, the method below should access the methods of one of the two classes based on which checkbox is ticked, However I am having issues passing the objects created within the IF statements into the main body of the method. Is there way to achieve this without copying the main body of the method into both areas? Here is the code:
```
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
```
EDIT\*\*
Based on Salim's response, here is the error message I am receiving:
[](https://i.stack.imgur.com/vKEFD.png)
To confirm, the method getBusinessName() is in both supplier and deliveryCompany classes.
My apologies if this is a novice question, I am fairly new to Java, any help with this is appreciated. | 2020/01/18 | [
"https://Stackoverflow.com/questions/59797191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12287824/"
] | If this is possible, you can change the way the beans are created by removing the `@Component` annotations:
In the first project, the `BeanChild3` would be refactored to get the `bean` in the constructor
```java
public class Bean3 {
private final Bean bean;
public Bean3(final Bean bean) {
this.bean = bean;
}
}
```
Then we can create the beans in a `BeansConfig` class
```java
@Configuration
class BeansConfig {
@ConditionalOnMissingBean
@Bean("bean1")
Bean bean1(){
return new Bean1();
}
@Bean("bean2")
Bean bean2(){
return new Bean2();
}
@Bean("bean3")
Bean bean3(@Autowired @Qualifier("bean1") Bean){
return new Bean3(bean);
}
}
```
The `@ConditionalOnMissingBean` allows us to provide another bean with the same name to be used instead. If no such bean exists, then the default one would be used.
You will then need to create a `beanChild1` bean in your second project and it should be picked up.
```java
@Bean("bean1")
Bean bean1(){
return new Bean1Child();
}
``` | You have multiple beans of the same type and want to prevent `Bean2` from injecting. In some project inject `Bean1` and in others `Bean1Child`.
There are multiple options.
Override bean definition with `@Bean`
-------------------------------------
Make `Bean1Child` bean definition the same as `Bean1` has using `@Bean`
```
@Configuration
public class Config {
@Primary
@Bean
public Bean1 bean1() { //return type must be Bean1
return new Bean1Child();
}
}
```
and set the property `spring.main.allow-bean-definition-overriding=true`
Create custom `@Qualifier` annotation
-------------------------------------
```
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface BeanType {
}
@BeanType
public @interface Bean1Type {
}
@Bean1Type
@Component("bean1")
public class Bean1 implements Bean {
}
@Component("bean2")
public class Bean2 implements Bean {
}
@Component("bean3")
public class Bean3 {
private final Bean bean;
public Bean3(@Bean1Type Bean bean) {
this.bean = bean;
}
}
@Bean1Type
@Primary
@Component("bean1Child")
public class Bean1Child extends Bean1 {
}
``` |
59,797,191 | I have two classes that have some identical methods, the method below should access the methods of one of the two classes based on which checkbox is ticked, However I am having issues passing the objects created within the IF statements into the main body of the method. Is there way to achieve this without copying the main body of the method into both areas? Here is the code:
```
public void populateSupplyChainTextFields() {
if (jDeliveryCheckBox.isSelected() == true) {
DeliveryCompany supplyChainMember = new DeliveryCompany();
supplyChainMember = theDeliveryCompanyList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
} else {
Supplier supplyChainMember = new Supplier();
supplyChainMember = theSupplierList.Find(jSupplyChainSearchBox.getSelectedItem().toString());
}
jCategoryTextField.setText(supplyChainMember.getCategory());
jPriceTextField.setText(String.valueOf(supplyChainMember.getPrice()));
jUnitCostTextField.setText(String.valueOf(supplyChainMember.getUnitCost()));
```
EDIT\*\*
Based on Salim's response, here is the error message I am receiving:
[](https://i.stack.imgur.com/vKEFD.png)
To confirm, the method getBusinessName() is in both supplier and deliveryCompany classes.
My apologies if this is a novice question, I am fairly new to Java, any help with this is appreciated. | 2020/01/18 | [
"https://Stackoverflow.com/questions/59797191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12287824/"
] | You can easily achieve this using `@ConditionalOnMissingBean` feature.
Modify your `Bean1` class as below
```
@Component("bean1")
@ConditionalOnMissingBean(type = "bean1")
public class Bean1 implements Bean {
}
```
modify `Bean1Child` class as below
```
@Component
@Qualifier("bean1")
@Primary
public class Bean1Child extends Bean1 {
}
```
**How it works?**
* Spring will try to load a bean named "bean1". If it doesn't find any bean by the same name that is marked as `@Primary` it will fall back to `Bean1` class and load it as "bean1".
* `Bean1Child` has to be marked as primary because spring is going to find 2 beans by the same name. We need to tell which to load. | You have multiple beans of the same type and want to prevent `Bean2` from injecting. In some project inject `Bean1` and in others `Bean1Child`.
There are multiple options.
Override bean definition with `@Bean`
-------------------------------------
Make `Bean1Child` bean definition the same as `Bean1` has using `@Bean`
```
@Configuration
public class Config {
@Primary
@Bean
public Bean1 bean1() { //return type must be Bean1
return new Bean1Child();
}
}
```
and set the property `spring.main.allow-bean-definition-overriding=true`
Create custom `@Qualifier` annotation
-------------------------------------
```
@Qualifier
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface BeanType {
}
@BeanType
public @interface Bean1Type {
}
@Bean1Type
@Component("bean1")
public class Bean1 implements Bean {
}
@Component("bean2")
public class Bean2 implements Bean {
}
@Component("bean3")
public class Bean3 {
private final Bean bean;
public Bean3(@Bean1Type Bean bean) {
this.bean = bean;
}
}
@Bean1Type
@Primary
@Component("bean1Child")
public class Bean1Child extends Bean1 {
}
``` |
3,957,054 | [](https://i.stack.imgur.com/u1bVt.jpg)
In the below picture, angle A is obtuse, AD is a median.
We are also given the relation $AB^2 = AF\*AC$.
We want to prove that area of triangle $(ABC) = AB\*AD$.
What I have tried:
Area of triangle is $A = \frac {1}{2}\*AC\*BF$.
Replacing AC from the given relation $AB^2 = AF\*AC$, we get $A = \frac {1}{2}\*\frac{AB^2\*BF}{AF}$.
Also from Pythagoras, we replace $AB^2$ with $BF^2+AF^2$.
But I can't see how to involve AD and prove the required relation!
Any help please? | 2020/12/21 | [
"https://math.stackexchange.com/questions/3957054",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/469488/"
] | As you have noted, the area $\cal A$ can be written as $AC\times BF/2$. Proving ${\cal A}=AB\times AD$ is equivalent to proving $$AB^2\times 4AD^2=AC^2\times BF^2\tag1$$ on squaring both sides.
The median $AD$ has the property that $4AD^2=2AC^2+2AB^2-BC^2$ as shown [here](https://math.stackexchange.com/a/1850097/471884). Using Pythagoras on $\triangle CFB$ yields $$BC^2=(AF+AC)^2+BF^2=AF^2+AC^2+2AF\times AC+BF^2.$$ Since $AF^2+BF^2=AB^2=AF\times AC$ we obtain $BC^2=3AB^2+AC^2$ so that $$4AD^2=AC^2-AB^2\tag2.$$ Finally, using the same identity, we have $BF^2=AF\times(AC-AF)$ so that $$AC^2\times BF^2=AF\times AC\times(AC^2-AF\times AC)=AB^2\times(AC^2-AB^2).$$ Substituting in $(2)$ gives $(1)$ so it follows that ${\cal A}=AB\times AD$. | $BE$ parallel to $DA$, $E$ on the line $CA$
Let $AB=c$, $AC=b$, $BC=2a$ , $AD=d$
we have $BE=2d$
Given $AF = \frac{c^2}{b}$
We get $EF=b-\frac{c^2}{b}$, $CF=b+\frac{c^2}{b}$
using Pythagoras, express $BF^2$ in two different ways
$4d^2-\left(b-\frac{c^2}{b}\right)^2=4a^2-\left(b+\frac{c^2}{b}\right)^2$
it follows from this that $d^2+c^2=a^2$
and so $BAD$ is a right angle, area $ABD = \frac{1}{2} cd$ and therefore area $ABC=cd$ |
60,620,257 | Examples:
**example.com/asd -> example.com/portal.php?id=asd**
**example.com -> example.com/portal.php**
**example.com/asd?document=new -> example.com/portal.php?id=asd&document=new**
So far works only:
*example.com -> example.com/portal.php*
**This is what I have so far:**
```
server {
listen 80;
listen [::]:80;
root /var/www/html/public_html;
server_name example.com;
if ($http_x_forwarded_proto = 'http'){
return 301 https://$host$request_uri;
}
location / {
# try to serve file directly, fallback to index.php
try_files $uri /portal.php$is_args$args;
}
# LEGACY
# This rule should only be placed on your development environment
# In production, don't include this and don't deploy app_dev.php or config.php
location ~ ^/(portal)\.php(/|$) {
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param HTTPS on;
# When you are using symlinks to link the document root to the
# current version of your application, you should pass the real
# application path instead of the path to the symlink to PHP
# FPM.
# Otherwise, PHP's OPcache may not properly detect changes to
# your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
# for more information).
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
internal;
}
# return 404 for all other php files not matching the front controller
# this prevents access to other php files you don't want to be accessible.
location ~ \.php$ {
return 404;
}
error_log /var/log/nginx/project_error.log;
access_log /var/log/nginx/project_access.log;
}
``` | 2020/03/10 | [
"https://Stackoverflow.com/questions/60620257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047170/"
] | Unless you are able to modify such global variable, there is now way of restricting the scope of a global variable in C++. | The answer to this problem is:
split the specialization into two parts:
- part one: the definition of the specialization in the header file.
- part two: the implementation of the specialization in the cpp file
Part one(`InterruptVectorTable.hpp`):
```cpp
template <>
class InterruptVectorTable<DeviceAtmega328p, IRQType>
{
private:
InterruptVectorTable();
public:
InterruptVectorTable(InterruptVectorTable const&) = delete;
void operator=(InterruptVectorTable const&) = delete;
static auto getInstance() -> InterruptVectorTable&;
auto setISR(IRQType InterruptIndex, void (*Callback)(void)) -> void;
};
```
Part two(`InterruptVectorTable.cpp`):
```cpp
#inlcude "InterruptVectorTable.hpp"
static void (*s_VectorTable[26])(void);
ISR(INT0_vect)
{
g_VectorTable[1]();
}
// ...
auto InterruptVectorTable<DeviceAtmega328p, IRQType>::setISR(IRQType InterruptIndex, void (*Callback)(void)) -> void {
s_VectorTable[static_cast<int>(IRQType)] = Callback;
}
//...
```
The last step is to put the variable definition into the .cpp source file (see above) and mark it as `static` to hide it from external access, while being in the global visibility scope. |
30,002,079 | Problem :- In case i have more than 1 line in my edittext, the previous line goes out of the visible area. I was expecting it to grow downwards so that all lines are visible.
Xml for my compound control which has this edittext:-
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/composite_control_layout"
android:background="@null"
tools:context="com.gp.app.professionalpa.layout.ListItemLayout" >
<Button android:id="@+id/compositeControlAddItem"
android:layout_height="30dip"
android:layout_width="30dip"
android:text="@string/plus"/>
<ImageView
android:id="@+id/compositeControlImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null"
android:contentDescription="@string/note_image"
android:scaleType="fitStart"
android:adjustViewBounds="true"
android:layout_toRightOf="@id/compositeControlAddItem"
android:layout_alignBottom="@id/compositeControlAddItem"
android:layout_alignParentLeft="true"
android:visibility="invisible"/>
<!-- <ImageButton
android:id="@+id/compositeControlBulletButton"
android:layout_width="35dip"
android:layout_height="@dimen/composite_control_height"
android:layout_marginRight="2dip"
android:contentDescription="@string/set_importance"
android:src="@drawable/ic_pin_black_bullet_point" /> -->
<EditText
android:id="@+id/compositeControlTextBox"
android:layout_width="250dip"
android:layout_height="@dimen/composite_control_height"
android:background="@null"
android:hint="@string/add_note"
android:layout_marginLeft="2dip"
android:layout_toRightOf="@+id/compositeControlAddItem"
android:layout_alignBottom="@+id/compositeControlAddItem"
android:inputType="textAutoCorrect|textMultiLine|textAutoComplete|textCapSentences"
android:maxLines="7"
android:maxLength="200"/>
<Button android:id="@+id/compositeControlDeleteItem"
android:layout_height="30dip"
android:layout_width="30dip"
android:layout_toRightOf="@+id/compositeControlTextBox"
android:layout_alignBottom="@+id/compositeControlTextBox"
android:text="@string/minus"/>
</RelativeLayout>
```
In my activity i am creating this compound contrl using the following code:-
```
private void addNewListItem()
{
ListViewItemLayout currentAddedListItem = new ListViewItemLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.alignWithParent = true;
if(lastAddedListItem != null)
{
layoutParams.addRule(RelativeLayout.BELOW, lastAddedListItem.getId());
}
currentAddedListItem.setLayoutParams(layoutParams);
activityLayout.addView(currentAddedListItem, listItems.size());
listItems.add(currentAddedListItem);
Button button = currentAddedListItem.getAddButton();
lastAddedListItem = currentAddedListItem;
}
```
Image showing that the previous lines becomes invisible in case edittext enters new line:-
 | 2015/05/02 | [
"https://Stackoverflow.com/questions/30002079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743554/"
] | For your particular calculation -- assuming the values are all positive -- just square the difference between the minimum and maximum values:
```
select power(max(prod_year) - min(prod_year), 2)
from mediaitems mi;
```
This can easily be modified to handle negative values, but that seems unlikely in a column named `prod_year`. | A `cross join` should do the trick - it pairs every item with every other item, giving the "nested loops" effect you wanted here.
```
SELECT MAX(POWER(a.prod_year - b.prod_year), 2)
FROM MediaItems a
CROSS JOIN MediaItems b
``` |
30,002,079 | Problem :- In case i have more than 1 line in my edittext, the previous line goes out of the visible area. I was expecting it to grow downwards so that all lines are visible.
Xml for my compound control which has this edittext:-
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/composite_control_layout"
android:background="@null"
tools:context="com.gp.app.professionalpa.layout.ListItemLayout" >
<Button android:id="@+id/compositeControlAddItem"
android:layout_height="30dip"
android:layout_width="30dip"
android:text="@string/plus"/>
<ImageView
android:id="@+id/compositeControlImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null"
android:contentDescription="@string/note_image"
android:scaleType="fitStart"
android:adjustViewBounds="true"
android:layout_toRightOf="@id/compositeControlAddItem"
android:layout_alignBottom="@id/compositeControlAddItem"
android:layout_alignParentLeft="true"
android:visibility="invisible"/>
<!-- <ImageButton
android:id="@+id/compositeControlBulletButton"
android:layout_width="35dip"
android:layout_height="@dimen/composite_control_height"
android:layout_marginRight="2dip"
android:contentDescription="@string/set_importance"
android:src="@drawable/ic_pin_black_bullet_point" /> -->
<EditText
android:id="@+id/compositeControlTextBox"
android:layout_width="250dip"
android:layout_height="@dimen/composite_control_height"
android:background="@null"
android:hint="@string/add_note"
android:layout_marginLeft="2dip"
android:layout_toRightOf="@+id/compositeControlAddItem"
android:layout_alignBottom="@+id/compositeControlAddItem"
android:inputType="textAutoCorrect|textMultiLine|textAutoComplete|textCapSentences"
android:maxLines="7"
android:maxLength="200"/>
<Button android:id="@+id/compositeControlDeleteItem"
android:layout_height="30dip"
android:layout_width="30dip"
android:layout_toRightOf="@+id/compositeControlTextBox"
android:layout_alignBottom="@+id/compositeControlTextBox"
android:text="@string/minus"/>
</RelativeLayout>
```
In my activity i am creating this compound contrl using the following code:-
```
private void addNewListItem()
{
ListViewItemLayout currentAddedListItem = new ListViewItemLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.alignWithParent = true;
if(lastAddedListItem != null)
{
layoutParams.addRule(RelativeLayout.BELOW, lastAddedListItem.getId());
}
currentAddedListItem.setLayoutParams(layoutParams);
activityLayout.addView(currentAddedListItem, listItems.size());
listItems.add(currentAddedListItem);
Button button = currentAddedListItem.getAddButton();
lastAddedListItem = currentAddedListItem;
}
```
Image showing that the previous lines becomes invisible in case edittext enters new line:-
 | 2015/05/02 | [
"https://Stackoverflow.com/questions/30002079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743554/"
] | For your particular calculation -- assuming the values are all positive -- just square the difference between the minimum and maximum values:
```
select power(max(prod_year) - min(prod_year), 2)
from mediaitems mi;
```
This can easily be modified to handle negative values, but that seems unlikely in a column named `prod_year`. | When comparing values with a single dimension the maximum distance comes just from the maximum and minimum elements. Any other pair will give you a lower distance so the best way to evaluate distance in your table is:
```
SELECT abs(MAX(prod_year) - MIN(prod_year))
FROM MediaItems
```
If you have only positive values for prod\_year you don't need to use the abs function. I don't understand why you need the squared difference in with single dimension values. |
15,575,663 | Trying to rewrite former urls to the latter. Rewrite that doesn't work for some reason. How to fix? Thanks.
www.example.com/example-example.html
www.example.com/example-example/
```
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([a-z]+-?[a-z]+)/$ /$1.html
``` | 2013/03/22 | [
"https://Stackoverflow.com/questions/15575663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2103958/"
] | x86\_64 does not use the stack for the first 6 args. You need to load them in the proper registers. Those are:
```
rdi, rsi, rdx, rcx, r8, r9
```
The trick I use to remember the first two is to imagine the function is `memcpy` implemented as `rep movsb`, | You're calling a varargs function -- printf expects a variable number of arguments and you have to account for that in the argument stack. See here: <http://www.csee.umbc.edu/portal/help/nasm/sample.shtml#printf1> |
11,013,899 | in my PHP script I have a variable like the following:
```
$names = '<a href="%URL$%" rel="tag">Name Surname</a>, <a href="%URL$%" rel="tag">Name Surname</a>, <a href="%URL$%" rel="tag">Name Surname</a>';
```
Is it possible to filter $names in order to have this result?
```
$names = '<a href="%URL$%" rel="tag">N. Surname</a>, <a href="%URL$%" rel="tag">N. Surname</a>, <a href="%URL$%" rel="tag">N. Surname</a>';
``` | 2012/06/13 | [
"https://Stackoverflow.com/questions/11013899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225992/"
] | You could use `preg_replace_callback`:
```
$names = preg_replace_callback(
'/(<a[^>]*>)(\w+)( \w+</a>)',
function($matches) {
return $matches[1] . substr($matches[2], 0, 1) . "." . $matches[3];
},
$names
);
``` | Really short answer: Use a HTML parser (like <http://simplehtmldom.sourceforge.net/>)
Regexes and HTML only work when you are sure you are only pulling apart a really predictable string of code. |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | store last char of your string at temp string and then check your temp string with regular exp
`Regex lettersOnly = new Regex("^[a-zA-Z]$");`
where
* ^ means "begin matching at start of string"
* [a-zA-Z] means "match lower case and upper case letters a-z"
* $ means "only match if cursor is at end of string"
tri it (i am not sure if it work) | You can use this function and send your string as parameter to this
```
private bool IsAlphabet(string input)
{
bool alphabet = false;
char ch = input[input.Length - 1];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
alphabet = true;
return alphabet;
}
``` |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | Here is a Regex solution:
```
Regex.IsMatch(name, "[a-zA-Z]$");
``` | You can use this function and send your string as parameter to this
```
private bool IsAlphabet(string input)
{
bool alphabet = false;
char ch = input[input.Length - 1];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
alphabet = true;
return alphabet;
}
``` |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | There is a function in the Char class that does this already.
```
string name = "ajsbbc";
if (Char.IsLetter(name[name.Length - 1]))
Console.WriteLine("True");
else
Console.WriteLine("False");
``` | You can use this function and send your string as parameter to this
```
private bool IsAlphabet(string input)
{
bool alphabet = false;
char ch = input[input.Length - 1];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
alphabet = true;
return alphabet;
}
``` |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | Here is a Regex solution:
```
Regex.IsMatch(name, "[a-zA-Z]$");
``` | store last char of your string at temp string and then check your temp string with regular exp
`Regex lettersOnly = new Regex("^[a-zA-Z]$");`
where
* ^ means "begin matching at start of string"
* [a-zA-Z] means "match lower case and upper case letters a-z"
* $ means "only match if cursor is at end of string"
tri it (i am not sure if it work) |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | There is a function in the Char class that does this already.
```
string name = "ajsbbc";
if (Char.IsLetter(name[name.Length - 1]))
Console.WriteLine("True");
else
Console.WriteLine("False");
``` | store last char of your string at temp string and then check your temp string with regular exp
`Regex lettersOnly = new Regex("^[a-zA-Z]$");`
where
* ^ means "begin matching at start of string"
* [a-zA-Z] means "match lower case and upper case letters a-z"
* $ means "only match if cursor is at end of string"
tri it (i am not sure if it work) |
8,515,208 | I would like to create obfuscated package of my j2me application for improving the size and performance.So, I have downloaded `proguard` from sourgeforge.net. I have put the `proguard.jar` into my `C:\WTK2.5.2_01\bin` folder.
When I try to create obfuscated package from `project->package->Create Obfuscation package` it raised the following exception
```
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error: C:\Documents (The system cannot find the file specified)
Obfuscation failed.
Build failed
```
So, What is the cause of this error message and How do I obfuscate my application? | 2011/12/15 | [
"https://Stackoverflow.com/questions/8515208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | There is a function in the Char class that does this already.
```
string name = "ajsbbc";
if (Char.IsLetter(name[name.Length - 1]))
Console.WriteLine("True");
else
Console.WriteLine("False");
``` | Here is a Regex solution:
```
Regex.IsMatch(name, "[a-zA-Z]$");
``` |
56,462 | I was just wondering if it's possible for me to enter the United States with a US visa that is issued outside of India(My home country).I studied and worked in Canada for over 5 years and I applied for a US visitor visa in 2014 and I was approved and visited the US a few times for commercial deliveries and shopping. Now the visa is valid until 2024 and I want to know if the CBP will create problems for me since the issuing post in my visa is Ottawa instead of a city in India. I would like to attend the E3 gaming convention next year in LA :3
**Bigger question:** Will the Airline allow me to board the flight since they can be extremely picky. | 2015/09/22 | [
"https://travel.stackexchange.com/questions/56462",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/35509/"
] | If you have a multiple entry B1 (visitor) visa, and I believe they grant those for 10 years now, I don't see why they would refuse you entry (assuming there are no other red flags). A visa is a visa, if it's valid and your passport is valid, it should be no problem.
You say you visited the US before, why is this a problem now ?
The same goes for the airline, they're required to check you're legally allowed to enter your destination country and by way of your visa, you are.
You mention "commercial deliveries", if you have a business visa this may be problematic at the border if your intent is tourism. It's a little arbitrary at this point, I've seen a friend granted entry for tourism while on a business visa. But I'd say it's more risky than a regular tourist visa | Both my passport and my US visa were issued in a country in which I am not a resident, and which is not related to my nationality.
It has made no difference to my entries to the US. A visa is a visa. |
11,327,119 | I try to integrate dotcmis and alfresco into my application.
When creating my unit tests, I face this issue :
- I set up my test environment by deleting "myfolder" if any
- I create back myfolder and put a document into it
then I try to find the document :
- The first time (when myfolder does not exist before), Search returns 0 results
- Next times, when myfolder exists before and is deleted by my test setup, I get an exception :
```
Apache Chemistry OpenCMIS - runtime error
HTTP Status 500 - <!--exception-->runtime<!--/exception--><p><!--message-->Node does not exist: missing://missing/missing(null)<!--/message--></p><hr noshade='noshade'/><!-- stacktrace--><pre>
org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException: Node does not exist: missing://missing/missing(null)
at org.alfresco.opencmis.AlfrescoCmisExceptionInterceptor.invoke(AlfrescoCmisExceptionInterceptor.java:80)
at ...
```
When I go to Alfresco, the document exists.
It seems that the folder and document are not yet disponible for query, but why ?
If I put in comment the test environment init, the document is found
Maybe I do something wrong but what ?
Here is my code :
```
[TestMethod()]
[DeploymentItem(@"Files\SearchTest_1", @"Files\SearchTest_1")]
public void SearchTest_2()
{
string myfoldername = "myfolder";
// Session creation
var p = new Dictionary<String, String>();
p[SessionParameter.User] = _userName;
p[SessionParameter.Password] = _userPassword;
p[SessionParameter.BindingType] = BindingType.AtomPub;
p[SessionParameter.AtomPubUrl] = _serverUrl;
var session = DotCMIS.Client.Impl.SessionFactory.NewInstance().GetRepositories(p)[0].CreateSession();
session.DefaultContext.CacheEnabled = false;
var operationContext = session.CreateOperationContext();
operationContext.IncludeAcls = true;
// Delete and create back folder and document
// /*
DotCMIS.Client.IFolder rootFolder = this._testSession.GetRootFolder(operationContext);
DotCMIS.Client.IFolder myFolder = null;
Dictionary<String, Object> properties = null;
// Le dossier de destination des tests existe-t-il ?
var myFolderExists = rootFolder.GetChildren(operationContext).Any(child => child.Name.Equals(myfoldername));
if (myFolderExists)
{
myFolder = (DotCMIS.Client.IFolder)session.GetObjectByPath(String.Format(@"/{0}", myfoldername), operationContext);
myFolder.DeleteTree(true, DotCMIS.Enums.UnfileObject.Delete, true);
}
properties = new Dictionary<String, Object>();
properties[PropertyIds.Name] = myfoldername;
properties[PropertyIds.ObjectTypeId] = "cmis:folder";
myFolder = rootFolder.CreateFolder(properties);
rootFolder.Refresh();
myFolder = (DotCMIS.Client.IFolder)session.GetObjectByPath(String.Format(@"/{0}", myfoldername), operationContext);
FileInfo sourceFile = new FileInfo(@"Files\SearchTest_1\SearchTest_1.pdf");
properties = new Dictionary<String, Object>();
properties[PropertyIds.ObjectTypeId] = "cmis:document";
properties[PropertyIds.Name] = sourceFile.Name;
using (var fileStream = sourceFile.OpenRead())
{
var contentStream = new DotCMIS.Data.Impl.ContentStream();
contentStream.MimeType = "application/pdf";
contentStream.Stream = fileStream;
contentStream.Length = fileStream.Length;
//this._testSession.CreateDocument(properties, this._testSession.CreateObjectId(myFolder.Id), contentStream, null);
DotCMIS.Client.IDocument createdDocument = myFolder.CreateDocument(properties, contentStream, null);
}
// */
// Recherche
string query = @"SELECT * FROM cmis:document WHERE cmis:name = 'SearchTest_1.pdf'";
var results = this._testSession.Query(query, false, operationContext).ToArray();
Assert.AreEqual(1, results.Length);
}
``` | 2012/07/04 | [
"https://Stackoverflow.com/questions/11327119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896673/"
] | Are you using Alfresco 4.0 with Solr for indexing? The Solr index is eventually consistent, this means that it can take a while (up to 15 seconds in the default configuration) for updates to show up in search results.
If you need updates to show up immediately you could switch to Lucene as the indexing subsystem. | I don't think the "eventually consistent" aspect of solr is an issue in production.
It may be when testing, but I prefer having a better system in production and having some problems in debug than the other way round.
To solve my issue in debug I first put a Thread.Sleep(20)... and it worked, but.. it's quite long while debugging.
My second solution that seem to work is to check the indexing state of solr using the url address:8080/solr/admin/cores?action=REPORT (\_solrStateUrl in my code).
The problem is that it's only accessible by SSL by default.
So you need to get the file "browser.p12" from the afresco server and put it in your project.
So I made 2 methods :
- CheckIndexingState that is parsing the xml response to find transactions in progress
- WaitForIndexingDone that is looping on CheckIndexingState
This code may not be very safe, but it's just for testing...
Here it is. Hope this will help someone...
```
private bool CheckIndexingState()
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(delegate(object sender2, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; });
System.Net.HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(_solrStateUrl);
request.ClientCertificates.Add(new X509Certificate2(@"ssl/browser.p12", "alfresco"));
var sb = new System.Text.StringBuilder();
byte[] buffer = new byte[256];
int nbRead = -1;
using (var stream = request.GetResponse().GetResponseStream())
{
while (nbRead != 0)
{
nbRead = stream.Read(buffer, 0, 256);
sb.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, nbRead));
}
}
String state = sb.ToString();
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
var node = doc.SelectSingleNode(@"/response/lst[@name='report']/lst[@name='alfresco']/long[@name='Count of transactions in the index but not the DB']");
int count = Int32.Parse(node.InnerText);
if (count > 0)
return false;
node = doc.SelectSingleNode(@"/response/lst[@name='report']/lst[@name='alfresco']/long[@name='Count of acl transactions in the index but not the DB']");
count = Int32.Parse(node.InnerText);
if (count > 0)
return false;
node = doc.SelectSingleNode(@"/response/lst[@name='report']/lst[@name='alfresco']/long[@name='Count of missing transactions from the Index']");
count = Int32.Parse(node.InnerText);
if (count > 0)
return false;
node = doc.SelectSingleNode(@"/response/lst[@name='report']/lst[@name='alfresco']/long[@name='Count of missing acl transactions from the Index']");
count = Int32.Parse(node.InnerText);
if (count > 0)
return false;
}
catch (Exception)
{
throw;
}
return true;
}
``` |
68,915,689 | i badly need help idk what this is-
```
matrix (c (1, 2, 1, 2, 2, 2), nrow= 2, ncol = 2, byrow = TRUE))
```
idk if this is right | 2021/08/25 | [
"https://Stackoverflow.com/questions/68915689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16745835/"
] | It's probably easier to see what's happening if you replace the numbers with letters, e.g.
```
matrix(c("A", "B", "C", "D", "E", "F"), nrow= 2, ncol = 2, byrow = TRUE)
#> [,1] [,2]
#> [1,] "A" "B"
#> [2,] "C" "D"
```
Basically, you are filling up a 2X2 matrix 'by row' and the last two elements in your vector are excluded. If you change your dimensions you can include all of the elements in the vector:
```
matrix(c("A", "B", "C", "D", "E", "F"), nrow= 3, ncol = 2, byrow = TRUE)
#> [,1] [,2]
#> [1,] "A" "B"
#> [2,] "C" "D"
#> [3,] "E" "F"
matrix(c("A", "B", "C", "D", "E", "F"), nrow= 2, ncol = 3, byrow = TRUE)
#> [,1] [,2] [,3]
#> [1,] "A" "B" "C"
#> [2,] "D" "E" "F"
```
Edit
----
I think I've figured out what you are trying to ask - based on your title you want to fill a matrix using "i + j" (i.e. a nested for loop). Here is a potential solution:
```
vector_of_letters <- c("A", "B", "C", "D", "E", "F")
mymatrix <- matrix(nrow = 2, ncol = 2)
count <- 0
for (i in 1:2) {
for (j in 1:2) {
count <- count + 1
mymatrix[i, j] <- vector_of_letters[count]
}
}
#> [,1] [,2]
#> [1,] "A" "B"
#> [2,] "C" "D"
``` | Its a matrix that looks like this:
```
|1 2|
|1 2|
```
In this example R fills numbers by row from the concatenated list of numbers until it runs out of space. In this case each row has 2 element with only 2 rows total meaning that R will drop the last 2 numbers.
---
**Update:** Answer to your comment
```
matrix (c ((1 + 1)^2/2, (1 + 2)^2/2, (2 + 1)^2/2, (2 + 2)^2/2), nrow= 2, ncol = 2, byrow = TRUE)
```
**Output:**
```
[,1] [,2]
[1,] 2.0 4.5
[2,] 4.5 8.0
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.