Programs & Examples On #Prebuild

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

How to clear react-native cache?

I had a similar problem, I tried to clear all the caches possible (tried almost all the solutions above) and the only thing that worked for me was to kill the expo app and to restart it.

Node.js: Python not found exception due to node-sass and node-gyp

so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:

  1. delete node_modulesfolder
  2. running npm install --global windows-build-tools
  3. reinstalling node modules or node-sass with npm install

react-native :app:installDebug FAILED

I had this issue. Mine worked on the emulator well but it didn't work on the device and the error was

app:installDebug FAILED.

If you have a different app with the same name (or package name) on the device: Rename the app or delete it from your device.

The number of method references in a .dex file cannot exceed 64k API 17

I have been facing the same problem and for multidex support, you have to keep in mind the minSdkVersion of your application. If you are using minSdkVersion 21 or above then just write multiDexEnabled true like this

defaultConfig {
    applicationId *******************
    minSdkVersion 21
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}

It works for me and if you are using minSdkVersion below 21 (below lolipop) then you have to do two extra simple things

1. First add this dependency

compile 'com.android.support:multidex:1.0.1'

in your build.gradle.

2. Last and second add one this below line to your application in manifest

android:name="android.support.multidex.MultiDexApplication"

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:name="android.support.multidex.MultiDexApplication"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Bingo then it will work in the lower version also..:) Happy coding

Execution failed for task ':app:processDebugResources' even with latest build tools

Another possible reason

resConfigs "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"

can be source of this issue

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

On Linux or Ubuntu you need to use the complete path.

For example

/home/ubuntu/.android/keystorname.keystore

In my case I was using ~ instead of /home/user/. Using shorthands like the below does not work

~/.android/keystorname.keystore
./keystorename.keystore

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Solved the problem of getting an exception

java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process Make sure to call FirebaseApp.initializeApp(Context) first.

in FirebaseInstanceId.getInstance().getToken()

Check that package_name exactly matches applicationId 1) build.gradle

defaultConfig {
        applicationId "build.gradle.exactly.matches.json"
...
}

should exactly match 2) google-services.json

{
      "client_info": {
        "mobilesdk_app_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
        "android_client_info": {
          "package_name": "build.gradle.exactly.matches.json"
        ....

android : Error converting byte to dex

I've noticed this can happen (sometimes) when editing java files while Android Studio is building.

I solved this by manually deleting the build folder and running agin.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I also faced the same issue. But I forgot to add google-services.json in my project. You can get this file from Google.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

  1. Look at the folders drawable-hdpi, drawable-mdpi, drawable-xhdpi and so on.
  2. If there is a wrong bitmap file, Delete it and resave.
  3. Go to Build->Rebuild Project

Android java.exe finished with non-zero exit value 1

I got this error after transferring my project from my laptop to my desktop in Android Studio.

My solution was to restart Android Studio, then clean the project and finally execute the project.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

It's more than one error

Under apply plugin: 'android-library'

add this ::

android {
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

In case of duplicate files it's easy, look inside the JAR under the META-INF dir and see what's causing the error. It could be multiple. In my case Couchbase Lite plugin. As you add more plugins, you will need more exceptions

Link to all Visual Studio $ variables

Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE), but I wanted to err on the side of inclusiveness here.

For example, this is the first time that I see $(Language) (expanding to C++ for this project) being mentioned outside of the IDE.

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

Where to find this list within Visual Studio:

  1. Open your C++ project's dialogue Property Pages
  2. Select any textual field that can use a configuration variable. (in the screenshot, I use Target Name)
  3. On the right side of the text box, click the small combobox button and select option <Edit...>.
  4. In the new window (here, title is Target Name), click on button Macros>>.
  5. Scroll through the giant list of environment/linker/macro variables.

Motivational screenshot:

Visual Studio project Property Pages with exemplary Macro variable list

Detecting iOS orientation change instantly

Why you didn`t use

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

?

Or you can use this

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

Or this

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

Hope it owl be useful )

How to calculate number of days between two given dates?

You want the datetime module.

>>> from datetime import datetime, timedelta 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

Another example:

>>> import datetime 
>>> today = datetime.date.today() 
>>> print(today)
2008-09-01 
>>> last_year = datetime.date(2007, 9, 1) 
>>> print(today - last_year)
366 days, 0:00:00 

As pointed out here

How do I create a basic UIButton programmatically?

Swift3 version should be

let myButton:UIButton = {
            let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
            myButton.setTitle("Hai Touch Me", for: .normal)
            myButton.setTitleColor(UIColor.blue, for: .normal)
            myButton.frame = CGRect(x: 20, y: 20, width: 100, height: 40)

            myButton.addTarget(self, action: #selector(ViewController.pressedAction(_:)), for: .touchUpInside)
            self.view.addSubview(myButton)

            return myButton

        }()

How to get datetime in JavaScript?

var now = new Date();

now.format("dd/MM/yyyy hh:mm TT");

Get full details here: Flagrant Badassery » JavaScript Date Format

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

What does the Java assert keyword do, and when should it be used?

Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).

An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext() is called before next() in an Iterator).

how to set start page in webconfig file in asp.net c#

If your project contains a RouteConfig.cs file, then you probably need to ignore the route to the root by adding routes.IgnoreRoute(""); in this file.

If it doen't solve your problem, try this :

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.AppRelativeCurrentExecutionFilePath == "~/")
        Response.Redirect("~/index.aspx");
}

passing form data to another HTML page

Using pure JavaScript.It's very easy using local storage.
The first page form:

_x000D_
_x000D_
function getData()
{
    //gettting the values
    var email = document.getElementById("email").value;
    var password= document.getElementById("password").value; 
    var telephone= document.getElementById("telephone").value; 
    var mobile= document.getElementById("mobile").value; 
    //saving the values in local storage
    localStorage.setItem("txtValue", email);
    localStorage.setItem("txtValue1", password);
    localStorage.setItem("txtValue2", mobile);
    localStorage.setItem("txtValue3", telephone);   
}
_x000D_
  input{
    font-size: 25px;
  }
  label{
    color: rgb(16, 8, 46);
    font-weight: bolder;
  }
  #data{

  }
_x000D_
   <fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
        <form action="action.html">
        <legend>Sign Up Form</legend>
        <label>Email:<br />
        <input type="text" name="email" id="email"/></label><br />
        <label>Password<br />
        <input type="text" name="password" id="password"/></label><br>
        <label>Mobile:<br />
        <input type="text" name="mobile" id="mobile"/></label><br />
        <label>Telephone:<br />
        <input type="text" name="telephone" id="telephone"/></label><br> 
        <input type="submit" value="Submit" onclick="getData()">
    </form>
    </fieldset>
_x000D_
_x000D_
_x000D_

This is the second page:

_x000D_
_x000D_
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
_x000D_
 <div style=" font-size: 30px;  color: rgb(32, 7, 63); text-align: center;">
    <div style="font-size: 40px; color: red; margin: 0 auto;">
        Here's Your data
    </div>
    The Email is equal to: <span id="data"> Email</span><br> 
    The Password is equal to <span id="data1"> Password</span><br>
    The Mobile is equal to <span id="data2"> Mobile</span><br>
    The Telephone is equal to <span id="data3"> Telephone</span><br>
    </div>
_x000D_
_x000D_
_x000D_

Important Note:

Please don't forget to give name "action.html" to the second html file to work the code properly. I can't use multiple pages in a snippet, that's why its not working here try in the browser in your editor where it will surely work.

How to create CSV Excel file C#?

Please forgive me

But I think a public open-source repository is a better way to share code and make contributions, and corrections, and additions like "I fixed this, I fixed that"

So I made a simple git-repository out of the topic-starter's code and all the additions:

https://github.com/jitbit/CsvExport

I also added a couple of useful fixes myself. Everyone could add suggestions, fork it to contribute etc. etc. etc. Send me your forks so I merge them back into the repo.

PS. I posted all copyright notices for Chris. @Chris if you're against this idea - let me know, I'll kill it.

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

How can I write a heredoc to a file in Bash script?

Note:

The question (how to write a here document (aka heredoc) to a file in a bash script?) has (at least) 3 main independent dimensions or subquestions:

  1. Do you want to overwrite an existing file, append to an existing file, or write to a new file?
  2. Does your user or another user (e.g., root) own the file?
  3. Do you want to write the contents of your heredoc literally, or to have bash interpret variable references inside your heredoc?

(There are other dimensions/subquestions which I don't consider important. Consider editing this answer to add them!) Here are some of the more important combinations of the dimensions of the question listed above, with various different delimiting identifiers--there's nothing sacred about EOF, just make sure that the string you use as your delimiting identifier does not occur inside your heredoc:

  1. To overwrite an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << EOF > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    EOF
    
  2. To append an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:

    cat << FOE >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    FOE
    
  3. To overwrite an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'END_OF_FILE' > /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    END_OF_FILE
    
  4. To append an existing file (or write to a new file) that you own, with the literal contents of the heredoc:

    cat << 'eof' >> /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    eof
    
  5. To overwrite an existing file (or write to a new file) owned by root, substituting variable references inside the heredoc:

    cat << until_it_ends | sudo tee /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, with the variable contents substituted.
    until_it_ends
    
  6. To append an existing file (or write to a new file) owned by user=foo, with the literal contents of the heredoc:

    cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file
    This line will write to the file.
    ${THIS} will also write to the file, without the variable contents substituted.
    Screw_you_Foo
    

How can I scan barcodes on iOS?

with Swift 5 it's Simple and Super fast!!

You just need to add cocoa pods "BarcodeScanner" here is the full code

source 'https://github.com/CocoaPods/Specs.git' 
platform :ios, '12.0' 
target 'Simple BarcodeScanner' 
do   
pod 'BarcodeScanner' 
end

Make sure add Camera permission in your .plist file

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

And add Scanner and handle result in your ViewController this way

import UIKit
import BarcodeScanner

class ViewController: UIViewController, BarcodeScannerCodeDelegate, BarcodeScannerErrorDelegate, BarcodeScannerDismissalDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let viewController = BarcodeScannerViewController()
        viewController.codeDelegate = self
        viewController.errorDelegate = self
        viewController.dismissalDelegate = self

        present(viewController, animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didCaptureCode code: String, type: String) {
        print("Product's Bar code is :", code)
        controller.dismiss(animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didReceiveError error: Error) {
        print(error)
    }

    func scannerDidDismiss(_ controller: BarcodeScannerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

Still and any question or challenges, please check sample application here with full source code

Proper way of checking if row exists in table in PL/SQL block

Select 'YOU WILL SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 1);

Select 'YOU CAN NOT SEE ME' as ANSWER from dual
where exists (select 1 from dual where 1 = 0);

Select 'YOU WILL SEE ME, TOO' as ANSWER from dual
where not exists (select 1 from dual where 1 = 0);

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

MySQL Workbench not opening on Windows

What works for me (workbench 64bit) is that I installed Visual Studio 2015, 2017 and 2019 here is url: https://support.microsoft.com/en-ph/help/2977003/the-latest-supported-visual-c-downloads

I installed both x86: vc_redist.x86.exe and x64: vc_redist.x64.exe

Implementing autocomplete

Update: This answer has led to the development of ng2-completer an Angular2 autocomplete component. This is the list of existing autocomplete components for Angular2:

  1. ng2-completer
  2. ng2-auto-complete
  3. ng2-typeahead

Credit goes to @dan-cancro for coming up with the idea

Keeping the original answer for those who wish to create their own directive:

To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:

  1. Obtain a reference to the nativeElement and manipulate the DOM directly
  2. Dynamically load a list component using DynamicComponentLoader

It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.

This is the directive code:

"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";

@Directive({
    selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
    host: {
        "(keyup)": "onKey($event)" // Liten to keyup events on the host component
    }
})
export class AutocompleteDirective implements OnInit {
    // The search function should be passed as an input
    @Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
    // The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
    @Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();

    private term = "";
    private listCmp: ComponentRef<AutocompleteList> = undefined;
    private refreshTimer: any = undefined;
    private searchInProgress = false;
    private searchRequired = false;

    constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
    /**
     * On key event is triggered when a key is released on the host component
     * the event starts a timer to prevent concurrent requests
     */
    public onKey(event: any) {
        if (!this.refreshTimer) {
            this.refreshTimer = setTimeout(
            () => {
                if (!this.searchInProgress) {
                    this.doSearch();
                } else {
                    // If a request is in progress mark that a new search is required
                    this.searchRequired = true;
                }
            },
            200);
        }
        this.term = event.target.value;
        if (this.term === "" && this.listCmp) {
            // clean the list if the search term is empty
            this.removeList();
        }
    }

    public ngOnInit() {
        // When an item is selected remove the list
        this.selected.subscribe(() => {
            this.removeList();
        });
    }

    /**
     * Call the search function and handle the results
     */
    private doSearch() {
        this.refreshTimer = undefined;
        // if we have a search function and a valid search term call the search
        if (this.search && this.term !== "") {
            this.searchInProgress = true;
            this.search(this.term)
            .then((res) => {
                this.searchInProgress = false;
                // if the term has changed during our search do another search
                if (this.searchRequired) {
                    this.searchRequired = false;
                    this.doSearch();
                } else {
                    // display the list of results
                    this.displayList(res);
                }
            })
            .catch(err => {
                console.log("search error:", err);
                this.removeList();
            });
        }
    }

    /**
     * Display the list of results
     * Dynamically load the list component if it doesn't exist yet and update the suggestions list
     */
    private displayList(list: Array<{ text: string, data: any }>) {
        if (!this.listCmp) {
            this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
            .then(cmp => {
                // The component is loaded
                this.listCmp = cmp;
                this.updateList(list);
                // Emit the selectd event when the component fires its selected event
                (<AutocompleteList>(this.listCmp.instance)).selected
                    .subscribe(selectedItem => {

                    this.selected.emit(selectedItem);
                });
            });
        } else {
            this.updateList(list);
        }
    }

    /**
     * Update the suggestions list in the list component
     */
    private updateList(list: Array<{ text: string, data: any }>) {
        if (this.listCmp) {
            (<AutocompleteList>(this.listCmp.instance)).list = list;
        }
    }

    /**
     * remove the list component
     */
    private removeList() {
        this.searchInProgress = false;
        this.searchRequired = false;
        if (this.listCmp) {
            this.listCmp.destroy();
            this.listCmp = undefined;
        }
    }
}

The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:

"use strict";
import {Component, Output, EventEmitter} from "@angular/core";

@Component({
    selector: "autocomplete-list",
    template: `<div class="dropdown-menu  search-results">
                    <a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
               </div>`, // Use a bootstrap 4 dropdown-menu to display the list
    styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList  {
    // Emit a selected event when an item in the list is selected
    @Output() public selected = new EventEmitter();

    public list;

    /**
     * Listen for a click event on the list
     */
    public onClick(item: {text: string, data: any}) {
        this.selected.emit(item);
    }
}

To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:

 "use strict";
import {Component} from "@angular/core";

import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";

@Component({
    selector: "my-cmp",
    directives: [AutocompleteDirective],
    template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent  {

    /**
     * generate a search function that returns a Promise that resolves to array of text and optionally additional data
     */  
    public search() {
        return (filter: string): Promise<Array<{ text: string, data: any }>> => {
            // do the search
            resolve({text: "one item", data: null});
        };
    }

    /**
     * handle item selection
     */  
    public onItemSelected(selected: { text: string, data: any }) {
        console.log("selected: ", selected.text);
    }
}

Update: code compatible with angular2 rc.1

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It is ternary operator, like an if/else statement.

if(a > b) {
what to do;
}
else {
what to do;
}

In ternary operator it is like that: condition ? what to do if condition is true : what to do if it is false;

(a > b) ? what to do if true : what to do if false;

&& (AND) and || (OR) in IF statements

No, if a is true (in a or test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.

Make a simple test:

if (true || ((String) null).equals("foobar")) {
    ...
}

will not throw a NullPointerException!

Get the string within brackets in Python

You can also use

re.findall(r"\[([A-Za-z0-9_]+)\]", string)

if there are many occurrences that you would like to find.

See also for more info: How can I find all matches to a regular expression in Python?

How to find out if an installed Eclipse is 32 or 64 bit version?

Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807

As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.

For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.

Remove scrollbar from iframe

iframe {
  display: block;
  border: none;         /* Reset default border */
  height: 100vh;        /* Viewport-relative units */
  width: calc(100% + 17px);
}
div {
  overflow-x: hidden;
}

Like this you make the width of the Iframe larger than it should be. Then you hide the horizontal scrollbar with overflow-x: hidden.

Zooming MKMapView to fit annotation pins?

If your are looking for iOS 8 and above, the simplest way to do it is to set the var layoutMargins: UIEdgeInsets { get set } of your map view before calling func showAnnotations(annotations: [MKAnnotation], animated: Bool)

For instance (Swift 2.1):

@IBOutlet weak var map: MKMapView! {
    didSet {
        map.delegate = self
        map.mapType = .Standard
        map.pitchEnabled = false
        map.rotateEnabled = false
        map.scrollEnabled = true
        map.zoomEnabled = true
    }
}

// call 'updateView()' when viewWillAppear or whenever you set the map annotations
func updateView() {
    map.layoutMargins = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25)
    map.showAnnotations(map.annotations, animated: true)
}

gnuplot : plotting data from multiple input files in a single graph

You're so close!

Change

plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548"  using 1:2 title "Flow 3", \ 
plot "print_401125"  using 1:2 title "Flow 4", \
plot "print_401275"  using 1:2 title "Flow 5", \
plot "print_401276"  using 1:2 title "Flow 6"

to

plot "print_1012720" using 1:2 title "Flow 1", \
     "print_1058167" using 1:2 title "Flow 2", \
     "print_193548"  using 1:2 title "Flow 3", \ 
     "print_401125"  using 1:2 title "Flow 4", \
     "print_401275"  using 1:2 title "Flow 5", \
     "print_401276"  using 1:2 title "Flow 6"

The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).

How to add row of data to Jtable from values received from jtextfield and comboboxes

String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);

Here;this is the solution.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If you want to use SOCKS5 proxy, you may try rubygems-socksproxy https://github.com/gussan/rubygems-socksproxy.

It works for me on OSX 10.9.3.

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

Is there a decent wait function in C++?

Before the return statement in you main, insert this code:

system("pause");

This will hold the console until you hit a key.

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause");
    return 0; // this return statement isn't necessary
}

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

Last element in .each() set

For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

This directly compares elements rather than just checking index numbers.

$yourset.each(function() {
    var $this = $(this);
    if($this[0] === $yourset.last()[0]) {
        //$this is the last one
    }
});

When should I use a struct rather than a class in C#?

Structures are in most ways like classes/objects. Structure can contain functions, members and can be inherited. But structures are in C# used just for data holding. Structures does take less RAM than classes and are easier for garbage collector to collect. But when you use functions in your structure, then compiler actually takes that structure very similarly as class/object, so if you want something with functions, then use class/object.

Calculate difference in keys contained in two Python dictionaries

Here is a solution for deep comparing 2 dictionaries keys:

def compareDictKeys(dict1, dict2):
  if type(dict1) != dict or type(dict2) != dict:
      return False

  keys1, keys2 = dict1.keys(), dict2.keys()
  diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)

  if not diff:
      for key in keys1:
          if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
              diff = True
              break

  return not diff

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

How to correctly implement custom iterators and const_iterators?

There are plenty of good answers but I created a template header I use that is quite concise and easy to use.

To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:

#include <iostream>
#include <vector>
#include "iterator_tpl.h"

struct myClass {
  std::vector<float> vec;

  // Add some sane typedefs for STL compliance:
  STL_TYPEDEFS(float);

  struct it_state {
    int pos;
    inline void begin(const myClass* ref) { pos = 0; }
    inline void next(const myClass* ref) { ++pos; }
    inline void end(const myClass* ref) { pos = ref->vec.size(); }
    inline float& get(myClass* ref) { return ref->vec[pos]; }
    inline bool cmp(const it_state& s) const { return pos != s.pos; }

    // Optional to allow operator--() and reverse iterators:
    inline void prev(const myClass* ref) { --pos; }
    // Optional to allow `const_iterator`:
    inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
  };
  // Declare typedef ... iterator;, begin() and end() functions:
  SETUP_ITERATORS(myClass, float&, it_state);
  // Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
  SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};

Then you can use it as you would expect from an STL iterator:

int main() {
  myClass c1;
  c1.vec.push_back(1.0);
  c1.vec.push_back(2.0);
  c1.vec.push_back(3.0);

  std::cout << "iterator:" << std::endl;
  for (float& val : c1) {
    std::cout << val << " "; // 1.0 2.0 3.0
  }

  std::cout << "reverse iterator:" << std::endl;
  for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
    std::cout << *it << " "; // 3.0 2.0 1.0
  }
}

I hope it helps.

How do I check what version of Python is running my script?

Use platform's python_version from the stdlib:

>>> from platform import python_version
>>> print(python_version())
2.7.8

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

What's the purpose of the LEA instruction?

As the existing answers mentioned, LEA has the advantages of performing memory addressing arithmetic without accessing memory, saving the arithmetic result to a different register instead of the simple form of add instruction. The real underlying performance benefit is that modern processor has a separate LEA ALU unit and port for effective address generation (including LEA and other memory reference address), this means the arithmetic operation in LEA and other normal arithmetic operation in ALU could be done in parallel in one core.

Check this article of Haswell architecture for some details about LEA unit: http://www.realworldtech.com/haswell-cpu/4/

Another important point which is not mentioned in other answers is LEA REG, [MemoryAddress] instruction is PIC (position independent code) which encodes the PC relative address in this instruction to reference MemoryAddress. This is different from MOV REG, MemoryAddress which encodes relative virtual address and requires relocating/patching in modern operating systems (like ASLR is common feature). So LEA can be used to convert such non PIC to PIC.

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Error when trying to access XAMPP from a network

This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185

Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin"> to have the following code:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

How to set an environment variable in a running docker container

For a somewhat narrow use case, docker issue 8838 mentions this sort-of-hack:

You just stop docker daemon and change container config in /var/lib/docker/containers/[container-id]/config.json (sic)

This solution updates the environment variables without the need to delete and re-run the container, having to migrate volumes and remembering parameters to run.

However, this requires a restart of the docker daemon. And, until issue issue 2658 is addressed, this includes a restart of all containers.

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

GET async

public async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        requestBody.Write(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

    

POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

Create two-dimensional arrays and access sub-arrays in Ruby

There are some problems with 2 dimensional Arrays the way you implement them.

a= [[1,2],[3,4]]
a[0][2]= 5 # works
a[2][0]= 6 # error

Hash as Array

I prefer to use Hashes for multi dimensional Arrays

a= Hash.new
a[[1,2]]= 23
a[[5,6]]= 42

This has the advantage, that you don't have to manually create columns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash does not become too big.

You can even set a default value for all not specified elements

a= Hash.new(0)

So now about how to get subarrays

(3..5).to_a.product([2]).collect { |index| a[index] }
[2].product((3..5).to_a).collect { |index| a[index] }

(a..b).to_a runs in O(n). Retrieving an element from an Hash is almost O(1), so the collect runs in almost O(n). There is no way to make it faster than O(n), as copying n elements always is O(n).

Hashes can have problems when they are getting too big. So I would think twice about implementing a multidimensional Array like this, if I knew my amount of data is getting big.

Shell Script Syntax Error: Unexpected End of File

I have found that this is sometimes caused by running a MS Dos version of a file. If that's the case dos2ux should fix that.

dos2ux file1 > file2

App can't be opened because it is from an unidentified developer

Right-click (or control-click) the application in question and choose "Open"

JavaScript function in href vs. onclick

Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.

Java for loop multiple variables

Only two Semicolons are allowed to be used in for loop.

  1. Before first semicolon is the initialization part.
  2. After first semicolon and before second semicolon is condition part (must result in boolean).
  3. After second semicolon is variable manipulation part (increment/decrement part).

If you have do initialization of multiple variables or manipulation of multiple variables, you can achieve it by separating them with comma(,).

for(int i=0, j=5; i < 5; i++, j--)

NOTE: Multiple conditions separated by comma are NOT allowed.

for(int i=0, j=5; i < 5, j > 5; i++, j--) // This is NOT allowed.

Loading PictureBox Image from resource file with path (Part 3)

The path should be something like: "Images\a.bmp". (Note the lack of a leading slash, and the slashes being back slashes.)

And then:

pictureBox1.Image = Image.FromFile(@"Images\a.bmp");

I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".

Visual Studio 2008 Product Key in Registry?

Just delete key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

Or run in command line:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

How to change MySQL column definition?

This should do it:

ALTER TABLE test MODIFY locationExpert VARCHAR(120) 

adding to window.onload event?

You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

Loading local JSON file

What worked for me is the following:

Input:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript Code:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>

Best way to create enum of strings?

I don't know what you want to do, but this is how I actually translated your example code....

package test;

/**
 * @author The Elite Gentleman
 *
 */
public enum Strings {
    STRING_ONE("ONE"),
    STRING_TWO("TWO")
    ;

    private final String text;

    /**
     * @param text
     */
    Strings(final String text) {
        this.text = text;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return text;
    }
}

Alternatively, you can create a getter method for text.

You can now do Strings.STRING_ONE.toString();

Javascript setInterval not working

That's because you should pass a function, not a string:

function funcName() {
    alert("test");
}

setInterval(funcName, 10000);

Your code has two problems:

  • var func = funcName(); calls the function immediately and assigns the return value.
  • Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

How to add a border to a widget in Flutter?

As stated in the documentation, flutter prefer composition over parameters. Most of the time what you're looking for is not a property, but instead a wrapper (and sometimes a few helpers/"builder")

For borders what you want is DecoratedBox, which has a decoration property that defines borders ; but also background images or shadows.

Alternatively like @Aziza said, you can use Container. Which is the combination of DecoratedBox, SizedBox and a few other useful widgets.

Splitting a table cell into two columns in HTML

Use this example, you can split with the colspan attribute

<TABLE BORDER>
     <TR>
         <TD>Item 1</TD>
         <TD>Item 1</TD>
         <TD COLSPAN=2>Item 2</TD>
    </TR>
    <TR>
         <TD>Item 3</TD>
         <TD>Item 3</TD>
         <TD>Item 4</TD>
         <TD>Item 5</TD>
    </TR>
</TABLE>

More examples at http://hypermedia.univ-paris8.fr/jean/internet/ex_table.html.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

Try This

if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))

This will return the value between 1 to 10 & 20 to 40.

How to find tags with only certain attributes - BeautifulSoup

Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:

from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
    <td width="580" valign="top">.......</td>\
    <td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')

Github Push Error: RPC failed; result=22, HTTP code = 413

Do you use https links instead of ssh links? Because the https link is limited by the size of the upload of HttpServer (such as Apache, Ngnix), there is no such restriction when using ssh.

Use the following method to switch to the ssh link.

  1. Open terminal.
  2. Switch to your project's working directory.
  3. Get the name of the remote repository
$ git remote -v
origin  https://github.com/[user_name]/[project_name].git (fetch)
origin  https://github.com/[user_name]/[project_name].git (push)
  1. Modify the git address to ssh link.
git remote set-url origin [email protected]:[user_name]/[project_name].git

If you determine the remote repository name, proceed directly to step 4. Now, you can do the push operation happily.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplify. Cherry-pick the commits. Don't cherry-pick the merge.

Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:

You're trying to cherry pick fd9f578, which was a merge with two parents.

Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.

Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.

explanation

The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.

If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.

alternatives

If you determine you need to include the merge vs cherry-picking the related commits, you have two options:

  1. (More complicated and obscure; also discards history) you can indicate which parent should apply.

    • Use the -m option to do so. For example, git cherry-pick -m 1 fd9f578 will use the first parent listed in the merge as the base.

    • Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

  2. (Simpler and more familiar; preserves history) you can use git merge instead of git cherry-pick.

    • As is usual with git merge, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

AngularJS - add HTML element to dom in directive without jQuery

In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.

So basically, you can rewrite your code to something like this:

link: function (scope, iElement, iAttrs) {
  var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');
  angular.element(svgTag).appendTo(iElement[0]);
  //...
}

Git, How to reset origin/master to a commit?

Assuming that your branch is called master both here and remotely, and that your remote is called origin you could do:

git reset --hard <commit-hash>
git push -f origin master

However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.

What is a wrapper class?

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

What represents a double in sql server?

It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.

However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.

Making Maven run all tests, even when some fail

A quick answer:

mvn -fn test

Works with nested project builds.

Best way to incorporate Volley (or other library) into Android Studio project

LATEST UPDATE:

Use the official version from jCenter instead.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

The dependencies below points to deprecated volley that is no longer maintained.

ORIGINAL ANSWER

You can use this in dependency section of your build.gradle file to use volley

  dependencies {
      compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  }

UPDATED:

Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.

https://github.com/mcxiaoke/android-volley

Crystal Reports - Adding a parameter to a 'Command' query

When you are in the Command, click Create to create a new parameter; call it project_name. Once you've created it, double click its name to add it to the command's text. You query should resemble:

SELECT Projecttname, ReleaseDate, TaskName
FROM DB_Table
WHERE Project_Name LIKE {?project_name} + '*'
AND ReleaseDate >= getdate() --assumes sql server

If desired, link the main report to the subreport on this ({?project_name}) field. If you don't establish a link between the main and subreport, CR will prompt you for the subreport's parameter.

In versions prior to 2008, a command's parameter was only allowed to be a scalar value.

Count all occurrences of a string in lots of files with grep

The AWK solution which also handles file names including colons:

grep -c string * | sed -r 's/^.*://' | awk 'BEGIN{}{x+=$1}END{print x}'

Keep in mind that this method still does not find multiple occurrences of string on the same line.

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same exception and I was excluding javassist because of its issue with powermock. Then I was adding it again as below but it was not working:

<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>org.javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.20.0-GA</version>
   <scope>test</scope>
</dependency>

Finally I found out that I have to remove <scope>test</scope> from javassist dependency. Hope it helps someone.

How do you simulate Mouse Click in C#?

An example I found somewhere here in the past. Might be of some help:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class Form1 : Form
{
   [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
   public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
   //Mouse actions
   private const int MOUSEEVENTF_LEFTDOWN = 0x02;
   private const int MOUSEEVENTF_LEFTUP = 0x04;
   private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
   private const int MOUSEEVENTF_RIGHTUP = 0x10;

   public Form1()
   {
   }

   public void DoMouseClick()
   {
      //Call the imported function with the cursor's current position
      uint X = (uint)Cursor.Position.X;
      uint Y = (uint)Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
   }

   //...other code needed for the application
}

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

How to do scanf for single char in C

Here is a similiar thing that I would like to share,

while you're working on Visual Studio you could get an error like:

'scanf': function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

To prevent this, you should write it in the following format

A single character may be read as follows:

char c;
scanf_s("%c", &c, 1);

When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.

char c[4];
scanf_s("%4c", &c, _countof(c));

How do I join two lines in vi?

Shift+J removes the line change character from the current line, so by pressing "J" at any place in the line you can combine the current line and the next line in the way you want.

Extract source code from .jar file

Use JD GUI. Open the application, drag and drop your JAR file into it.

Recommended way to get hostname in Java

Environment variables may also provide a useful means -- COMPUTERNAME on Windows, HOSTNAME on most modern Unix/Linux shells.

See: https://stackoverflow.com/a/17956000/768795

I'm using these as "supplementary" methods to InetAddress.getLocalHost().getHostName(), since as several people point out, that function doesn't work in all environments.

Runtime.getRuntime().exec("hostname") is another possible supplement. At this stage, I haven't used it.

import java.net.InetAddress;
import java.net.UnknownHostException;

// try InetAddress.LocalHost first;
//      NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
    String result = InetAddress.getLocalHost().getHostName();
    if (StringUtils.isNotEmpty( result))
        return result;
} catch (UnknownHostException e) {
    // failed;  try alternate means.
}

// try environment properties.
//      
String host = System.getenv("COMPUTERNAME");
if (host != null)
    return host;
host = System.getenv("HOSTNAME");
if (host != null)
    return host;

// undetermined.
return null;

How do I start PowerShell from Windows Explorer?

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
if(-not (Test-Path -Path "HKCR:\Directory\shell\$KeyName"))
{
    Try
    {
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName" -value "Open PowerShell in this Folder" -ErrorAction Stop
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName\command" -value "$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location '%V'" -ErrorAction Stop
        Write-Host "Successfully!"
     }
     Catch
     {
         Write-Error $_.Exception.Message
     }
}
else
{
    Write-Warning "The specified key name already exists. Type another name and try again."
}

You can download detail script from how to start PowerShell from Windows Explorer

How to click a href link using Selenium

To click() on the element with text as App Configuration you can use either of the following Locator Strategies:

  • linkText:

    driver.findElement(By.linkText("App Configuration")).click();
    
  • cssSelector:

    driver.findElement(By.cssSelector("a[href='/docs/configuration']")).click();
    
  • xpath:

    driver.findElement(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']")).click();
    

Ideally, to click() on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("App Configuration"))).click();
    
  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/docs/configuration']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/docs/configuration' and text()='App Configuration']"))).click();
    

References

You can find a couple of relevant detailed discussions in:

multiple plot in one figure in Python

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

Bootstrap 3 Glyphicons are not working

IIS will not server .woff files by default, so in IIS you'll need to add a <mimeMap> entry to your web.config file;

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".woff" mimeType="application/x-woff" />
        </staticContent>
    </system.webServer>
</configuration>

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

PYTHONPATH only affects import statements, not the top-level Python interpreter's lookup of python files given as arguments.

Needing PYTHONPATH to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.

Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.

Creating a singleton in Python

One liner (I am not proud, but it does the job):

class Myclass:
  def __init__(self):
      # do your stuff
      globals()[type(self).__name__] = lambda: self # singletonify

form_for with nested resources

You don't need to do special things in the form. You just build the comment correctly in the show action:

class ArticlesController < ActionController::Base
  ....
  def show
    @article = Article.find(params[:id])
    @new_comment = @article.comments.build
  end
  ....
end

and then make a form for it in the article view:

<% form_for @new_comment do |f| %>
   <%= f.text_area :text %>
   <%= f.submit "Post Comment" %>
<% end %>

by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

SQL Error: ORA-01861: literal does not match format string 01861

Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')

How to trigger ngClick programmatically

The syntax is the following:

function clickOnUpload() {
  $timeout(function() {
    angular.element('#myselector').triggerHandler('click');
  });
};

// Using Angular Extend
angular.extend($scope, {
  clickOnUpload: clickOnUpload
});

// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;

More info on Angular Extend way here.

If you are using old versions of angular, you should use trigger instead of triggerHandler.

If you need to apply stop propagation you can use this method as follows:

<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
  Something
</a>

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

In a nutshell, [[ is better because it doesn't fork another process. No brackets or a single bracket is slower than a double bracket because it forks another process.

How do I convert a String to a BigInteger?

For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}

how to pass command line arguments to main method dynamically

We can pass string value to main method as argument without using commandline argument concept in java through Netbean

 package MainClass;
 import java.util.Scanner;
 public class CmdLineArgDemo {

static{
 Scanner readData = new Scanner(System.in);   
 System.out.println("Enter any string :");
 String str = readData.nextLine();
 String [] str1 = str.split(" ");
 // System.out.println(str1.length);
 CmdLineArgDemo.main(str1);
}  

   public static void main(String [] args){
      for(int i = 0 ; i<args.length;i++) {
        System.out.print(args[i]+" ");
      }
    }
  }

Output

Enter any string : 
Coders invent Digital World 
Coders invent Digital World

Sorting options elements alphabetically using jQuery

I know this topic is old but I think my answer can be useful for a lot of people.

Here is jQuery plugin made from Pointy's answer using ES6:

/**
 * Sort values alphabetically in select
 * source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
 */
$.fn.extend({
    sortSelect() {
        let options = this.find("option"),
            arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();

        arr.sort((o1, o2) => { // sort select
            let t1 = o1.t.toLowerCase(), 
                t2 = o2.t.toLowerCase();
            return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
        });

        options.each((i, o) => {
            o.value = arr[i].v;
            $(o).text(arr[i].t);
        });
    }
});

Use is very easy

$("select").sortSelect();

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

Right Align button in horizontal LinearLayout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"             
    android:orientation="horizontal" 
    android:layout_marginTop="35dp">

    <TextView
        android:id="@+id/lblExpenseCancel"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:text="@string/cancel" 
        android:textColor="#404040"         
        android:layout_marginLeft="10dp" 
        android:textSize="20sp" 
        android:layout_marginTop="9dp"/>              

    <Button
        android:id="@+id/btnAddExpense"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:layout_height="wrap_content"
        android:background="@drawable/stitch_button"
        android:layout_marginLeft="10dp"                    
        android:text="@string/add" 
        android:layout_gravity="right" 
        android:layout_marginRight="15dp"/>

</LinearLayout>

This will solve your problem

Selecting the first "n" items with jQuery

You probably want to read up on slice. Your code will look something like this:

$("a").slice(0,20)

Convert PDF to clean SVG?

You can use Inkscape on the commandline only, without opening a GUI. Try this:

inkscape \
  --without-gui \
  --file=input.pdf \
  --export-plain-svg=output.svg 

For a complete list of all commandline options, run inkscape --help.

Making a triangle shape using xml definitions?

You can use vector drawables.

If your minimum API is lower than 21, Android Studio automatically creates PNG bitmaps for those lower versions at build time (see Vector Asset Studio). If you use the support library, Android even manages "real vectors" down to API 7 (more on that in the update of this post at the bottom).

A red upwards pointing triangle would be:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#FF0000"
            android:pathData="m 50,0 l 50,100 -100,0 z" />
    </group>
</vector>

Add it to your layout and remember to set clipChildren="false" if you rotate the triangle.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false">

    <ImageView
        android:layout_width="130dp"
        android:layout_height="100dp"
        android:rotation="0"
        android:layout_centerInParent="true"
        android:background="@drawable/triangle"/>

</RelativeLayout>

enter image description here

Change the size (width/height) of the triangle by setting the Views layout_width/layout_height attributes. This way you can also get an eqilateral triagle if you do the math correct.

UPDATE 25.11.2017

If you use the support library you can use real vectors (instead if bitmap creation) as far back as API 7. Simply add:

vectorDrawables.useSupportLibrary = true

do your defaultConfig in your module's build.gradle.

Then set the (vector xml) drawable like this:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/triangle" />

Everything is documented very nicely on the Vector Asset Studio page.

Ever since this feature I've been working entirely without bitmaps in terms of icons. This also reduces APK size quite a bit.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

Some reasons why this might happen:

  • Tomcat may have crashed
  • The web application did not respond in time and the request from Apache timed out
  • The Tomcat threads are timing out
  • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

  • ProxyTimeout directive of Apache's mod_proxy
  • Connector config of Apache Tomcat
  • Your network device's manual

Access denied for user 'test'@'localhost' (using password: YES) except root user

Do not grant all privileges over all databases to a non-root user, it is not safe (and you already have "root" with that role)

GRANT <privileges> ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This statement creates a new user and grants selected privileges to it. I.E.:

GRANT INSERT, SELECT, DELETE, UPDATE ON database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

Take a look at the docs to see all privileges detailed

EDIT: you can look for more info with this query (log in as "root"):

select Host, User from mysql.user;

To see what happened

How to pass an array within a query string?

This works for me:

In link, to attribute has value:

to="/filter/arr?fruits=apple&fruits=banana"

Route can handle this:

path="/filter/:arr"

For Multiple arrays:

to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"

Route stays same.

SCREENSHOT

enter image description here

How to initialize java.util.date to empty

It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.

'JSON' is undefined error in JavaScript in Internet Explorer

Maybe it is not what you are looking for, but I had a similar problem and i solved it including JSON 2 to my application:

https://github.com/douglascrockford/JSON-js

Other browsers natively implements JSON but IE < 8 (also IE 8 compatibility mode) does not, that's why you need to include it.

Here is a related question: JSON on IE6 (IE7)

UPDATE

the JSON parser has been updated so you should use the new one: http://bestiejs.github.io/json3/

Random String Generator Returning Same String

Just for people stopping by and what to have a random string in just one single line of code

int yourRandomStringLength = 12; //maximum: 32
Guid.NewGuid().ToString("N").Substring(0, yourRandomStringLength);

PS: Please keep in mind that yourRandomStringLength cannot exceed 32 as Guid has max length of 32.

link_to image tag. how to add class to a tag

Just adding that you can pass the link_to method a block:

<%= link_to href: 'http://www.example.com/' do %>
    <%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>

results in:

<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
    <img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>

This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.

MySQL Workbench not displaying query results

I had the same issue. Using MySQL 6.1 Workbench.

After a while (2 mins), it just crashed. Reported bug, saved files and reopened. It works now.

I guess I would suggest if that happens again, to immediately save the open scripts, close MySQL and restart it.

How do I purge a linux mail box with huge number of emails?

alternative way:

mail -N
d *
quit

-N Inhibits the initial display of message headers when reading mail or editing a mail folder.
d * delete all mails

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

setTimeout loop problem with solution

_x000D_
_x000D_
// it will print 5 times 5._x000D_
for(var i=0;i<5;i++){_x000D_
setTimeout(()=> _x000D_
console.log(i), _x000D_
2000)_x000D_
}               // 5 5 5 5 5_x000D_
_x000D_
// improved using let_x000D_
for(let i=0;i<5;i++){_x000D_
setTimeout(()=> _x000D_
console.log('improved using let: '+i), _x000D_
2000)_x000D_
}_x000D_
_x000D_
// improved using closure_x000D_
for(var i=0;i<5;i++){_x000D_
((x)=>{_x000D_
setTimeout(()=> _x000D_
console.log('improved using closure: '+x), _x000D_
2000)_x000D_
})(i);_x000D_
} 
_x000D_
_x000D_
_x000D_

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

append multiple values for one key in a dictionary

You would be best off using collections.defaultdict (added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list).

So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.

A quick example using your data:

>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
...     d[year].append(month)
... 
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})

This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

Git cli: get user info from username

Try this

git config user.name

git config command stores and gives all the information.

git config -l

This commands gives you all the required info that you want.

You can change the information using

git config --global user.name "<Your-name>"

Similarly you can change many info shown to you using -l option.

Concatenate String in String Objective-c

Variations on a theme:

NSString *varying = @"whatever it is";
NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying];

NSString *varying = @"whatever it is";
NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendFormat:@"%@ third part", varying];

NSMutableString *final = [NSMutableString stringWithString:@"first part"];
[final appendString:varying];
[final appendString:@"third part"];

ASP.NET MVC passing an ID in an ActionLink to the controller

The ID will work with @ sign in front also, but we have to add one parameter after that. that is null

look like:

@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)

How to overload __init__ method based on argument type?

Quick and dirty fix

class MyData:
    def __init__(string=None,list=None):
        if string is not None:
            #do stuff
        elif list is not None:
            #do other stuff
        else:
            #make data empty

Then you can call it with

MyData(astring)
MyData(None, alist)
MyData()

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to iterate through property names of Javascript object?

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}

Multi-line strings in PHP

$xml="l" . PHP_EOL;
$xml.="vv";
echo $xml;

Will echo:

l
vv

Documentation on PHP_EOL.

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Converting String to Int using try/except in Python

Here it is:

s = "123"
try:
  i = int(s)
except ValueError as verr:
  pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
  pass # do job to handle: Exception occurred while converting to int

Animate the transition between fragments

For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

How to insert a value that contains an apostrophe (single quote)?

Single quotes are escaped by doubling them up,

The following SQL illustrates this functionality.

declare @person TABLE (
    [First] nvarchar(200),
    [Last] nvarchar(200)
)

insert into @person 
    (First, Last)
values
    ('Joe', 'O''Brien')

select * from @person

Results

First   | Last
===================
Joe     | O'Brien

Add animated Gif image in Iphone UIImageView

Swift 3:

As suggested above I'm using FLAnimatedImage with an FLAnimatedImageView. And I'm loading the gif as a data set from xcassets. This allows me to provide different gifs for iphone and ipad for appearance and app slicing purposes. This is far more performant than anything else I've tried. It's also easy to pause using .stopAnimating().

if let asset = NSDataAsset(name: "animation") {
    let gifData = asset.data
    let gif = FLAnimatedImage(animatedGIFData: gifData)
    imageView.animatedImage = gif
  }

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Returning data from Axios API

You can use Async - Await:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

How do I mount a remote Linux folder in Windows through SSH?

Dokan looks like a FUSE and sshfs implementation for Windows. If it works as expected and advertised, it would do exactly what you are looking for.

(Link updated and working 2015-10-15)

how can select from drop down menu and call javascript function

Greetings if i get you right you need a JavaScript function that doing it

function report(v) {
//To Do
  switch(v) {
    case "daily":
      //Do something
      break;
    case "monthly":
      //Do somthing
      break;
    }
  }

Regards

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

Adding a simple spacer to twitter bootstrap

My approach. Tricky, but works well for me

<p>&nbsp;</p>

How can I inspect element in chrome when right click is disabled?

Press F12 to Inspect Element and Ctrl+U to View Page Source

How to delete mysql database through shell command

Another suitable way:

$ mysql -u you -p
<enter password>

>>> DROP DATABASE foo;

first-child and last-child with IE8

If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

For me I switched a call for my collection view header where I was registering the nib to registering the class. That fixed it.

How to run a Runnable thread in Android at defined intervals?

If I understand correctly the documentation of Handler.post() method:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

So examples provided by @alex2k8, even though are working correctly, are not the same. In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT. After that, EDT only executes Runnable.run(), nothing else.

Remember: Runnable != Thread.

What does this thread join code mean?

For me, Join() behavior was always confusing because I was trying to remember who will wait for whom. Don't try to remember it that way.

Underneath, it is pure wait() and notify() mechanism.

We all know that, when we call wait() on any object(t1), calling object(main) is sent to waiting room(Blocked state).

Here, main thread is calling join() which is wait() under the covers. So main thread will wait until it is notified. Notification is given by t1 when it finishes it's run(thread completion).

After receiving the notification, main comes out of waiting room and proceeds it's execution.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

forEach loop Java 8 for Map entry set

Maybe the best way to answer the questions like "which version is faster and which one shall I use?" is to look to the source code:

map.forEach() - from Map.java

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

javadoc

map.entrySet().forEach() - from Iterable.java

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

javadoc

This immediately reveals that map.forEach() is also using Map.Entry internally. So I would not expect any performance benefit in using map.forEach() over the map.entrySet().forEach(). So in your case the answer really depends on your personal taste :)

For the complete list of differences please refer to the provided javadoc links. Happy coding!

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

How to add a changed file to an older (not last) commit in Git

with git 1.7, there's a really easy way using git rebase:

stage your files:

git add $files

create a new commit and re-use commit message of your "broken" commit

git commit -c master~4

prepend fixup! in the subject line (or squash! if you want to edit commit (message)):

fixup! Factored out some common XPath Operations

use git rebase -i --autosquash to fixup your commit

Make WPF Application Fullscreen (Cover startmenu)

When you're doing it by code the trick is to call

WindowStyle = WindowStyle.None;

first and then

WindowState = WindowState.Maximized;

to get it to display over the Taskbar.

What is the simplest way to SSH using Python?

For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.

import base64
import paramiko

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

This code was adapted from demo of https://github.com/paramiko/paramiko It works for me.

Dump all tables in CSV format using 'mysqldump'

It looks like others had this problem also, and there is a simple Python script now, for converting output of mysqldump into CSV files.

wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
mysqldump -u username -p --host=rdshostname database table | python mysqldump_to_csv.py > table.csv

How to get a list of installed android applications and pick one to run

Getting list of installed non-system apps

public static void installedApps()
{
    List<PackageInfo> packList = getPackageManager().getInstalledPackages(0);
    for (int i=0; i < packList.size(); i++)
    {
        PackageInfo packInfo = packList.get(i);
        if (  (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
        {
            String appName = packInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            Log.e("App ? " + Integer.toString(i), appName);
        }
    }
}

Check if key exists in JSON object using jQuery

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false

Mongoose delete array element in document and save

This is working for me and really very helpful.

SubCategory.update({ _id: { $in:
        arrOfSubCategory.map(function (obj) {
            return mongoose.Types.ObjectId(obj);
        })
    } },
    {
        $pull: {
            coupon: couponId,
        }
    }, { multi: true }, function (err, numberAffected) {
        if(err) {
            return callback({
                error:err
            })
        }
    })
});

I have a model which name is SubCategory and I want to remove Coupon from this category Array. I have an array of categories so I have used arrOfSubCategory. So I fetch each array of object from this array with map function with the help of $in operator.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

DO NOT Use GUID For Key

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) 
       Guid.NewGuid().ToString(), myScript, true);

and if you want to do that , call Something Like this function

 public static string GetGuidClear(string x)
 {
      return x.Replace("-", "").Replace("0", "").Replace("1", "")
              .Replace("2",  "").Replace("3", "").Replace("4", "")
              .Replace("5", "").Replace("6", "").Replace("7", "")
              .Replace("8", "").Replace("9", "");
 }

No visible cause for "Unexpected token ILLEGAL"

If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.

  1. In nginx.conf sendfile off

  2. uwsgi application / config --disable-sendfile

What is the use of verbose in Keras while validating the model?

verbose: Integer. 0, 1, or 2. Verbosity mode.

Verbose=0 (silent)

Verbose=1 (progress bar)

Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: 
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: 
0.8071 - val_loss: 0.4617 - val_acc: 0.8168

Verbose=2 (one line per epoch)

Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046

Convert Char to String in C

You could do many of the given answers, but if you just want to do it to be able to use it with strcpy, then you could do the following:

...
    strcpy( ... , (char[2]) { (char) c, '\0' } );
...

The (char[2]) { (char) c, '\0' } part will temporarily generate null-terminated string out of a character c.

This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.

Passing arguments to JavaScript function from code-behind

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call java script function on Code behind</title>
    <script  type="text/javascript">
    function abc()
    {
        var a=20;
        var b=30;
        alert("you enter"+a+":"+b);
    }
    </script>
</head>

cs code

protected void Page_Load(object sender, EventArgs e)
{
    TextBox2.Attributes.Add("onkeypress", "return abc();");
}

try this

JBoss default password

just commenting the line of user and password in file ./server/default/conf/props jmx-console-users.properties worked for me

Convert String to Double - VB

I simple used Eval(string) and it evaluated as Double.

Where is Maven's settings.xml located on Mac OS?

After I have downloaded the binary from apache site I, have placed the extracted folder in /Library
So now the location of the settings.xml file is in:

/Library/apache_maven_3.6.3/conf

Git Clone from GitHub over https with two-factor authentication

It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.

How to Authenticate Git using Access Tokens

  1. Go to https://github.com/settings/tokens
  2. Click Generate New Token button on top right.
  3. Give your token a descriptive name.
  4. Set all required permissions for the token.
  5. Click Generate token button at the bottom.
  6. Copy the generated token to a safe place.
  7. Use this token instead of password when you use git clone.

Wow, it works!

JSLint says "missing radix parameter"

You can also simply add this line right above your parseInt line:

// eslint-disable-next-line

This will disable eslint check for the next line. Use this if you only need to skip one or two lines.

Launch Image does not show up in my iOS App

I had the same issue after I started using Xcode 6.1 and changed my launcher images. I had all images in an Asset Catalog. I would get only a black screen instead of the expected static image. After trying so many things, I realised the problem was that the Asset Catalog had the Project 'Target Membership' ticked-off in its FileInspector view. Ticking it to ON did the magic and the image started to appear on App launch.

Git stash pop- needs merge, unable to refresh index

You need to add app.coffee to staging.

Do git add app.coffee and then you will be able to apply your stash (after that commit and push).

Is "else if" faster than "switch() case"?

Why do you care?

99.99% of the time, you shouldn't care.

These sorts of micro-optimizations are unlikely to affect the performance of your code.

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

Parse string to date with moment.js

  • How to change any string date to object date (also with moment.js):

let startDate = "2019-01-16T20:00:00.000"; let endDate = "2019-02-11T20:00:00.000"; let sDate = new Date(startDate); let eDate = new Date(endDate);

  • with moment.js:

startDate = moment(sDate); endDate = moment(eDate);

What is the difference between server side cookie and client side cookie?

HTTP COOKIES

Cookies are key/value pairs used by websites to store state information on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store information on the browser.

Browser request example:

GET /index.html HTTP/1.1
Host: www.example.com

Example answer from the server:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest  of the response

Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.

GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*

SESSIONS: Server side cookies

Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.

Examples of usage

You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...

Pros and Cons

Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.

Cookie Pros:

  • scalability: all the data is stored in the browser so each request can go through a load balancer to different webservers and you have all the information needed to fullfill the request;
  • they can be accessed via javascript on the browser;
  • not being on the server they will survive server restarts;
  • RESTful: requests don't depend on server state

Cookie Cons:

Session Pros:

  • generally easier to use, in PHP there's probably not much difference.
  • unlimited storage

Session Cons:

  • more difficult to scale
  • on web server restarts you can lose all sessions or not depending on the implementation
  • not RESTful

HTML <sup /> tag affecting line height, how to make it consistent?

I had the same problem and non of the given answers worked. But I found a git commit with a fix that did work for me:

sup {
  font-size: 0.8em;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
  top: -0.5em;
}

How to stop docker under Linux

The output of ps aux looks like you did not start docker through systemd/systemctl.

It looks like you started it with:

sudo dockerd -H gridsim1103:2376

When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

The correct way to start docker is to use systemd/systemctl:

systemctl enable docker
systemctl start docker

After this, docker should start on system start.

EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

Bloomberg Open API

Since the data is not free, you can use this Bloomberg API Emulator (disclaimer: it's my project) to learn how to send requests and make subscriptions. This emulator looks and acts just like the real Bloomberg API, although it doesn't return real data. In my time developing applications that use the Bloomberg API, I rarely care about the actual data that I'm handling; I care about how to retrieve data.

If you want to learn how to use the Bloomberg API give it a try. If you want to test out your code without an account, use this. A Bloomberg account costs about $2,000 a month, so you can save a lot with this project.

The emulator now supports Java and C++ in addition to C#.

C#, C++, and Java:

  • Intraday Tick Requests
  • Intraday Bar Requests
  • Reference Data Requests
  • Historical Data Requests
  • Market Data Subscriptions

Edit: Updated Project link, moved to github

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I use below code after js file include and it's working now.

<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
            jQuery.browser.msie = true;
            jQuery.browser.version = RegExp.$1;
        }
    })();
</script>

Removing all line breaks and adding them after certain text

  • Open Notepad++
  • Paste your text
  • Control + H

In the pop up

  • Find what: \r\n
  • Replace with: BLANK_SPACE

You end up with a big line. Then

  • Control + H

In the pop up

  • Find what: (\.)
  • Replace with: \r\n

So you end up with lines that end by dot

And if you have to do the same process lots of times

  • Go to Macro
  • Start recording
  • Do the process above
  • Go to Macro
  • Stop recording
  • Save current recorded macro
  • Choose a short cut
  • Select the text you want to apply the process (Control + A)
  • Do the shortcut

Adding a month to a date in T SQL

DATEADD is the way to go with this

See the W3Schools tutorial: http://www.w3schools.com/sql/func_dateadd.asp

What's the difference between :: (double colon) and -> (arrow) in PHP?

When the left part is an object instance, you use ->. Otherwise, you use ::.

This means that -> is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while :: is usually used to access static members (though in a few special cases, it's used to access instance members).

In general, :: is used for scope resolution, and it may have either a class name, parent, self, or (in PHP 5.3) static to its left. parent refers to the scope of the superclass of the class where it's used; self refers to the scope of the class where it's used; static refers to the "called scope" (see late static bindings).

The rule is that a call with :: is an instance call if and only if:

  • the target method is not declared as static and
  • there is a compatible object context at the time of the call, meaning these must be true:
    1. the call is made from a context where $this exists and
    2. the class of $this is either the class of the method being called or a subclass of it.

Example:

class A {
    public function func_instance() {
        echo "in ", __METHOD__, "\n";
    }
    public function callDynamic() {
        echo "in ", __METHOD__, "\n";
        B::dyn();
    }

}

class B extends A {
    public static $prop_static = 'B::$prop_static value';
    public $prop_instance = 'B::$prop_instance value';

    public function func_instance() {
        echo "in ", __METHOD__, "\n";
        /* this is one exception where :: is required to access an
         * instance member.
         * The super implementation of func_instance is being
         * accessed here */
        parent::func_instance();
        A::func_instance(); //same as the statement above
    }

    public static function func_static() {
        echo "in ", __METHOD__, "\n";
    }

    public function __call($name, $arguments) {
        echo "in dynamic $name (__call)", "\n";
    }

    public static function __callStatic($name, $arguments) {
        echo "in dynamic $name (__callStatic)", "\n";
    }

}

echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";

echo '$b->func_instance():', "\n", $b->func_instance(), "\n";

/* This is more tricky
 * in the first case, a static call is made because $this is an
 * instance of A, so B::dyn() is a method of an incompatible class
 */
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
 * instance of B (despite the fact we are in a method of A), so
 * B::dyn() is a method of a compatible class (namely, it's the
 * same class as the object's)
 */
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";

Output:

B::$prop_static: B::$prop_static value
B::func_static(): in B::func_static

$b->prop_instance: B::$prop_instance value
$b->func_static(): in B::func_static

$b->func_instance():
in B::func_instance
in A::func_instance
in A::func_instance

$a->dyn():
in A::callDynamic
in dynamic dyn (__callStatic)

$b->dyn():
in A::callDynamic
in dynamic dyn (__call)

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

Swift extract regex matches

This is how I did it, I hope it brings a new perspective how this works on Swift.

In this example below I will get the any string between []

var sample = "this is an [hello] amazing [world]"

var regex = NSRegularExpression(pattern: "\\[.+?\\]"
, options: NSRegularExpressionOptions.CaseInsensitive 
, error: nil)

var matches = regex?.matchesInString(sample, options: nil
, range: NSMakeRange(0, countElements(sample))) as Array<NSTextCheckingResult>

for match in matches {
   let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
    println("found= \(r)")
}

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

SIMPLY, You must set initial state first

If you don't set initial state react will treat that as an uncontrolled component

Operator overloading in Java

Or, you can make Java Groovy and just overload these functions to achieve what you want

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Both of them are ways of subsetting. The single bracket will return a subset of the list, which in itself will be a list. ie:It may or may not contain more than one elements. On the other hand a double bracket will return just a single element from the list.

-Single bracket will give us a list. We can also use single bracket if we wish to return multiple elements from the list. consider the following list:-

>r<-list(c(1:10),foo=1,far=2);

Now please note the way the list is returned when I try to display it. I type r and press enter

>r

#the result is:-

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

$foo

[1] 1

$far

[1] 2

Now we will see the magic of single bracket:-

>r[c(1,2,3)]

#the above command will return a list with all three elements of the actual list r as below

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

$foo

[1] 1


$far

[1] 2

which is exactly the same as when we tried to display value of r on screen, which means the usage of single bracket has returned a list, where at index 1 we have a vector of 10 elements, then we have two more elements with names foo and far. We may also choose to give a single index or element name as input to the single bracket. eg:

> r[1]

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

In this example we gave one index "1" and in return got a list with one element(which is an array of 10 numbers)

> r[2]

$foo

[1] 1

In the above example we gave one index "2" and in return got a list with one element

> r["foo"];

$foo

[1] 1

In this example we passed the name of one element and in return a list was returned with one element.

You may also pass a vector of element names like:-

> x<-c("foo","far")

> r[x];

$foo

[1] 1

$far
[1] 2

In this example we passed an vector with two element names "foo" and "far"

In return we got a list with two elements.

In short single bracket will always return you another list with number of elements equal to the number of elements or number of indices you pass into the single bracket.

In contrast, a double bracket will always return only one element. Before moving to double bracket a note to be kept in mind. NOTE:THE MAJOR DIFFERENCE BETWEEN THE TWO IS THAT SINGLE BRACKET RETURNS YOU A LIST WITH AS MANY ELEMENTS AS YOU WISH WHILE A DOUBLE BRACKET WILL NEVER RETURN A LIST. RATHER A DOUBLE BRACKET WILL RETURN ONLY A SINGLE ELEMENT FROM THE LIST.

I will site a few examples. Please keep a note of the words in bold and come back to it after you are done with the examples below:

Double bracket will return you the actual value at the index.(It will NOT return a list)

  > r[[1]]

     [1]  1  2  3  4  5  6  7  8  9 10


  >r[["foo"]]

    [1] 1

for double brackets if we try to view more than one elements by passing a vector it will result in an error just because it was not built to cater to that need, but just to return a single element.

Consider the following

> r[[c(1:3)]]
Error in r[[c(1:3)]] : recursive indexing failed at level 2
> r[[c(1,2,3)]]
Error in r[[c(1, 2, 3)]] : recursive indexing failed at level 2
> r[[c("foo","far")]]
Error in r[[c("foo", "far")]] : subscript out of bounds

Link and execute external JavaScript file hosted on GitHub

To make things clear and short

//raw.githubusercontent.com --> //rawgit.com

Note that this is handled by rawgit's development hosting and not their cdn for production hosting

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to determine the IP address of a Solaris system

/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'

This will list down the exact ip address for the machine

ip address validation in python using regex

The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:

[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Example:

your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Output:

>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Best way to define private methods for a class in Objective-C

You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables.

//.h file
@interface MyClass : Object
{
    int test;
}
- (void) someMethod: anArg;

@end


//.m file    
@implementation MyClass

static void somePrivateMethod (MyClass *myClass, id anArg)
{
    fprintf (stderr, "MyClass (%d) was passed %p", myClass->test, anArg);
}


- (void) someMethod: (id) anArg
{
    somePrivateMethod (self, anArg);
}

@end

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

Read carefully the warning message :

The POM for org.raml:jaxrs-code-generator:jar:2.0.0 is missing, no dependency information available

The problem is not the jar, but the pom.xml that is missing.
The pom.xml lists the required dependencies for this jar that Maven will pull during the build and overall the packaging of your application. So, you may really need it.

Note that this problem may of course occur for other Maven dependencies and the ideas to solve that is always the same.

The Mule website documents very well that in addition to some information related to.


How to solve ?

1) Quick workaround : looking for in the internet the pom.xml of the artifact

Googling the artifact id, the group id and its version gives generally interesting results : maven repository links to download it.
In the case of the org.raml:jaxrs-code-generator:jar:2.0.0 dependency, you can download the pom.xml from the Maven mule repository :

https://repository.mulesoft.org/nexus/content/repositories/releases/org/raml/jaxrs-code-generator/2.0.0/

2) Clean workaround for a single Maven project : adding the repository declaration in your pom.

In your case, add the Maven mule repositories :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-snapshots</id>
            <name>MuleSoft Snapshot Repository</name>
            <url>http://repository.mulesoft.org/snapshots/</url>
            <layout>default</layout>
        </repository>
    </repositories>
    ...
</project>

3) Clean workaround for any Maven projects : add the repository declaration in your settings.xml

 <profile> 
   <repositories>
    ...
    <repository>
      <id>mulesoft-releases</id>
      <name>MuleSoft Repository</name>
      <url>http://repository.mulesoft.org/releases/</url>
      <layout>default</layout>
    </repository>
    <repository>
      <id>mulesoft-snapshots</id>
      <name>MuleSoft Snapshot Repository</name>
      <url>http://repository.mulesoft.org/snapshots/</url>
      <layout>default</layout>
    </repository>
     ...
  </repositories>     
</profile>

Note that in some rare cases, the pom.xml declaring the dependencies is nowhere. So, you have to identify yourself whether the artifact requires dependencies.

Removing object from array in Swift 3

In Swift 5, Use this Extension:

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.firstIndex(of: element) {
            self.remove(at: i)
        }
    }
}

example:

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

In Swift 3, Use this Extension:

extension Array where Element: Equatable{
    mutating func remove (element: Element) {
        if let i = self.index(of: element) {
            self.remove(at: i)
        }
    }
}

example:

var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")

How can I simulate an anchor click via jquery?

I've recently found how to trigger mouse click event via jQuery.

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

Remove empty space before cells in UITableView

I just found a solution for this.

Just select tableview and clic Editor -> Arrange -> Send to Front

It worked for me and hope it helps you all.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

There might be two reasons:

  1. Have you opened the connection to the database prior to calling mysql_query function? I don't see that in your code. Use mysql_connect before making the query. See php.net/manual/en/function.mysql-connect.php

  2. The variable $username is used inside a single quote string, so its value will not be evaluated inside the query. The query will definitely fail.

Thirdly, the structure of query is prone to SQL injection. You may use prepared statements to avoid this security threat.

iOS Remote Debugging

Many remote consoles work fine. http://farjs.com is my project, and I was able to successfully debug issues specific to Crome iOS and not happening in safari using it. (and probably all other mobile browsers)

The problem is that injecting the debugging code is slightly tricky since Chrome doesn't allow you to install bookmarklets.

Instead you could open one tab on the page that you would debug, and another on farjs.com and then click "the bookmarklet"

Copy the bookmarklet JS code, get back to the first tab, with the page that should be debugged, and paste the bookmarklet code in the location bar.

Last step is to scroll to the beginning of the location bar and add "javascript:", since Chrome will remove it.

Find and Replace string in all files recursive using grep and sed

The GNU guys REALLY messed up when they introduced recursive file searching to grep. grep is for finding REs in files and printing the matching line (g/re/p remember?) NOT for finding files. There's a perfectly good tool with a very obvious name for FINDing files. Whatever happened to the UNIX mantra of do one thing and do it well?

Anyway, here's how you'd do what you want using the traditional UNIX approach (untested):

find /path/to/folder -type f -print |
while IFS= read -r file
do
   awk -v old="$oldstring" -v new="$newstring" '
      BEGIN{ rlength = length(old) }
      rstart = index($0,old) { $0 = substr($0,rstart-1) new substr($0,rstart+rlength) }
      { print }
   ' "$file" > tmp &&
   mv tmp "$file"
done

Not that by using awk/index() instead of sed and grep you avoid the need to escape all of the RE metacharacters that might appear in either your old or your new string plus figure out a character to use as your sed delimiter that can't appear in your old or new strings, and that you don't need to run grep since the replacement will only occur for files that do contain the string you want. Having said all of that, if you don't want the file timestamp to change if you don't modify the file, then just do a diff on tmp and the original file before doing the mv or throw in an fgrep -q before the awk.

Caveat: The above won't work for file names that contain newlines. If you have those then let us know and we can show you how to handle them.

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

WPF - add static items to a combo box

<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>