Programs & Examples On #Webbrowser control

This tag refers to the WebBrowser ActiveX Control (native) and for Windows Forms or WPF applications (.NET). This control "hosts Web pages and provides Web browsing capabilities to your application".

Load local HTML file in a C# WebBrowser

  1. Somewhere, nearby the assembly you're going to run.
  2. Use reflection to get path to your executing assembly, then do some magic to locate your HTML file.

Like this:

var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");

How to wait until WebBrowser is completely loaded in VB.NET?

I made similar function (only that works to me); sorry it is in C# but easy to translate...

private void WaitForPageLoad () {

     while (pageReady == false)
         Application.DoEvents();

     while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
}

C# how to wait for a webpage to finish loading before continuing

yuna and bnl code failed in the case below;

failing example:

1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");

//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

how to fix this unwanted situation:

usage

    public myForm1 {

        myForm1_load() { }

        // func to make browser wait is inside the Extended class More tidy.
        WebBrowserEX wbEX = new WebBrowserEX();

        button1_click(){
            wbEX.Navigate("site1.com");
            wbEX.waitWebBrowserToComplete(wb);

            wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
            //submit does navigation
            wbEX.Document.GetElementById("formid").InvokeMember("submit");
            wbEX.waitWebBrowserToComplete(wb);
            // this actually waits for document Compelete. worked for me.

            var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
            var rawHtml = wbEX.DocumentText;
         }
     }

//put this  extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
   //ctor
   WebBrowserEX()
   {
     //wired aumatically here. we dont need to worry our sweet brain.
     this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
   }
     //instead of checking  readState, get state from DocumentCompleted Event 
     // via bool value
     bool webbrowserDocumentCompleted = false;
     public void waitWebBrowserToComplete()
     {
       while (!webbrowserDocumentCompleted )
       { Application.DoEvents();  }
       webbrowserDocumentCompleted = false;
     }

 }

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

A note about 64bit Windows which seems to trip up a few folks. If your app is running under 64bit Windows, you likely have to set the DWORD under [HKLM\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION] instead.

Detect WebBrowser complete page loading

If you're using WPF there is a LoadCompleted event.

If it's Windows.Forms, the DocumentCompleted event should be the correct one. If the page you're loading has frames, your WebBrowser control will fire the DocumentCompleted event for each frame (see here for more details). I would suggest checking the IsBusy property each time the event is fired and if it is false then your page is fully done loading.

Disable JavaScript error in WebBrowser control

None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).

The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:

/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
/// 
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
/// 
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
    #region Constructor

    /// <summary>
    /// Default constructor.
    /// Initialise browser control and attach customer event handlers.
    /// </summary>
    public WebBrowserEx()
    {
        this.ScriptErrorsSuppressed = false;
    }

    #endregion

    #region Overrides

    /// <summary>
    /// Override to allow custom script error handling.
    /// </summary>
    /// <returns></returns>
    protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
        return new WebBrowserSiteEx(this);
    }

    #endregion

    #region Inner Class [WebBrowserSiteEx]

    /// <summary>
    /// Sub-class to allow custom script error handling.
    /// </summary>
    protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
        {   
        }

        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
        /// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
        {
            if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
            {   // Do nothing (suppress script errors)
                return NativeMethods.S_OK;
            }

            // Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
            return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
        }
    }

    #endregion
}

~

/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
    /// From docobj.h
    public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;

    /// <summary>
    /// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
    /// </summary>
    public enum OLECMDID
    {
        /// <summary />
        OLECMDID_OPEN = 1,
        /// <summary />
        OLECMDID_NEW,
        /// <summary />
        OLECMDID_SAVE,
        /// <summary />
        OLECMDID_SAVEAS,
        /// <summary />
        OLECMDID_SAVECOPYAS,
        /// <summary />
        OLECMDID_PRINT,
        /// <summary />
        OLECMDID_PRINTPREVIEW,
        /// <summary />
        OLECMDID_PAGESETUP,
        /// <summary />
        OLECMDID_SPELL,
        /// <summary />
        OLECMDID_PROPERTIES,
        /// <summary />
        OLECMDID_CUT,
        /// <summary />
        OLECMDID_COPY,
        /// <summary />
        OLECMDID_PASTE,
        /// <summary />
        OLECMDID_PASTESPECIAL,
        /// <summary />
        OLECMDID_UNDO,
        /// <summary />
        OLECMDID_REDO,
        /// <summary />
        OLECMDID_SELECTALL,
        /// <summary />
        OLECMDID_CLEARSELECTION,
        /// <summary />
        OLECMDID_ZOOM,
        /// <summary />
        OLECMDID_GETZOOMRANGE,
        /// <summary />
        OLECMDID_UPDATECOMMANDS,
        /// <summary />
        OLECMDID_REFRESH,
        /// <summary />
        OLECMDID_STOP,
        /// <summary />
        OLECMDID_HIDETOOLBARS,
        /// <summary />
        OLECMDID_SETPROGRESSMAX,
        /// <summary />
        OLECMDID_SETPROGRESSPOS,
        /// <summary />
        OLECMDID_SETPROGRESSTEXT,
        /// <summary />
        OLECMDID_SETTITLE,
        /// <summary />
        OLECMDID_SETDOWNLOADSTATE,
        /// <summary />
        OLECMDID_STOPDOWNLOAD,
        /// <summary />
        OLECMDID_ONTOOLBARACTIVATED,
        /// <summary />
        OLECMDID_FIND,
        /// <summary />
        OLECMDID_DELETE,
        /// <summary />
        OLECMDID_HTTPEQUIV,
        /// <summary />
        OLECMDID_HTTPEQUIV_DONE,
        /// <summary />
        OLECMDID_ENABLE_INTERACTION,
        /// <summary />
        OLECMDID_ONUNLOAD,
        /// <summary />
        OLECMDID_PROPERTYBAG2,
        /// <summary />
        OLECMDID_PREREFRESH,
        /// <summary />
        OLECMDID_SHOWSCRIPTERROR,
        /// <summary />
        OLECMDID_SHOWMESSAGE,
        /// <summary />
        OLECMDID_SHOWFIND,
        /// <summary />
        OLECMDID_SHOWPAGESETUP,
        /// <summary />
        OLECMDID_SHOWPRINT,
        /// <summary />
        OLECMDID_CLOSE,
        /// <summary />
        OLECMDID_ALLOWUILESSSAVEAS,
        /// <summary />
        OLECMDID_DONTDOWNLOADCSS,
        /// <summary />
        OLECMDID_UPDATEPAGESTATUS,
        /// <summary />
        OLECMDID_PRINT2,
        /// <summary />
        OLECMDID_PRINTPREVIEW2,
        /// <summary />
        OLECMDID_SETPRINTTEMPLATE,
        /// <summary />
        OLECMDID_GETPRINTTEMPLATE
    }

    /// <summary>
    /// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
    /// </summary>
    public const int S_OK = 0;

    /// <summary>
    /// OLE command structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class OLECMD
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdID;
        /// <summary>
        /// Flags associated with cmdID.
        /// </summary>
        [MarshalAs(UnmanagedType.U4)]
        public int cmdf;
    }

    /// <summary>
    /// Enables the dispatching of commands between objects and containers.
    /// </summary>
    [ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComImport]
    public interface IOleCommandTarget
    {
        /// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
        /// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
        /// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include the following.
        /// E_FAIL The operation failed.
        /// E_UNEXPECTED An unexpected error has occurred.
        /// E_POINTER The <paramref name="prgCmds" /> argument is null.
        /// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);

        /// <summary>Executes the specified command.</summary>
        /// <param name="pguidCmdGroup">The GUID of the command group.</param>
        /// <param name="nCmdID">The command ID.</param>
        /// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
        /// <param name="pvaIn">The input arguments of the command.</param>
        /// <param name="pvaOut">The output arguments of the command.</param>
        /// <returns>This method returns S_OK on success. Other possible return values include 
        /// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
        /// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
        /// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
        /// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
        /// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
        [PreserveSig]
        [return: MarshalAs(UnmanagedType.I4)]
        int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
    }
}

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Use latest version of Internet Explorer in the webbrowser control

Visual Basic Version:

Private Sub setRegisterForWebBrowser()

    Dim appName = Process.GetCurrentProcess().ProcessName + ".exe"
    SetIE8KeyforWebBrowserControl(appName)
End Sub

Private Sub SetIE8KeyforWebBrowserControl(appName As String)
    'ref:    http://stackoverflow.com/questions/17922308/use-latest-version-of-ie-in-webbrowser-control
    Dim Regkey As RegistryKey = Nothing
    Dim lgValue As Long = 8000
    Dim strValue As Long = lgValue.ToString()

    Try

        'For 64 bit Machine 
        If (Environment.Is64BitOperatingSystem) Then
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\MAIN\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
        Else  'For 32 bit Machine 
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", True)
        End If


        'If the path Is Not correct Or 
        'If user't have priviledges to access registry 
        If (Regkey Is Nothing) Then

            MessageBox.Show("Application Settings Failed - Address Not found")
            Return
        End If


        Dim FindAppkey As String = Convert.ToString(Regkey.GetValue(appName))

        'Check if key Is already present 
        If (FindAppkey = strValue) Then

            MessageBox.Show("Required Application Settings Present")
            Regkey.Close()
            Return
        End If


        'If key Is Not present add the key , Kev value 8000-Decimal 
        If (String.IsNullOrEmpty(FindAppkey)) Then
            ' Regkey.SetValue(appName, BitConverter.GetBytes(&H1F40), RegistryValueKind.DWord)
            Regkey.SetValue(appName, lgValue, RegistryValueKind.DWord)

            'check for the key after adding 
            FindAppkey = Convert.ToString(Regkey.GetValue(appName))
        End If

        If (FindAppkey = strValue) Then
            MessageBox.Show("Registre de l'application appliquée avec succès")
        Else
            MessageBox.Show("Échec du paramètrage du registre, Ref: " + FindAppkey)
        End If
    Catch ex As Exception


        MessageBox.Show("Application Settings Failed")
        MessageBox.Show(ex.Message)

    Finally

        'Close the Registry 
        If (Not Regkey Is Nothing) Then
            Regkey.Close()
        End If
    End Try
End Sub

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

How to inject Javascript in WebBrowser control?

I used this :D

HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT");
script.SetAttribute("TEXT", "function GetNameFromBrowser() {" + 
"return 'My name is David';" + 
"}");

this.WebNavegador.Document.Body.AppendChild(script);

Then you can execute and get the result with:

string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser");

I hope to be helpful

Replacing .NET WebBrowser control with a better browser, like Chrome?

Chrome uses (a fork of) Webkit if you didn't know, which is also used by Safari. Here's a few questions that are of the same vein:

The webkit one isn't great as the other answer states, one version no longer works (the google code one) and the Mono one is experimental. It'd be nice if someone made the effort to make a decent .NET wrapper for it but it's not something anyone seems to want to do - which is surprising given it now has support for HTML5 and so many other features that the IE(8) engine lacks.

Update (2014)

There's new dual-licensed project that allows you embed Chrome into your .NET applications called Awesomium. It comes with a .NET api but requires quite a few hacks for rendering (the examples draw the browser window to a buffer, paint the buffer as an image and refresh on a timer).

I think this is the browser used by Origin in Battlefield 3.

Update (2016)

There is now DotnetBrowser, a commercial alternative to Awesomium. It's based off Chromium.

Difference between F5, Ctrl + F5 and click on refresh button?

I did small research regarding this topic and found different behavior for the browsers:

enter image description here

See my blog post "Behind refresh button" for more details.

how to add css class to html generic control div?

dynDiv.Attributes["class"] = "myCssClass";

Converting between datetime and Pandas Timestamp objects

You can use the to_pydatetime method to be more explicit:

In [11]: ts = pd.Timestamp('2014-01-23 00:00:00', tz=None)

In [12]: ts.to_pydatetime()
Out[12]: datetime.datetime(2014, 1, 23, 0, 0)

It's also available on a DatetimeIndex:

In [13]: rng = pd.date_range('1/10/2011', periods=3, freq='D')

In [14]: rng.to_pydatetime()
Out[14]:
array([datetime.datetime(2011, 1, 10, 0, 0),
       datetime.datetime(2011, 1, 11, 0, 0),
       datetime.datetime(2011, 1, 12, 0, 0)], dtype=object)

How to join multiple collections with $lookup in mongodb

First add the collections and then apply lookup on these collections. Don't use $unwind as unwind will simply separate all the documents of each collections. So apply simple lookup and then use $project for projection. Here is mongoDB query:

db.userInfo.aggregate([
    {
        $lookup: {
           from: "userRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $lookup: {
            from: "userInfo",
            localField: "userId",
            foreignField: "userId",
            as: "userInfo"
        }
    },
    {$project: {
        "_id":0,
        "userRole._id":0,
        "userInfo._id":0
        }
        } ])

Here is the output:

/* 1 */ {
    "userId" : "AD",
    "phone" : "0000000000",
    "userRole" : [ 
        {
            "userId" : "AD",
            "role" : "admin"
        }
    ],
    "userInfo" : [ 
        {
            "userId" : "AD",
            "phone" : "0000000000"
        }
    ] }

Thanks.

Min and max value of input in angular4 application

Simply do this in angular2+ by adding (onkeypress)

<input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (onkeypress)="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
    name="rateInput">

Tested on Angular 7

How is a CRC32 checksum calculated?

In order to reduce crc32 to taking the reminder you need to:

  1. Invert bits on each byte
  2. xor first four bytes with 0xFF (this is to avoid errors on the leading 0s)
  3. Add padding at the end (this is to make the last 4 bytes take part in the hash)
  4. Compute the reminder
  5. Reverse the bits again
  6. xor the result again.

In code this is:


func CRC32 (file []byte) uint32 {
    for i , v := range(file) {
        file[i] = bits.Reverse8(v)
    }
    for i := 0; i < 4; i++ {
        file[i] ^= 0xFF
    }

    // Add padding
    file = append(file, []byte{0, 0, 0, 0}...)
    newReminder := bits.Reverse32(reminderIEEE(file))

    return newReminder ^ 0xFFFFFFFF
}

where reminderIEEE is the pure reminder on GF(2)[x]

Convert pandas data frame to series

You can retrieve the series through slicing your dataframe using one of these two methods:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html

import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randn(1,8))

series1=df.iloc[0,:]
type(series1)
pandas.core.series.Series

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

How to merge multiple dicts with same key or different key?

Here is one approach you can use which would work even if both dictonaries don't have same keys:

d1 = {'a':'test','b':'btest','d':'dreg'}
d2 = {'a':'cool','b':'main','c':'clear'}

d = {}

for key in set(d1.keys() + d2.keys()):
    try:
        d.setdefault(key,[]).append(d1[key])        
    except KeyError:
        pass

    try:
        d.setdefault(key,[]).append(d2[key])          
    except KeyError:
        pass

print d

This would generate below input:

{'a': ['test', 'cool'], 'c': ['clear'], 'b': ['btest', 'main'], 'd': ['dreg']}

How to restart adb from root to user mode?

For quick steps just check summary. If interested to know details, go on to read below.

adb is a daemon. Doing ps adb we can see its process.

shell@grouper:/ $ ps adb
USER     PID   PPID  VSIZE  RSS     WCHAN    PC        NAME
shell     133   1     4636   212   ffffffff 00000000 S /sbin/adbd

I just checked what additional property variables it is using when adb is running as root and user.

adb user mode :

shell@grouper:/ $ getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

adb root mode :

shell@grouper:/ # getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[service.adb.root]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

We can see that service.adb.root is a new prop variable that came up when we did adb root.

So, to change back adb to user from root, I went ahead and made this 0

setprop service.adb.root 0

But this did not change anything.

Then I went ahead and killed the process (with an intention to restart the process). The pid of adbd process in my device is 133

kill -9 133

I exited from shell automatically after I had killed the process.

I did adb shell again it was in user mode.

SUMMARY :

So, we have 3 very simple steps.

  1. Enter adb shell as a root.
  2. setprop service.adb.root 0
  3. kill -9 (pid of adbd)

After these steps just re-enter the shell with adb shell and you are back on your device as a user.

Apache POI error loading XSSFWorkbook class

If you have downloaded pio-3.17 On eclipse: right click on the project folder -> build path -> configure build path -> libraries -> add external jars -> add all the commons jar file from the "lib". It's worked for me.

Make Vim show ALL white spaces as a character

As others have said, you could use

:set list

which will, in combination with

:set listchars=...

display invisible characters.
Now, there isn't an explicit option which you can use to show whitespace, but in listchars, you could set a character to show for everything BUT whitespace. For example, mine looks like this

:set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<

so, now, after you use

:set list

everything that isn't explicitly shown as something else, is then, really, a plain old whitespace.

As usual, to understand how listchars works, use the help. It provides great information about what chars can be displayed (like trailing space, for instance) and how to do it:

:help listchars

It might be helpful to add a toggle to it so you can see the changes mid editing easily (source: VIM :set list! as a toggle in .vimrc):

noremap <F5> :set list!<CR>
inoremap <F5> <C-o>:set list!<CR>
cnoremap <F5> <C-c>:set list!<CR>

How to switch text case in visual studio code

I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case

To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}




EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.

How do I generate sourcemaps when using babel and webpack?

On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.

https://webpack.js.org/configuration/devtool

devtool best dev options

                                build   rebuild      quality                       look
eval-source-map                 slow    pretty fast  original source               worst
inline-source-map               slow    slow         original source               medium
cheap-module-eval-source-map    medium  fast         original source (lines only)  worst
inline-cheap-module-source-map  medium  pretty slow  original source (lines only)  best

lines only

Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.

REVISITING THIS

On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s

PHP: Get key from array?

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

Reading a resource file from within jar

I had this problem before and I made fallback way for loading. Basically first way work within .jar file and second way works within eclipse or other IDE.

public class MyClass {

    public static InputStream accessFile() {
        String resource = "my-file-located-in-resources.txt";

        // this is the path within the jar file
        InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource);
        if (input == null) {
            // this is how we load file within editor (eg eclipse)
            input = MyClass.class.getClassLoader().getResourceAsStream(resource);
        }

        return input;
    }
}

Check Whether a User Exists

I like this nice one line solution

getent passwd username > /dev/null 2&>1 && echo yes || echo no

and in script:

#!/bin/bash

if [ "$1" != "" ]; then
        getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
else
        echo "missing username"
        exit -1
fi

use:

[mrfish@yoda ~]$ ./u_exists.sh root
yes
[mrfish@yoda ~]$ echo $?
0

[mrfish@yoda ~]$ ./u_exists.sh
missing username
[mrfish@yoda ~]$ echo $?
255

[mrfish@yoda ~]$ ./u_exists.sh aaa
no
[mrfish@indegy ~]$ echo $?
2

moment.js get current time in milliseconds?

var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.

'Conda' is not recognized as internal or external command

I was faced with the same issue in windows 10, Updating the environment variable following steps, it's working fine.

I know It is a lengthy answer for the simple environment setups, I thought it's may be useful for the new window 10 users.

1) Open Anaconda Prompt:

enter image description here

2) Check Conda Installed Location.

where conda

enter image description here

3) Open Advanced System Settings

enter image description here

4) Click on Environment Variables

enter image description here

5) Edit Path

enter image description here

6) Add New Path

 C:\Users\RajaRama\Anaconda3\Scripts

 C:\Users\RajaRama\Anaconda3

 C:\Users\RajaRama\Anaconda3\Library\bin

enter image description here

7) Open Command Prompt and Check Versions

8) After 7th step type conda install anaconda-navigator in cmd then press y

enter image description here

Git: How to find a deleted file in the project commit history?

Could not edit the accepted response so adding it as an answer here,

to restore the file in git, use the following (note the '^' sign just after the SHA)

git checkout <SHA>^ -- /path/to/file

How to uninstall Golang?

sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

This is perfect for Ubuntu 18.18

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.

This will simply solve your problem.

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

As a quick workaround I just saved the workbook as an Excel 97-2003 .xls file. I was able to import with that format with no error.

CSS opacity only to background color, not the text on it?

The easiest solution is to create 3 divs. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.

C# DLL config file

I had the same problem and searched the web for several hours but I couldn't find any solution so I made my own. I wondered why the .net configuration system is so inflexible.

Background: I want to have my DAL.dll to have its own config file for database and DAL settings. I also need the app.config for Enterprise Library and its own configurations. So I need both the app.config and dll.config.

What I did not wanted to do is pass-through every property/setting from the app to my DAL layer!

to bend the "AppDomain.CurrentDomain.SetupInformation.ConfigurationFile" is not possible because I need it for the normal app.config behavior.

My requirements/point of views were:

  • NO manual copy of anything from ClassLibrary1.dll.config to WindowsFormsApplication1.exe.config because this is unreproducible for other developers.
  • retain the usage of strong typing "Properties.Settings.Default.NameOfValue" (Settings behavior) because I think this is a major feature and I didn't want to lose it
  • I found out the lack of ApplicationSettingsBase to inject your own/custom config file or management (all necessary fields are private in these classes)
  • the usage of "configSource" file redirection is not possible because we would have to copy/rewrite the ClassLibrary1.dll.config and provide several XML files for several sections (I also didn't like this)
  • I didn't like to write my own SettingsProvider for this simple task as MSDN suggests because I thought that simply would be too much
  • I only need sections applicationSettings and connectionStrings from the config file

I came up with modifying the Settings.cs file and implemented a method that opens the ClassLibrary1.dll.config and reads the section information in a private field. After that, I've overriden "this[string propertyName]" so the generated Settings.Desginer.cs calls into my new Property instead of the base class. There the setting is read out of the List.

Finally there is the following code:

internal sealed partial class Settings
{
    private List<ConfigurationElement> list;

    /// <summary>
    /// Initializes a new instance of the <see cref="Settings"/> class.
    /// </summary>
    public Settings()
    {
        this.OpenAndStoreConfiguration();
    }

    /// <summary>
    /// Opens the dll.config file and reads its sections into a private List of ConfigurationElement.
    /// </summary>
    private void OpenAndStoreConfiguration()
    {
        string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
        Uri p = new Uri(codebase);
        string localPath = p.LocalPath;
        string executingFilename = System.IO.Path.GetFileNameWithoutExtension(localPath);
        string sectionGroupName = "applicationSettings";
        string sectionName = executingFilename + ".Properties.Settings";
        string configName = localPath + ".config";
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = configName;
        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

        // read section of properties
        var sectionGroup = config.GetSectionGroup(sectionGroupName);
        var settingsSection = (ClientSettingsSection)sectionGroup.Sections[sectionName];
        list = settingsSection.Settings.OfType<ConfigurationElement>().ToList();

        // read section of Connectionstrings
        var sections = config.Sections.OfType<ConfigurationSection>();
        var connSection = (from section in sections
                           where section.GetType() == typeof(ConnectionStringsSection)
                           select section).FirstOrDefault() as ConnectionStringsSection;
        if (connSection != null)
        {
            list.AddRange(connSection.ConnectionStrings.Cast<ConfigurationElement>());
        }
    }

    /// <summary>
    /// Gets or sets the <see cref="System.Object"/> with the specified property name.
    /// </summary>
    /// <value></value>
    public override object this[string propertyName]
    {
        get
        {
            var result = (from item in list
                         where Convert.ToString(item.ElementInformation.Properties["name"].Value) == propertyName
                         select item).FirstOrDefault();
            if (result != null)
            {
                if (result.ElementInformation.Type == typeof(ConnectionStringSettings))
                {
                    return result.ElementInformation.Properties["connectionString"].Value;
                }
                else if (result.ElementInformation.Type == typeof(SettingElement))
                {
                    return result.ElementInformation.Properties["value"].Value;
                }
            }
            return null;
        }
        // ignore
        set
        {
            base[propertyName] = value;
        }
    }

You just will have to copy your ClassLibrary1.dll.config from the ClassLibrary1 output directory to your application's output directory. Perhaps someone will find it useful.

Best way to verify string is empty or null

To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:

if(myString==null || myString.isEmpty()){
    //do something
}

or if blank spaces need to be detected as well:

if(myString==null || myString.trim().isEmpty()){
    //do something
}

you could easily wrap these into utility methods to be more concise since these are very common checks to make:

public final class StringUtils{

    private StringUtils() { }   

    public static bool isNullOrEmpty(string s){
        if(s==null || s.isEmpty()){
            return true;
        }
        return false;
    }

    public static bool isNullOrWhiteSpace(string s){
        if(s==null || s.trim().isEmpty()){
            return true;
        }
        return false;
    }
}

and then call these methods via:

if(StringUtils.isNullOrEmpty(myString)){...}

and

if(StringUtils.isNullOrWhiteSpace(myString)){...}

Oracle date difference to get number of years

I had to implement a year diff function which works similarly to datediff. In that case the real year difference is counted, not the rounded day difference. So if there are two dates separated by one day, the year difference can be 1 (see select datediff(year, '20141231', '20150101')).

If the year diff has to be counted this way then use:

EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)

Just for the log the (almost) complete datediff function:

CREATE OR REPLACE FUNCTION datediff (datepart IN VARCHAR2, date_from IN DATE, date_to IN DATE)
RETURN NUMBER
AS
  diff NUMBER;
BEGIN
  diff :=  CASE datepart
    WHEN 'day'   THEN TRUNC(date_to,'DD') - TRUNC(date_from, 'DD')
    WHEN 'week'  THEN (TRUNC(date_to,'DAY') - TRUNC(date_from, 'DAY')) / 7
    WHEN 'month' THEN MONTHS_BETWEEN(TRUNC(date_to, 'MONTH'), TRUNC(date_from, 'MONTH'))
    WHEN 'year'  THEN EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)
  END;
  RETURN diff;
END;";

Sublime 3 - Set Key map for function Goto Definition

For anyone else who wants to set Eclipse style goto definition, you need to create .sublime-mousemap file in Sublime User folder.

Windows - create Default (Windows).sublime-mousemap in %appdata%\Sublime Text 3\Packages\User

Linux - create Default (Linux).sublime-mousemap in ~/.config/sublime-text-3/Packages/User

Mac - create Default (OSX).sublime-mousemap in ~/Library/Application Support/Sublime Text 3/Packages/User

Now open that file and put the following configuration inside

[
    {
        "button": "button1", 
        "count": 1, 
        "modifiers": ["ctrl"],
        "press_command": "drag_select",
        "command": "goto_definition"
    }
]

You can change modifiers key as you like.


Since Ctrl-button1 on Windows and Linux is used for multiple selections, adding a second modifier key like Alt might be a good idea if you want to use both features:

[
    {
        "button": "button1", 
        "count": 1, 
        "modifiers": ["ctrl", "alt"],
        "press_command": "drag_select",
        "command": "goto_definition"
    }
]

Alternatively, you could use the right mouse button (button2) with Ctrl alone, and not interfere with any built-in functions.

Add a column with a default value to an existing table in SQL Server

ALTER TABLE <YOUR_TABLENAME>
ADD <YOUR_COLUMNNAME> <DATATYPE> <NULL|NOT NULL> 
ADD CONSTRAINT <CONSTRAINT_NAME>   ----OPTIONAL
DEFAULT <DEFAULT_VALUE>

If you are not giving constrain name then sql server use default name for this.

Example:-

ALTER TABLE TEMP_TABLENAME
ADD COLUMN1 NUMERIC(10,0) NOT NULL
ADD CONSTRAINT ABCDE   ----OPTIONAL
DEFAULT (0)

BACKUP LOG cannot be performed because there is no current database backup

I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.

android:layout_height 50% of the screen size

it's so easy if you want divide your screen two part vertically ( top30% + bottom70%)

<LinearLayout
            android:id="@+id/LinearLayoutTop"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="2">

     </LinearLayout>
     <LinearLayout
            android:id="@+id/LinearLayoutBottom"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">

     </LinearLayout>

Add element to a list In Scala

Use import scala.collection.mutable.MutableList or similar if you really need mutation.

import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)

How to git commit a single file/directory

If you are in the folder which contains the file

git commit -m 'my notes' ./name_of_file.ext

Java associative-array

You can accomplish this via Maps. Something like

Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");

But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do

class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);

Git Clone from GitHub over https with two-factor authentication

To everyone struggling, what worked for me was creating personal access token and then using it as a username AND password (in the prompt that opened).

How to create a Jar file in Netbeans

I also tried to make an executable jar file that I could run with the following command:

java -jar <jarfile>

After some searching I found the following link:

Packaging and Deploying Desktop Java Applications

I set the project's main class:

  1. Right-click the project's node and choose Properties
  2. Select the Run panel and enter the main class in the Main Class field
  3. Click OK to close the Project Properties dialog box
  4. Clean and build project

Then in the fodler dist the newly created jar should be executable with the command I mentioned above.

How to remove item from array by value?

ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

Validating URL in Java

You need to create both a URL object and a URLConnection object. The following code will test both the format of the URL and whether a connection can be established:

try {
    URL url = new URL("http://www.yoursite.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}

Convert a string representation of a hex dump to a byte array using Java?

The Hex class in commons-codec should do that for you.

http://commons.apache.org/codec/

import org.apache.commons.codec.binary.Hex;
...
byte[] decoded = Hex.decodeHex("00A0BF");
// 0x00 0xA0 0xBF

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

Passing null arguments to C# methods

You can use NullableValueTypes (like int?) for this. The code would be like this:

private void Example(int? arg1, int? arg2)
{
    if(!arg1.HasValue)
    {
        //do something
    }
    if(!arg2.HasValue)
    {
        //do something else
    }
}

Correct way to use get_or_create?

get_or_create() returns a tuple:

customer.source, created  = Source.objects.get_or_create(name="Website")
  • created ? has a boolean value, is created or not.

  • customer.source ? has an object of get_or_create() method.

How to use regex in XPath "contains" function

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

How can I Remove .DS_Store files from a Git repository?

When initializing your repository, skip the git command that contains

-u

and it shouldn't be an issue.

Hide HTML element by id

<style type="text/css">
  #nav-ask{ display:none; }
</style>

How to set the opacity/alpha of a UIImage?

Set the opacity of its view it is showed in.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0

Use this in an animation. You can change the alpha in an animation for an duration.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];

Can't change z-index with JQuery

That's invalid Javascript syntax; a property name cannot have a -.

Use either zIndex or "z-index".

How to validate white spaces/empty spaces? [Angular 2]

In your app.component.html

<form [formGroup]="signupForm">

           <input  type="text" name="name" [formControl]="signupForm.controls['name']"
              placeholder="First Name"
              required
            />
     <small
            *ngIf="signupForm.controls['name'].hasError('pattern')"
            class="form-error-msg"
            >First Name without space</small>

    </form>

In your app.componen.ts file

import { Validators, FormGroup, FormControl } from "@angular/forms";
signupForm: FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
  name: new FormControl("", [
    Validators.required,
    Validators.pattern("^[a-zA-Z]+$"),
    Validators.minLength(3)
  ])
})

How to emulate GPS location in the Android Emulator?

Assuming you've got a mapview set up and running:

MapView mapView = (MapView) findViewById(R.id.mapview);
final MyLocationOverlay myLocation = new MyLocationOverlay(this, mapView);

mapView.getOverlays().add(myLocation);
myLocation.enableMyLocation();

myLocation.runOnFirstFix(new Runnable() {
    public void run() {
        GeoPoint pt = myLocation.getMyLocation();
    }
});

You'll need the following permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

And to send mock coordinates to the emulator from Eclipse, Go to the "Window" menu, select "Show View" > "Other" > "Emulator control", and you can send coordinates from the emulator control pane that appears.

How do I determine if a port is open on a Windows server?

If you're checking from the outside, not from the server itself, and you don't want to bother installing telnet (as it doesn't come with the last versions of Windows) or any other software, then you have native PowerShell:

Test-NetConnection -Port 800 -ComputerName 192.168.0.1 -InformationLevel Detailed

(Unfortunately this only works with PowerShell 4.0 or newer. To check your PowerShell version, type $PSVersionTable.)

PS: Note, these days there are some claims on the twittersphere that hint that this answer could be improved by mentioning "Test-Connection" from PowerShell Core, or the shortcut "tnc". See https://twitter.com/david_obrien/status/1214082339203993600 and help me edit this answer to improve it please!


(If you have a PSVersion < 4.0, you're out of luck. Check this table:

Enter image description here

Even though you can upgrade your version of PowerShell by installing the Windows Management Framework 4.0, it didn't do the trick for me, Test-NetConnection cmdlet is still not available).

How can I set response header on express.js assets

_x000D_
_x000D_
service.use(function(req, res, next) {_x000D_
    res.header("Access-Control-Allow-Origin", "*");_x000D_
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");_x000D_
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");_x000D_
    next();_x000D_
  });
_x000D_
_x000D_
_x000D_

Convert Map<String,Object> to Map<String,String>

The following will transform your existing entries.

TransformedMap.decorateTransform(params, keyTransformer, valueTransformer)

Where as

MapUtils.transformedMap(java.util.Map map, keyTransformer, valueTransformer)

only transforms new entries into your map

Get a pixel from HTML Canvas?

Note that getImageData returns a snapshot. Implications are:

  • Changes will not take effect until subsequent putImageData
  • getImageData and putImageData calls are relatively slow

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.

The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.

In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.

My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

Get table column names in MySQL?

$col = $db->query("SHOW COLUMNS FROM category");

while ($fildss = $col->fetch_array())
{             
    $filds[] = '"{'.$fildss['Field'].'}"';
    $values[] = '$rows->'.$fildss['Field'].'';
}

if($type == 'value')
{
    return $values = implode(',', $values);
}
else {
     return $filds = implode(',', $filds);
}

How do I query for all dates greater than a certain date in SQL Server?

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

Java collections maintaining insertion order

Why is it necessary to maintain the order of insertion? If you use HashMap, you can get the entry by key. It does not mean it does not provide classes that do what you want.

Asynchronous method call in Python?

It's not in the language core, but a very mature library that does what you want is Twisted. It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually.

Python 3 ImportError: No module named 'ConfigParser'

For me the following command worked:

sudo python3 -m pip install mysql-connector

Why doesn't TFS get latest get the latest?

Every time this happens to me (so far) is because I have local edits pending on the .csproj project file. That file seems to keep a list of all the files included in the project. Any new files added by somebody else are "not downloaded" because they are not in my locally edited (now stale) project file. To get all the files I first have to undo pending changes to the .csproj file first then "get all". I do not have to undo other changes I have made, but I may have to go back and include my new files again (and then the next guy gets the same problem when he tries to "get all"...)

It seems to me there is some fundamental kludginess when multiple people are adding new files at the same time.

(this is in .Net Framework projects, maybe the other frameworks like Core behave differently)

OnChange event using React JS for drop down

import React, { PureComponent, Fragment } from 'react';
import ReactDOM from 'react-dom';

class Select extends PureComponent {
  state = {
    options: [
      {
        name: 'Select…',
        value: null,
      },
      {
        name: 'A',
        value: 'a',
      },
      {
        name: 'B',
        value: 'b',
      },
      {
        name: 'C',
        value: 'c',
      },
    ],
    value: '?',
  };

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  };

  render() {
    const { options, value } = this.state;

    return (
      <Fragment>
        <select onChange={this.handleChange} value={value}>
          {options.map(item => (
            <option key={item.value} value={item.value}>
              {item.name}
            </option>
          ))}
        </select>
        <h1>Favorite letter: {value}</h1>
      </Fragment>
    );
  }
}

ReactDOM.render(<Select />, window.document.body);

Two dimensional array in python

In my case I had to do this:

for index, user in enumerate(users):
    table_body.append([])
    table_body[index].append(user.user.id)
    table_body[index].append(user.user.username)

Output:

[[1, 'john'], [2, 'bill']]

How to concatenate multiple lines of output to one line?

This is an example which produces output separate by commas. You can replace the comma by whatever separator you need.

cat <<EOD | xargs | sed 's/ /,/g'
> 1
> 2
> 3
> 4
> 5
> EOD

produces:

1,2,3,4,5

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Homebrew refusing to link OpenSSL

After trying everything I could find and nothing worked, I just tried this:

touch ~/.bash_profile; open ~/.bash_profile

Inside the file added this line.

export PATH="$PATH:/usr/local/Cellar/openssl/1.0.2j/bin/openssl"

now it works :)

Jorns-iMac:~ jorn$ openssl version -a
OpenSSL 1.0.2j  26 Sep 2016
built on: reproducible build, date unspecified
//blah blah
OPENSSLDIR: "/usr/local/etc/openssl"

Jorns-iMac:~ jorn$ which openssl
/usr/local/opt/openssl/bin/openssl

Query Mongodb on month, day, year... of a datetime

You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression

db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })

or simply

db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})

(But i prefer the first one)

Check out the below shell commands to get the parts of date

>date = ISODate("2011-09-25T10:12:34Z")
> date.getYear()
111
> date.getMonth()
8
> date.getdate()
25

EDIT:

Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.

and check out the link $where Clauses and Functions in Queries for more info

How to embed HTML into IPython output?

This seems to work for me:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

The trick is to wrap it in "display" as well.

Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

How to serialize an Object into a list of URL query parameters?

ES2017 approach

Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&')

jQuery add required to input fields

$("input").prop('required',true);

DEMO FIDDLE

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

Visual Studio Code always asking for git credentials

The following steps walk you through how to:

  1. Generate SSH keys (without passphrase**)
  2. Add the public key generated in step 1 to your Git repository
  3. Confirm the above steps have been completed successfully
  4. Make your first commit (without having to provide a username / password)

**Generating SSH keys without a passphrase is unwise if your work is particularly sensitive.

OS - Fedora 28 | Editor - VS Code v1.23.0 | Repository - Git

Generate SSH keys:

  • ssh-keygen -t rsa -C "[email protected]"
  • Enter file in which to save the key: Press Enter
  • Enter passphrase: Press Enter
  • Enter same passphrase again: Press Enter

After completing the above steps, the location of your public key is shown in the terminal window. If the currently logged in user is 'bob' the location of your public key would be /home/bob/.ssh/id_rsa.pub

Copy and import public key to GitHub:

  • cat /home/bob/.ssh/id_rsa.pub

  • Copy the whole public key that is now displayed in your terminal window to the clipboard

  • Go to https://github.com and sign in
  • Click the user icon in the top right corner of the screen and select Settings
  • Click SSH and GPG keys
  • Click New SSH key
  • Enter a title, paste the public key copied to the clipboard in the first bullet point, and click Add SSH key

Confirm the above steps:

  • ssh -T [email protected]

  • yes

  • Hi ! You've successfully authenticated, but GitHub does not provide shell access.

First commit / push without having to enter a username / password: - touch test.txt

  • git add test.txt

  • git commit - opens editor, enter a message and save the file. If vi is your editor, press i once the file opens, enter a message, press esc, and then enter :x to save changes.

  • git push

The only hiccup you may encounter is when you attempt to SSH to GitHub. This link will provide some assistance -

Happy hunting!

Send and receive messages through NSNotificationCenter in Objective-C?

To expand upon dreamlax's example... If you want to send data along with the notification

In posting code:

NSDictionary *userInfo = 
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName: 
                       @"TestNotification" object:nil userInfo:userInfo];

In observing code:

- (void) receiveTestNotification:(NSNotification *) notification {

    NSDictionary *userInfo = notification.userInfo;
    MyObject *myObject = [userInfo objectForKey:@"someKey"];
}

What is the Java equivalent for LINQ?

Check out tiny-q. (Note that you currently can't download it.)

Here's an example adapted the above link:

First we need a collection of some data, let's say a set of strings

String[] strings = { "bla", "mla", "bura", "bala", "mura", "buma" };

Now we want to select only the strings which start with "b":

Query<String> stringsStartingWithB = new Query<String>(strings).where(
    new Query.Func<String, Boolean>(){
        public Boolean run(String in) {
            return in.startsWith("b");
        }
    }
);

No actual data moved copied or anything like that, it will get processed as soon as you start iterating:

for(String string : stringsStartingWithB ) {
    System.out.println(string);
}

Difference between "as $key => $value" and "as $value" in PHP foreach

Say you have an array like this:

$array = (0=>'123',1=>'abc','test'=>'hi there!')

In your foreach loop, each loop would be:

$key = 0, $value = '123'
$key = 1, $value = 'abc'
$key = 'test', $value = 'hi there!'

It's great for those times when you need to know the array key.

Convert object to JSON string in C#

Use .net inbuilt class JavaScriptSerializer

  JavaScriptSerializer js = new JavaScriptSerializer();
  string json = js.Serialize(obj);

Could not install packages due to an EnvironmentError: [Errno 13]

I was making the same mistakes then I realized that I have created my virtual environment as root user. It was write protected, so please check whether your virtual environment is write protected. make a new venv and try again

How to create a file in Ruby

File.new and File.open default to read mode ('r') as a safety mechanism, to avoid possibly overwriting a file. We have to explicitly tell Ruby to use write mode ('w' is the most common way) if we're going to output to the file.

If the text to be output is a string, rather than write:

File.open('foo.txt', 'w') { |fo| fo.puts "bar" }

or worse:

fo = File.open('foo.txt', 'w')
fo.puts "bar"
fo.close

Use the more succinct write:

File.write('foo.txt', 'bar')

write has modes allowed so we can use 'w', 'a', 'r+' if necessary.

open with a block is useful if you have to compute the output in an iterative loop and want to leave the file open as you do so. write is useful if you are going to output the content in one blast then close the file.

See the documentation for more information.

Progress Bar with HTML and CSS

_x000D_
_x000D_
.loading {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
  height: 200px;_x000D_
  border: 1px solid rgba(160, 160, 164, 0.2);_x000D_
  background-color: rgba(160, 160, 164, 0.2);_x000D_
  border-radius: 3px;_x000D_
}_x000D_
_x000D_
span.loader {_x000D_
  position: absolute;_x000D_
  top: 40%;_x000D_
  left: 10%;_x000D_
  width: 250px;_x000D_
  height: 20px;_x000D_
  border-radius: 8px;_x000D_
  border: 2px solid rgba(160, 160, 164, 0.8);_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
span.loader span.innerLoad {_x000D_
  text-align: center;_x000D_
  width: 140px;_x000D_
  font-size: 15px;_x000D_
  font-stretch: extra-expanded;_x000D_
  color: #2A00FF;_x000D_
  padding: 1px 18px 3px 80px;_x000D_
  border-radius: 8px;_x000D_
  background: rgb(250, 198, 149);_x000D_
  background: -moz-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgba(250, 198, 149, 1)), color-stop(47%, rgba(245, 171, 102, 1)), color-stop(100%, rgba(239, 141, 49, 1)));_x000D_
  background: -webkit-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -o-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: -ms-linear-gradient(left, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  background: linear-gradient(to right, rgba(250, 198, 149, 1) 0%, rgba(245, 171, 102, 1) 47%, rgba(239, 141, 49, 1) 100%);_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fac695', endColorstr='#ef8d31', GradientType=1);_x000D_
}
_x000D_
<div class="loading">_x000D_
  <span class="loader">_x000D_
      <span class="innerLoad">Loading...</span>_x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Docker Networking - nginx: [emerg] host not found in upstream

At the first glance, I missed, that my "web" service didn't actually start, so that's why nginx couldn't find any host

web_1    | python3: can't open file '/var/www/app/app/app.py': [Errno 2] No such file or directory
web_1 exited with code 2
nginx_1  | [emerg] 1#1: host not found in upstream "web:4044" in /etc/nginx/conf.d/nginx.conf:2

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:

$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);


function fixAmps(&$html, $offset) {
    $positionAmp = strpos($html, '&', $offset);
    $positionSemiColumn = strpos($html, ';', $positionAmp+1);

    $string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);

    if ($positionAmp !== false) { // If an '&' can be found.
        if ($positionSemiColumn === false) { // If no ';' can be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // Replace straight away.
        } else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // This mean we need to escape the '&' sign.
            fixAmps($html, $positionAmp+5); // Recursive call from the new position.
        } else {
            fixAmps($html, $positionAmp+1); // Recursive call from the new position.
        }
    }
}

Setting the selected attribute on a select list using jQuery

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

Catch browser's "zoom" event in JavaScript

On iOS 10 it is possible to add an event listener to the touchmove event and to detect, if the page is zoomed with the current event.

_x000D_
_x000D_
var prevZoomFactorX;_x000D_
var prevZoomFactorY;_x000D_
element.addEventListener("touchmove", (ev) => {_x000D_
  let zoomFactorX = document.documentElement.clientWidth / window.innerWidth;_x000D_
  let zoomFactorY = document.documentElement.clientHeight / window.innerHeight;_x000D_
  let pageHasZoom = !(zoomFactorX === 1 && zoomFactorY === 1);_x000D_
_x000D_
  if(pageHasZoom) {_x000D_
    // page is zoomed_x000D_
    _x000D_
    if(zoomFactorX !== prevZoomFactorX || zoomFactorY !== prevZoomFactorY) {_x000D_
      // page is zoomed with this event_x000D_
    }_x000D_
  }_x000D_
  prevZoomFactorX = zoomFactorX;_x000D_
  prevZoomFactorY = zoomFactorY;_x000D_
});
_x000D_
_x000D_
_x000D_

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

BookTitle have a Composite key. so if the key of BookTitle is referenced as a foreign key you have to bring the complete composite key.

So to resolve the problem you need to add the complete composite key in the BookCopy. So add ISBN column as well. and they at the end.

foreign key (ISBN, Title) references BookTitle (ISBN, Title)

Find all packages installed with easy_install/pip?

If Debian behaves like recent Ubuntu versions regarding pip install default target, it's dead easy: it installs to /usr/local/lib/ instead of /usr/lib (apt default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

I am an ArchLinux user and as I experimented with pip I met this same problem. Here's how I solved it in Arch.

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

Key here is /usr/lib/python2.7/site-packages, which is the directory pip installs to, YMMV. pacman -Qo is how Arch's pac kage man ager checks for ownership of the file. No package is part of the return it gives when no package owns the file: error: No package owns $FILENAME. Tricky workaround: I'm querying about __init__.py because pacman -Qo is a little bit ignorant when it comes to directories :(

In order to do it for other distros, you have to find out where pip installs stuff (just sudo pip install something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S) and what is the "no package owns that path" return (Debian/Ubuntu is no path found matching pattern). Debian/Ubuntu users, beware: dpkg -S will fail if you give it a symbolic link. Just resolve it first by using realpath. Like this:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora users can try (thanks @eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

Git refusing to merge unrelated histories on rebase

I had the same problem. The problem is remote had something preventing this.

I first created a local repository. I added a LICENSE and README.md file to my local and committed.

Then I wanted a remote repository so I created one on GitHub. Here I made a mistake of checking "Initialize this repository with a README", which created a README.md in remote too.

So now when I ran

git push --set-upstream origin master

I got:

error: failed to push some refs to 'https://github.com/lokeshub/myTODs.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes
(e.g. hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Now to overcome this I did

git pull origin master

Which resulted in the below error:

From https://github.com/lokeshub/myTODs
branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories**

I tried:

git pull origin master --allow-unrelated-histories

Result:

From https://github.com/lokeshub/myTODs
 * branch            master     -> FETCH_HEAD
Auto-merging README.md
CONFLICT (add/add): Merge conflict in README.md
Automatic merge failed;
fix conflicts and then commit the result.

Solution:

I removed the remote repository and created a new (I think only removing file README could have worked) and after that the below worked:

git remote rm origin
git remote add origin https://github.com/lokeshub/myTODOs.git
git push --set-upstream origin master

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

JPA Hibernate One-to-One relationship

JPA doesn't allow the @Id annotation on a OneToOne or ManyToOne mapping. What you are trying to do is one-to-one entity association with shared primary key. The simplest case is unidirectional one-to-one with shared key:

@Entity
public class Person {
    @Id
    private int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private OtherInfo otherInfo;

    rest of attributes ...
}

The main problem with this is that JPA provides no support for shared primary key generation in OtherInfo entity. The classic book Java Persistence with Hibernate by Bauer and King gives the following solution to the problem using Hibernate extension:

@Entity
public class OtherInfo {
    @Id @GeneratedValue(generator = "customForeignGenerator")
    @org.hibernate.annotations.GenericGenerator(
        name = "customForeignGenerator",
        strategy = "foreign",
        parameters = @Parameter(name = "property", value = "person")
    )
    private Long id;

    @OneToOne(mappedBy="otherInfo")
    @PrimaryKeyJoinColumn
    public Person person;

    rest of attributes ...
}

Also, see here.

S3 limit to objects in a bucket

While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.

How can I strip all punctuation from a string in JavaScript using regex?

/[^A-Za-z0-9\s]/g should match all punctuation but keep the spaces. So you can use .replace(/\s{2,}/g, " ") to replace extra spaces if you need to do so. You can test the regex in http://rubular.com/

.replace(/[^A-Za-z0-9\s]/g,"").replace(/\s{2,}/g, " ")

Update: Will only work if the input is ANSI English.

How do I put two increment statements in a C++ 'for' loop?

A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus:

for(int i = 0; i != 5; ++i,++j) 
    do_something(i,j);

But is it really a comma operator?

Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and not a comma operator at all. I checked that in GCC as follows:

int i=0;
int a=5;
int x=0;

for(i; i<5; x=i++,a++){
    printf("i=%d a=%d x=%d\n",i,a,x);
}

I was expecting x to pick up the original value of a, so it should have displayed 5,6,7.. for x. What I got was this

i=0 a=5 x=0
i=1 a=6 x=0
i=2 a=7 x=1
i=3 a=8 x=2
i=4 a=9 x=3

However, if I bracketed the expression to force the parser into really seeing a comma operator, I get this

int main(){
    int i=0;
    int a=5;
    int x=0;

    for(i=0; i<5; x=(i++,a++)){
        printf("i=%d a=%d x=%d\n",i,a,x);
    }
}

i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8

Initially I thought that this showed it wasn't behaving as a comma operator at all, but as it turns out, this is simply a precedence issue - the comma operator has the lowest possible precedence, so the expression x=i++,a++ is effectively parsed as (x=i++),a++

Thanks for all the comments, it was an interesting learning experience, and I've been using C for many years!

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

add scroll bar to table body

This is because you are adding your <tbody> tag before <td> in table you cannot print any data without <td>.

So for that you have to make a <div> say #header with position: fixed;

 header
 {
      position: fixed;
 }

make another <div> which will act as <tbody>

tbody
{
    overflow:scroll;
}

Now your header is fixed and the body will scroll. And the header will remain there.

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

How can I find whitespace in a String?

You can basically do this

if(s.charAt(i)==32){
   return true;
}

You must write boolean method.Whitespace char is 32.

JavaScript equivalent of PHP’s die

There is no function exit equivalent to php die() in JS, if you are not using any function then you can simply use return;

return;

Instantiating a generic class in Java

For Java 8 ....

There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.

This uses Java 8 Supplier functional interface

Load different application.yml in SpringBoot Test

You can set your test properties in src/test/resources/config/application.yml file. Spring Boot test cases will take properties from application.yml file in test directory.

The config folder is predefined in Spring Boot.

As per documentation:

If you do not like application.properties as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:

java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

The same works for application.yml

Documentation:

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

How to add buttons dynamically to my form?

I had the same doubt and came up with the following contribution:

 int height = this.Size.Height;
 int width = this.Size.Width;

 int widthOffset = 10;
 int heightOffset = 10;

 int btnWidth = 100;  // Button Widht
 int btnHeight = 40;  // Button Height

 for (int i = 0; i < 50; ++i)
 {
     if ((widthOffset + btnWidth) >= width)
     {                    
         widthOffset = 10;
         heightOffset = heightOffset + btnHeight

         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
     }

     else
     {                        
         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
      }
  }

Expected Behaviour:
This will generate the buttons dinamically and using the current window size, "break a line" when the button exceeds the right margin of your window.

Syntax for async arrow function

Async Arrow function syntax with parameters

const myFunction = async (a, b, c) => {
   // Code here
}

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

Load a WPF BitmapImage from a System.Drawing.Bitmap

Thanks to Hallgrim, here is the code I ended up with:

ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   bmp.GetHbitmap(), 
   IntPtr.Zero, 
   System.Windows.Int32Rect.Empty, 
   BitmapSizeOptions.FromWidthAndHeight(width, height));

I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question

How to simulate target="_blank" in JavaScript

This might help

var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    link.href = 'http://www.google.com';
    link.target = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true
    });
    link.dispatchEvent(event);

How to know what the 'errno' means?

On Linux there is also a very neat tool that can tell right away what each error code means. On Ubuntu: apt-get install errno.

Then if for example you want to get the description of error type 2, just type errno 2 in the terminal.

With errno -l you get a list with all errors and their descriptions. Much easier that other methods mentioned by previous posters.

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

How to include bootstrap css and js in reactjs app?

Hope this is helpful ;)

Step 1: using NPM install this bellow command

npm install --save reactstrap@next react react-dom

Step 2: example index.js main script import bellow command

import 'bootstrap/dist/css/bootstrap.min.css';

Step 3: UI components refer bellow website reactstrap.github.io

Exception Error c0000005 in VC++

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

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

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

Get the IP address of the machine

  1. Create a socket.
  2. Perform ioctl(<socketfd>, SIOCGIFCONF, (struct ifconf)&buffer);

Read /usr/include/linux/if.h for information on the ifconf and ifreq structures. This should give you the IP address of each interface on the system. Also read /usr/include/linux/sockios.h for additional ioctls.

How to fix: "HAX is not working and emulator runs in emulation mode"

The way I solved it is by setting the AVD memory limit and HAXM memory to be equal in size which is 1 GB = 1024 MB. The AVD cannot have higher memory limit than the HAXM.

1. Setting the HAXM memory to be 1024 M

The only way to change the HAXM memory is by installing it again. I did it using the terminal. Locate Hardware_Accelerated_Execution_Manager in your machine. Then change directory that folder to run the installation script.

cd ~/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager

-OR-

cd ~/Library/Developer/Xamarin/android-sdk-macosx/extras/intel/Hardware_Accelerated_Execution_Manager

May need to change permissions:

sudo chmod 755 "HAXM installation"

Then:

./HAXM\ installation -m 1024

-OR-

sudo ./"HAXM installation" -m 1024

2. Setting the virtual device the same size with HAXM memory limit

enter image description here

This works for me. Good luck!

Loading .sql files from within PHP

Try This:

// SQL File
$SQLFile = 'YourSQLFile.sql';

// Server Name
$hostname = 'localhost';

// User Name
$db_user = 'root';

// User Password
$db_password = '';

// DBName
$database_name = 'YourDBName';

// Connect MySQL
$link = mysql_connect($hostname, $db_user, $db_password);

if (!$link) {
die("MySQL Connection error");
}

// Select MySQL DB
mysql_select_db($database_name, $link) or die("Wrong MySQL Database");

// Function For Run Multiple Query From .SQL File
function MultiQuery($sqlfile, $sqldelimiter = ';') {
set_time_limit(0);

if (is_file($sqlfile) === true) {
$sqlfile = fopen($sqlfile, 'r');

if (is_resource($sqlfile) === true) {
$query = array();
echo "<table cellspacing='3' cellpadding='3' border='0'>";

while (feof($sqlfile) === false) {
$query[] = fgets($sqlfile);

if (preg_match('~' . preg_quote($sqldelimiter, '~') . '\s*$~iS', end($query)) === 1) {
$query = trim(implode('', $query));

if (mysql_query($query) === false) {
echo '<tr><td>ERROR:</td><td> ' . $query . '</td></tr>';
} else {
echo '<tr><td>SUCCESS:</td><td>' . $query . '</td></tr>';
}

while (ob_get_level() &gt; 0) {
ob_end_flush();
}

flush();
}

if (is_string($query) === true) {
$query = array();
}
}
echo "</table>";

return fclose($sqlfile);
}
}

return false;
}

/* * * Use Function Like This: ** */

MultiQuery($SQLFile);

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

For each error of the form:

npm WARN {something} requires a peer of {other thing} but none is installed. You must install peer dependencies yourself.

You should:

$ npm install --save-dev "{other thing}"

Note: The quotes are needed if the {other thing} has spaces, like in this example:

npm WARN [email protected] requires a peer of rollup@>=0.66.0 <2 but none was installed.

Resolved with:

$ npm install --save-dev "rollup@>=0.66.0 <2"

Getting RSA private key from PEM BASE64 Encoded private key file

Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

iOS9 Untrusted Enterprise Developer with no option to trust

On iOS 9.2 Profiles renamed to Device Management.
Now navigation looks like that:
Settings -> General -> Device Management -> Tap on necessary profile in list -> Trust.

Branch from a previous commit using Git

If you are not sure which commit you want to branch from in advance you can check commits out and examine their code (see source, compile, test) by

git checkout <sha1-of-commit>

once you find the commit you want to branch from you can do that from within the commit (i.e. without going back to the master first) just by creating a branch in the usual way:

git checkout -b <branch_name>

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

How to dynamically set bootstrap-datepicker's date value?

You can use this simple method like :

qsFromDate = '2017-05-10';
$("#dtMinDate").datepicker("setDate", new Date(qsFromDate));
$('#dtMinDate').datepicker('update');

Check whether an array is empty

From the PHP-documentation:

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

How do you decrease navbar height in Bootstrap 3?

If you have only one nav and you want to change it, you should change your variables.less: @navbar-height (somewhere near line 265, I can't recall how many lines I added to mine).

This is referenced by the mixin .navbar-vertical-align, which is used for example to position the "toggle" element, anything with .navbar-form, .navbar-btn, and .navbar-text.

If you have two navbars and want them to be different heights, Minder Saini's answer may work well enough, when qualified further by an , e.g., #topnav.navbar but should be tested across multiple device widths.

How to enable scrolling on website that disabled scrolling?

What worked for me was disabling the position: fixed; CSS.

Transport security has blocked a cleartext HTTP

For those who came here trying to find the reason why their WKWebView is always white and loads nothing (exactly as described here how do I get WKWebView to work in swift and for an macOS App) :

If all the rocket science above does not work for you check the obvious: the sandbox settings

sandbox settings]

Being new to swift and cocoa, but pretty experienced in programming I've spend about 20 hours to find this solution. None of dozens hipster-iOS-tutorials nor apple keynotes – nothing mentions this small checkbox.

Adding devices to team provisioning profile

There are two types of provisioning profiles.

  • development and
  • distribution

When app is live on app store then distribution profiles works and do not need any devices to be added.

Only development profiles need to add devices.In order to do so these are the steps-

  1. Login to developer.apple.com member centre.
  2. Go to Certificates, Identifiers & Profiles.
  3. Get UDID of your device and add it in the devices.
  4. Select a developer provisioning profile and edit it.
  5. Click on check box next to the device you just added.
  6. Generate and download the profile.
  7. Double click on it to install it.
  8. Connect your device and retry.

This worked for me hope it works for you.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Tell Ruby Program to Wait some amount of time

Implementation of seconds/minutes/hours, which are rails methods. Note that implicit returns aren't needed, but they look cleaner, so I prefer them. I'm not sure Rails even has .days or if it goes further, but these are the ones I need.

class Integer
   def seconds
      return self
   end
   def minutes
      return self * 60
   end
   def hours
      return self * 3600
   end
   def days
      return self * 86400
   end
end

After this, you can do: sleep 5.seconds to sleep for 5 seconds. You can do sleep 5.minutes to sleep for 5 min. You can do sleep 5.hours to sleep for 5 hours. And finally, you can do sleep 5.days to sleep for 5 days... You can add any method that return the value of self * (amount of seconds in that timeframe). As an exercise, try implementing it for months!

PHP MySQL Google Chart JSON - Complete Example

You can do this more easy way. And 100% works that you want

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";  //your database password
    $dbname = "demo";  //your database name

    $con = new mysqli($servername, $username, $password, $dbname);

    if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
    }
    else
    {
        //echo ("Connect Successfully");
    }
    $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
    $aresult = $con->query($query);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Massive Electronics</title>
    <script type="text/javascript" src="loder.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});

        google.charts.setOnLoadCallback(drawChart);
        function drawChart(){
            var data = new google.visualization.DataTable();
            var data = google.visualization.arrayToDataTable([
                ['Date_time','Tempout'],
                <?php
                    while($row = mysqli_fetch_assoc($aresult)){
                        echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
                    }
                ?>
               ]);

            var options = {
                title: 'Date_time Vs Room Out Temp',
                curveType: 'function',
                legend: { position: 'bottom' }
            };

            var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
            chart.draw(data, options);
        }

    </script>
</head>
<body>
     <div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>

loder.js link here loder.js

Node.js request CERT_HAS_EXPIRED

The best way to fix this:

Renew the certificate. This can be done for free using Greenlock which issues certificates via Let's Encrypt™ v2

A less insecure way to fix this:

'use strict';

var request = require('request');
var agentOptions;
var agent;

agentOptions = {
  host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};

agent = new https.Agent(agentOptions);

request({
  url: "https://www.example.com/api/endpoint"
, method: 'GET'
, agent: agent
}, function (err, resp, body) {
  // ...
});

By using an agent with rejectUnauthorized you at least limit the security vulnerability to the requests that deal with that one site instead of making your entire node process completely, utterly insecure.

Other Options

If you were using a self-signed cert you would add this option:

agentOptions.ca = [ selfSignedRootCaPemCrtBuffer ];

For trusted-peer connections you would also add these 2 options:

agentOptions.key = clientPemKeyBuffer;
agentOptions.cert = clientPemCrtSignedBySelfSignedRootCaBuffer;

Bad Idea

It's unfortunate that process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; is even documented. It should only be used for debugging and should never make it into in sort of code that runs in the wild. Almost every library that runs atop https has a way of passing agent options through. Those that don't should be fixed.

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

How to set a maximum execution time for a mysql query?

Please rewrite your query like

select /*+ MAX_EXECUTION_TIME(1000) */ * from table


this statement will kill your query after the specified time

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

When I catch an exception, how do I get the type, file, and line number?

Simplest form that worked for me.

import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())

Output

Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

No Main class found in NetBeans

The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)

enter image description here

Java : Sort integer array without using Arrays.sort()

here is the Sorting Simple Example try it

public class SortingSimpleExample {

    public static void main(String[] args) {
        int[] a={10,20,1,5,4,20,6,4,2,5,4,6,8,-5,-1};
              a=sort(a);
        for(int i:a)
              System.out.println(i);
}
    public static int[] sort(int[] a){

        for(int i=0;i<a.length;i++){
            for(int j=0;j<a.length;j++){
                int temp=0;
                if(a[i]<a[j]){
                    temp=a[j];                  
                    a[j]=a[i];                  
                    a[i]=temp;      
                  }         
                }
        }
        return a;

    }
}

How do I write a for loop in bash

From this site:

for i in $(seq 1 10);
do
    echo $i
done

CSS list-style-image size

I'm using:

_x000D_
_x000D_
li {_x000D_
 margin: 0;_x000D_
 padding: 36px 0 36px 84px;_x000D_
 list-style: none;_x000D_
 background-image: url("../../images/checked_red.svg");_x000D_
 background-repeat: no-repeat;_x000D_
 background-position: left center;_x000D_
 background-size: 40px;_x000D_
}
_x000D_
_x000D_
_x000D_

where background-size set the background image size.

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

complex if statement in python

if x == 80 or x == 443 or 1024 <= x <= 65535

should definitely do

Can't find/install libXtst.so.6?

Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.

Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.

npm behind a proxy fails with status 403

I had the same issue and finally it was resolved by disconnecting from all VPN .

Can JavaScript connect with MySQL?

Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver. Nodejs-MySQL

How to Clone Objects

To clone your class object you can use the Object.MemberwiseClone method,

just add this function to your class :

public class yourClass
{
    // ...
    // ...

    public yourClass DeepCopy()
    {
        yourClass othercopy = (yourClass)this.MemberwiseClone();
        return othercopy;
    }
}

then to perform a deep independant copy, just call the DeepCopy method :

yourClass newLine = oldLine.DeepCopy();

What is the most efficient way to loop through dataframes with pandas?

The newest versions of pandas now include a built-in function for iterating over rows.

for index, row in df.iterrows():

    # do some logic here

Or, if you want it faster use itertuples()

But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code.

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Half circle with CSS (border, outline only)

I had a similar issue not long time ago and this was how I solved it

_x000D_
_x000D_
.rotated-half-circle {_x000D_
  /* Create the circle */_x000D_
  width: 40px;_x000D_
  height: 40px;_x000D_
  border: 10px solid black;_x000D_
  border-radius: 50%;_x000D_
  /* Halve the circle */_x000D_
  border-bottom-color: transparent;_x000D_
  border-left-color: transparent;_x000D_
  /* Rotate the circle */_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
_x000D_
_x000D_

Can Android do peer-to-peer ad-hoc networking?

In addition to Telmo Marques answer: I use Virtual Router for this.

Like connectify it creates an accesspoint on your Windows 8, Windows 7 or 2008 R2 machine, but it's open-source.

Android ImageView's onClickListener does not work

As a beginner to android development, my issue wasn't any of these solutions. I had several problems.

Firstly, I didn't realise that you had to use the bug symbol to use the debugger to hit breakpoints.

Then I was silently getting an error in my on click listener, I was trying to pass something to a method, but the method required a float value.

However in the ide, the method was shown as unused. It wasn't until I cast the value that the method was shown in the correct colour and wasn't marked as unused anymore.

Not sure why I didn't get an error from trying to use a method with the wrong type ?

Also I had to add the android:debuggable="true" to my manifest to get debugging to hit breakpoints.

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

List directory tree structure in python?

Maybe faster than @ellockie ( Maybe )

import os
def file_writer(text):
    with open("folder_structure.txt","a") as f_output:
        f_output.write(text)
def list_files(startpath):


    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = '\t' * 1 * (level)
        output_string = '{}{}/ \n'.format(indent, os.path.basename(root))
        file_writer(output_string)
        subindent = '\t' * 1 * (level + 1)
        output_string = '%s %s \n' %(subindent,[f for f in files])
        file_writer(''.join(output_string))


list_files("/")

Test results in screenshot below:

enter image description here

Open a PDF using VBA in Excel

Here is a simplified version of this script to copy a pdf into a XL file.


Sub CopyOnePDFtoExcel()

    Dim ws As Worksheet
    Dim PDF_path As String

    PDF_path = "C:\Users\...\Documents\This-File.pdf"


    'open the pdf file
    ActiveWorkbook.FollowHyperlink PDF_path

    SendKeys "^a", True
    SendKeys "^c"

    Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)

    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet1")

    ws.Activate
    ws.Range("A1").ClearContents
    ws.Range("A1").Select
    ws.Paste

    Application.ScreenUpdating = True

End Sub

Find PHP version on windows command line

It is most likely that php is not in your specified path.

Try to issue the php command with the full path, for example:

C:\> "C:\Program Files\php\php.exe" -v

Please note, that this is just an example, your php installation might be in a different directory.

GIT: Checkout to a specific folder

For a single file:

git show HEAD:abspath/to/file > file.copy

Difference between Key, Primary Key, Unique Key and Index in MySQL

Unique Key :

  1. More than one value can be null.
  2. No two tuples can have same values in unique key.
  3. One or more unique keys can be combined to form a primary key, but not vice versa.

Primary Key

  1. Can contain more than one unique keys.
  2. Uniquely represents a tuple.

Run a vbscript from another vbscript

I saw the below code working. Simple, but I guess not documented. Anyone else used the 'Execute' command ?

   Dim body, my_script_file
   Set Fso = CreateObject("Scripting.FileSystemObject")


   Set my_script_file = fso.OpenTextFile(FILE)
   body = my_script_file.ReadAll
    my_script_file.Close

    Execute body

Is there a command line command for verifying what version of .NET is installed

you can check installed c# compilers and the printed version of the .net:

@echo off

for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
    set "l="
    for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
        if not defined l (
            echo Installed: %%$
            set l=%%$
        )
    )
)

echo latest installed .NET %l%

the csc.exe does not have a -version switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.

Link to "pin it" on pinterest without generating a button

I had the same question. This works great in Wordpress!

<a href="//pinterest.com/pin/create/link/?url=<?php the_permalink();?>&amp;description=<?php the_title();?>">Pin this</a>

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Spring MVC - How to return simple String as JSON in Rest Controller

Add produces = "application/json" in @RequestMapping annotation like:

@RequestMapping(value = "api/login", method = RequestMethod.GET, produces = "application/json")

Hint: As a return value, i recommend to use ResponseEntity<List<T>> type. Because the produced data in JSON body need to be an array or an object according to its specifications, rather than a single simple string. It may causes problems sometimes (e.g. Observables in Angular2).

Difference:

returned String as json: "example"

returned List<String> as json: ["example"]

RestTemplate: How to send URL and query parameters together

I would use buildAndExpand from UriComponentsBuilder to pass all types of URI parameters.

For example:

String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";

// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("planets", "Mars");
urlParams.put("moons", "Phobos");

// Query parameters
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
        // Add query parameter
        .queryParam("firstName", "Mark")
        .queryParam("lastName", "Watney");

System.out.println(builder.buildAndExpand(urlParams).toUri());
/**
 * Console output:
 * http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney
 */

restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,
        requestEntity, class_p);

/**
 * Log entry:
 * org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"
 */

How do I count columns of a table

Simply use mysql_fetch_assoc and count the array using count() function

How to truncate string using SQL server

If you only want to return a few characters of your long string, you can use:

select 
  left(col, 15) + '...' col
from yourtable

See SQL Fiddle with Demo.

This will return the first 15 characters of the string and then concatenates the ... to the end of it.

If you want to to make sure than strings less than 15 do not get the ... then you can use:

select 
  case 
    when len(col)>=15
    then left(col, 15) + '...' 
    else col end col
from yourtable

See SQL Fiddle with Demo

How to check if IEnumerable is null or empty?

if (collection?.Any() == true){
    // if collection contains more than one item
}
if (collection?.Any() != true){
    // if collection is null
    // if collection does not contain any item
}

JavaScript: Is there a way to get Chrome to break on all errors?

Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.

Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.

If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error object given to the catch block has a stack property that shows where the exception happened.

Read XML file using javascript

If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.

If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.

Python: Figure out local timezone

I was asking the same to myself, and I found the answer in 1:

Take a look at section 8.1.7: the format "%z" (lowercase, the Z uppercase returns also the time zone, but not in the 4-digit format, but in the form of timezone abbreviations, like in [3]) of strftime returns the form "+/- 4DIGIT" that is standard in email headers (see section 3.3 of RFC 2822, see [2], which obsoletes the other ways of specifying the timezone for email headers).

So, if you want your timezone in this format, use:

time.strftime("%z")

[1] http://docs.python.org/2/library/datetime.html

[2] http://tools.ietf.org/html/rfc2822#section-3.3

[3] Timezone abbreviations: http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations , only for reference.

Among $_REQUEST, $_GET and $_POST which one is the fastest?

There are certain security concerns involved as a hacker can set a cookie that will override a $_POST or $_GET value. If you handle sensitive data, I would not recommend using $_REQUEST. – Xandor

you can't be used $_GET alternative of $_POST on some case.

When ??

  • when you want to upload a file.
  • when you don't won't to show a data in url.

GET also has limits on the amount of information to send. The limitation is about 2000 characters.

Other thing's there are few case when you can't retrieve a data using $_POST

When ?

  • when data is passed in URL.

For Rest Service

`GET` - Provides a read only access to a resource.

`PUT` - Used to create a new resource.

there is nothing be wrong to use $_REQUEST.

But the way to do that is to check $_SERVER['REQUEST_METHOD'] explicitly, not rely on $_POST being empty for a GET.

Populate one dropdown based on selection in another

_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
  var colours = ['Black', 'White', 'Blue'];_x000D_
  var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
  var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
  switch (ddl1.value) {_x000D_
    case 'Colours':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < colours.length; i++) {_x000D_
        createOption(ddl2, colours[i], colours[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Shapes':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < shapes.length; i++) {_x000D_
        createOption(ddl2, shapes[i], shapes[i]);_x000D_
      }_x000D_
      break;_x000D_
    case 'Names':_x000D_
      ddl2.options.length = 0;_x000D_
      for (i = 0; i < names.length; i++) {_x000D_
        createOption(ddl2, names[i], names[i]);_x000D_
      }_x000D_
      break;_x000D_
    default:_x000D_
      ddl2.options.length = 0;_x000D_
      break;_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
  var opt = document.createElement('option');_x000D_
  opt.value = value;_x000D_
  opt.text = text;_x000D_
  ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
  <option value=""></option>_x000D_
  <option value="Colours">Colours</option>_x000D_
  <option value="Shapes">Shapes</option>_x000D_
  <option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

In python, how do I cast a class object to a dict

It's hard to say without knowing the whole context of the problem, but I would not override __iter__.

I would implement __what_goes_here__ on the class.

as_dict(self:
    d = {...whatever you need...}
    return d

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

How to implement zoom effect for image view in android?

I prefered the library davemorrissey/subsampling-scale-image-view over chrisbanes/PhotoView (answer of star18bit)

  • Both are active projects (both have some commits in 2015)
  • Both have a Demo on the PlayStore
  • subsampling-scale-image-view supports large images (above 1080p) without memory exception due to sub sampling, which PhotoView doesn't support
  • subsampling-scale-image-view seems to have larger API and better documentation

See How to convert AAR to JAR, if you like to use subsampling-scale-image-view with Eclipse/ADT

Is it possible to append to innerHTML without destroying descendants' event listeners?

Using .insertAdjacentHTML() preserves event listeners, and is supported by all major browsers. It's a simple one-line replacement for .innerHTML.

var html_to_insert = "<p>New paragraph</p>";

// with .innerHTML, destroys event listeners
document.getElementById('mydiv').innerHTML += html_to_insert;

// with .insertAdjacentHTML, preserves event listeners
document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert);

The 'beforeend' argument specifies where in the element to insert the HTML content. Options are 'beforebegin', 'afterbegin', 'beforeend', and 'afterend'. Their corresponding locations are:

<!-- beforebegin -->
<div id="mydiv">
  <!-- afterbegin -->
  <p>Existing content in #mydiv</p>
  <!-- beforeend -->
</div>
<!-- afterend -->

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.


Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

Change a Git remote HEAD to point to something besides master

Since you mention GitHub, to do it on their site simply go into your project, then...

admin > Default Branch > (choose something)

Done.

Using Position Relative/Absolute within a TD?

This is because according to CSS 2.1, the effect of position: relative on table elements is undefined. Illustrative of this, position: relative has the desired effect on Chrome 13, but not on Firefox 4. Your solution here is to add a div around your content and put the position: relative on that div instead of the td. The following illustrates the results you get with the position: relative (1) on a div good), (2) on a td(no good), and finally (3) on a div inside a td (good again).

On Firefox 4

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="position:relative;">_x000D_
        <span style="position:absolute; left:150px;">_x000D_
          Absolute span_x000D_
        </span>_x000D_
        Relative div_x000D_
      </div>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

In laymans terms, what does 'static' mean in Java?

In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.

References with text in LaTeX

Have a look to this wiki: LaTeX/Labels and Cross-referencing:

The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:

\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Encoding Javascript Object to Json string

Unless the variable k is defined, that's probably what's causing your trouble. Something like this will do what you want:

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

You can also do it all at once:

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

Ways to iterate over a list in Java

I don't know what you consider pathological, but let me provide some alternatives you could have not seen before:

List<E> sl= list ;
while( ! sl.empty() ) {
    E element= sl.get(0) ;
    .....
    sl= sl.subList(1,sl.size());
}

Or its recursive version:

void visit(List<E> list) {
    if( list.isEmpty() ) return;
    E element= list.get(0) ;
    ....
    visit(list.subList(1,list.size()));
}

Also, a recursive version of the classical for(int i=0... :

void visit(List<E> list,int pos) {
    if( pos >= list.size() ) return;
    E element= list.get(pos) ;
    ....
    visit(list,pos+1);
}

I mention them because you are "somewhat new to Java" and this could be interesting.

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

SELECT *, COUNT(*) in SQLite

SELECT *, COUNT(*) FROM my_table is not what you want, and it's not really valid SQL, you have to group by all the columns that's not an aggregate.

You'd want something like

SELECT somecolumn,someothercolumn, COUNT(*) 
   FROM my_table 
GROUP BY somecolumn,someothercolumn

Changing MongoDB data store directory

Copy the contents of /var/lib/mongodb to /data/db. The files you should be looking for should have names like your_db_name.ns and your_dbname.n where n is a number starting with 0. If you do not see such files under /var/lib/mongodb, search for them on your filesystem.

Once copied over, use --dbpath=/data/db when starting MongoDB via the mongod command.

How can I convert my Java program to an .exe file?

I would say launch4j is the best tool for converting a java source code(.java) to .exe file You can even bundle a jre with it for distribution and the exe can even be iconified. Although the size of application increases, it makes sure that the application will work perfectly even if the user does not have a jre installed. It also makes sure that you are able to provide the specific jre required for your app without the user having to install it separately. But unfortunately, java loses its importance. Its multi platform support is totally ignored and the final app is only supported for windows. But that is not a big deal, if you are catering only to windows users.

How to use SSH to run a local shell script on a remote machine?

ssh user@hostname ".~/.bashrc;/cd path-to-file/;.filename.sh"

highly recommended to source the environment file(.bashrc/.bashprofile/.profile). before running something in remote host because target and source hosts environment variables may be deffer.

Prevent direct access to a php include file

I had this problem once, solved with:

if (strpos($_SERVER['REQUEST_URI'], basename(__FILE__)) !== false) ...

but the ideal solution is to place the file outside of the web-server document root, as mentioned in another anwser.

conversion from string to json object android

You just need the lines of code as below:

   try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //displaying the JSONObject as a String
        Log.d("JSONObject = ", jsonObject.toString());
        //getting specific key values
        Log.d("phonetype = ", jsonObject.getString("phonetype"));
        Log.d("cat = ", jsonObject.getString("cat");
    }catch (Exception ex) {
         StringWriter stringWriter = new StringWriter();
         ex.printStackTrace(new PrintWriter(stringWriter));
         Log.e("exception ::: ", stringwriter.toString());
    }

change <audio> src with javascript

with jQuery:

 $("#playerSource").attr("src", "new_src");

    var audio = $("#player");      

    audio[0].pause();
    audio[0].load();//suspends and restores all audio element

    if (isAutoplay) 
        audio[0].play();

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

The model backing the <Database> context has changed since the database was created

For Entity Framework 5.0.0.0 - 6.1.3

You DO indeed want to do the following:

1. using System.Data.Entity;   to startup file (console app --> Program.cs / mvc --> global.asax
2. Database.SetInitializer<YourDatabaseContext>(null);

Yes, Matt Frear is correct. UPDATE -EDIT: Caveat is that I agree with others in that instead of adding this code to global.asax added to your DbContext class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other code 
    Database.SetInitializer<YOURContext>(null);
    // more code here.
}

As others mentioned this also is good for handling the unit testing.

Currently I am using this with Entity Framework 6.1.3 /.net 4.6.1

I will come back to provide a CORE snippet in the near future.