Programs & Examples On #Visual c++

Microsoft Visual C++ is a C, C++ and C++/CLI compiler for Windows. The most recent version of the compiler is Visual C++ 2017. The compiler supports the following languages: C: Supports C90 and most of C99 and C11 parts of the ISO C++ standard as of Visual Studio 2017 C++: Support for most C++11 features and some C++14 and C++17 features as of Visual Studio 2017 C++/CLI

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

change it to Console (/SUBSYSTEM:CONSOLE) it will work

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

How do I set the path to a DLL file in Visual Studio?

Another possibility would be to set the Working Directory under the debugging options to be the directory that has that DLL.

Edit: I was going to mention using a batch file to start Visual Studio (and set the PATH variable in the batch file). So then did a bit of searching and see that this exact same question was asked not long ago in this post. The answer suggests the batch file option as well as project settings that apparently may do the job (I did not test it).

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

What is the difference between C++ and Visual C++?

C++ is a standardized language. Visual C++ is a product that more or less implements that standard. You can write portable C++ using Visual C++, but you can also use Microsoft-only extensions that destroy your portability but enhance your productivity. This is a trade-off. You have to decide what appeals most to you.

I've maintained big desktop apps that were written in Visual C++, so that is perfectly feasible. From what I know of Visual Basic, the main advantage seems to be that the first part of the development cycle may be done faster than when using Visual C++, but as the complexity of a project increases, C++ programs tend to be more maintainable (If the programmers are striving for maintainability, that is).

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

Identifier is undefined

You may also be missing using namespace std;

How to install numpy on windows using pip install?

First go through this link https://www.python.org/downloads/ to download python 3.6.1 or 2.7.13 either of your choice.I preferred to use python 2.7 or 3.4.4 .now after installation go to the folder name python27/python34 then click on script now here open the command prompt by left click ad run as administration. After the command prompt appear write their "pip install numpy" this will install the numpy latest version and installing it will show success comment that's all. Similarly matplotlib can be install by just typing "pip install matplotlip". And now if you want to download scipy then just write "pip install scipy" and if it doesn't work then you need to download python scipy from the link https://sourceforge.net/projects/scipy/ and install it.

Why is this program erroneously rejected by three C++ compilers?

You could try different colors for brackets, maybe some green or red would help ? I think your compiler can't rcognize black ink :P

Visual C++: How to disable specific linker warnings?

(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.

For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)

How to add additional libraries to Visual Studio project?

Add #pragma comment(lib, "Your library name here") to your source.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

Since Visual Studio 2010 and later stopped using WinSxS, it may be enough to just check for %windir%\system32\msvcr110.dll. If you want to verify you have a new enough version, you can check whether the file version is 11.0.50727.1 (VS2012 RTM) or 11.0.51106.1 (VS2012 Update 1).

How to determine if a string is a number with C++?

bool isNumeric(string s){
    if ( !s.empty() && s[0] != '-' )
        s = "0" + s; //prepend 0

    string garbage;

    stringstream ss(s); 
    ss >> *(auto_ptr<double>(new double)) >> garbage;
/*
//the line above extracts the number into an anonymous variable. it could also be done like this:
double x;
ss >> x >> garbage;
*/
    //if there is no garbage return true or else return false
    return garbage.empty(); 
}

how it works: the stringstream >> overload can convert strings to various arithmetic types it does this by reading characters sequentially from the stringstream (ss in this case) until it runs out of characters OR the next character does not meet the criteria to be stored into the destination variable type.

example1:

stringstream ss("11");
double my_number;
ss >> my_number; //my number = 11

example2:

stringstream ss("011");
double my_number;
ss >> my_number; //my number = 11

example3:

stringstream ss("11ABCD");
double my_number;
ss >> my_number; //my number = 11 (even though there are letters after the 11)

the "garbage" variable explanation":

why not just check if extraction into my double has a valid value and then return true if it does?

notice example3 above will still successfully read the number 11 into the my_number variable even if the input string is "11ABCD" (which is not a number).

to handle this case we can do another extraction into a string variable(which I named garbage) which can read anything that may have been left over in the string buffer after the initial extraction into the variable of type double. If anything is left over it will be read into "garbage" which means the full string passed in was not a number (it just begins with one). in this which case we'd want to return false;

the prepended "0" explanation":

attempting to extract a single character into a double will fail(returning 0 into our double) but will still move the string buffer position to after the character. In this case our garbage read will be empty which would cause the function to incorrectly return true. to get around this I prepended a 0 to the string so that if for example the string passed in was "a" it gets changed to "0a" so that the 0 will be extracted into the double and "a" gets extracted into garbage.

prepending a 0 will not affect the value of the number so the number will still be correctly extracted into our double variable.

Visual Studio debugger error: Unable to start program Specified file cannot be found

Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.

The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.

DLL References in Visual C++

The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.

If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

My problem was a missing .lib extension, I was just linking against mylib and VS decided to look for mylib.obj.

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

Cannot open include file 'afxres.h' in VC2010 Express

Alternatively you can create your own afxres.h:

#ifndef _AFXRES_H
#define _AFXRES_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _WINDOWS_H
#include <windows.h>
#endif

/* IDC_STATIC is documented in winuser.h, but not defined. */
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif

#ifdef __cplusplus
}
#endif
#endif   

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

this happens to me when i convert my VS2008 solution to VS2010 & change win32 configuration to X64, in my old solution I have mfcs90d.lib (Configuration->Linker->Input->Additional dependencies), as I am using VS010 i just checked in VS2010 folder where it is mfcs100d.lib, so I changed mfcs90d.lib to mfcs100d.lib in (Configuration->Linker->Input->Additional dependencies) it worked fine.

How to define relative paths in Visual Studio Project?

I have used a syntax like this before:

$(ProjectDir)..\headers

or

..\headers

As other have pointed out, the starting directory is the one your project file is in(vcproj or vcxproj), not where your main code is located.

What is C# equivalent of <map> in C++?

Take a look at the Dictionary class in System::Collections::Generic.

Dictionary<myComplex, int> myMap = new Dictionary<myComplex, int>();

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.

p.s. if you use only visual studio the secure template overloads could be a good solution.

Link to all Visual Studio $ variables

Nikita's answer is nice for the macros that Visual Studio sets up in its environment, but this is far from comprehensive. (Environment variables become MSBuild macros, but not vis-a-versa.)

Slight tweak to ojdo's answer: Go to the "Pre-build event command line" in "Build Events" of the IDE for any project (where you find this in the IDE may depend on the language, i.e. C#, c++, etc. See other answers for location.) Post the code below into the "Pre-build event command line", then build that project. After the build starts, you will have a "macros.txt" file in your TEMP directory with a nice list of all the macros and their values. I based the list entirely on the list contained within ojdo's answer. I have no idea if it is comprehensive, but it's a good start!

echo AllowLocalNetworkLoopback=$(AllowLocalNetworkLoopback) >>$(TEMP)\macros.txt
echo ALLUSERSPROFILE=$(ALLUSERSPROFILE) >>$(TEMP)\macros.txt
echo AndroidTargetsPath=$(AndroidTargetsPath) >>$(TEMP)\macros.txt
echo APPDATA=$(APPDATA) >>$(TEMP)\macros.txt
echo AppxManifestMetadataClHostArchDir=$(AppxManifestMetadataClHostArchDir) >>$(TEMP)\macros.txt
echo AppxManifestMetadataCITargetArchDir=$(AppxManifestMetadataCITargetArchDir) >>$(TEMP)\macros.txt
echo Attach=$(Attach) >>$(TEMP)\macros.txt
echo BaseIntermediateOutputPath=$(BaseIntermediateOutputPath) >>$(TEMP)\macros.txt
echo BuildingInsideVisualStudio=$(BuildingInsideVisualStudio) >>$(TEMP)\macros.txt
echo CharacterSet=$(CharacterSet) >>$(TEMP)\macros.txt
echo CLRSupport=$(CLRSupport) >>$(TEMP)\macros.txt
echo CommonProgramFiles=$(CommonProgramFiles) >>$(TEMP)\macros.txt
echo CommonProgramW6432=$(CommonProgramW6432) >>$(TEMP)\macros.txt
echo COMPUTERNAME=$(COMPUTERNAME) >>$(TEMP)\macros.txt
echo ComSpec=$(ComSpec) >>$(TEMP)\macros.txt
echo Configuration=$(Configuration) >>$(TEMP)\macros.txt
echo ConfigurationType=$(ConfigurationType) >>$(TEMP)\macros.txt
echo CppWinRT_IncludePath=$(CppWinRT_IncludePath) >>$(TEMP)\macros.txt
echo CrtSDKReferencelnclude=$(CrtSDKReferencelnclude) >>$(TEMP)\macros.txt
echo CrtSDKReferenceVersion=$(CrtSDKReferenceVersion) >>$(TEMP)\macros.txt
echo CustomAfterMicrosoftCommonProps=$(CustomAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo CustomBeforeMicrosoftCommonProps=$(CustomBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo DebugCppRuntimeFilesPath=$(DebugCppRuntimeFilesPath) >>$(TEMP)\macros.txt
echo DebuggerFlavor=$(DebuggerFlavor) >>$(TEMP)\macros.txt
echo DebuggerLaunchApplication=$(DebuggerLaunchApplication) >>$(TEMP)\macros.txt
echo DebuggerRequireAuthentication=$(DebuggerRequireAuthentication) >>$(TEMP)\macros.txt
echo DebuggerType=$(DebuggerType) >>$(TEMP)\macros.txt
echo DefaultLanguageSourceExtension=$(DefaultLanguageSourceExtension) >>$(TEMP)\macros.txt
echo DefaultPlatformToolset=$(DefaultPlatformToolset) >>$(TEMP)\macros.txt
echo DefaultWindowsSDKVersion=$(DefaultWindowsSDKVersion) >>$(TEMP)\macros.txt
echo DefineExplicitDefaults=$(DefineExplicitDefaults) >>$(TEMP)\macros.txt
echo DelayImplib=$(DelayImplib) >>$(TEMP)\macros.txt
echo DesignTimeBuild=$(DesignTimeBuild) >>$(TEMP)\macros.txt
echo DevEnvDir=$(DevEnvDir) >>$(TEMP)\macros.txt
echo DocumentLibraryDependencies=$(DocumentLibraryDependencies) >>$(TEMP)\macros.txt
echo DotNetSdk_IncludePath=$(DotNetSdk_IncludePath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath=$(DotNetSdk_LibraryPath) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm=$(DotNetSdk_LibraryPath_arm) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_arm64=$(DotNetSdk_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x64=$(DotNetSdk_LibraryPath_x64) >>$(TEMP)\macros.txt
echo DotNetSdk_LibraryPath_x86=$(DotNetSdk_LibraryPath_x86) >>$(TEMP)\macros.txt
echo DotNetSdkRoot=$(DotNetSdkRoot) >>$(TEMP)\macros.txt
echo DriverData=$(DriverData) >>$(TEMP)\macros.txt
echo EmbedManifest=$(EmbedManifest) >>$(TEMP)\macros.txt
echo EnableManagedIncrementalBuild=$(EnableManagedIncrementalBuild) >>$(TEMP)\macros.txt
echo EspXtensions=$(EspXtensions) >>$(TEMP)\macros.txt
echo ExcludePath=$(ExcludePath) >>$(TEMP)\macros.txt
echo ExecutablePath=$(ExecutablePath) >>$(TEMP)\macros.txt
echo ExtensionsToDeleteOnClean=$(ExtensionsToDeleteOnClean) >>$(TEMP)\macros.txt
echo FPS_BROWSER_APP_PROFILE_STRING=$(FPS_BROWSER_APP_PROFILE_STRING) >>$(TEMP)\macros.txt
echo FPS_BROWSER_USER_PROFILE_STRING=$(FPS_BROWSER_USER_PROFILE_STRING) >>$(TEMP)\macros.txt
echo FrameworkDir=$(FrameworkDir) >>$(TEMP)\macros.txt
echo FrameworkDir_110=$(FrameworkDir_110) >>$(TEMP)\macros.txt
echo FrameworkSdkDir=$(FrameworkSdkDir) >>$(TEMP)\macros.txt
echo FrameworkSDKRoot=$(FrameworkSDKRoot) >>$(TEMP)\macros.txt
echo FrameworkVersion=$(FrameworkVersion) >>$(TEMP)\macros.txt
echo GenerateManifest=$(GenerateManifest) >>$(TEMP)\macros.txt
echo GPURefDebuggerBreakOnAllThreads=$(GPURefDebuggerBreakOnAllThreads) >>$(TEMP)\macros.txt
echo HOMEDRIVE=$(HOMEDRIVE) >>$(TEMP)\macros.txt
echo HOMEPATH=$(HOMEPATH) >>$(TEMP)\macros.txt
echo IgnorelmportLibrary=$(IgnorelmportLibrary) >>$(TEMP)\macros.txt
echo ImportByWildcardAfterMicrosoftCommonProps=$(ImportByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportByWildcardBeforeMicrosoftCommonProps=$(ImportByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportDirectoryBuildProps=$(ImportDirectoryBuildProps) >>$(TEMP)\macros.txt
echo ImportProjectExtensionProps=$(ImportProjectExtensionProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardAfterMicrosoftCommonProps=$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo ImportUserLocationsByWildcardBeforeMicrosoftCommonProps=$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps) >>$(TEMP)\macros.txt
echo IncludePath=$(IncludePath) >>$(TEMP)\macros.txt
echo IncludeVersionInInteropName=$(IncludeVersionInInteropName) >>$(TEMP)\macros.txt
echo IntDir=$(IntDir) >>$(TEMP)\macros.txt
echo InteropOutputPath=$(InteropOutputPath) >>$(TEMP)\macros.txt
echo iOSTargetsPath=$(iOSTargetsPath) >>$(TEMP)\macros.txt
echo Keyword=$(Keyword) >>$(TEMP)\macros.txt
echo KIT_SHARED_IncludePath=$(KIT_SHARED_IncludePath) >>$(TEMP)\macros.txt
echo LangID=$(LangID) >>$(TEMP)\macros.txt
echo LangName=$(LangName) >>$(TEMP)\macros.txt
echo Language=$(Language) >>$(TEMP)\macros.txt
echo LIBJABRA_TRACE_LEVEL=$(LIBJABRA_TRACE_LEVEL) >>$(TEMP)\macros.txt
echo LibraryPath=$(LibraryPath) >>$(TEMP)\macros.txt
echo LibraryWPath=$(LibraryWPath) >>$(TEMP)\macros.txt
echo LinkCompiled=$(LinkCompiled) >>$(TEMP)\macros.txt
echo LinkIncremental=$(LinkIncremental) >>$(TEMP)\macros.txt
echo LOCALAPPDATA=$(LOCALAPPDATA) >>$(TEMP)\macros.txt
echo LocalDebuggerAttach=$(LocalDebuggerAttach) >>$(TEMP)\macros.txt
echo LocalDebuggerDebuggerlType=$(LocalDebuggerDebuggerlType) >>$(TEMP)\macros.txt
echo LocalDebuggerMergeEnvironment=$(LocalDebuggerMergeEnvironment) >>$(TEMP)\macros.txt
echo LocalDebuggerSQLDebugging=$(LocalDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo LocalDebuggerWorkingDirectory=$(LocalDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo LocalGPUDebuggerTargetType=$(LocalGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo LOGONSERVER=$(LOGONSERVER) >>$(TEMP)\macros.txt
echo MicrosoftCommonPropsHasBeenImported=$(MicrosoftCommonPropsHasBeenImported) >>$(TEMP)\macros.txt
echo MpiDebuggerCleanupDeployment=$(MpiDebuggerCleanupDeployment) >>$(TEMP)\macros.txt
echo MpiDebuggerDebuggerType=$(MpiDebuggerDebuggerType) >>$(TEMP)\macros.txt
echo MpiDebuggerDeployCommonRuntime=$(MpiDebuggerDeployCommonRuntime) >>$(TEMP)\macros.txt
echo MpiDebuggerNetworkSecurityMode=$(MpiDebuggerNetworkSecurityMode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerNode=$(MpiDebuggerSchedulerNode) >>$(TEMP)\macros.txt
echo MpiDebuggerSchedulerTimeout=$(MpiDebuggerSchedulerTimeout) >>$(TEMP)\macros.txt
echo MSBuild_ExecutablePath=$(MSBuild_ExecutablePath) >>$(TEMP)\macros.txt
echo MSBuildAllProjects=$(MSBuildAllProjects) >>$(TEMP)\macros.txt
echo MSBuildAssemblyVersion=$(MSBuildAssemblyVersion) >>$(TEMP)\macros.txt
echo MSBuildBinPath=$(MSBuildBinPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath=$(MSBuildExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath32=$(MSBuildExtensionsPath32) >>$(TEMP)\macros.txt
echo MSBuildExtensionsPath64=$(MSBuildExtensionsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath=$(MSBuildFrameworkToolsPath) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath32=$(MSBuildFrameworkToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsPath64=$(MSBuildFrameworkToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildFrameworkToolsRoot=$(MSBuildFrameworkToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildLoadMicrosoftTargetsReadOnly=$(MSBuildLoadMicrosoftTargetsReadOnly) >>$(TEMP)\macros.txt
echo MSBuildNodeCount=$(MSBuildNodeCount) >>$(TEMP)\macros.txt
echo MSBuildProgramFiles32=$(MSBuildProgramFiles32) >>$(TEMP)\macros.txt
echo MSBuildProjectDefaultTargets=$(MSBuildProjectDefaultTargets) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectory=$(MSBuildProjectDirectory) >>$(TEMP)\macros.txt
echo MSBuildProjectDirectoryNoRoot=$(MSBuildProjectDirectoryNoRoot) >>$(TEMP)\macros.txt
echo MSBuildProjectExtension=$(MSBuildProjectExtension) >>$(TEMP)\macros.txt
echo MSBuildProjectExtensionsPath=$(MSBuildProjectExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildProjectFile=$(MSBuildProjectFile) >>$(TEMP)\macros.txt
echo MSBuildProjectFullPath=$(MSBuildProjectFullPath) >>$(TEMP)\macros.txt
echo MSBuildProjectName=$(MSBuildProjectName) >>$(TEMP)\macros.txt
echo MSBuildRuntimeType=$(MSBuildRuntimeType) >>$(TEMP)\macros.txt
echo MSBuildRuntimeVersion=$(MSBuildRuntimeVersion) >>$(TEMP)\macros.txt
echo MSBuildSDKsPath=$(MSBuildSDKsPath) >>$(TEMP)\macros.txt
echo MSBuildStartupDirectory=$(MSBuildStartupDirectory) >>$(TEMP)\macros.txt
echo MSBuildToolsPath=$(MSBuildToolsPath) >>$(TEMP)\macros.txt
echo MSBuildToolsPath32=$(MSBuildToolsPath32) >>$(TEMP)\macros.txt
echo MSBuildToolsPath64=$(MSBuildToolsPath64) >>$(TEMP)\macros.txt
echo MSBuildToolsRoot=$(MSBuildToolsRoot) >>$(TEMP)\macros.txt
echo MSBuildToolsVersion=$(MSBuildToolsVersion) >>$(TEMP)\macros.txt
echo MSBuildUserExtensionsPath=$(MSBuildUserExtensionsPath) >>$(TEMP)\macros.txt
echo MSBuildVersion=$(MSBuildVersion) >>$(TEMP)\macros.txt
echo MultiToolTask=$(MultiToolTask) >>$(TEMP)\macros.txt
echo NETFXKitsDir=$(NETFXKitsDir) >>$(TEMP)\macros.txt
echo NETFXSDKDir=$(NETFXSDKDir) >>$(TEMP)\macros.txt
echo NuGetProps=$(NuGetProps) >>$(TEMP)\macros.txt
echo NUMBER_OF_PROCESSORS=$(NUMBER_OF_PROCESSORS) >>$(TEMP)\macros.txt
echo OCTAVE_EXECUTABLE=$(OCTAVE_EXECUTABLE) >>$(TEMP)\macros.txt
echo OneDrive=$(OneDrive) >>$(TEMP)\macros.txt
echo OneDriveCommercial=$(OneDriveCommercial) >>$(TEMP)\macros.txt
echo OS=$(OS) >>$(TEMP)\macros.txt
echo OutDir=$(OutDir) >>$(TEMP)\macros.txt
echo OutDirWasSpecified=$(OutDirWasSpecified) >>$(TEMP)\macros.txt
echo OutputType=$(OutputType) >>$(TEMP)\macros.txt
echo Path=$(Path) >>$(TEMP)\macros.txt
echo PATHEXT=$(PATHEXT) >>$(TEMP)\macros.txt
echo PkgDefApplicationConfigFile=$(PkgDefApplicationConfigFile) >>$(TEMP)\macros.txt
echo Platform=$(Platform) >>$(TEMP)\macros.txt
echo Platform_Actual=$(Platform_Actual) >>$(TEMP)\macros.txt
echo PlatformArchitecture=$(PlatformArchitecture) >>$(TEMP)\macros.txt
echo PlatformName=$(PlatformName) >>$(TEMP)\macros.txt
echo PlatformPropsFound=$(PlatformPropsFound) >>$(TEMP)\macros.txt
echo PlatformShortName=$(PlatformShortName) >>$(TEMP)\macros.txt
echo PlatformTarget=$(PlatformTarget) >>$(TEMP)\macros.txt
echo PlatformTargetsFound=$(PlatformTargetsFound) >>$(TEMP)\macros.txt
echo PlatformToolset=$(PlatformToolset) >>$(TEMP)\macros.txt
echo PlatformToolsetVersion=$(PlatformToolsetVersion) >>$(TEMP)\macros.txt
echo PostBuildEventUseInBuild=$(PostBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreBuildEventUseInBuild=$(PreBuildEventUseInBuild) >>$(TEMP)\macros.txt
echo PreferredToolArchitecture=$(PreferredToolArchitecture) >>$(TEMP)\macros.txt
echo PreLinkEventUselnBuild=$(PreLinkEventUselnBuild) >>$(TEMP)\macros.txt
echo PROCESSOR_ARCHITECTURE=$(PROCESSOR_ARCHITECTURE) >>$(TEMP)\macros.txt
echo PROCESSOR_ARCHITEW6432=$(PROCESSOR_ARCHITEW6432) >>$(TEMP)\macros.txt
echo PROCESSOR_IDENTIFIER=$(PROCESSOR_IDENTIFIER) >>$(TEMP)\macros.txt
echo PROCESSOR_LEVEL=$(PROCESSOR_LEVEL) >>$(TEMP)\macros.txt
echo PROCESSOR_REVISION=$(PROCESSOR_REVISION) >>$(TEMP)\macros.txt
echo ProgramData=$(ProgramData) >>$(TEMP)\macros.txt
echo ProgramFiles=$(ProgramFiles) >>$(TEMP)\macros.txt
echo ProgramW6432=$(ProgramW6432) >>$(TEMP)\macros.txt
echo ProjectDir=$(ProjectDir) >>$(TEMP)\macros.txt
echo ProjectExt=$(ProjectExt) >>$(TEMP)\macros.txt
echo ProjectFileName=$(ProjectFileName) >>$(TEMP)\macros.txt
echo ProjectGuid=$(ProjectGuid) >>$(TEMP)\macros.txt
echo ProjectName=$(ProjectName) >>$(TEMP)\macros.txt
echo ProjectPath=$(ProjectPath) >>$(TEMP)\macros.txt
echo PSExecutionPolicyPreference=$(PSExecutionPolicyPreference) >>$(TEMP)\macros.txt
echo PSModulePath=$(PSModulePath) >>$(TEMP)\macros.txt
echo PUBLIC=$(PUBLIC) >>$(TEMP)\macros.txt
echo ReferencePath=$(ReferencePath) >>$(TEMP)\macros.txt
echo RemoteDebuggerAttach=$(RemoteDebuggerAttach) >>$(TEMP)\macros.txt
echo RemoteDebuggerConnection=$(RemoteDebuggerConnection) >>$(TEMP)\macros.txt
echo RemoteDebuggerDebuggerlype=$(RemoteDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo RemoteDebuggerDeployDebugCppRuntime=$(RemoteDebuggerDeployDebugCppRuntime) >>$(TEMP)\macros.txt
echo RemoteDebuggerServerName=$(RemoteDebuggerServerName) >>$(TEMP)\macros.txt
echo RemoteDebuggerSQLDebugging=$(RemoteDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo RemoteDebuggerWorkingDirectory=$(RemoteDebuggerWorkingDirectory) >>$(TEMP)\macros.txt
echo RemoteGPUDebuggerTargetType=$(RemoteGPUDebuggerTargetType) >>$(TEMP)\macros.txt
echo RetargetAlwaysSupported=$(RetargetAlwaysSupported) >>$(TEMP)\macros.txt
echo RootNamespace=$(RootNamespace) >>$(TEMP)\macros.txt
echo RoslynTargetsPath=$(RoslynTargetsPath) >>$(TEMP)\macros.txt
echo SDK35ToolsPath=$(SDK35ToolsPath) >>$(TEMP)\macros.txt
echo SDK40ToolsPath=$(SDK40ToolsPath) >>$(TEMP)\macros.txt
echo SDKDisplayName=$(SDKDisplayName) >>$(TEMP)\macros.txt
echo SDKIdentifier=$(SDKIdentifier) >>$(TEMP)\macros.txt
echo SDKVersion=$(SDKVersion) >>$(TEMP)\macros.txt
echo SESSIONNAME=$(SESSIONNAME) >>$(TEMP)\macros.txt
echo SolutionDir=$(SolutionDir) >>$(TEMP)\macros.txt
echo SolutionExt=$(SolutionExt) >>$(TEMP)\macros.txt
echo SolutionFileName=$(SolutionFileName) >>$(TEMP)\macros.txt
echo SolutionName=$(SolutionName) >>$(TEMP)\macros.txt
echo SolutionPath=$(SolutionPath) >>$(TEMP)\macros.txt
echo SourcePath=$(SourcePath) >>$(TEMP)\macros.txt
echo SpectreMitigation=$(SpectreMitigation) >>$(TEMP)\macros.txt
echo SQLDebugging=$(SQLDebugging) >>$(TEMP)\macros.txt
echo SystemDrive=$(SystemDrive) >>$(TEMP)\macros.txt
echo SystemRoot=$(SystemRoot) >>$(TEMP)\macros.txt
echo TargetExt=$(TargetExt) >>$(TEMP)\macros.txt
echo TargetFrameworkVersion=$(TargetFrameworkVersion) >>$(TEMP)\macros.txt
echo TargetName=$(TargetName) >>$(TEMP)\macros.txt
echo TargetPlatformMinVersion=$(TargetPlatformMinVersion) >>$(TEMP)\macros.txt
echo TargetPlatformVersion=$(TargetPlatformVersion) >>$(TEMP)\macros.txt
echo TargetPlatformWinMDLocation=$(TargetPlatformWinMDLocation) >>$(TEMP)\macros.txt
echo TargetUniversalCRTVersion=$(TargetUniversalCRTVersion) >>$(TEMP)\macros.txt
echo TEMP=$(TEMP) >>$(TEMP)\macros.txt
echo TMP=$(TMP) >>$(TEMP)\macros.txt
echo ToolsetPropsFound=$(ToolsetPropsFound) >>$(TEMP)\macros.txt
echo ToolsetTargetsFound=$(ToolsetTargetsFound) >>$(TEMP)\macros.txt
echo UCRTContentRoot=$(UCRTContentRoot) >>$(TEMP)\macros.txt
echo UM_IncludePath=$(UM_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_IncludePath=$(UniversalCRT_IncludePath) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm=$(UniversalCRT_LibraryPath_arm) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_arm64=$(UniversalCRT_LibraryPath_arm64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x64=$(UniversalCRT_LibraryPath_x64) >>$(TEMP)\macros.txt
echo UniversalCRT_LibraryPath_x86=$(UniversalCRT_LibraryPath_x86) >>$(TEMP)\macros.txt
echo UniversalCRT_PropsPath=$(UniversalCRT_PropsPath) >>$(TEMP)\macros.txt
echo UniversalCRT_SourcePath=$(UniversalCRT_SourcePath) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir=$(UniversalCRTSdkDir) >>$(TEMP)\macros.txt
echo UniversalCRTSdkDir_10=$(UniversalCRTSdkDir_10) >>$(TEMP)\macros.txt
echo UseDebugLibraries=$(UseDebugLibraries) >>$(TEMP)\macros.txt
echo UseLegacyManagedDebugger=$(UseLegacyManagedDebugger) >>$(TEMP)\macros.txt
echo UseOfATL=$(UseOfATL) >>$(TEMP)\macros.txt
echo UseOfMfc=$(UseOfMfc) >>$(TEMP)\macros.txt
echo USERDOMAIN=$(USERDOMAIN) >>$(TEMP)\macros.txt
echo USERDOMAIN_ROAMINGPROFILE=$(USERDOMAIN_ROAMINGPROFILE) >>$(TEMP)\macros.txt
echo USERNAME=$(USERNAME) >>$(TEMP)\macros.txt
echo USERPROFILE=$(USERPROFILE) >>$(TEMP)\macros.txt
echo UserRootDir=$(UserRootDir) >>$(TEMP)\macros.txt
echo VBOX_MSI_INSTALL_PATH=$(VBOX_MSI_INSTALL_PATH) >>$(TEMP)\macros.txt
echo VC_ATLMFC_IncludePath=$(VC_ATLMFC_IncludePath) >>$(TEMP)\macros.txt
echo VC_ATLMFC_SourcePath=$(VC_ATLMFC_SourcePath) >>$(TEMP)\macros.txt
echo VC_CRT_SourcePath=$(VC_CRT_SourcePath) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM=$(VC_ExecutablePath_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_ARM64=$(VC_ExecutablePath_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64=$(VC_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM=$(VC_ExecutablePath_x64_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_ARM64=$(VC_ExecutablePath_x64_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x64=$(VC_ExecutablePath_x64_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x64_x86=$(VC_ExecutablePath_x64_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86=$(VC_ExecutablePath_x86) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM=$(VC_ExecutablePath_x86_ARM) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_ARM64=$(VC_ExecutablePath_x86_ARM64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x64=$(VC_ExecutablePath_x86_x64) >>$(TEMP)\macros.txt
echo VC_ExecutablePath_x86_x86=$(VC_ExecutablePath_x86_x86) >>$(TEMP)\macros.txt
echo VC_IFCPath=$(VC_IFCPath) >>$(TEMP)\macros.txt
echo VC_IncludePath=$(VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM=$(VC_LibraryPath_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ARM64=$(VC_LibraryPath_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM=$(VC_LibraryPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_ARM64=$(VC_LibraryPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x64=$(VC_LibraryPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_ATL_x86=$(VC_LibraryPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM=$(VC_LibraryPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Desktop=$(VC_LibraryPath_VC_ARM_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_OneCore=$(VC_LibraryPath_VC_ARM_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM_Store=$(VC_LibraryPath_VC_ARM_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64=$(VC_LibraryPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Desktop=$(VC_LibraryPath_VC_ARM64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_OneCore=$(VC_LibraryPath_VC_ARM64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_ARM64_Store=$(VC_LibraryPath_VC_ARM64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64=$(VC_LibraryPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Desktop=$(VC_LibraryPath_VC_x64_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_OneCore=$(VC_LibraryPath_VC_x64_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x64_Store=$(VC_LibraryPath_VC_x64_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86=$(VC_LibraryPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Desktop=$(VC_LibraryPath_VC_x86_Desktop) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_OneCore=$(VC_LibraryPath_VC_x86_OneCore) >>$(TEMP)\macros.txt
echo VC_LibraryPath_VC_x86_Store=$(VC_LibraryPath_VC_x86_Store) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x64=$(VC_LibraryPath_x64) >>$(TEMP)\macros.txt
echo VC_LibraryPath_x86=$(VC_LibraryPath_x86) >>$(TEMP)\macros.txt
echo VC_PGO_RunTime_Dir=$(VC_PGO_RunTime_Dir) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM=$(VC_ReferencesPath_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ARM64=$(VC_ReferencesPath_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM=$(VC_ReferencesPath_ATL_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_ARM64=$(VC_ReferencesPath_ATL_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x64=$(VC_ReferencesPath_ATL_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_ATL_x86=$(VC_ReferencesPath_ATL_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM=$(VC_ReferencesPath_VC_ARM) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_ARM64=$(VC_ReferencesPath_VC_ARM64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x64=$(VC_ReferencesPath_VC_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_VC_x86=$(VC_ReferencesPath_VC_x86) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x64=$(VC_ReferencesPath_x64) >>$(TEMP)\macros.txt
echo VC_ReferencesPath_x86=$(VC_ReferencesPath_x86) >>$(TEMP)\macros.txt
echo VC_SourcePath=$(VC_SourcePath) >>$(TEMP)\macros.txt
echo VC_VC_IncludePath=$(VC_VC_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_IncludePath=$(VC_VS_IncludePath) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_ARM=$(VC_VS_LibraryPath_VC_VS_ARM) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x64=$(VC_VS_LibraryPath_VC_VS_x64) >>$(TEMP)\macros.txt
echo VC_VS_LibraryPath_VC_VS_x86=$(VC_VS_LibraryPath_VC_VS_x86) >>$(TEMP)\macros.txt
echo VC_VS_SourcePath=$(VC_VS_SourcePath) >>$(TEMP)\macros.txt
echo VCIDEInstallDir=$(VCIDEInstallDir) >>$(TEMP)\macros.txt
echo VCIDEInstallDir_150=$(VCIDEInstallDir_150) >>$(TEMP)\macros.txt
echo VCInstallDir=$(VCInstallDir) >>$(TEMP)\macros.txt
echo VCInstallDir_150=$(VCInstallDir_150) >>$(TEMP)\macros.txt
echo VCLibPackagePath=$(VCLibPackagePath) >>$(TEMP)\macros.txt
echo VCProjectVersion=$(VCProjectVersion) >>$(TEMP)\macros.txt
echo VCTargetsPath=$(VCTargetsPath) >>$(TEMP)\macros.txt
echo VCTargetsPath10=$(VCTargetsPath10) >>$(TEMP)\macros.txt
echo VCTargetsPath11=$(VCTargetsPath11) >>$(TEMP)\macros.txt
echo VCTargetsPath12=$(VCTargetsPath12) >>$(TEMP)\macros.txt
echo VCTargetsPath14=$(VCTargetsPath14) >>$(TEMP)\macros.txt
echo VCTargetsPath15=$(VCTargetsPath15) >>$(TEMP)\macros.txt
echo VCTargetsPathActual=$(VCTargetsPathActual) >>$(TEMP)\macros.txt
echo VCTargetsPathEffective=$(VCTargetsPathEffective) >>$(TEMP)\macros.txt
echo VCToolArchitecture=$(VCToolArchitecture) >>$(TEMP)\macros.txt
echo VCToolsInstallDir=$(VCToolsInstallDir) >>$(TEMP)\macros.txt
echo VCToolsInstallDir_150=$(VCToolsInstallDir_150) >>$(TEMP)\macros.txt
echo VCToolsVersion=$(VCToolsVersion) >>$(TEMP)\macros.txt
echo VisualStudioDir=$(VisualStudioDir) >>$(TEMP)\macros.txt
echo VisualStudioEdition=$(VisualStudioEdition) >>$(TEMP)\macros.txt
echo VisualStudioVersion=$(VisualStudioVersion) >>$(TEMP)\macros.txt
echo VS_ExecutablePath=$(VS_ExecutablePath) >>$(TEMP)\macros.txt
echo VS140COMNTOOLS=$(VS140COMNTOOLS) >>$(TEMP)\macros.txt
echo VSAPPIDDIR=$(VSAPPIDDIR) >>$(TEMP)\macros.txt
echo VSAPPIDNAME=$(VSAPPIDNAME) >>$(TEMP)\macros.txt
echo VSInstallDir=$(VSInstallDir) >>$(TEMP)\macros.txt
echo VSInstallDir_150=$(VSInstallDir_150) >>$(TEMP)\macros.txt
echo VsInstallRoot=$(VsInstallRoot) >>$(TEMP)\macros.txt
echo VSLANG=$(VSLANG) >>$(TEMP)\macros.txt
echo VSSKUEDITION=$(VSSKUEDITION) >>$(TEMP)\macros.txt
echo VSVersion=$(VSVersion) >>$(TEMP)\macros.txt
echo WDKBinRoot=$(WDKBinRoot) >>$(TEMP)\macros.txt
echo WebBrowserDebuggerDebuggerlype=$(WebBrowserDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerDebuggerlype=$(WebServiceDebuggerDebuggerlype) >>$(TEMP)\macros.txt
echo WebServiceDebuggerSQLDebugging=$(WebServiceDebuggerSQLDebugging) >>$(TEMP)\macros.txt
echo WholeProgramOptimization=$(WholeProgramOptimization) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityInstrument=$(WholeProgramOptimizationAvailabilityInstrument) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityOptimize=$(WholeProgramOptimizationAvailabilityOptimize) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityTrue=$(WholeProgramOptimizationAvailabilityTrue) >>$(TEMP)\macros.txt
echo WholeProgramOptimizationAvailabilityUpdate=$(WholeProgramOptimizationAvailabilityUpdate) >>$(TEMP)\macros.txt
echo windir=$(windir) >>$(TEMP)\macros.txt
echo Windows81SdkInstalled=$(Windows81SdkInstalled) >>$(TEMP)\macros.txt
echo WindowsAppContainer=$(WindowsAppContainer) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath=$(WindowsSDK_ExecutablePath) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm=$(WindowsSDK_ExecutablePath_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_arm64=$(WindowsSDK_ExecutablePath_arm64) >>$(TEMP)\macros.txt
echo WindowsSDK_ExecutablePath_x64=$(WindowsSDK_ExecutablePath_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_LibraryPath_x86=$(WindowsSDK_LibraryPath_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataFoundationPath=$(WindowsSDK_MetadataFoundationPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPath=$(WindowsSDK_MetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK_MetadataPathVersioned=$(WindowsSDK_MetadataPathVersioned) >>$(TEMP)\macros.txt
echo WindowsSDK_PlatformPath=$(WindowsSDK_PlatformPath) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_arm=$(WindowsSDK_SupportedAPIs_arm) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x64=$(WindowsSDK_SupportedAPIs_x64) >>$(TEMP)\macros.txt
echo WindowsSDK_SupportedAPIs_x86=$(WindowsSDK_SupportedAPIs_x86) >>$(TEMP)\macros.txt
echo WindowsSDK_UnionMetadataPath=$(WindowsSDK_UnionMetadataPath) >>$(TEMP)\macros.txt
echo WindowsSDK80Path=$(WindowsSDK80Path) >>$(TEMP)\macros.txt
echo WindowsSdkDir=$(WindowsSdkDir) >>$(TEMP)\macros.txt
echo WindowsSdkDir_10=$(WindowsSdkDir_10) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81=$(WindowsSdkDir_81) >>$(TEMP)\macros.txt
echo WindowsSdkDir_81A=$(WindowsSdkDir_81A) >>$(TEMP)\macros.txt
echo WindowsSDKToolArchitecture=$(WindowsSDKToolArchitecture) >>$(TEMP)\macros.txt
echo WindowsTargetPlatformVersion=$(WindowsTargetPlatformVersion) >>$(TEMP)\macros.txt
echo WinRT_IncludePath=$(WinRT_IncludePath) >>$(TEMP)\macros.txt
echo WMSISProject=$(WMSISProject) >>$(TEMP)\macros.txt
echo WMSISProjectDirectory=$(WMSISProjectDirectory) >>$(TEMP)\macros.txt

'uint32_t' identifier not found error

On Windows I usually use windows types. To use it you have to include <Windows.h>.

In this case uint32_t is UINT32 or just UINT.

All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx

How to run regasm.exe from command line other than Visual Studio command prompt?

I use the following in a batch file:

path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause

How do I turn off Unicode in a VC++ project?

Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.

How to keep the console window open in Visual C++?

Here's a way to keep the command window open regardless of how execution stops without modifying any code:

In Visual Studio, open Project Property Pages -> Debugging.

For Command, enter $(ComSpec)

For Command Arguments, enter /k $(TargetPath). Append any arguments to your own application.

Now F5 or Ctrl-F5 executes Windows/System32/cmd.exe in a new window, and /k ensures that the command prompt stays open after execution completes.

The downside is that execution won't stop on breakpoints.

How to write to the Output window in Visual Studio?

OutputDebugString function will do it.

example code

    void CClass::Output(const char* szFormat, ...)
{
    char szBuff[1024];
    va_list arg;
    va_start(arg, szFormat);
    _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
    va_end(arg);

    OutputDebugString(szBuff);
}

How do I clear a C++ array?

Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize

std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });

You can do ints too e.g.

std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

or just

std::generate(v.begin(), v.end(), [] (){ return 0; });

but I imagine std::fill is faster for the simplest case

how to initialize a char array?

char * msg = new char[65546]();

It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C).

Note that this won't work for any value other than zero. I think C++0x will offer a way to do that, but I'm a bit behind the times so I can't comment on that.

UPDATE: it seems my ruminations on the past and future of the language aren't entirely accurate; see the comments for corrections.

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Fatal error: "No Target Architecture" in Visual Studio

Another cause of this can be including a header that depends on windows.h, before including windows.h.

In my case I included xinput.h before windows.h and got this error. Swapping the order solved the problem.

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.

The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.

So the solution is to recompile Projectname1.lib with VS2012.

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Just run it without options.

P:\>cl.exe
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

fopen deprecated warning

For those who are using Visual Studio 2017 version, it seems like the preprocessor definition required to run unsafe operations has changed. Use instead:

#define _CRT_SECURE_NO_WARNINGS

It will compile then.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

LPCSTR, LPCTSTR and LPTSTR

Quick and dirty:

LP == Long Pointer. Just think pointer or char*

C = Const, in this case, I think they mean the character string is a const, not the pointer being const.

STR is string

the T is for a wide character or char (TCHAR) depending on compile options.

Disable single warning error

Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.

Although there are some other options, including #pramga warning (once).

fatal error LNK1104: cannot open file 'kernel32.lib'

I had a differnt problem on Windows 10 with Visual Studio 2017 but with the same effects. I think my problems came down to VS being installed onto a drive other than "C:\". I solved the problem by Reinstalling Windows 10 SDK

First I had to uninstall the Windows SDK (there were two versions installed). Then ran the executable. Once installed, ran visual studio and it worked fine.

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Get a file name from a path

If you can use boost,

#include <boost/filesystem.hpp>
path p("C:\\MyDirectory\\MyFile.bat");
string basename = p.filename().string();
//or 
//string basename = path("C:\\MyDirectory\\MyFile.bat").filename().string();

This is all.

I recommend you to use boost library. Boost gives you a lot of conveniences when you work with C++. It supports almost all platforms. If you use Ubuntu, you can install boost library by only one line sudo apt-get install libboost-all-dev (ref. How to Install boost on Ubuntu?)

Convert CString to const char*

Generic Conversion Macros (TN059 Other Considerations section is important):

A2CW     (LPCSTR)  -> (LPCWSTR)  
A2W      (LPCSTR)  -> (LPWSTR)  
W2CA     (LPCWSTR) -> (LPCSTR)  
W2A      (LPCWSTR) -> (LPSTR) 

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback

https://support.microsoft.com/en-us/help/148652/a-lnk2005-error-occurs-when-the-crt-library-and-mfc-libraries-are-linked-in-the-wrong-order-in-visual-c

https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h

https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html

https://msdn.microsoft.com/en-us/library/y23kc048.aspx

https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How to play or open *.mp3 or *.wav sound file in c++ program?

First of all, write the following code:

#include <Mmsystem.h>
#include <mciapi.h>
//these two headers are already included in the <Windows.h> header
#pragma comment(lib, "Winmm.lib")

To open *.mp3:

mciSendString("open \"*.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);

To play *.mp3:

mciSendString("play mp3", NULL, 0, NULL);

To play and wait until the *.mp3 has finished playing:

mciSendString("play mp3 wait", NULL, 0, NULL);

To replay (play again from start) the *.mp3:

mciSendString("play mp3 from 0", NULL, 0, NULL);

To replay and wait until the *.mp3 has finished playing:

mciSendString("play mp3 from 0 wait", NULL, 0, NULL);

To play the *.mp3 and replay it every time it ends like a loop:

mciSendString("play mp3 repeat", NULL, 0, NULL);

If you want to do something when the *.mp3 has finished playing, then you need to RegisterClassEx by the WNDCLASSEX structure, CreateWindowEx and process it's messages with the GetMessage, TranslateMessage and DispatchMessage functions in a while loop and call:

mciSendString("play mp3 notify", NULL, 0, hwnd); //hwnd is an handle to the window returned from CreateWindowEx. If this doesn't work, then replace the hwnd with MAKELONG(hwnd, 0).

In the window procedure, add the case MM_MCINOTIFY: The code in there will be executed when the mp3 has finished playing.

But if you program a Console Application and you don't deal with windows, then you can CreateThread in suspend state by specifying the CREATE_SUSPENDED flag in the dwCreationFlags parameter and keep the return value in a static variable and call it whatever you want. For instance, I call it mp3. The type of this static variable is HANDLE of course.

Here is the ThreadProc for the lpStartAddress of this thread:

DWORD WINAPI MP3Proc(_In_ LPVOID lpParameter) //lpParameter can be a pointer to a structure that store data that you cannot access outside of this function. You can prepare this structure before `CreateThread` and give it's address in the `lpParameter`
{
    Data *data = (Data*)lpParameter; //If you call this structure Data, but you can call it whatever you want.
    while (true)
    {
        mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
        //Do here what you want to do when the mp3 playback is over
        SuspendThread(GetCurrentThread()); //or the handle of this thread that you keep in a static variable instead
    }
}

All what you have to do now is to ResumeThread(mp3); every time you want to replay your mp3 and something will happen every time it finishes.

You can #define play_my_mp3 ResumeThread(mp3); to make your code more readable.

Of course you can remove the while (true), SuspendThread and the from 0 codes, if you want to play your mp3 file only once and do whatever you want when it is over.

If you only remove the SuspendThread call, then the sound will play over and over again and do something whenever it is over. This is equivalent to:

mciSendString("play mp3 repeat notify", NULL, 0, hwnd); //or MAKELONG(hwnd, 0) instead

in windows.

To pause the *.mp3 in middle:

mciSendString("pause mp3", NULL, 0, NULL);

and to resume it:

mciSendString("resume mp3", NULL, 0, NULL);

To stop it in middle:

mciSendString("stop mp3", NULL, 0, NULL);

Note that you cannot resume a sound that has been stopped, but only paused, but you can replay it by carrying out the play command. When you're done playing this *.mp3, don't forget to:

mciSendString("close mp3", NULL, 0, NULL);

All these actions also apply to (work with) wave files too, but with wave files, you can use "waveaudio" instead of "mpegvideo". Also you can just play them directly without opening them:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME);

If you don't want to specify an handle to a module:

sndPlaySound("*.wav", SND_FILENAME);

If you don't want to wait until the playback is over:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC);

To play the wave file over and over again:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC | SND_LOOP);

Note that you must specify both the SND_ASYNC and SND_LOOP flags, because you never going to wait until a sound, that repeats itself countless times, is over!

Also you can fopen the wave file and copy all it's bytes to a buffer (an enormous/huge (very big) array of bytes) with the fread function and then:

PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC | SND_LOOP);
//or
sndPlaySound(buffer, SND_MEMORY);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC | SND_LOOP);

Either OpenFile or CreateFile or CreateFile2 and either ReadFile or ReadFileEx functions can be used instead of fopen and fread functions.

Hope this fully answers perfectly your question.

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

ERROR: Cannot open source file " "

This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.

I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ; of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.

How to use _CRT_SECURE_NO_WARNINGS

If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

Convert MFC CString to integer

The problem with the accepted answer is that it cannot signal failure. There's strtol (STRing TO Long) which can. It's part of a larger family: wcstol (Wide Character String TO Long, e.g. Unicode), strtoull (TO Unsigned Long Long, 64bits+), wcstoull, strtof (TO Float) and wcstof.

Failure during conversion to COFF: file invalid or corrupt

Had to install VS 2010 SP1 in order to get it to work again for myself. Lame microsoft.

How to call C++ function from C?

You can prefix the function declaration with extern “C” keyword, e.g.

extern “C” int Mycppfunction()

{

// Code goes here

return 0;

}

For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.

How to increment an iterator by 2?

http://www.cplusplus.com/reference/std/iterator/advance/

std::advance(it,n);

where n is 2 in your case.

The beauty of this function is, that If "it" is an random access iterator, the fast

it += n

operation is used (i.e. vector<,,>::iterator). Otherwise its rendered to

for(int i = 0; i < n; i++)
    ++it;

(i.e. list<..>::iterator)

How to view the assembly behind the code using Visual C++?

There are several approaches:

  1. You can normally see assembly code while debugging C++ in visual studio (and eclipse too). For this in Visual Studio put a breakpoint on code in question and when debugger hits it rigth click and find "Go To Assembly" ( or press CTRL+ALT+D )

  2. Second approach is to generate assembly listings while compiling. For this go to project settings -> C/C++ -> Output Files -> ASM List Location and fill in file name. Also select "Assembly Output" to "Assembly With Source Code".

  3. Compile the program and use any third-party debugger. You can use OllyDbg or WinDbg for this. Also you can use IDA (interactive disassembler). But this is hardcore way of doing it.

In Visual Studio C++, what are the memory allocation representations?

This link has more information:

https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values

* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you actually want to use _tWinMain() instead of main() make sure your project relevant configuration have

  1. Linker-> System -> SubSystem => Windows(/SUBSYSTEM:WINDOWS)
  2. C/C++ -> Preprocessor -> Preprocessor Definitions => Replace _CONSOLE with _WINDOWS
  3. In the c/cpp file where _tWinMain() is defined, add:

    #include <Windows.h> #include <tchar.h>

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Make sure that you've installed these required packages.Worked perfectly in my case as i installed the checked packages enter image description here

How to make Visual Studio copy a DLL file to the output directory?

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(TargetDir)"

You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.

xcopy /y /d  "$(ProjectDir)..\External\*.dll" "$(TargetDir)"

The /y option copies without confirmation. The /d option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.

I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir) is undefined and had to use $(ProjectDir) instead.

Leaving out a target folder in xcopy should default to the output directory. That is important to understand reason $(OutDir) alone is not helpful.

$(OutDir), at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug.

Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir).

However $(TargetDir) will provide the output directory in one step.

Microsoft's list of MSBuild macros for current and previous versions of Visual Studio

Why is Visual Studio 2010 not able to find/open PDB files?

I've found that these errors sometimes are from lack of permissions when compiling a project - so I run as administrator to get it to work properly.

Unresolved external symbol in object files

In my case, I needed add the function name to the DEF file.

LIBRARY   DEMO
EXPORTS
   ExistingFunction   @1
   MyNewFunction      @2

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

Unexpected end of file error

If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:

  • In the Solution Explorer pane of the project, right-click the project name, and then click Properties.
  • In the left pane, click the C/C++ folder.
  • Click the Precompiled Headers node.
  • In the right pane, click Create/Use Precompiled Header, and then click Not Using Precompiled Headers.

Android - running a method periodically using postDelayed() call

Perhaps involve the activity's life-cycle methods to achieve this:

Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      handler.post(sendData);
}

@Override
protected void onDestroy() {
      super.onDestroy();
      handler.removeCallbacks(sendData);
}


private final Runnable sendData = new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..


            handler.postDelayed(this, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

Where Is Machine.Config?

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

How to completely uninstall kubernetes

use kubeadm reset command. this will un-configure the kubernetes cluster.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Yet another thing to check:

We had our nightly QA restore job stop working all of a sudden after another developer remoted into the QA server and tried to start the restore job during the middle of the day, which subsequently failed with the "untrusted domain" message. Somehow the server pointed to be the job's maintenance plan was (changed?) using the ip address, instead of the local machine's name. Upon replacing with the machine name the issue was resolved.

Validate a username and password against Active Directory?

Try this code (NOTE: Reported to not work on windows server 2000)

#region NTLogonUser
#region Direct OS LogonUser Code
[DllImport( "advapi32.dll")]
private static extern bool LogonUser(String lpszUsername, 
    String lpszDomain, String lpszPassword, int dwLogonType, 
    int dwLogonProvider, out int phToken);

[DllImport("Kernel32.dll")]
private static extern int GetLastError();

public static bool LogOnXP(String sDomain, String sUser, String sPassword)
{
   int token1, ret;
   int attmpts = 0;

   bool LoggedOn = false;

   while (!LoggedOn && attmpts < 2)
   {
      LoggedOn= LogonUser(sUser, sDomain, sPassword, 3, 0, out token1);
      if (LoggedOn) return (true);
      else
      {
         switch (ret = GetLastError())
         {
            case (126): ; 
               if (attmpts++ > 2)
                  throw new LogonException(
                      "Specified module could not be found. error code: " + 
                      ret.ToString());
               break;

            case (1314): 
               throw new LogonException(
                  "Specified module could not be found. error code: " + 
                      ret.ToString());

            case (1326): 
               // edited out based on comment
               //  throw new LogonException(
               //   "Unknown user name or bad password.");
            return false;

            default: 
               throw new LogonException(
                  "Unexpected Logon Failure. Contact Administrator");
              }
          }
       }
   return(false);
}
#endregion Direct Logon Code
#endregion NTLogonUser

except you'll need to create your own custom exception for "LogonException"

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

Indent multiple lines quickly in vi

This answer summarises the other answers and comments of this question, and it adds extra information based on the Vim documentation and the Vim wiki. For conciseness, this answer doesn't distinguish between Vi and Vim-specific commands.

In the commands below, "re-indent" means "indent lines according to your indentation settings." shiftwidth is the primary variable that controls indentation.

General Commands

>>   Indent line by shiftwidth spaces
<<   De-indent line by shiftwidth spaces
5>>  Indent 5 lines
5==  Re-indent 5 lines

>%   Increase indent of a braced or bracketed block (place cursor on brace first)
=%   Reindent a braced or bracketed block (cursor on brace)
<%   Decrease indent of a braced or bracketed block (cursor on brace)
]p   Paste text, aligning indentation with surroundings

=i{  Re-indent the 'inner block', i.e. the contents of the block
=a{  Re-indent 'a block', i.e. block and containing braces
=2a{ Re-indent '2 blocks', i.e. this block and containing block

>i{  Increase inner block indent
<i{  Decrease inner block indent

You can replace { with } or B, e.g. =iB is a valid block indent command. Take a look at "Indent a Code Block" for a nice example to try these commands out on.

Also, remember that

.    Repeat last command

, so indentation commands can be easily and conveniently repeated.

Re-indenting complete files

Another common situation is requiring indentation to be fixed throughout a source file:

gg=G  Re-indent entire buffer

You can extend this idea to multiple files:

" Re-indent all your C source code:
:args *.c
:argdo normal gg=G
:wall

Or multiple buffers:

" Re-indent all open buffers:
:bufdo normal gg=G:wall

In Visual Mode

Vjj> Visually mark and then indent three lines

In insert mode

These commands apply to the current line:

CTRL-t   insert indent at start of line
CTRL-d   remove indent at start of line
0 CTRL-d remove all indentation from line

Ex commands

These are useful when you want to indent a specific range of lines, without moving your cursor.

:< and :> Given a range, apply indentation e.g.
:4,8>   indent lines 4 to 8, inclusive

Indenting using markers

Another approach is via markers:

ma     Mark top of block to indent as marker 'a'

...move cursor to end location

>'a    Indent from marker 'a' to current location

Variables that govern indentation

You can set these in your .vimrc file.

set expandtab       "Use softtabstop spaces instead of tab characters for indentation
set shiftwidth=4    "Indent by 4 spaces when using >>, <<, == etc.
set softtabstop=4   "Indent by 4 spaces when pressing <TAB>

set autoindent      "Keep indentation from previous line
set smartindent     "Automatically inserts indentation in some cases
set cindent         "Like smartindent, but stricter and more customisable

Vim has intelligent indentation based on filetype. Try adding this to your .vimrc:

if has ("autocmd")
    " File type detection. Indent based on filetype. Recommended.
    filetype plugin indent on
endif

References

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

Meaning of $? (dollar question mark) in shell scripts

Outputs the result of the last executed unix command

0 implies true
1 implies false

How to put a new line into a wpf TextBlock control?

For completeness: You can also do this:

 <TextBlock Text="Line1&#x0a;Line 2"/>

x0A is the escaped hexadecimal Line Feed. The equivalent of \n

Scroll back to the top of scrollable div

these two codes worked for me like a charm this first will take to scroll to the top of the page but if you want to scroll to some specific div use the second one with your div id.

$('body, html, #containerDiv').scrollTop(0);
document.getElementById('yourDivID').scrollIntoView();

If you want to scroll to by a class name use the below code

var $container = $("html,body");
var $scrollTo = $('.main-content');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300);

How to change the time format (12/24 hours) of an <input>?

It depends on the time format of the user's operating system when the web browser was launched.

So:

  • If your computer's system prefs are set to use a 24-hour clock, the browser will render the <input type="time"> element as --:-- (time range: 00:00–23:59).
  • If you change your computer's syst prefs to use 12-hour, the output won't change until you quit and relaunch the browser. Then it will change to --:-- -- (time range: 12:00 AM – 11:59 PM).

And (as of this writing), browser support is only about 75% (caniuse). Yay: Edge, Chrome, Opera, Android. Boo: IE, Firefox, Safari).

Using .htaccess to make all .html pages to run as .php files?

None of the answers posted here worked for me.

In my case the problem was, by the one hand, that the .conf file (/etc/apache2/sites-available/default-ssl.conf or /etc/apache2/sites-available/000-default.conf) did not contain the directive AllowOverride All for the site directory, which caused the .htaccess to not been processed. To solve this, add:

<Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

On the other hand, the problem was that the .htaccess was created by the root user, and therefore the apache user could not read it. So, changing the file owner solved definitely the problem:

chown www-data:www-data .htaccess

Mockito How to mock and assert a thrown exception?

Or if your exception is thrown from the constructor of a class:

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void myTest() {    

    exception.expect(MyException.class);
    CustomClass myClass= mock(CustomClass.class);
    doThrow(new MyException("constructor failed")).when(myClass);  

}

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

How do I make flex box work in safari?

I had to add the webkit prefix for safari (but flex not flexbox):

display:-webkit-flex

.NET String.Format() to add commas in thousands place for a number

String.Format("{0:n}", 1234);  // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876

Get real path from URI, Android KitKat new storage access framework

Try this:

//KITKAT
i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, CHOOSE_IMAGE_REQUEST);

Use the following in the onActivityResult:

Uri selectedImageURI = data.getData();
input = c.getContentResolver().openInputStream(selectedImageURI);
BitmapFactory.decodeStream(input , null, opts);

How to copy part of an array to another array in C#?

Note: I found this question looking for one of the steps in the answer to how to resize an existing array.

So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.

For anyone else finding this question looking for the same thing I was, it is very simple:

Array.Resize<T>(ref arrayVariable, newSize);

where T is the type, i.e. where arrayVariable is declared:

T[] arrayVariable;

That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.

See the MSDN article for more.

How to append rows to an R data frame

My solution is almost the same as the original answer but it doesn't worked for me.

So, I gave names for the columns and it works:

painel <- rbind(painel, data.frame("col1" = xtweets$created_at,
                                   "col2" = xtweets$text))

Getting the last argument passed to a shell script

This is part of my copy function:

eval echo $(echo '$'"$#")

To use in scripts, do this:

a=$(eval echo $(echo '$'"$#"))

Explanation (most nested first):

  1. $(echo '$'"$#") returns $[nr] where [nr] is the number of parameters. E.g. the string $123 (unexpanded).
  2. echo $123 returns the value of 123rd parameter, when evaluated.
  3. eval just expands $123 to the value of the parameter, e.g. last_arg. This is interpreted as a string and returned.

Works with Bash as of mid 2015.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

As the accepted answer suggests you can add "using" to all views by adding to section of config file.

But for a single view you could just use

@using SomeNamespace.Extensions

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Way to create multiline comments in Bash?

Multiline comment in bash

: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines.  Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2 
comment3
END_COMMENT

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

An item with the same key has already been added

Another way to encounter this error is from a dataset with unnamed columns. The error is thrown when the dataset is serialized into JSON.

This statement will result in error:

select @column1, @column2

Adding column names will prevent the error:

select @column1 as col1, @column2 as col2

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

Bootstrap change div order with pull-right, pull-left on 3 columns

Bootstrap 3

Using Bootstrap 3's grid system:

<div class="container">
  <div class="row">
    <div class="col-xs-4">Menu</div>
    <div class="col-xs-8">
      <div class="row">
        <div class="col-md-4 col-md-push-8">Right Content</div>
        <div class="col-md-8 col-md-pull-4">Content</div>
      </div>
    </div>
  </div>
</div>

Working example: http://bootply.com/93614

Explanation

First, we set two columns that will stay in place no matter the screen resolution (col-xs-*).

Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*).

Finally, we shift the display order using the matching class (col-md-[push|pull]-*). You push the first column over by the amount of the second, and pull the second by the amount of the first.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

binning data in python with scipy/numpy

The numpy_indexed package (disclaimer: I am its author) contains functionality to efficiently perform operations of this type:

import numpy_indexed as npi
print(npi.group_by(np.digitize(data, bins)).mean(data))

This is essentially the same solution as the one I posted earlier; but now wrapped in a nice interface, with tests and all :)

DBMS_OUTPUT.PUT_LINE not printing

For SQL Developer

You have to execute it manually

SET SERVEROUTPUT ON 

After that if you execute any procedure with DBMS_OUTPUT.PUT_LINE('info'); or directly .

This will print the line

And please don't try to add this

 SET SERVEROUTPUT ON

inside the definition of function and procedure, it will not compile and will not work.

Javascript: The prettiest way to compare one value against multiple values

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.

Let me be clear:

My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)

Here is the code:

new Date().toLocaleDateString("sv") // "2020-02-23" // 

This works because the Sweden locale uses the ISO 8601 format.

"E: Unable to locate package python-pip" on Ubuntu 18.04

ls /bin/python*

Identify the highest version of python listed. If the highest version is something like python2.7 then install python2-pip If its something like python3.8 then install python3-pip

Example for python3.8:

sudo apt-get install python3-pip

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

Comparing two java.util.Dates to see if they are in the same day

in addition to Binil Thomas solution

public static boolean isOnSameDay(Timestamp... dates) {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
    String date1 = fmt.format(dates[0]);
    for (Timestamp date : dates) {
        if (!fmt.format(date).equals(date1)) {
            return false;
        }
    }
    return true;
}

usage

    isOnSameDay(date1,date2,date3 ...);
//or 
    isOnSameDay(mydates);

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I tried with the correct answer by @Lahiru, but did not work with MySQL server version 8.0.16 (Community) on macOS Mojave.

Followed the instructions by Sameer Choudhary above and with some adjustments, I was able to change root password and enable root access from localhost.

Update: All of these are not required, if you are installing on Mac OS using homebrew: "brew install mysql"

How can I check if given int exists in array?

You almost never have to write your own loops in C++. Here, you can use std::find.

const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
  std::cout << "Found.\n"
}
else
{
  std::cout << "Not found.\n";
}

std::end requires C++11. Without it, you can find the number of elements in the array with:

const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);

...and the end with:

int* end = myArray + numElements;

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

Error importing SQL dump into MySQL: Unknown database / Can't create database

I create the database myself using the command line. Then try to import again, it works.

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

Apache giving 403 forbidden errors

The server may need read permission for your home directory and .htaccess therein

How does C compute sin() and other math functions?

The actual implementation of library functions is up to the specific compiler and/or library provider. Whether it's done in hardware or software, whether it's a Taylor expansion or not, etc., will vary.

I realize that's absolutely no help.

Set a default font for whole iOS app?

As @Randall in his answer mentioned iOS 5.0+ UIAppearance proxy can be used to customize the appearance of all instances of a class read more.

UILabel.appearance().font = .systemFont(ofSize: 17, weight: .regular)

Chart.js canvas resize

If anyone is having problems, I found a solution that doesn't involve sacrificing responsiveness etc.

Simply wrap your canvas in a div container (no styling) and reset the contents of the div to an empty canvas with ID before calling the Chart constructor.

Example:

HTML:

<div id="chartContainer">
    <canvas id="myChart"></canvas>
</div>

JS:

$("#chartContainer").html('<canvas id="myChart"></canvas>');
//call new Chart() as usual

.Net System.Mail.Message adding multiple "To" addresses

You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas

How do I get the classes of all columns in a data frame?

Hello was looking for the same, and it could be also

unlist(lapply(mtcars,class))

Where does the iPhone Simulator store its data?

If the Simulator is running you can get the path to any app's container:

xcrun simctl get_app_container booted <app bundle identifier>

Example output:

$ xcrun simctl get_app_container booted com.example.app
/Users/jappleseed/Library/Developer/CoreSimulator/Devices/7FB6CB8F-63CB-4F27-BDAB-884814DA6FE0/data/Containers/Bundle/Application/466AE987-76BC-47CF-A207-266E65E7DE0A/example.app

"booted" can be substituted to most simctl commands anywhere a device UDID is expected.

You can see the list of devices with xcrun simctl list and get help on specific commands with xcrun simctl help.

Update: By popular request in Xcode 8.3 you can now specify the kind of container you want by appending "app", "data", "groups", or an app group identifier.

To get the data container:

$ xcrun simctl get_app_container booted com.example.app data

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

Send data from activity to fragment in Android

You can create public static method in fragment where you will get static reference of that fragment and then pass data to that function and set that data to argument in same method and get data via getArgument on oncreate method of fragment, and set that data to local variables.

SOAP or REST for Web Services?

I'd recommend you go with REST first - if you're using Java look at JAX-RS and the Jersey implementation. REST is much simpler and easy to interop in many languages.

As others have said in this thread, the problem with SOAP is its complexity when the other WS-* specifications come in and there are countless interop issues if you stray into the wrong parts of WSDL, XSDs, SOAP, WS-Addressing etc.

The best way to judge the REST v SOAP debate is look on the internet - pretty much all the big players in the web space, google, amazon, ebay, twitter et al - tend to use and prefer RESTful APIs over the SOAP ones.

The other nice approach to going with REST is that you can reuse lots of code and infratructure between a web application and a REST front end. e.g. rendering HTML versus XML versus JSON of your resources is normally pretty easy with frameworks like JAX-RS and implicit views - plus its easy to work with RESTful resources using a web browser

how to delete all cookies of my website in php

PHP setcookie()

Taken from that page, this will unset all of the cookies for your domain:

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

http://www.php.net/manual/en/function.setcookie.php#73484

increase font size of hyperlink text html

increase the padding size of font and then try to increase font size:-

style="padding-bottom:40px; font-size: 50px;"

Convert list of ints to one number?

Just for completeness, here's a variant that uses print() (works on Python 2.6-3.x):

from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
     from io import StringIO

def to_int(nums, _s = StringIO()):
    print(*nums, sep='', end='', file=_s)
    s = _s.getvalue()
    _s.truncate(0)
    return int(s)

Time performance of different solutions

I've measured performance of @cdleary's functions. The results are slightly different.

Each function tested with the input list generated by:

def randrange1_10(digit_count): # same as @cdleary
    return [random.randrange(1, 10) for i in xrange(digit_count)]

You may supply your own function via --sequence-creator=yourmodule.yourfunction command-line argument (see below).

The fastest functions for a given number of integers in a list (len(nums) == digit_count) are:

  • len(nums) in 1..30

    def _accumulator(nums):
        tot = 0
        for num in nums:
            tot *= 10
            tot += num
        return tot
    
  • len(nums) in 30..1000

    def _map(nums):
        return int(''.join(map(str, nums)))
    
    def _imap(nums):
        return int(''.join(imap(str, nums)))
    

Figure: N = 1000

|------------------------------+-------------------|
| Fitting polynom              | Function          |
|------------------------------+-------------------|
| 1.00  log2(N)   +  1.25e-015 | N                 |
| 2.00  log2(N)   +  5.31e-018 | N*N               |
| 1.19  log2(N)   +      1.116 | N*log2(N)         |
| 1.37  log2(N)   +      2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21  log2(N)   +      0.063 | _interpolation    |
| 1.24  log2(N)   -      0.610 | _genexp           |
| 1.25  log2(N)   -      0.968 | _imap             |
| 1.30  log2(N)   -      1.917 | _map              |

Figure: N = 1000_000

To plot the first figure download cdleary.py and make-figures.py and run (numpy and matplotlib must be installed to plot):

$ python cdleary.py 

Or

$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000 

How to programmatically disable page scrolling with jQuery

For folks who have centered layouts (via margin:0 auto;), here's a mash-up of the position:fixed solution along with @tfe's proposed solution.

Use this solution if you're experiencing page-snapping (due to the scrollbar showing/hiding).

// lock scroll position, but retain settings for later
var scrollPosition = [
    window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
    window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
];
var $html = $('html'); // bow to the demon known as MSIE(v7)
$html.addClass('modal-noscroll');
$html.data('scroll-position', scrollPosition);
$html.data('margin-top', $html.css('margin-top'));
$html.css('margin-top', -1 * scrollPosition[1]);

…combined with…

// un-lock scroll position
var $html = $('html').removeClass('modal-noscroll');
var scrollPosition = $html.data('scroll-position');
var marginTop = $html.data('margin-top');
$html.css('margin-top', marginTop);
window.scrollTo(scrollPosition[0], scrollPosition[1])

…and finally, the CSS for .modal-noscroll

.modal-noscroll
{
    position: fixed;
    overflow-y: scroll;
    width: 100%;
}

I would venture to say this is more of a proper fix than any of the other solutions out there, but I haven't tested it that thoroughly yet… :P


Edit: please note that I have no clue how badly this might perform (read: blow up) on a touch device.

Expression must have class type

a is a pointer. You need to use->, not .

python: Appending a dictionary to a list - I see a pointer like behavior

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

Live Video Streaming with PHP

PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.

For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.

Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.

PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).

Hope this helps.

Using 'starts with' selector on individual class names

<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

in this case as question Josh Stodola answer is correct Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

but if element have multiple classes like this

<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>

then Josh Stodola's solution will do not work
for this have to do some thing like this

$('.some-parent-class div').filter(function () {
  return this.className.match(/\bapple-/);// this is for start with
  //return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");

may be it helps some one else thanks

How link to any local file with markdown syntax?

If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md) should work.

Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md).

At least works from Chrome.

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

How to format DateTime in Flutter , How to get current time in flutter?

You can use DateFormat from intl package.

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Stop Visual Studio from launching a new browser window when starting debug?

You can now also get to the Web properties by clicking the dropdown arrow next to the Run button!

  1. Click dropdown button next to "Run"
  2. { Project name } Properties
  3. Click "Web" in the list on the left
  4. Under the "Start Action" segment, click Don't open a page.

You're all set!

PS: This works for me, I'm on version 16.5.5 of VS Professional 2019 :)

any tool for java object to object mapping?

I'm happy to add Moo as an option, although clearly I'm biased towards it: http://geoffreywiseman.github.com/Moo/

It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.

What is the point of "final class" in Java?

Object Orientation is not about inheritance, it is about encapsulation. And inheritance breaks encapsulation.

Declaring a class final makes perfect sense in a lot of cases. Any object representing a “value” like a color or an amount of money could be final. They stand on their own.

If you are writing libraries, make your classes final unless you explicitly indent them to be derived. Otherwise, people may derive your classes and override methods, breaking your assumptions / invariants. This may have security implications as well.

Joshua Bloch in “Effective Java” recommends designing explicitly for inheritance or prohibiting it and he notes that designing for inheritance is not that easy.

What would be the Unicode character for big bullet in the middle of the character?

If you are on Windows (Any Version)

Go to start -> then search character map

that's where you will find 1000s of characters with their Unicode in the advance view you can get more options that you can use for different encoding symbols.

Android Calling JavaScript functions in WebView

Yes you have the syntax error. If you want to get your Javascript errors and printing statements in your logcat you must implement the onConsoleMessage(ConsoleMessage cm) method in your WebChromeClient. It gives the complete stack traces like Web console(Inspect element). Here is the method.

public boolean onConsoleMessage(ConsoleMessage cm) 
    {
        Log.d("Message", cm.message() + " -- From line "
                             + cm.lineNumber() + " of "
                             + cm.sourceId() );
        return true;
    }

After implementation you will get your Javascript errors and print statements (console.log) on your logcat.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Change the URL in the browser without loading the new page using JavaScript

Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:

Before clicking 'next':

/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507

After clicking 'next':

/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507

Note the hash-bang (#!) immediately followed by the new URL.

Copy map values to vector in STL

If you are using the boost libraries, you can use boost::bind to access the second value of the pair as follows:

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

int main()
{
   typedef std::map<std::string, int> MapT;
   typedef std::vector<int> VecT;
   MapT map;
   VecT vec;

   map["one"] = 1;
   map["two"] = 2;
   map["three"] = 3;
   map["four"] = 4;
   map["five"] = 5;

   std::transform( map.begin(), map.end(),
                   std::back_inserter(vec),
                   boost::bind(&MapT::value_type::second,_1) );
}

This solution is based on a post from Michael Goldshteyn on the boost mailing list.

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

How to display HTML in TextView?

I have implemented this using web view. In my case i have to load image from URL along with the text in text view and this works for me.

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

How to get correct timestamp in C#

var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

Python dictionary: are keys() and values() always the same order?

Good references to the docs. Here's how you can guarantee the order regardless of the documentation / implementation:

k, v = zip(*d.iteritems())

CSS vertical alignment text inside li

In the future, this problem will be solved by flexbox. Right now the browser support is dismal, but it is supported in one form or another in all current browsers.

Browser support: http://caniuse.com/flexbox

.vertically_aligned {

    /* older webkit */
    display: -webkit-box;
    -webkit-box-align: center;
    -webkit-justify-content: center;

    /* older firefox */
    display: -moz-box;
    -moz-box-align: center;
    -moz-box-pack: center;

    /* IE10*/
    display: -ms-flexbox;
    -ms-flex-align: center;
    -ms-flex-pack: center;

    /* newer webkit */
    display: -webkit-flex;
    -webkit-align-items: center;
    -webkit-box-pack: center;

    /* Standard Form - IE 11+, FF 22+, Chrome 29+, Opera 17+ */
    display: flex;
    align-items: center;
    justify-content: center;
}

Background on Flexbox: http://css-tricks.com/snippets/css/a-guide-to-flexbox/

Displaying the Indian currency symbol on a website

Please try the following solution:

<span style='font-family:Arial;'>&#8377;</span>

This will be displayed as : ₹

How to fix 'Notice: Undefined index:' in PHP form action

Use empty() to check if it is available. Try with -

will generate the error if host is not present here

if(!empty($_GET["host"]))
if($_GET["host"]!="")

LINQ query to find if items in a list are contained in another list

var output = emails.Where(e => domains.All(d => !e.EndsWith(d)));

Or if you prefer:

var output = emails.Where(e => !domains.Any(d => e.EndsWith(d)));

Programmatic equivalent of default(Type)

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

Formatting a Date String in React Native

There is no need to include a bulky library such as Moment.js to fix such a simple issue.

The issue you are facing is not with formatting, but with parsing.

As John Shammas mentions in another answer, the Date constructor (and Date.parse) are picky about the input. Your 2016-01-04 10:34:23 may work in one JavaScript implementation, but not necessarily in the other.

According to the specification of ECMAScript 5.1, Date.parse supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.

All you have to do is change the input format just a little. Swap the space for a T: 2016-01-04T10:34:23; and optionally add a time zone (2016-01-04T10:34:23+01:00), otherwise UTC is assumed.

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Simple bubble sort c#

I wanted to add to the accepted answer something different: Number of iterations can be reduced as well, as below.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;
int arrLength = arr.Length;

for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
    for (int sort = 0; sort < arrLength - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

foreach (var item in arr)
{
    Console.WriteLine(item);
}

Regex to match string containing two names in any order

Vim has a branch operator \& that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.

For example,

/.*jack\&.*james

will match a line containing jack and james, in any order.

See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

How can I customize the tab-to-space conversion factor?

User3550138 is correct. lonefy.vscode-js-css-html-formatter overrides all the settings mentioned in other answers. However, you don't have to disable or uninstall it as it can be configured.

Full instructions can be found by opening the extensions sidebar and clicking on this extension and it will display configuration instructions in the editor workspace. At least it does for me in Visual Studio Code version 1.14.1.

Remove border radius from Select tag in bootstrap 3

In addition to border-radius: 0, add -webkit-appearance: none;.

How to set minDate to current date in jQuery UI Datepicker?

can also use:

$("input.DateFrom").datepicker({
    minDate: 'today'
});

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

Is floating point math broken?

Many of this question's numerous duplicates ask about the effects of floating point rounding on specific numbers. In practice, it is easier to get a feeling for how it works by looking at exact results of calculations of interest rather than by just reading about it. Some languages provide ways of doing that - such as converting a float or double to BigDecimal in Java.

Since this is a language-agnostic question, it needs language-agnostic tools, such as a Decimal to Floating-Point Converter.

Applying it to the numbers in the question, treated as doubles:

0.1 converts to 0.1000000000000000055511151231257827021181583404541015625,

0.2 converts to 0.200000000000000011102230246251565404236316680908203125,

0.3 converts to 0.299999999999999988897769753748434595763683319091796875, and

0.30000000000000004 converts to 0.3000000000000000444089209850062616169452667236328125.

Adding the first two numbers manually or in a decimal calculator such as Full Precision Calculator, shows the exact sum of the actual inputs is 0.3000000000000000166533453693773481063544750213623046875.

If it were rounded down to the equivalent of 0.3 the rounding error would be 0.0000000000000000277555756156289135105907917022705078125. Rounding up to the equivalent of 0.30000000000000004 also gives rounding error 0.0000000000000000277555756156289135105907917022705078125. The round-to-even tie breaker applies.

Returning to the floating point converter, the raw hexadecimal for 0.30000000000000004 is 3fd3333333333334, which ends in an even digit and therefore is the correct result.

Regular expression for number with length of 4, 5 or 6

Try this:

^[0-9]{4,6}$

{4,6} = between 4 and 6 characters, inclusive.

MySQL: Delete all rows older than 10 minutes

If time_created is a unix timestamp (int), you should be able to use something like this:

DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);

(600 seconds = 10 minutes - obviously)

Otherwise (if time_created is mysql timestamp), you could try this:

DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)

Is there a limit to the length of a GET request?

This article sums it up pretty well

Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.

URIs should be readable, even when used to send data.

Swift - how to make custom header for UITableView?

I have had some problems in Swift 5 with this. When using this function I had a wrong alignment with the header cell:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
     return headerCell
}

The cell view was shown with a bad alignment and the top part of the tableview was shown. So I had to make some tweak like this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 90))
     let headerCell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER")
     headerCell?.frame = headerView.bounds
     headerView.addSubview(headerCell!)
     return headerView
 }

I am having this problem in Swift 5 and Xcode 12.0.1, I don't know if it is just a problem for me or it is a bug. Hope it helps ! I have lost a morning...

Make body have 100% of the browser height

I style the div container - usually the sole child of the body with the following css

.body-container {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

Is there a foreach loop in Go?

This may be obvious, but you can inline the array like so:

package main

import (
    "fmt"
)

func main() {
    for _, element := range [3]string{"a", "b", "c"} {
        fmt.Print(element)
    }
}

outputs:

abc

https://play.golang.org/p/gkKgF3y5nmt

Change the icon of the exe file generated from Visual Studio 2010

To specify an application icon

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. In the Icon list, choose an icon (.ico) file.

To specify an application icon and add it to your project

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

The icon file is added to your project as a content file.

reference : for details see here

Angular - Can't make ng-repeat orderBy work

in Eike Thies's response above, if we use underscore.js, filter could be simplified to :

var app = angular.module('myApp', []).filter('object2Array', function() {
  return function(input) {
    return _.toArray(input);
  }
});

Perform Segue programmatically and pass parameters to the destination view

In case if you use new swift version.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

javascript cell number validation

I used the follow code.

var mobileNumber=parseInt(no)
  if(!mobileNumber || mobileNumber.toString().length!=10){
  Alert("Please provide 10 Digit numeric value")
}

If the mobile number is not a number, it will give NaN value.

Multiple Errors Installing Visual Studio 2015 Community Edition

I've faced the same problem with Visual Studio 2015 Community Edition Update 1. The problem in my case was, the installer somehow could not install Visual C++ Redistributable x86 version. When I checked Add Remove Programs only x64 version was installed.

If that's the case for you, you can get the missing redistributable package from here; or you can find the version appropriate to you through a google search.

Xcode doesn't see my iOS device but iTunes does

If none of these work, try simpling restarting your iphone or device! Works every time for me (:

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Find element's index in pandas Series

I'm impressed with all the answers here. This is not a new answer, just an attempt to summarize the timings of all these methods. I considered the case of a series with 25 elements and assumed the general case where the index could contain any values and you want the index value corresponding to the search value which is towards the end of the series.

Here are the speed tests on a 2013 MacBook Pro in Python 3.7 with Pandas version 0.25.3.

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

@Jeff's answer seems to be the fastest - although it doesn't handle duplicates.

Correction: Sorry, I missed one, @Alex Spangher's solution using the list index method is by far the fastest.

Update: Added @EliadL's answer.

Hope this helps.

Amazing that such a simple operation requires such convoluted solutions and many are so slow. Over half a millisecond in some cases to find a value in a series of 25.

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In My Case, Im trying to pass messages from Salesforce Marketing Cloud Custom Activity(Domain 1) to Heroku(Domain 2) on load.

The Error Appeared in console, when I loaded my original html page from where message is being passed.

Issue I noticed after reading many blogs is that, the receiver page is not loaded yet. i.e

I need to debug from my receiver page not from sender page.

Simple but glad if it helps anyone.

The target principal name is incorrect. Cannot generate SSPI context

I'm running a Mickey Mouse testing system based on SQL.COM.

I ran setspn -T sql -F -Q */Servername (in this case SQL01) on both the machine I couldn't connect to and a machine I could. I then simply removed the additional entries in the problem machine and it all worked, e.g. setspn -D MSSQLSvc/SQL01.SQL.COM:1433 SQL01

Splitting string into multiple rows in Oracle

I would like to propose a different approach using a PIPELINED table function. It's somewhat similar to the technique of the XMLTABLE, except that you are providing your own custom function to split the character string:

-- Create a collection type to hold the results
CREATE OR REPLACE TYPE typ_str2tbl_nst AS TABLE OF VARCHAR2(30);
/

-- Split the string according to the specified delimiter
CREATE OR REPLACE FUNCTION str2tbl (
  p_string    VARCHAR2,
  p_delimiter CHAR DEFAULT ',' 
)
RETURN typ_str2tbl_nst PIPELINED
AS
  l_tmp VARCHAR2(32000) := p_string || p_delimiter;
  l_pos NUMBER;
BEGIN
  LOOP
    l_pos := INSTR( l_tmp, p_delimiter );
    EXIT WHEN NVL( l_pos, 0 ) = 0;
    PIPE ROW ( RTRIM( LTRIM( SUBSTR( l_tmp, 1, l_pos-1) ) ) );
    l_tmp := SUBSTR( l_tmp, l_pos+1 );
  END LOOP;
END str2tbl;
/

-- The problem solution
SELECT name, 
       project, 
       TRIM(COLUMN_VALUE) error
  FROM t, TABLE(str2tbl(error));

Results:

      NAME PROJECT    ERROR
---------- ---------- --------------------
       108 test       Err1
       108 test       Err2
       108 test       Err3
       109 test2      Err1

The problem with this type of approach is that often the optimizer won't know the cardinality of the table function and it will have to make a guess. This could be potentialy harmful to your execution plans, so this solution can be extended to provide execution statistics for the optimizer.

You can see this optimizer estimate by running an EXPLAIN PLAN on the query above:

Execution Plan
----------------------------------------------------------
Plan hash value: 2402555806

----------------------------------------------------------------------------------------------
| Id  | Operation                          | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                   |         | 16336 |   366K|    59   (0)| 00:00:01 |
|   1 |  NESTED LOOPS                      |         | 16336 |   366K|    59   (0)| 00:00:01 |
|   2 |   TABLE ACCESS FULL                | T       |     2 |    42 |     3   (0)| 00:00:01 |
|   3 |   COLLECTION ITERATOR PICKLER FETCH| STR2TBL |  8168 | 16336 |    28   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------

Even though the collection has only 3 values, the optimizer estimated 8168 rows for it (default value). This may seem irrelevant at first, but it may be enough for the optimizer to decide for a sub-optimal plan.

The solution is to use the optimizer extensions to provide statistics for the collection:

-- Create the optimizer interface to the str2tbl function
CREATE OR REPLACE TYPE typ_str2tbl_stats AS OBJECT (
  dummy NUMBER,

  STATIC FUNCTION ODCIGetInterfaces ( p_interfaces OUT SYS.ODCIObjectList )
  RETURN NUMBER,

  STATIC FUNCTION ODCIStatsTableFunction ( p_function  IN  SYS.ODCIFuncInfo,
                                           p_stats     OUT SYS.ODCITabFuncStats,
                                           p_args      IN  SYS.ODCIArgDescList,
                                           p_string    IN  VARCHAR2,
                                           p_delimiter IN  CHAR DEFAULT ',' )
  RETURN NUMBER
);
/

-- Optimizer interface implementation
CREATE OR REPLACE TYPE BODY typ_str2tbl_stats
AS
  STATIC FUNCTION ODCIGetInterfaces ( p_interfaces OUT SYS.ODCIObjectList )
  RETURN NUMBER
  AS
  BEGIN
    p_interfaces := SYS.ODCIObjectList ( SYS.ODCIObject ('SYS', 'ODCISTATS2') );
    RETURN ODCIConst.SUCCESS;
  END ODCIGetInterfaces;

  -- This function is responsible for returning the cardinality estimate
  STATIC FUNCTION ODCIStatsTableFunction ( p_function  IN  SYS.ODCIFuncInfo,
                                           p_stats     OUT SYS.ODCITabFuncStats,
                                           p_args      IN  SYS.ODCIArgDescList,
                                           p_string    IN  VARCHAR2,
                                           p_delimiter IN  CHAR DEFAULT ',' )
  RETURN NUMBER
  AS
  BEGIN
    -- I'm using basically half the string lenght as an estimator for its cardinality
    p_stats := SYS.ODCITabFuncStats( CEIL( LENGTH( p_string ) / 2 ) );
    RETURN ODCIConst.SUCCESS;
  END ODCIStatsTableFunction;

END;
/

-- Associate our optimizer extension with the PIPELINED function   
ASSOCIATE STATISTICS WITH FUNCTIONS str2tbl USING typ_str2tbl_stats;

Testing the resulting execution plan:

Execution Plan
----------------------------------------------------------
Plan hash value: 2402555806

----------------------------------------------------------------------------------------------
| Id  | Operation                          | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                   |         |     1 |    23 |    59   (0)| 00:00:01 |
|   1 |  NESTED LOOPS                      |         |     1 |    23 |    59   (0)| 00:00:01 |
|   2 |   TABLE ACCESS FULL                | T       |     2 |    42 |     3   (0)| 00:00:01 |
|   3 |   COLLECTION ITERATOR PICKLER FETCH| STR2TBL |     1 |     2 |    28   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------

As you can see the cardinality on the plan above is not the 8196 guessed value anymore. It's still not correct because we are passing a column instead of a string literal to the function.

Some tweaking to the function code would be necessary to give a closer estimate in this particular case, but I think the overall concept is pretty much explained here.

The str2tbl function used in this answer was originally developed by Tom Kyte: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:110612348061

The concept of associating statistics with object types can be further explored by reading this article: http://www.oracle-developer.net/display.php?id=427

The technique described here works in 10g+.

How do I launch a program from command line without opening a new cmd window?

1-Open you folder that contains your application in the File Explorer. 2-Press SHIFT and Right Click in White Space. 3-Click on "Open command window here". 4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

How to format numbers?

Let me also throw my solution in here. I've commented each line for ease of reading and also provided some examples, so it may look big.

_x000D_
_x000D_
function format(number) {_x000D_
_x000D_
    var decimalSeparator = ".";_x000D_
    var thousandSeparator = ",";_x000D_
_x000D_
    // make sure we have a string_x000D_
    var result = String(number);_x000D_
_x000D_
    // split the number in the integer and decimals, if any_x000D_
    var parts = result.split(decimalSeparator);_x000D_
_x000D_
    // if we don't have decimals, add .00_x000D_
    if (!parts[1]) {_x000D_
      parts[1] = "00";_x000D_
    }_x000D_
  _x000D_
    // reverse the string (1719 becomes 9171)_x000D_
    result = parts[0].split("").reverse().join("");_x000D_
_x000D_
    // add thousand separator each 3 characters, except at the end of the string_x000D_
    result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);_x000D_
_x000D_
    // reverse back the integer and replace the original integer_x000D_
    parts[0] = result.split("").reverse().join("");_x000D_
_x000D_
    // recombine integer with decimals_x000D_
    return parts.join(decimalSeparator);_x000D_
}_x000D_
_x000D_
document.write("10 => " + format(10) + "<br/>");_x000D_
document.write("100 => " + format(100) + "<br/>");_x000D_
document.write("1000 => " + format(1000) + "<br/>");_x000D_
document.write("10000 => " + format(10000) + "<br/>");_x000D_
document.write("100000 => " + format(100000) + "<br/>");_x000D_
document.write("100000.22 => " + format(100000.22) + "<br/>");
_x000D_
_x000D_
_x000D_

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Python - Move and overwrite files and folders

If you also need to overwrite files with read only flag use this:

def copyDirTree(root_src_dir,root_dst_dir):
"""
Copy directory tree. Overwrites also read only files.
:param root_src_dir: source directory
:param root_dst_dir:  destination directory
"""
for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            try:
                os.remove(dst_file)
            except PermissionError as exc:
                os.chmod(dst_file, stat.S_IWUSR)
                os.remove(dst_file)

        shutil.copy(src_file, dst_dir)

How do I get an element to scroll into view, using jQuery?

Since you want to know how it works, I'll explain it step-by-step.

First you want to bind a function as the image's click handler:

$('#someImage').click(function () {
    // Code to do scrolling happens here
});

That will apply the click handler to an image with id="someImage". If you want to do this to all images, replace '#someImage' with 'img'.

Now for the actual scrolling code:

  1. Get the image offsets (relative to the document):

    var offset = $(this).offset(); // Contains .top and .left
    
  2. Subtract 20 from top and left:

    offset.left -= 20;
    offset.top -= 20;
    
  3. Now animate the scroll-top and scroll-left CSS properties of <body> and <html>:

    $('html, body').animate({
        scrollTop: offset.top,
        scrollLeft: offset.left
    });
    

How to add an element at the end of an array?

You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :

public static void main(String[] args) {
    int[] array = new int[] {1, 2, 3};
    System.out.println(Arrays.toString(array));
    array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
    array[array.length - 1] = 4;
    System.out.println(Arrays.toString(array));
}

I would still recommend to drop working with an array and use a List.

browser.msie error after update to jQuery 1.9.1

For simple IE detection I tend to use:

(/msie|trident/i).test(navigator.userAgent)

Visit the Microsoft Developer Network to learn about the IE useragent: http://msdn.microsoft.com/library/ms537503.aspx

How do I load the contents of a text file into a javascript variable?

One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is

    client.onreadystatechange = function() {

and in danb's case, it is

 function(data) {

This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

It means you're calling http from https. You can use src="//url.to/script.js" in your script tag and it will auto-detect.

Alternately you can use use https in your src even if you will be publishing it to a http page. This will avoid the potential issue mentioned in the comments.

How to check the gradle version in Android Studio?

File->Project Structure->Project pane->"Android plugin version".

Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects

Ring Buffer in Java

Since Guava 15.0 (released September 2013) there's EvictingQueue:

A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.

This class is not thread-safe, and does not accept null elements.

Example use:

EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Enum Naming Convention - Plural

Microsoft recommends using singular for Enums unless the Enum represents bit fields (use the FlagsAttribute as well). See Enumeration Type Naming Conventions (a subset of Microsoft's Naming Guidelines).

To respond to your clarification, I see nothing wrong with either of the following:

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass { 
    public OrderStatus OrderStatus { get; set; }
}

or

public enum OrderStatus { Pending, Fulfilled, Error };

public class SomeClass {
    public OrderStatus Status { get; set; }
}

"fatal: Not a git repository (or any of the parent directories)" from git status

in my case, i had the same problem while i try any git -- commands (eg git status) using windows cmd. so what i do is after installing git for window https://windows.github.com/ in the environmental variables, add the class path of the git on the "PATH" varaiable. usually the git will installed on C:/user/"username"/appdata/local/git/bin add this on the PATH in the environmental variable

and one more thing on the cmd go to your git repository or cd to where your clone are on your window usually they will be stored on the documents under github

cd Document/Github/yourproject

after that you can have any git commands

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

What are the most common naming conventions in C?

You know, I like to keep it simple, but clear... So here's what I use, in C:

  • Trivial Variables: i,n,c,etc... (Only one letter. If one letter isn't clear, then make it a Local Variable)
  • Local Variables: lowerCamelCase
  • Global Variables: g_lowerCamelCase
  • Const Variables: ALL_CAPS
  • Pointer Variables: add a p_ to the prefix. For global variables it would be gp_var, for local variables p_var, for const variables p_VAR. If far pointers are used then use an fp_ instead of p_.
  • Structs: ModuleCamelCase (Module = full module name, or a 2-3 letter abbreviation, but still in CamelCase.)
  • Struct Member Variables: lowerCamelCase
  • Enums: ModuleCamelCase
  • Enum Values: ALL_CAPS
  • Public Functions: ModuleCamelCase
  • Private Functions: CamelCase
  • Macros: CamelCase

I typedef my structs, but use the same name for both the tag and the typedef. The tag is not meant to be commonly used. Instead it's preferrable to use the typedef. I also forward declare the typedef in the public module header for encapsulation and so that I can use the typedef'd name in the definition.

Full struct Example:

typdef struct TheName TheName;
struct TheName{
    int var;
    TheName *p_link;
};

Given an array of numbers, return array of products of all other numbers (no division)

Here is my code:

int multiply(int a[],int n,int nextproduct,int i)
{
    int prevproduct=1;
    if(i>=n)
        return prevproduct;
    prevproduct=multiply(a,n,nextproduct*a[i],i+1);
    printf(" i=%d > %d\n",i,prevproduct*nextproduct);
    return prevproduct*a[i];
}

int main()
{
    int a[]={2,4,1,3,5};
    multiply(a,5,1,0);
    return 0;
}

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.

I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:

if (isset($_GET['AuthorizationJack'])) {
    $request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}

What is the curl error 52 "empty reply from server"?

My case was due to SSL certificate expiration

Invalidating JSON Web Tokens

The ideas posted above are good, but a very simple and easy way to invalidate all the existing JWTs is simply to change the secret.

If your server creates the JWT, signs it with a secret (JWS) then sends it to the client, simply changing the secret will invalidating all existing tokens and require all users to gain a new token to authenticate as their old token suddenly becomes invalid according to the server.

It doesn't require any modifications to the actual token contents (or lookup ID).

Clearly this only works for an emergency case when you wanted all existing tokens to expire, for per token expiry one of the solutions above is required (such as short token expiry time or invalidating a stored key inside the token).

Fatal error: Class 'Illuminate\Foundation\Application' not found

In my situation, I didn't have the full vendor dependencies in place (composer file was messed up during original install) - so running any artisan commands caused a failure.

I was able to use the --no-scripts flag to prevent artisan from executing before it was included. Once my dependencies were in place, everything worked as expected.

composer update --no-scripts

How do I get the current timezone name in Postgres 9.3?

See this answer: Source

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source

This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.

It seems to have the System's timezone to be set is possible indeed.

Get the OS local time zone from the shell. In psql:

=> \! date +%Z

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

Create Directory When Writing To File In Node.js

Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-frança fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

function mkdirp(filepath) {
    var dirname = path.dirname(filepath);

    if (!fs.existsSync(dirname)) {
        mkdirp(dirname);
    }

    fs.mkdirSync(filepath);
}

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

Add a scrollbar to a <textarea>

What you need is overflow-y: scroll;

Demo

_x000D_
_x000D_
    textarea {_x000D_
        overflow-y: scroll;_x000D_
        height: 100px;_x000D_
        resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
    }
_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

Use css gradient over background image

Ok, I solved it by adding the url for the background image at the end of the line.

Here's my working code:

_x000D_
_x000D_
.css {_x000D_
  background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
_x000D_
_x000D_

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

pandas: multiple conditions while indexing data frame - unexpected behavior

You can also use query(), i.e.:

df_filtered = df.query('a == 4 & b != 2')

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

How to SELECT by MAX(date)?

This would work perfectely, if you are using current timestamp

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS)

This would also work, if you are not using current timestamp but you are using date and time column seperately

SELECT * FROM reports WHERE date_entered = (SELECT max(date_entered) FROM REPORTS) ORDER BY time DESC LIMIT 1

How to set css style to asp.net button?

nobody wants to go to the clutter of using a class, try this:

<asp:button Style="margin:0px" runat="server" />

Intellisense won't suggest it but it will get the job done without throwing errors, warnings, or messages. Don't forget the capital S in Style

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Are HTTPS URLs encrypted?

Yes and no.

The server address portion is NOT encrypted since it is used to set up the connection.

This may change in future with encrypted SNI and DNS but as of 2018 both technologies are not commonly in use.

The path, query string etc. are encrypted.

Note for GET requests the user will still be able to cut and paste the URL out of the location bar, and you will probably not want to put confidential information in there that can be seen by anyone looking at the screen.

mingw-w64 threads: posix vs win32

Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads

From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.

Static method in a generic class?

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

In my opinion SET XACT_ABORT ON was made obsolete by the addition of BEGIN TRY/BEGIN CATCH in SQL 2k5. Before exception blocks in Transact-SQL it was really difficult to handle errors and unbalanced procedures were all too common (procedures that had a different @@TRANCOUNT at exit compared to entry).

With the addition of Transact-SQL exception handling is much easier to write correct procedures that are guaranteed to properly balance the transactions. For instance I use this template for exception handling and nested transactions:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    end catch   
end
go

It allows me to write atomic procedures that rollback only their own work in case of recoverable errors.

One of the main issues Transact-SQL procedures face is data purity: sometimes the parameters received or the data in the tables are just plain wrong, resulting in duplicate key errors, referential constrain errors, check constrain errors and so on and so forth. After all, that's exactly the role of these constrains, if these data purity errors would be impossible and all caught by the business logic, the constrains would be all obsolete (dramatic exaggeration added for effect). If XACT_ABORT is ON then all these errors result in the entire transaction being lost, as opposed to being able to code exception blocks that handle the exception gracefully. A typical example is trying to do an INSERT and reverting to an UPDATE on PK violation.

Responsive width Facebook Page Plugin

I'm using the solution proposed by Robert Smith with max-width instead of width:

.fb-page,
.fb-page span,
.fb-page span iframe[style] {
    max-width: 100% !important;
}

Also, i'm using the Yugal Jindle's proposal and so i've

data-width="555"

and

data-adapt-container-width="true"

Now my page is ok! Thank you alot!

How to save to local storage using Flutter?

You can use shared preferences from flutter's official plugins. https://github.com/flutter/plugins/tree/master/packages/shared_preferences

It uses Shared Preferences for Android, NSUserDefaults for iOS.

setTimeout / clearTimeout problems

This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.

function onUserHold(element, func, hold, clearfunc) {
    //var holdTime = 0;
    var holdTimeout;

    element.addEventListener('mousedown', function(e) {
        holdTimeout = setTimeout(function() {
            func();
            clearTimeout(holdTimeout);
            holdTime = 0;
        }, hold);
        //alert('UU');
    });

    element.addEventListener('mouseup', clearTime);
    element.addEventListener('mouseout', clearTime);

    function clearTime() {
        clearTimeout(holdTimeout);
        holdTime = 0;
        if(clearfunc) {
            clearfunc();
        }
    }
}

The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

How can you create multiple cursors in Visual Studio Code

https://code.visualstudio.com/Updates

New version (Visual Studio 0.3.0) support more multi cursor feature.

Multi-cursor
Here's multi-cursor improvements that we've made.

?D selects the word at the cursor, or the next occurrence of the current selection.
?K ?D moves the last added cursor to next occurrence of the current selection.
The two actions pick up the matchCase and matchWholeWord settings of the find widget.
?U undoes the last cursor action, so if you added one cursor too many or made a mistake, press ?U to return to the previous cursor state.
Insert cursor above (???) and insert cursor below (???) now reveals the last added cursor, making it easier to work with multi-cursors spanning more than one screen height (i.e., working with 300 lines while only 80 fit in the screen).

And short cut of select multi cursor change into cmd + d(it's same as Sublime Text. lol)

We can expect that next version supports more convenient feature about multi cursor ;)

Best practices for copying files with Maven

In order to copy a file use:

        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>copy-resource-one</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>

                    <configuration>
                        <outputDirectory>${basedir}/destination-folder</outputDirectory>
                        <resources>
                            <resource>
                                <directory>/source-folder</directory>
                                <includes>
                                    <include>file.jar</include>
                                </includes>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
           </executions>
        </plugin>

In order to copy folder with sub-folders use next configuration:

           <configuration>
              <outputDirectory>${basedir}/target-folder</outputDirectory>
              <resources>          
                <resource>
                  <directory>/source-folder</directory>
                  <filtering>true</filtering>
                </resource>
              </resources>              
            </configuration>  

Checking for empty or null List<string>

What about using an extension method?

public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
  if (source != null && source.Any())
    return true;
  else
    return false;
}

How do check if a PHP session is empty?

I would use isset and empty:

session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!';
}

array_key_exists is a nice alternative to using isset to check for keys:

session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!';
}

Make sure you're calling session_start before reading from or writing to the session array.

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

Browse for a directory in C#

or even more better, you can put this code in a class file

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal class OpenFolderDialog : IDisposable {

    /// <summary>
    /// Gets/sets folder in which dialog will be open.
    /// </summary>
    public string InitialFolder { get; set; }

    /// <summary>
    /// Gets/sets directory in which dialog will be open if there is no recent directory available.
    /// </summary>
    public string DefaultFolder { get; set; }

    /// <summary>
    /// Gets selected folder.
    /// </summary>
    public string Folder { get; private set; }


    internal DialogResult ShowDialog(IWin32Window owner) {
        if (Environment.OSVersion.Version.Major >= 6) {
            return ShowVistaDialog(owner);
        } else {
            return ShowLegacyDialog(owner);
        }
    }

    private DialogResult ShowVistaDialog(IWin32Window owner) {
        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
        uint options;
        frm.GetOptions(out options);
        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
        frm.SetOptions(options);
        if (this.InitialFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetFolder(directoryShellItem);
            }
        }
        if (this.DefaultFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetDefaultFolder(directoryShellItem);
            }
        }

        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
            NativeMethods.IShellItem shellItem;
            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
                IntPtr pszString;
                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
                    if (pszString != IntPtr.Zero) {
                        try {
                            this.Folder = Marshal.PtrToStringAuto(pszString);
                            return DialogResult.OK;
                        } finally {
                            Marshal.FreeCoTaskMem(pszString);
                        }
                    }
                }
            }
        }
        return DialogResult.Cancel;
    }

    private DialogResult ShowLegacyDialog(IWin32Window owner) {
        using (var frm = new SaveFileDialog()) {
            frm.CheckFileExists = false;
            frm.CheckPathExists = true;
            frm.CreatePrompt = false;
            frm.Filter = "|" + Guid.Empty.ToString();
            frm.FileName = "any";
            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
            frm.OverwritePrompt = false;
            frm.Title = "Select Folder";
            frm.ValidateNames = false;
            if (frm.ShowDialog(owner) == DialogResult.OK) {
                this.Folder = Path.GetDirectoryName(frm.FileName);
                return DialogResult.OK;
            } else {
                return DialogResult.Cancel;
            }
        }
    }


    public void Dispose() { } //just to have possibility of Using statement.

}

internal static class NativeMethods {

    #region Constants

    public const uint FOS_PICKFOLDERS = 0x00000020;
    public const uint FOS_FORCEFILESYSTEM = 0x00000040;
    public const uint FOS_NOVALIDATE = 0x00000100;
    public const uint FOS_NOTESTFILECREATE = 0x00010000;
    public const uint FOS_DONTADDTORECENT = 0x02000000;

    public const uint S_OK = 0x0000;

    public const uint SIGDN_FILESYSPATH = 0x80058000;

    #endregion


    #region COM

    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
    internal class FileOpenDialogRCW { }


    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IFileDialog {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        [PreserveSig()]
        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow 


        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypeIndex([In] uint iFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileTypeIndex(out uint piFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Unadvise([In] uint dwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOptions([In] uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetOptions(out uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetClientGuid([In] ref Guid guid);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint ClearClientData();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
    }


    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IShellItem {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
    }

    #endregion


    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);

}

And use it like this

using (var frm = new OpenFolderDialog()) {
                if (frm.ShowDialog(this)== DialogResult.OK) {
                    MessageBox.Show(this, frm.Folder);
                }
            }

Why are there no ++ and --? operators in Python?

To complete already good answers on that page:

Let's suppose we decide to do this, prefix (++i) that would break the unary + and - operators.

Today, prefixing by ++ or -- does nothing, because it enables unary plus operator twice (does nothing) or unary minus twice (twice: cancels itself)

>>> i=12
>>> ++i
12
>>> --i
12

So that would potentially break that logic.

now if one needs it for list comprehensions or lambdas, from python 3.8 it's possible with the new := assignment operator (PEP572)

pre-incrementing a and assign it to b:

>>> a = 1
>>> b = (a:=a+1)
>>> b
2
>>> a
2

post-incrementing just needs to make up the premature add by subtracting 1:

>>> a = 1
>>> b = (a:=a+1)-1
>>> b
1
>>> a
2

How to change the status bar background color and text color on iOS 7?

Here's a total, copy and paste solution, with an

absolutely correct explanation

of every issue involved.

With thanks to Warif Akhand Rishi !

for the amazing find regarding keyPath statusBarWindow.statusBar. Good one.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    // handle the iOS bar!
    
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // "Status Bar Style" refers to the >>>>>color of the TEXT<<<<<< of the Apple status bar,
    // it does NOT refer to the background color of the bar. This causes a lot of confusion.
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    // >>>>>NOTE<<<<<
    
    // our app is white, so we want the Apple bar to be white (with, obviously, black writing)
    
    // make the ultimate window of OUR app actually start only BELOW Apple's bar....
    // so, in storyboard, never think about the issue. design to the full height in storyboard.
    let h = UIApplication.shared.statusBarFrame.size.height
    let f = self.window?.frame
    self.window?.frame = CGRect(x: 0, y: h, width: f!.size.width, height: f!.size.height - h)
    
    // next, in your plist be sure to have this: you almost always want this anyway:
    // <key>UIViewControllerBasedStatusBarAppearance</key>
    // <false/>
    
    // next - very simply in the app Target, select "Status Bar Style" to Default.
    // Do nothing in the plist regarding "Status Bar Style" - in modern Xcode, setting
    // the "Status Bar Style" toggle simply sets the plist for you.
    
    // finally, method A:
    // set the bg of the Apple bar to white.  Technique courtesy Warif Akhand Rishi.
    // note: self.window?.clipsToBounds = true-or-false, makes no difference in method A.
    if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
        sb.backgroundColor = UIColor.white
        // if you prefer a light gray under there...
        //sb.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.9, alpha: 1)
    }
    
    /*
    // if you prefer or if necessary, method B:
    // explicitly actually add a background, in our app, to sit behind the apple bar....
    self.window?.clipsToBounds = false // MUST be false if you use this approach
    let whiteness = UIView()
    whiteness.frame = CGRect(x: 0, y: -h, width: f!.size.width, height: h)
    whiteness.backgroundColor = UIColor.green
    self.window!.addSubview(whiteness)
    */
    
    return true
}

Node.js fs.readdir recursive directory search

Here's a recursive method of getting all files including subdirectories.

const FileSystem = require("fs");
const Path = require("path");

//...

function getFiles(directory) {
    directory = Path.normalize(directory);
    let files = FileSystem.readdirSync(directory).map((file) => directory + Path.sep + file);

    files.forEach((file, index) => {
        if (FileSystem.statSync(file).isDirectory()) {
            Array.prototype.splice.apply(files, [index, 1].concat(getFiles(file)));
        }
    });

    return files;
}

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

How to restore to a different database in sql server?

Actually, there is no need to restore the database in native SQL Server terms, since you "want to fiddle with some data" and "browse through the data of that .bak file"

You can use ApexSQL Restore – a SQL Server tool that attaches both native and natively compressed SQL database backups and transaction log backups as live databases, accessible via SQL Server Management Studio, Visual Studio or any other third-party tool. It allows attaching single or multiple full, differential and transaction log backups

Moreover, I think that you can do the job while the tool is in fully functional trial mode (14 days)

Disclaimer: I work as a Product Support Engineer at ApexSQL

Create Test Class in IntelliJ

With the cursor on the class name declaration I do ALT + Return and my Intellij 14.1.4 offers me a popup with the option to 'Create Test'.

PHP random string generator

One liner.

It is fast for huge strings with some uniqueness.

function random_string($length){
    return substr(str_repeat(md5(rand()), ceil($length/32)), 0, $length);
}

Span inside anchor or anchor inside span or doesn't matter?

Personally, as a web developer, I only ever put a span within an anchor tag if I am trying to highlight a section of the links text, such as applying a background to one section.

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        output.push_back(substring);

        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

Matplotlib scatter plot with different text at each data point

I would love to add that you can even use arrows /text boxes to annotate the labels. Here is what I mean:

import random
import matplotlib.pyplot as plt


y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

ax.annotate(n[0], (z[0], y[0]), xytext=(z[0]+0.05, y[0]+0.3), 
    arrowprops=dict(facecolor='red', shrink=0.05))

ax.annotate(n[1], (z[1], y[1]), xytext=(z[1]-0.05, y[1]-0.3), 
    arrowprops = dict(  arrowstyle="->",
                        connectionstyle="angle3,angleA=0,angleB=-90"))

ax.annotate(n[2], (z[2], y[2]), xytext=(z[2]-0.05, y[2]-0.3), 
    arrowprops = dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1))

ax.annotate(n[3], (z[3], y[3]), xytext=(z[3]+0.05, y[3]-0.2), 
    arrowprops = dict(arrowstyle="fancy"))

ax.annotate(n[4], (z[4], y[4]), xytext=(z[4]-0.1, y[4]-0.2),
    bbox=dict(boxstyle="round", alpha=0.1), 
    arrowprops = dict(arrowstyle="simple"))

plt.show()

Which will generate the following graph: enter image description here

how can I enable PHP Extension intl?

Use phpinfo() function to find php.ini file path, open php.ini file. Here search extension=php_intl.dll then remove semi-colon (;) beginning of that line.

After removing semi-colon (;) restart you webserver (apache).

Should I use alias or alias_method?

alias_method can be redefined if need be. (it's defined in the Module class.)

alias's behavior changes depending on its scope and can be quite unpredictable at times.

Verdict: Use alias_method - it gives you a ton more flexibility.

Usage:

def foo
  "foo"
end

alias_method :baz, :foo

UILabel is not auto-shrinking text to fit label size

does not work if numberOfLines > 1 What i did made a condition like this-

if(lblRecLocation.text.length > 100)
    lblRecLocation.font = [UIFont fontWithName:@"app_font_name" size:10];

Efficient way to apply multiple filters to pandas DataFrame or Series

If you want to check any/all of multiple columns for a value, you can do:

df[(df[['HomeTeam', 'AwayTeam']] == 'Fulham').any(axis=1)]

Proper way to renew distribution certificate for iOS

Your live apps will not be taken down. Nothing will happen to anything that is live in the app store.

Once they formally expire, the only thing that will be impacted is your ability to sign code (and thus make new builds and provide updates).

Regarding your distribution certificate, once it expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. If you want to renew it before it expires, revoke the current certificate and you will get a button to request a new one.

Regarding the provisioning profile, don't worry about it before expiration, just keep using it. It's easy enough to just renew it once it expires.

The peace of mind is that nothing will happen to your live app in the store.

Is it possible to create a temporary table in a View and drop it after select?

Try creating another SQL view instead of a temporary table and then referencing it in the main SQL view. In other words, a view within a view. You can then drop the first view once you are done creating the main view.

How can I clear the SQL Server query cache?

Eight different ways to clear the plan cache

1. Remove all elements from the plan cache for the entire instance

DBCC FREEPROCCACHE;

Use this to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. This can cause a sudden, temporary decrease in query performance.

2. Flush the plan cache for the entire instance and suppress the regular completion message

"DBCC execution completed. If DBCC printed error messages, contact your system administrator."

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

3. Flush the ad hoc and prepared plan cache for the entire instance

DBCC FREESYSTEMCACHE ('SQL Plans');

4. Flush the ad hoc and prepared plan cache for one resource pool

DBCC FREESYSTEMCACHE ('SQL Plans', 'LimitedIOPool');

5. Flush the entire plan cache for one resource pool

DBCC FREEPROCCACHE ('LimitedIOPool');

6. Remove all elements from the plan cache for one database (does not work in SQL Azure)

-- Get DBID from one database name first
DECLARE @intDBID INT;
SET @intDBID = (SELECT [dbid] 
                FROM master.dbo.sysdatabases 
                WHERE name = N'AdventureWorks2014');

DBCC FLUSHPROCINDB (@intDBID);

7. Clear plan cache for the current database

USE AdventureWorks2014;
GO
-- New in SQL Server 2016 and SQL Azure
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

8. Remove one query plan from the cache

USE AdventureWorks2014;
GO

-- Run a stored procedure or query
EXEC dbo.uspGetEmployeeManagers 9;

-- Find the plan handle for that query 
-- OPTION (RECOMPILE) keeps this query from going into the plan cache
SELECT cp.plan_handle, cp.objtype, cp.usecounts, 
DB_NAME(st.dbid) AS [DatabaseName]
FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st 
WHERE OBJECT_NAME (st.objectid)
LIKE N'%uspGetEmployeeManagers%' OPTION (RECOMPILE); 

-- Remove the specific query plan from the cache using the plan handle from the above query 
DBCC FREEPROCCACHE (0x050011007A2CC30E204991F30200000001000000000000000000000000000000000000000000000000000000);
 

Source 1 2 3

How do I set the path to a DLL file in Visual Studio?

I know this question had been answered years ago, but for those like me who needed to change where the debugger starts the application, change the command property under Project Properties -> Debugging.

How to stop/terminate a python script from running?

Ctrl-Break it is more powerful than Ctrl-C

Generate random numbers following a normal distribution in C/C++

Take a look at what I found.

This library uses the Ziggurat algorithm.

How to set an environment variable in a running docker container

here is how to update a docker container config permanently

  1. stop container: docker stop <container name>
  2. edit container config: docker run -it -v /var/lib/docker:/var/lib/docker alpine vi $(docker inspect --format='/var/lib/docker/containers/{{.Id}}/config.v2.json' <container name>)
  3. restart docker

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");