Programs & Examples On #Safecontrols

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Yes, there are at least 2 solutions for this:

  1. Use the script directive (http://docs.angularjs.org/api/ng.directive:script) to put your partials in the initially loaded HTML
  2. You could also fill in $templateCache (http://docs.angularjs.org/api/ng.$templateCache) from JavaScript if needed (possibly based on result of $http call)

If you would like to use method (2) to fill in $templateCache you can do it like this:

$templateCache.put('second.html', '<b>Second</b> template');

Of course the templates content could come from a $http call:

$http.get('third.html', {cache:$templateCache});

Here is the plunker those techniques: http://plnkr.co/edit/J6Y2dc?p=preview

Browse for a directory in C#

or even more better, you can put this code in a class file

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

internal class OpenFolderDialog : IDisposable {

    /// <summary>
    /// Gets/sets folder in which dialog will be open.
    /// </summary>
    public string InitialFolder { get; set; }

    /// <summary>
    /// Gets/sets directory in which dialog will be open if there is no recent directory available.
    /// </summary>
    public string DefaultFolder { get; set; }

    /// <summary>
    /// Gets selected folder.
    /// </summary>
    public string Folder { get; private set; }


    internal DialogResult ShowDialog(IWin32Window owner) {
        if (Environment.OSVersion.Version.Major >= 6) {
            return ShowVistaDialog(owner);
        } else {
            return ShowLegacyDialog(owner);
        }
    }

    private DialogResult ShowVistaDialog(IWin32Window owner) {
        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
        uint options;
        frm.GetOptions(out options);
        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
        frm.SetOptions(options);
        if (this.InitialFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetFolder(directoryShellItem);
            }
        }
        if (this.DefaultFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetDefaultFolder(directoryShellItem);
            }
        }

        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
            NativeMethods.IShellItem shellItem;
            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
                IntPtr pszString;
                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
                    if (pszString != IntPtr.Zero) {
                        try {
                            this.Folder = Marshal.PtrToStringAuto(pszString);
                            return DialogResult.OK;
                        } finally {
                            Marshal.FreeCoTaskMem(pszString);
                        }
                    }
                }
            }
        }
        return DialogResult.Cancel;
    }

    private DialogResult ShowLegacyDialog(IWin32Window owner) {
        using (var frm = new SaveFileDialog()) {
            frm.CheckFileExists = false;
            frm.CheckPathExists = true;
            frm.CreatePrompt = false;
            frm.Filter = "|" + Guid.Empty.ToString();
            frm.FileName = "any";
            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
            frm.OverwritePrompt = false;
            frm.Title = "Select Folder";
            frm.ValidateNames = false;
            if (frm.ShowDialog(owner) == DialogResult.OK) {
                this.Folder = Path.GetDirectoryName(frm.FileName);
                return DialogResult.OK;
            } else {
                return DialogResult.Cancel;
            }
        }
    }


    public void Dispose() { } //just to have possibility of Using statement.

}

internal static class NativeMethods {

    #region Constants

    public const uint FOS_PICKFOLDERS = 0x00000020;
    public const uint FOS_FORCEFILESYSTEM = 0x00000040;
    public const uint FOS_NOVALIDATE = 0x00000100;
    public const uint FOS_NOTESTFILECREATE = 0x00010000;
    public const uint FOS_DONTADDTORECENT = 0x02000000;

    public const uint S_OK = 0x0000;

    public const uint SIGDN_FILESYSPATH = 0x80058000;

    #endregion


    #region COM

    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
    internal class FileOpenDialogRCW { }


    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IFileDialog {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        [PreserveSig()]
        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow 


        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypeIndex([In] uint iFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileTypeIndex(out uint piFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Unadvise([In] uint dwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOptions([In] uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetOptions(out uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetClientGuid([In] ref Guid guid);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint ClearClientData();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
    }


    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IShellItem {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
    }

    #endregion


    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);

}

And use it like this

using (var frm = new OpenFolderDialog()) {
                if (frm.ShowDialog(this)== DialogResult.OK) {
                    MessageBox.Show(this, frm.Folder);
                }
            }

React Native add bold or italics to single words in <Text> field

You can use <Text> like a container for your other text components. This is example:

...
<Text>
  <Text>This is a sentence</Text>
  <Text style={{fontWeight: "bold"}}> with</Text>
  <Text> one word in bold</Text>
</Text>
...

Here is an example.

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

AngularJS $http-post - convert binary to excel file and download

You could as well take an alternative approach -- you don't have to use $http, you don't need any extra libraries, and it ought to work in any browser.

Just place an invisible form on your page.

<form name="downloadForm" action="/MyApp/MyFiles/Download" method="post" target="_self">
    <input type="hidden" name="value1" value="{{ctrl.value1}}" />
    <input type="hidden" name="value2" value="{{ctrl.value2}}" />
</form>

And place this code in your angular controller.

ctrl.value1 = 'some value 1';  
ctrl.value2 = 'some value 2';  
$timeout(function () {
    $window.document.forms['downloadForm'].submit();
});

This code will post your data to /MyApp/MyFiles/Download and you'll receive a file in your Downloads folder.
It works with Internet Explorer 10.

If a conventional HTML form doesn't let you post your complex object, then you have two options:

1. Stringify your object and put it into one of the form fields as a string.

<input type="hidden" name="myObjJson" value="{{ctrl.myObj | json:0}}" />


2. Consider HTML JSON forms: https://www.w3.org/TR/html-json-forms/

Getting data from Yahoo Finance

As from the answer from BrianC use the YQL console. But after selecting the "Show Community Tables" go to the bottom of the tables list and expand yahoo where you find plenty of yahoo.finance tables:

Stock Quotes:

  • yahoo.finance.quotes
  • yahoo.finance.historicaldata

Fundamental analysis:

  • yahoo.finance.keystats
  • yahoo.finance.balancesheet
  • yahoo.finance.incomestatement
  • yahoo.finance.analystestimates
  • yahoo.finance.dividendhistory

Technical analysis:

  • yahoo.finance.historicaldata
  • yahoo.finance.quotes
  • yahoo.finance.quant
  • yahoo.finance.option*

General financial information:

  • yahoo.finance.industry
  • yahoo.finance.sectors
  • yahoo.finance.isin
  • yahoo.finance.quoteslist
  • yahoo.finance.xchange

2/Nov/2017: Yahoo finance has apparently killed this API, for more info and alternative resources see https://news.ycombinator.com/item?id=15616880

How to convert comma-delimited string to list in Python?

You can use this function to convert comma-delimited single character strings to list-

def stringtolist(x):
    mylist=[]
    for i in range(0,len(x),2):
        mylist.append(x[i])
    return mylist

How to turn off caching on Firefox?

You can use CTRL-F5 to reload bypassing the cache.

You can set the preferences in firefox not to use the cache

network.http.use-cache = false

You can setup you web server to send a no-cache/Expires/Cache-Control headers for the js files.

Here is an example for apache web server.

How to retrieve raw post data from HttpServletRequest in java

The request body is available as byte stream by HttpServletRequest#getInputStream():

InputStream body = request.getInputStream();
// ...

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

How to center horizontally div inside parent div

I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.

div#child {
    margin: 0 auto;
}

What is the Eclipse shortcut for "public static void main(String args[])"?

Alternately, you can start a program containing the line with one click.

Just select the method stub for it when creating the new Java class, where the code says,

Which method stubs would you like to create?

[check-box] public static void main(String[]args) <---- Select this one.

[check-box] Constructors from superclass

[check-box] Inherited abstract methods

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Update: 8-20-2015

Please note the instructions have changed since this question was asked 2 yrs ago.

So on Newer versions of Android and Chrome for Android. You need to use this.

https://developers.google.com/web/tools/setup/remote-debugging/remote-debugging?hl=en

Original Answer:

I have the S3 and it works fine. I have found that a common mistake is not enabling USB Debugging in Chrome mobile. Not only do you have to enable USB debugging on the device itself under developer options but you have to go to the Chrome Browser on your phone and enable it in the settings there too.

Try this with the SDK

  1. Chrome for Mobile - Settings > Developer Tools > [x] Enable USB Web debugging
  2. Device - Settings > Developer options > [x] USB debugging
  3. Connect Device to Computer
  4. Enable port forwarding on your computer by doing the following command below

    C:\adb forward tcp:9222 localabstract:chrome_devtools_remote

Go to http://localhost:9222 in Chrome on your Computer

TroubleShooting:

If you get command not found when trying to run ADB, make sure Platform-Tools is in your path or just use the whole path to your SDK and run it

C:\path-to-SDK\platform-tools\adb forward tcp:9222 localabstract:chrome_devtools_remote

If you get "device not found", then run adb kill-server and then try again.

Specifying java version in maven - differences between properties and compiler plugin

How to specify the JDK version?

Use any of three ways: (1) Spring Boot feature, or use Maven compiler plugin with either (2) source & target or (3) with release.

Spring Boot

  1. <java.version> is not referenced in the Maven documentation.
    It is a Spring Boot specificity.
    It allows to set the source and the target java version with the same version such as this one to specify java 1.8 for both :

    1.8

Feel free to use it if you use Spring Boot.

maven-compiler-plugin with source & target

  1. Using maven-compiler-plugin or maven.compiler.source/maven.compiler.target properties are equivalent.

That is indeed :

<plugins>
    <plugin>    
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>

is equivalent to :

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

according to the Maven documentation of the compiler plugin since the <source> and the <target> elements in the compiler configuration use the properties maven.compiler.source and maven.compiler.target if they are defined.

source

The -source argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.source.

target

The -target argument for the Java compiler.
Default value is: 1.6.
User property is: maven.compiler.target.

About the default values for source and target, note that since the 3.8.0 of the maven compiler, the default values have changed from 1.5 to 1.6.

maven-compiler-plugin with release instead of source & target

  1. The maven-compiler-plugin 3.6 and later versions provide a new way :

    org.apache.maven.plugins maven-compiler-plugin 3.8.0 9

You could also declare just :

<properties>
    <maven.compiler.release>9</maven.compiler.release>
</properties>

But at this time it will not work as the maven-compiler-plugin default version you use doesn't rely on a recent enough version.

The Maven release argument conveys release : a new JVM standard option that we could pass from Java 9 :

Compiles against the public, supported and documented API for a specific VM version.

This way provides a standard way to specify the same version for the source, the target and the bootstrap JVM options.
Note that specifying the bootstrap is a good practice for cross compilations and it will not hurt if you don't make cross compilations either.


Which is the best way to specify the JDK version?

The first way (<java.version>) is allowed only if you use Spring Boot.

For Java 8 and below :

About the two other ways : valuing the maven.compiler.source/maven.compiler.target properties or using the maven-compiler-plugin, you can use one or the other. It changes nothing in the facts since finally the two solutions rely on the same properties and the same mechanism : the maven core compiler plugin.

Well, if you don't need to specify other properties or behavior than Java versions in the compiler plugin, using this way makes more sense as this is more concise:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

From Java 9 :

The release argument (third point) is a way to strongly consider if you want to use the same version for the source and the target.

What happens if the version differs between the JDK in JAVA_HOME and which one specified in the pom.xml?

It is not a problem if the JDK referenced by the JAVA_HOME is compatible with the version specified in the pom but to ensure a better cross-compilation compatibility think about adding the bootstrap JVM option with as value the path of the rt.jar of the target version.

An important thing to consider is that the source and the target version in the Maven configuration should not be superior to the JDK version referenced by the JAVA_HOME.
A older version of the JDK cannot compile with a more recent version since it doesn't know its specification.

To get information about the source, target and release supported versions according to the used JDK, please refer to java compilation : source, target and release supported versions.


How handle the case of JDK referenced by the JAVA_HOME is not compatible with the java target and/or source versions specified in the pom?

For example, if your JAVA_HOME refers to a JDK 1.7 and you specify a JDK 1.8 as source and target in the compiler configuration of your pom.xml, it will be a problem because as explained, the JDK 1.7 doesn't know how to compile with.
From its point of view, it is an unknown JDK version since it was released after it.
In this case, you should configure the Maven compiler plugin to specify the JDK in this way :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <compilerVersion>1.8</compilerVersion>      
        <fork>true</fork>
        <executable>D:\jdk1.8\bin\javac</executable>                
    </configuration>
</plugin>

You could have more details in examples with maven compiler plugin.


It is not asked but cases where that may be more complicated is when you specify source but not target. It may use a different version in target according to the source version. Rules are particular : you can read about them in the Cross-Compilation Options part.


Why the compiler plugin is traced in the output at the execution of the Maven package goal even if you don't specify it in the pom.xml?

To compile your code and more generally to perform all tasks required for a maven goal, Maven needs tools. So, it uses core Maven plugins (you recognize a core Maven plugin by its groupId : org.apache.maven.plugins) to do the required tasks : compiler plugin for compiling classes, test plugin for executing tests, and so for... So, even if you don't declare these plugins, they are bound to the execution of the Maven lifecycle.
At the root dir of your Maven project, you can run the command : mvn help:effective-pom to get the final pom effectively used. You could see among other information, attached plugins by Maven (specified or not in your pom.xml), with the used version, their configuration and the executed goals for each phase of the lifecycle.

In the output of the mvn help:effective-pom command, you could see the declaration of these core plugins in the <build><plugins> element, for example :

...
<plugin>
   <artifactId>maven-clean-plugin</artifactId>
   <version>2.5</version>
   <executions>
     <execution>
       <id>default-clean</id>
       <phase>clean</phase>
       <goals>
         <goal>clean</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-resources-plugin</artifactId>
   <version>2.6</version>
   <executions>
     <execution>
       <id>default-testResources</id>
       <phase>process-test-resources</phase>
       <goals>
         <goal>testResources</goal>
       </goals>
     </execution>
     <execution>
       <id>default-resources</id>
       <phase>process-resources</phase>
       <goals>
         <goal>resources</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
 <plugin>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.1</version>
   <executions>
     <execution>
       <id>default-compile</id>
       <phase>compile</phase>
       <goals>
         <goal>compile</goal>
       </goals>
     </execution>
     <execution>
       <id>default-testCompile</id>
       <phase>test-compile</phase>
       <goals>
         <goal>testCompile</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
  ...

You can have more information about it in the introduction of the Maven lifeycle in the Maven documentation.

Nevertheless, you can declare these plugins when you want to configure them with other values as default values (for example, you did it when you declared the maven-compiler plugin in your pom.xml to adjust the JDK version to use) or when you want to add some plugin executions not used by default in the Maven lifecycle.

Make div scrollable

Place this into your DIV style

overflow:scroll;

Prevent WebView from displaying "web page not available"

I suppose that if you insist on doing this, you could just check if the resource is there before calling the loadURL function. Just simply override the functions and do the check before calling the super()

REMARK (maybe off-topic): In http, there is a method called HEAD which is described as follow:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response

This method might be handy. Anyway how ever you implement it ... check this code:

import java.util.Map;

import android.content.Context;
import android.webkit.WebView;

public class WebViewPreLoad extends WebView{

public WebViewPreLoad(Context context) {
super(context);
}
public void loadUrl(String str){
if(//Check if exists)
super.loadUrl(str);
else
//handle error
}
public void loadUrl(String url, Map<String,String> extraHeaders){
if(//Check if exists)
super.loadUrl(url, extraHeaders);
else
//handle error
}
}

You could try this check using

if(url.openConnection().getContentLength() > 0)

PHP remove special character from string

Your dot is matching all characters. Escape it (and the other special characters), like this:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

How can I do DNS lookups in Python, including referring to /etc/hosts?

The answer above was meant for Python 2. If you're using Python 3, here is the code.

>>> import socket
>>> print(socket.gethostbyname('google.com'))
8.8.8.8
>>>

C++ Matrix Class

You could do it that way. The only difference is you'd need to cast the result from malloc.

Rather, you would use a vector, either as a 1D array with computed indexing or an embedded vector. (The former matches your code better.)

For example:

template <typename T> // often, they are templates
struct matrix
{
    // should probably be hidden away, and the class would
    // provide `at` and `operator()` for access
    int col, row;
    std::vector<T> data;

    matrix(int columns, int rows) :
    col(columns), row(rows), 
    data(col * row)
    {}

}

matrix m(4, 4);
m.data[1 + 1 * 4] = /* ... */;

Or:

template <typename T>
struct matrix
{
    int col, row;
    std::vector<std::vector<T> > data;

    matrix(int columns, int rows) :
    col(columns), row(rows), 
    data(col, std::vector(row))
    {}
}

matrix m(4, 4);
m.data[1][1] = /* ... */;

But these are only examples. You'd want to make a full-fledged class; if you want more advice on that, edit your question and clarify you'd like to know the canonical way of implementing matrix classes.

There are pre-existing matrix classes. My favorite is that from boost, UBLAS.

python: restarting a loop

a = ['1', '2', '3']
ls = []
count = False

while ls != a :
    print(a[count])
    if a[count] != a[-1] :
        count = count + 1
    else :
        count = False

Restart while loop.

unable to install pg gem

On Mac brew install postgres THEN bundle install

Difference between agile and iterative and incremental development

Some important and successfully executed software projects like Google Chrome and Mozilla Firefox are fine examples of both iterative and incremental software development.

I will quote fine ars technica article which describes this approach: http://arstechnica.com/information-technology/2010/07/chrome-team-sets-six-week-cadence-for-new-major-versions/

According to Chrome program manager Anthony Laforge, the increased pace is designed to address three main goals. One is to get new features out to users faster. The second is make the release schedule predictable and therefore easier to plan which features will be included and which features will be targeted for later releases. Third, and most counterintuitive, is to cut the level of stress for Chrome developers. Laforge explains that the shorter, predictable time periods between releases are more like "trains leaving Grand Central Station." New features that are ready don't have to wait for others that are taking longer to complete—they can just hop on the current release "train." This can in turn take the pressure off developers to rush to get other features done, since another release train will be coming in six weeks. And they can rest easy knowing their work isn't holding the train from leaving the station.<<

JavaScript open in a new window, not tab

I think its not html target properties problem but you unchecked "open nw windows in a new tab instead" option in "tab" tab under firefox "options" menu. check it and try again.

enter image description here

Open two instances of a file in a single Visual Studio session

I came up with a hack that might produce the result intended in the original answer.

If you have the file you want in two windows in a source control, you can right-click on the file and select compare, you can compare the

If you do compare you will have a new window Called diff, showing you the contents of you file.

This is of course not ideal as the diff window will have the diff colors polluting the text. Note: you can compare the file you want to open to and empty file, and then you will have the window in a very ugly green background.

This is not perfect, it is a hack, but it was the only way I found to really have the same file in two windows.

Yes or No confirm box using jQuery

Try This... It's very simple just use confirm dialog box for alert with YES|NO.

if(confirm("Do you want to upgrade?")){ Your code }

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

https://angular-ui.github.io/bootstrap/#/carousel

Code snip from UI Bootstrap Demo at the above link.

angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
  $scope.myInterval = 5000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {
    var newWidth = 600 + slides.length + 1;
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/300',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
});

Html From UI Bootstrap, Notice I added the .fade class to the example.

<div ng-controller="CarouselDemoCtrl">
    <div style="height: 305px">
        <carousel class="fade" interval="myInterval">
          <slide ng-repeat="slide in slides" active="slide.active">
            <img ng-src="{{slide.image}}" style="margin:auto;">
            <div class="carousel-caption">
              <h4>Slide {{$index}}</h4>
              <p>{{slide.text}}</p>
            </div>
          </slide>
        </carousel>
    </div>
</div>

CSS from Robert McKee's answer above

.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
/*
Added z-index to raise the left right controls to the top
*/
.carousel-control {
z-index:3;
}

Remove accents/diacritics in a string in JavaScript

You can use the _.deburr() method from the Lodash library.

It's available as a stand-alone NPM package lodash.deburr, or as part of the lodash package.

const myStringWithAccent = 'Mon café est plein de caféïne';
const myStringWithoutAccent = _.deburr( myStringWithAccent, );

The result will be : "Mon cafe est plein de cafeine"

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I had the same problem. I am using mysql 5.6.11. To solve this problem I had to change my-default.ini file in mysql-5.6.11-win32 folder So I just pasted the following lines under line [mysqld]

basedir="D:\mysql-5.6.11-win32\"
datadir="D:\mysql-5.6.11-win32\data\"
port=3306
server-id=1
bind-address=127.0.0.1

Options basedir and datadir need to be modified for mysql location.

Pandas DataFrame to List of Lists

You could access the underlying array and call its tolist method:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

What is the difference between Numpy's array() and asarray() functions?

Here's a simple example that can demonstrate the difference.

The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.

import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)

The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

h3 is absolutly a better solution than h2, h1 or h6 !

  1. You have to use specific level : if you're in a h1, use h2, if you're in a h5, use h6 (if you're in a h6... hum, use strong or em for exemple). It not a obligation but a question of accessibility (Here, green part).

  2. You don't have to give title to list... because this element it doesn't exist. So screen reader will not use something special.

Therefore, using Hn is probably one of the best solution, but surely not a specific level.

How to cut a string after a specific character in unix

This will also do.

echo $var | cut -f2 -d":"

How do I check for equality using Spark Dataframe without SQL Query?

I had the same issue, and the following syntax worked for me:

df.filter(df("state")==="TX").show()

I'm using Spark 1.6.

Recursively counting files in a Linux directory

ls -l | grep -e -x -e -dr | wc -l 
  1. long list
  2. filter files and dirs
  3. count the filtered line no

Difference between SurfaceView and View?

Views are all drawn on the same GUI thread which is also used for all user interaction.

So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.

How to define servlet filter order of execution using annotations in WAR

You can indeed not define the filter execution order using @WebFilter annotation. However, to minimize the web.xml usage, it's sufficient to annotate all filters with just a filterName so that you don't need the <filter> definition, but just a <filter-mapping> definition in the desired order.

For example,

@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}

with in web.xml just this:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern>/url2/*</url-pattern>
</filter-mapping>

If you'd like to keep the URL pattern in @WebFilter, then you can just do like so,

@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}

@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}

but you should still keep the <url-pattern> in web.xml, because it's required as per XSD, although it can be empty:

<filter-mapping>
    <filter-name>filter1</filter-name>
    <url-pattern />
</filter-mapping>
<filter-mapping>
    <filter-name>filter2</filter-name>
    <url-pattern />
</filter-mapping>

Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping> without <filter>. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

Undefined symbols for architecture armv7

Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file. In this case you'll need to use extern "C" {...} when you import the header files.

Linker error calling C-Function from Objective-C++

How to start Spyder IDE on Windows

Try the command spyder3 If you check the scripts folder you'll find spyder3.exe

How to stop event bubbling on checkbox click

When using jQuery you do not need to call a stop function separate.

You can just return false in the event handler

This will stop the event and cancel bubbling..

Also see event.preventDefault() vs. return false

From the jQuery docs:

These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

Automapper missing type map configuration or unsupported mapping - Error

Check your Global.asax.cs file and be sure that this line be there

 AutoMapperConfig.Configure();

How to insert a character in a string at a certain position?

For Kotlin dudes ;) from the accepted answer (@MikeThomsen's)

fun String.insert(index: Int, string: String): String {
    return this.substring(0, index) + string + this.substring(index, this.length)
}

Test ?

"ThisTest".insert(4, "Is").should.equal("ThisIsTest")

How to configure nginx to enable kinda 'file browser' mode?

Just add this section to server, just before the location / {

location /your/folder/to/browse/ {
        autoindex on;
}

'cannot find or open the pdb file' Visual Studio C++ 2013

No problem. You're running your code under the debugger, and the debugger is telling you that it doesn't have debugging information for the system libraries.

If you really need that (usually for stack traces), you can download it from Microsoft's symbol servers, but for now you don't need to worry.

How to change border color of textarea on :focus

There is an input:focus as there is a textarea:focus

input:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}
textarea:focus { 
    outline: none !important;
    border-color: #719ECE;
    box-shadow: 0 0 10px #719ECE;
}

Generate random numbers using C++11 random library

Here is some resource you can read about pseudo-random number generator.

https://en.wikipedia.org/wiki/Pseudorandom_number_generator

Basically, random numbers in computer need a seed (this number can be the current system time).

Replace

std::default_random_engine generator;

By

std::default_random_engine generator(<some seed number>);

Safest way to run BAT file from Powershell script

What about invoke-item script.bat.

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

Invalid application of sizeof to incomplete type with a struct

I think that the problem is that you put #ifdef instead of #ifndef at the top of your header.h file.

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

How to convert an address into a Google Maps Link (NOT MAP)

The best way is to use this line:

var mapUrl = "http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&amp;aq=0&amp;sll=37.0625,-95.677068&amp;sspn=61.282355,146.513672&amp;ie=UTF8&amp;hq=&amp;hnear=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&amp;spn=0.01628,0.025663&amp;z=14&amp;iwloc=A&amp;output=embed"

Remember to replace the first and second addresses when necessary.

You can look at work sample

Is <img> element block level or inline level?

behaves as an inline-block element as it allows other images in same line i.e. inline and also we can change the width and height of the image and this is the property of a block element. Hence, provide both the features of inline and block elements.

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to deserialize JS date using Jackson?

I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?

Here's what I did:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = jsonParser.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

}

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

How to Import .bson file format on mongodb

You have to run this mongorestore command via cmd and not on Mongo Shell... Have a look at below command on...

Run this command on cmd (not on Mongo shell)

>path\to\mongorestore.exe -d dbname -c collection_name path\to\same\collection.bson

Here path\to\mongorestore.exe is path of mongorestore.exe inside bin folder of mongodb. dbname is name of databse. collection_name is name of collection.bson. path\to\same\collection.bson is the path up to that collection.

Now from mongo shell you can verify that database is created or not (If it does not exist, database with same name will be created with collection).

Failed to load c++ bson extension

The only thing which helps me on Windows 7 (x64): https://stackoverflow.com/a/29714359/2670121

Reinstall node and python with x32 versions.
I spent a lot of time with this error:

Failed to load c++ bson extension

and finally, when I installed module node-gyp (for building native addons) and even installed windows SDK with visual studio - nodejs didn't recognize assembled module bson.node as a module. After reinstalling the problem is gone.

Again, What does this error mean?

Actually, it's even not error. You still can use mongoose. But in this case, instead of fast native realization of bson module, you got js-realization, which is slower.

I saw many tips like: "edit path deep inside node_modules..." - which is totally useless, because it does not solve the problem, but just turned off the error messages.

Linking static libraries to other static libraries

Alternatively to Link Library Dependencies in project properties there is another way to link libraries in Visual Studio.

  1. Open the project of the library (X) that you want to be combined with other libraries.
  2. Add the other libraries you want combined with X (Right Click, Add Existing Item...).
  3. Go to their properties and make sure Item Type is Library

This will include the other libraries in X as if you ran

lib /out:X.lib X.lib other1.lib other2.lib

NVIDIA NVML Driver/library version mismatch

I experienced this problem after a normal kernel update on a CentOS machine. Since all CUDA and nVidia drivers and libraries have been installed via YUM repositories, I managed to solve the issues using the following steps:

sudo yum remove nvidia-driver-*
sudo reboot
sudo yum install nvidia-driver-cuda nvidia-modprobe
sudo modprobe nvidia # or just reboot

It made sure my kernel and my nVidia driver are consistent. I reckon that just rebooting may result in wrong version of kernel module being loaded.

How to copy file from HDFS to the local file system

In order to copy files from HDFS to the local file system the following command could be run:

hadoop dfs -copyToLocal <input> <output>

  • <input>: the HDFS directory path (e.g /mydata) that you want to copy
  • <output>: the destination directory path (e.g. ~/Documents)

Detect Route Change with react-router

Update for React Router 5.1+.

import React from 'react';
import { useLocation, Switch } from 'react-router-dom'; 

const App = () => {
  const location = useLocation();

  React.useEffect(() => {
    console.log('Location changed');
  }, [location]);

  return (
    <Switch>
      {/* Routes go here */}
    </Switch>
  );
};

Check string for nil & empty

Swift 3 solution Use the optional unwrapped value and check against the boolean.

if (string?.isempty == true) {
    // Perform action
}

Calculating Page Table Size

Since the Logical Address space is 32-bit long that means program size is 2^32 bytes i.e. 4GB. Now we have the page size of 4KB i.e.2^12 bytes.Thus the number of pages in program are 2^20.(no. of pages in program = program size/page size).Now the size of page table entry is 4 byte hence the size of page table is 2^20*4 = 4MB(size of page table = no. of pages in program * page table entry size). Hence 4MB space is required in Memory to store the page table.

What is the list of valid @SuppressWarnings warning names in Java?

I noticed that //noinspection can be auto-generated in IntelliJ

  • make sure you have not already a plan @SuppressWarninigs before the statement
  • Now you can auto-generate the specific //noinspection by hitting Alt+Enter when you have the warning selected and then use the right arrow key to see the Suppress for ... option

Ended up here when I wanted to suppress a "switch has too few case labels" warning from IntelliJ. I did not find a complete List for IntelliJ's @SuppressWarning support but //noinspection did the trick for me.

String replace a Backslash

Try

   sSource = sSource.replaceAll("\\\\", "");

Edit : Ok even in stackoverflow there is backslash escape... You need to have four backslashes in your replaceAll first String argument...

The reason of this is because backslash is considered as an escape character for special characters (like \n for instance).
Moreover replaceAll first arg is a regular expression that also use backslash as escape sequence.
So for the regular expression you need to pass 2 backslash. To pass those two backslashes by a java String to the replaceAll, you also need to escape both backslashes.
That drives you to have four backslashes for your expression! That's the beauty of regex in java ;)

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

UICollectionView Set number of columns

First add UICollectionViewDelegateFlowLayout as protocol.

Then:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
        var columnCount = 3
        let width  = (view.frame.width - 20) / columnCount
        return CGSize(width: width, height: width)
}

Create an Array of Arraylists

I find this easier to use...

static ArrayList<Individual> group[];
......
void initializeGroup(int size)
{
 group=new ArrayList[size];
 for(int i=0;i<size;i++)
 {
  group[i]=new ArrayList<Individual>();
 }

Background blur with CSS

In recent versions of major browsers you can use backdrop-filter property.

HTML

<div>backdrop blur</div>

CSS

div {
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
}

or if you need different background color for browsers without support:

div {
    background-color: rgba(255, 255, 255, 0.9);
}

@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
    div {
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        background-color: rgba(255, 255, 255, 0.5);  
    }
}

Demo: JSFiddle

Docs: Mozilla Developer: backdrop-filter

Is it for me?: CanIUse

jump to line X in nano editor

The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

"Parse Error : There is a problem parsing the package" while installing Android application

Similar issue, using this "borrowed" and slightly modified code:

                Intent intent = new Intent(Intent.ACTION_VIEW);
                File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "myapp.apk");
                intent.setDataAndType(Uri.fromFile(newApk), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                result = true;

Needed to change the file creation to this (comma instead of plus in the File constructor, was missing '/' after the download directory):

                    File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myapp.apk");

How to assign a value to a TensorFlow variable?

There is an easier approach:

x = tf.Variable(0)
x = x + 1
print x.eval()

How to submit a form when the return key is pressed?

IMO, this is the cleanest answer:

_x000D_
_x000D_
<form action="" method="get">_x000D_
  Name: <input type="text" name="name"/><br/>_x000D_
  Pwd: <input type="password" name="password"/><br/>_x000D_
  <div class="yourCustomDiv"/>_x000D_
  <input type="submit" style="display:none"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.


It has been noted that display:none will cause IE to ignore the input. I created a new JSFiddle example that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from StriplingWarrior.

changing source on html5 video tag

Instead of getting the same video player to load new files, why not erase the entire <video> element and recreate it. Most browsers will automatically load it if the src's are correct.

Example (using Prototype):

var vid = new Element('video', { 'autoplay': 'autoplay', 'controls': 'controls' });
var src = new Element('source', { 'src': 'video.ogg', 'type': 'video/ogg' });

vid.update(src);
src.insert({ before: new Element('source', { 'src': 'video.mp4', 'type': 'video/mp4' }) });

$('container_div').update(vid);

What does the question mark in Java generics' type parameter mean?

In English:

It's a List of some type that extends the class HasWord, including HasWord

In general the ? in generics means any class. And the extends SomeClass specifies that that object must extend SomeClass (or be that class).

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

How to convert an int array to String with toString method in Java

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"

Can I set a breakpoint on 'memory access' in GDB?

What you're looking for is called a watchpoint.

Usage

(gdb) watch foo: watch the value of variable foo

(gdb) watch *(int*)0x12345678: watch the value pointed by an address, casted to whatever type you want

(gdb) watch a*b + c/d: watch an arbitrarily complex expression, valid in the program's native language

Watchpoints are of three kinds:

  • watch: gdb will break when a write occurs
  • rwatch: gdb will break wnen a read occurs
  • awatch: gdb will break in both cases

You may choose the more appropriate for your needs.

For more information, check this out.

How to install Android SDK on Ubuntu?

Android SDK Manager

Get it from the Snap Store

sudo snap install androidsdk

Usage

You can use the sdkmanager to perform the following tasks.

List installed and available packages

androidsdk --list [options]

Install packages

androidsdk packages [options]

The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.

For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:

androidsdk "platform-tools" "platforms;android-28"

Alternatively, you can pass a text file that specifies all packages:

androidsdk --package_file=package_file [options]

The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).

To uninstall, simply add the --uninstall flag:

androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]

Update all installed packages

androidsdk --update [options]

Note

androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk

Location of installed android sdk files : /home/user/AndroidSDK

See all sdkmanager options in google documentation

jQuery - checkbox enable/disable

<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="chk9[120]" class="chkGroup">
<input type="checkbox" name="chk9[140]" class="chkGroup">
<input type="checkbox" name="chk9[150]" class="chkGroup">
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

[Vue warn]: Cannot find element

I've solved the problem by add attribute 'defer' to the 'script' element.

setting y-axis limit in matplotlib

This should work. Your code works for me, like for Tamás and Manoj Govindan. It looks like you could try to update Matplotlib. If you can't update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with matplotlib.use() could help.

How to hide console window in python?

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :

    import win32gui, win32con;

    frgrnd_wndw = win32gui.GetForegroundWindow();
    wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
    if wndw_title.endswith("python.exe"):
        win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
    #endif
except  :
    pass

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

How to convert all tables in database to one collation?

You need to execute a alter table statement for each table. The statement would follow this form:

ALTER TABLE tbl_name
[[DEFAULT] CHARACTER SET charset_name]
[COLLATE collation_name]

Now to get all the tables in the database you would need to execute the following query:

SELECT * 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDataBaseName"
AND TABLE_TYPE="BASE TABLE";

So now let MySQL write the code for you:

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE your_collation_name_here;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDatabaseName"
AND TABLE_TYPE="BASE TABLE";

You can copy the results and execute them. I have not tested the syntax but you should be able to figure out the rest. Think of it as a little exercise.

Hope That Helps!

How to display (print) vector in Matlab?

You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.

Error importing Seaborn module in Python

I had faced the same problem. Restarting the notebook solved my problem.

If that doesn't solve the problem, you can try this

pip install seaborn

Edit

As few people have posted in the comments, you can also use

python -m pip install seaborn

Plus, as per https://bugs.python.org/issue22295 it is a better way because in this case, you can specify which version of python (python3 or python2) to use for running pip

Simple way to change the position of UIView?

@TomSwift Swift 3 answer

aView.center = CGPoint(x: 150, y: 150); // set center

Or

aView.frame = CGRect(x: 100, y: 200, width: aView.frame.size.width, height: aView.frame.size.height ); // set new position exactly

Or

aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10)) // offset by an amount

Pass arguments to Constructor in VBA

Another approach

Say you create a class clsBitcoinPublicKey

In the class module create an ADDITIONAL subroutine, that acts as you would want the real constructor to behave. Below I have named it ConstructorAdjunct.

Public Sub ConstructorAdjunct(ByVal ...)

 ...

End Sub

From the calling module, you use an additional statement

Dim loPublicKey AS clsBitcoinPublicKey

Set loPublicKey = New clsBitcoinPublicKey

Call loPublicKey.ConstructorAdjunct(...)

The only penalty is the extra call, but the advantage is that you can keep everything in the class module, and debugging becomes easier.

How to do this in Laravel, subquery where in

Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres

Here's an example of what you're trying to achieve:

DB::table('users')
    ->whereIn('id', function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id = users.id
)

How to change the timeout on a .NET WebClient object

According to kisp solution this is my edited version working async:

Class WebConnection.cs

internal class WebConnection : WebClient
{
    internal int Timeout { get; set; }

    protected override WebRequest GetWebRequest(Uri Address)
    {
        WebRequest WebReq = base.GetWebRequest(Address);
        WebReq.Timeout = Timeout * 1000 // Seconds
        return WebReq;
    }
}

The async Task

private async Task GetDataAsyncWithTimeout()
{
    await Task.Run(() =>
    {
        using (WebConnection webClient = new WebConnection())
        {
            webClient.Timeout = 5; // Five seconds
            webClient.DownloadData("https://www.yourwebsite.com");
        }
    });
} // await GetDataAsyncWithTimeout()

Else, if you don't want to use async:

private void GetDataSyncWithTimeout()
{
    using (WebConnection webClient = new WebConnection())
    {
        webClient.Timeout = 5; // Five seconds
        webClient.DownloadData("https://www.yourwebsite.com");
    }
} // GetDataSyncWithTimeout()

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.

VBA equivalent to Excel's mod function

The top answer is actually wrong.

The suggested equation: a - (b * (a \ b))

Will solve to: a - a

Which is of course 0 in all cases.

The correct equation is:

a - (b * INT(a \ b))

Or, if the number (a) can be negative, use this:

a - (b * FIX(a \ b))

python multithreading wait till all threads finished

You need to use join method of Thread object in the end of the script.

t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

Thus the main thread will wait till t1, t2 and t3 finish execution.

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

In spring boot 2.x you need to reference provider specific properties.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database

The default, hikari can be set with spring.datasource.hikari.maximum-pool-size.

fatal: early EOF fatal: index-pack failed

Using @cmpickle answer, I built a script to simplify the clone process.

It is hosted here: https://gist.github.com/gianlucaparadise/10286e0b1c5409bd1049d67640fb7c03

You can run it using the following line:

curl -sL https://git.io/JvtZ5 | sh -s repo_uri repo_folder

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

encrypt and decrypt md5

It's not possible to decrypt MD5 hash which created. You need all information to decrypt the MD5 value which was used during encryption.

You can use AES algorithm to encrypt and decrypt

JavaScript AES encryption and decryption (Advanced Encryption Standard)

How to insert logo with the title of a HTML page?

Yes you right and I just want to make it understandable for complete beginners.

  1. Create favicon.ico file you want to be shown next to your url in browsers tab. You can do that online. I used http://www.prodraw.net/favicon/generator.php it worked juts fine.
  2. Save generated ico file in your web site root directory /images (yourwebsite/images) under the name favicon.ico.
  3. Copy this tag <link rel="shortcut icon" href="images/favicon.ico" /> and past it without any changes in between <head> opening and </head> closing tag.
  4. Save changes in your html file and reload your browser.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Here is the solution I found:

How to fix the missing MSVCR711.dll problem

You can find MSVCR71.dll file in following location of your installed SQL Developer 2.1 directory:

sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll

Adding an HTTP Header to the request in a servlet filter

as https://stackoverflow.com/users/89391/miku pointed out this would be a complete ServletFilter example that uses the code that also works for Jersey to add the remote_addr header.

package com.bitplan.smartCRM.web;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 
 * @author wf
 * 
 */
public class RemoteAddrFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        String remote_addr = request.getRemoteAddr();
        requestWrapper.addHeader("remote_addr", remote_addr);
        chain.doFilter(requestWrapper, response); // Goes to default servlet.
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // https://stackoverflow.com/questions/2811769/adding-an-http-header-to-the-request-in-a-servlet-filter
    // http://sandeepmore.com/blog/2010/06/12/modifying-http-headers-using-java/
    // http://bijubnair.blogspot.de/2008/12/adding-header-information-to-existing.html
    /**
     * allow adding additional header entries to a request
     * 
     * @author wf
     * 
     */
    public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {
        /**
         * construct a wrapper for this request
         * 
         * @param request
         */
        public HeaderMapRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        private Map<String, String> headerMap = new HashMap<String, String>();

        /**
         * add a header with given name and value
         * 
         * @param name
         * @param value
         */
        public void addHeader(String name, String value) {
            headerMap.put(name, value);
        }

        @Override
        public String getHeader(String name) {
            String headerValue = super.getHeader(name);
            if (headerMap.containsKey(name)) {
                headerValue = headerMap.get(name);
            }
            return headerValue;
        }

        /**
         * get the Header names
         */
        @Override
        public Enumeration<String> getHeaderNames() {
            List<String> names = Collections.list(super.getHeaderNames());
            for (String name : headerMap.keySet()) {
                names.add(name);
            }
            return Collections.enumeration(names);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            List<String> values = Collections.list(super.getHeaders(name));
            if (headerMap.containsKey(name)) {
                values.add(headerMap.get(name));
            }
            return Collections.enumeration(values);
        }

    }

}

web.xml snippet:

<!--  first filter adds remote addr header -->
<filter>
    <filter-name>remoteAddrfilter</filter-name>
    <filter-class>com.bitplan.smartCRM.web.RemoteAddrFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>remoteAddrfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

How to use format() on a moment.js duration?

You can use numeral.js to format your duration:

numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

Rails ActiveRecord date between

Just a note that the currently accepted answer is deprecated in Rails 3. You should do this instead:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

Or, if you want to or have to use pure string conditions, you can do:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)

Reset CSS display property to default value

A browser's default styles are defined in its user agent stylesheet, the sources of which you can find here. Unfortunately, the Cascading and Inheritance level 3 spec does not appear to propose a way to reset a style property to its browser default. However there are plans to reintroduce a keyword for this in Cascading and Inheritance level 4 — the working group simply hasn't settled on a name for this keyword yet (the link currently says revert, but it is not final). Information about browser support for revert can be found on caniuse.com.

While the level 3 spec does introduce an initial keyword, setting a property to its initial value resets it to its default value as defined by CSS, not as defined by the browser. The initial value of display is inline; this is specified here. The initial keyword refers to that value, not the browser default. The spec itself makes this note under the all property:

For example, if an author specifies all: initial on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.

This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g. display: block from the UA style sheet on block elements such as <div>) will also be blown away.

So I guess the only way right now using pure CSS is to look up the browser default value and set it manually to that:

div.foo { display: inline-block; }
div.foo.bar { display: block; }

(An alternative to the above would be div.foo:not(.bar) { display: inline-block; }, but that involves modifying the original selector rather than an override.)

How do I download NLTK data?

If you are running a really old version of nltk, then there is indeed no download module available (reference)

Try this:

import nltk
print(nltk.__version__)

As per the reference, anything after 0.9.5 should be fine

How to split a string in Java

Assuming, that

  • you don't really need regular expressions for your split
  • you happen to already use apache commons lang in your app

The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.

Set size on background image with CSS?

put the below code in the body of you css file

background-image: URL('../images/wave-green-plain-colour.jpg') ;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width:100px;

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

In reactJS, how to copy text to clipboard?

 copyclip = (item) => {
    var textField = document.createElement('textarea')
    textField.innerText = item
    document.body.appendChild(textField)
    textField.select()
    document.execCommand('copy')
    this.setState({'copy':"Copied"});
    textField.remove()
    setTimeout(() => {
      this.setState({'copy':""});
    }, 1000);
 }

 <span   className="cursor-pointer ml-1" onClick={()=> this.copyclip(passTextFromHere)} >Copy</span> <small>{this.state.copy}</small>

"relocation R_X86_64_32S against " linking Error

Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time, you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld . Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

Smooth scroll without the use of jQuery

I recently set out to solve this problem in a situation where jQuery wasn't an option, so I'm logging my solution here just for posterity.

var scroll = (function() {

    var elementPosition = function(a) {
        return function() {
            return a.getBoundingClientRect().top;
        };
    };

    var scrolling = function( elementID ) {

        var el = document.getElementById( elementID ),
            elPos = elementPosition( el ),
            duration = 400,
            increment = Math.round( Math.abs( elPos() )/40 ),
            time = Math.round( duration/increment ),
            prev = 0,
            E;

        function scroller() {
            E = elPos();

            if (E === prev) {
                return;
            } else {
                prev = E;
            }

            increment = (E > -20 && E < 20) ? ((E > - 5 && E < 5) ? 1 : 5) : increment;

            if (E > 1 || E < -1) {

                if (E < 0) {
                    window.scrollBy( 0,-increment );
                } else {
                    window.scrollBy( 0,increment );
                }

                setTimeout(scroller, time);

            } else {

                el.scrollTo( 0,0 );

            }
        }

        scroller();
    };

    return {
        To: scrolling
    }

})();

/* usage */
scroll.To('elementID');

The scroll() function uses the Revealing Module Pattern to pass the target element's id to its scrolling() function, via scroll.To('id'), which sets the values used by the scroller() function.

Breakdown

In scrolling():

  • el : the target DOM object
  • elPos : returns a function via elememtPosition() which gives the position of the target element relative to the top of the page each time it's called.
  • duration : transition time in milliseconds.
  • increment : divides the starting position of the target element into 40 steps.
  • time : sets the timing of each step.
  • prev : the target element's previous position in scroller().
  • E : holds the target element's position in scroller().

The actual work is done by the scroller() function which continues to call itself (via setTimeout()) until the target element is at the top of the page or the page can scroll no more.

Each time scroller() is called it checks the current position of the target element (held in variable E) and if that is > 1 OR < -1 and if the page is still scrollable shifts the window by increment pixels - up or down depending if E is a positive or negative value. When E is neither > 1 OR < -1, or E === prev the function stops. I added the DOMElement.scrollTo() method on completion just to make sure the target element was bang on the top of the window (not that you'd notice it being out by a fraction of a pixel!).

The if statement on line 2 of scroller() checks to see if the page is scrolling (in cases where the target might be towards the bottom of the page and the page can scroll no further) by checking E against its previous position (prev).

The ternary condition below it reduce the increment value as E approaches zero. This stops the page overshooting one way and then bouncing back to overshoot the other, and then bouncing back to overshoot the other again, ping-pong style, to infinity and beyond.

If your page is more that c.4000px high you might want to increase the values in the ternary expression's first condition (here at +/-20) and/or the divisor which sets the increment value (here at 40).

Playing about with duration, the divisor which sets increment, and the values in the ternary condition of scroller() should allow you to tailor the function to suit your page.

  • JSFiddle

  • N.B.Tested in up-to-date versions of Firefox and Chrome on Lubuntu, and Firefox, Chrome and IE on Windows8.

Batch command date and time in file name

I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.

Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)

If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!

The DOS Batch command:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"

Prints:

Tue 04/09/2012 10:40:38.25
20120904-104038

Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.


EDIT:

A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.

So, these three lines of DOS batch:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%

Produce:

20120904-114434

So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:

sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log

And I'm a happy camper again (except life was still SOOOOO much easier on Unix).

Android: combining text & image on a Button or ImageButton

<Button android:id="@+id/myButton" 
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:text="Image Button"
    android:drawableTop="@drawable/myimage"         
    />  

Or you can programmatically:

Drawable drawable = getResources.getDrawable(R.drawable.myimage);
drawable.setBounds(0, 0, 60, 60);
myButton.setCompoundDrawables(null, drawable, null, null);//to the Top of the Button

wget/curl large file from google drive

I was unable to get Nanoix's perl script to work, or other curl examples I had seen, so I started looking into the api myself in python. This worked fine for small files, but large files choked past available ram so I found some other nice chunking code that uses the api's ability to partial download. Gist here: https://gist.github.com/csik/c4c90987224150e4a0b2

Note the bit about downloading client_secret json file from the API interface to your local directory.

Source
$ cat gdrive_dl.py
from pydrive.auth import GoogleAuth  
from pydrive.drive import GoogleDrive    

"""API calls to download a very large google drive file.  The drive API only allows downloading to ram 
   (unlike, say, the Requests library's streaming option) so the files has to be partially downloaded
   and chunked.  Authentication requires a google api key, and a local download of client_secrets.json
   Thanks to Radek for the key functions: http://stackoverflow.com/questions/27617258/memoryerror-how-to-download-large-file-via-google-drive-sdk-using-python
"""

def partial(total_byte_len, part_size_limit):
    s = []
    for p in range(0, total_byte_len, part_size_limit):
        last = min(total_byte_len - 1, p + part_size_limit - 1)
        s.append([p, last])
    return s

def GD_download_file(service, file_id):
  drive_file = service.files().get(fileId=file_id).execute()
  download_url = drive_file.get('downloadUrl')
  total_size = int(drive_file.get('fileSize'))
  s = partial(total_size, 100000000) # I'm downloading BIG files, so 100M chunk size is fine for me
  title = drive_file.get('title')
  originalFilename = drive_file.get('originalFilename')
  filename = './' + originalFilename
  if download_url:
      with open(filename, 'wb') as file:
        print "Bytes downloaded: "
        for bytes in s:
          headers = {"Range" : 'bytes=%s-%s' % (bytes[0], bytes[1])}
          resp, content = service._http.request(download_url, headers=headers)
          if resp.status == 206 :
                file.write(content)
                file.flush()
          else:
            print 'An error occurred: %s' % resp
            return None
          print str(bytes[1])+"..."
      return title, filename
  else:
    return None          


gauth = GoogleAuth()
gauth.CommandLineAuth() #requires cut and paste from a browser 

FILE_ID = 'SOMEID' #FileID is the simple file hash, like 0B1NzlxZ5RpdKS0NOS0x0Ym9kR0U

drive = GoogleDrive(gauth)
service = gauth.service
#file = drive.CreateFile({'id':FILE_ID})    # Use this to get file metadata
GD_download_file(service, FILE_ID) 

Ubuntu: Using curl to download an image

Create a new file called files.txt and paste the URLs one per line. Then run the following command.

xargs -n 1 curl -O < files.txt

source: https://www.abeautifulsite.net/downloading-a-list-of-urls-automatically

To get specific part of a string in c#

You can use Substring:

string b = a.Substring(0,3);

Java collections convert a string to a list of characters

Use a Java 8 Stream.

myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());

Breakdown:

myString
    .chars() // Convert to an IntStream
    .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
    .collect(Collectors.toList()); // Collect in a List<Character>

(I have absolutely no idea why String#chars() returns an IntStream.)

Check if value exists in the array (AngularJS)

You can use indexOf(). Like:

var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.


If you want to search from end to start, use the lastIndexOf() method:

    var Color = ["blue", "black", "brown", "gold"];
    var a = Color.lastIndexOf("brown");
    alert(a);

The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.

Returns -1 if the item is not found.

In AngularJS, what's the difference between ng-pristine and ng-dirty?

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

How to use and style new AlertDialog from appCompat 22.1 and above

If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating.

Here's my basic theme that simply modifies some colors with no nested themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/theme_colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
        <item name="colorAccent">@color/theme_colorAccent</item>
        <item name="colorControlActivated">@color/theme_colorControlActivated</item>
        <item name="android:windowBackground">@color/theme_bg</item>
        <item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
        <item name="colorButtonNormal">@color/theme_colorPrimary</item>
        <item name="colorControlHighlight">@color/theme_colorAccent</item>
    </style>

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

How to send a POST request using volley with string body?

You can refer to the following code (of course you can customize to get more details of the network response):

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("Title", "Android Volley Demo");
    jsonBody.put("Author", "BNK");
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

jQuery click not working for dynamically created items

Do this:

 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.

So, you have a wrapper which is hard-coded into the HTML source code:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.


Btw, I recommend Backbone.js - it gives structure to this process:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

I don't think answer from Vincent Malgrat is correct. When NVARCHAR2 was introduced long time ago nobody was even talking about Unicode.

Initially Oracle provided VARCHAR2 and NVARCHAR2 to support localization. Common data (include PL/SQL) was hold in VARCHAR2, most likely US7ASCII these days. Then you could apply NLS_NCHAR_CHARACTERSET individually (e.g. WE8ISO8859P1) for each of your customer in any country without touching the common part of your application.

Nowadays character set AL32UTF8 is the default which fully supports Unicode. In my opinion today there is no reason anymore to use NLS_NCHAR_CHARACTERSET, i.e. NVARCHAR2, NCHAR2, NCLOB. Note, there are more and more Oracle native functions which do not support NVARCHAR2, so you should really avoid it. Maybe the only reason is when you have to support mainly Asian characters where AL16UTF16 consumes less storage compared to AL32UTF8.

Shortcut key for commenting out lines of Python code in Spyder

  • Single line comment

    Ctrl + 1

  • Multi-line comment select the lines to be commented

    Ctrl + 4

  • Unblock Multi-line comment

    Ctrl + 5

WARNING: Can't verify CSRF token authenticity rails

I just thought I'd link this here as the article has most of the answer you're looking for and it's also very interesting

http://www.kalzumeus.com/2011/11/17/i-saw-an-extremely-subtle-bug-today-and-i-just-have-to-tell-someone/

Only mkdir if it does not exist

Do a test

[[ -d dir ]] || mkdir dir

Or use -p option:

mkdir -p dir

Select All Rows Using Entity Framework

Here is a few ways to do it (Just assume I'm using Dependency Injection for the DbConext)

public class Example
{
    private readonly DbContext Context;

    public Example(DbContext context)
    {
        Context = context;
    }

    public DbSetSampleOne[] DbSamples { get; set; }

    public void ExampleMethod DoSomething()
    {
        // Example 1: This will select everything from the entity you want to select
        DbSamples = Context.DbSetSampleOne.ToArray();

        // Example 2: If you want to apply some filtering use the following example
        DbSamples = Context.DbSetSampleOne.ToArray().Where(p => p.Field.Equals("some filter"))

    }

Passing in class names to react components

pill ${this.props.styleName} will get "pill undefined" when you don't set the props

I prefer

className={ "pill " + ( this.props.styleName || "") }

or

className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }

installing vmware tools: location of GCC binary?

Install prerequisites VMware Tools for LinuxOS:

If you have RHEL/CentOS:

yum install perl gcc make kernel-headers kernel-devel -y

If you have Ubuntu/Debian:

sudo apt-get -y install linux-headers-server build-essential
  • build-essential, also install: dpkg-dev, g++, gcc, lib6-dev, libc-dev, make

Extracted from: http://www.sysadmit.com/2016/01/vmware-tools-linux-instalar-requisitos.html

Reading my own Jar's Manifest

I will admit up front that this answer does not answer the original question, that of generally being able to access the Manifest. However if what is really required is to read one of a number of "standard" Manifest attributes, the following solution is much simpler than those posted above. So I hope that the moderator will allow it. Note that this solution is in Kotlin, not Java, but I would expect that a port to Java would be trivial. (Although I admit I don't know the Java equivalent of ".`package`".

In my case I wanted to read the attribute "Implementation-Version" so I started with the solutions given above to obtain the stream and then read it to obtain the value. While this solution worked, a coworker reviewing my code showed me an easier way to do what I wanted. Note that this solution is in Kotlin, not Java.

val myPackage = MyApplication::class.java.`package`
val implementationVersion = myPackage.implementationVersion

Once again note that this does not answer the original question, in particular "Export-package" does not seem to be one of the supported attributes. That said, there is a myPackage.name that returns a value. Perhaps someone who understands this more than I can comment on whether that returns the value the original poster is requesting.

Python: Making a beep noise

Linux.

$ apt-get install beep

$ python
>>> os.system("beep -f 555 -l 460")

OR

$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460

Pandas DataFrame: replace all values in a column, based on condition

Another option is to use a list comprehension:

df['First Season'] = [1 if year > 1990 else year for year in df['First Season']]

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Name node is in safe mode. Not able to leave

Run the command below using the HDFS OS user to disable safe mode:

sudo -u hdfs hadoop dfsadmin -safemode leave

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

Spring RestTemplate timeout

Here is a really simple way to set the timeout:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
      new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Add these lines to the file xampp\phpMyAdmin\config.inc:

$cfg['Servers'][$i]['controluser'] = 'root'; 
$cfg['Servers'][$i]['controlpass'] = '';

How to include view/partial specific styling in AngularJS

@tennisgent's solution is great. However, I think is a little limited.

Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

For a full solution I suggest using AngularCSS.

  1. Supports Angular's ngRoute, UI Router, directives, controllers and services.
  2. Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  3. You can customize where the stylesheets are injected: head, body, custom selector, etc...
  4. Supports preloading, persisting and cache busting
  5. Supports media queries and optimizes page load via matchMedia API

https://github.com/door3/angular-css

Here are some examples:

Routes

  $routeProvider
    .when('/page1', {
      templateUrl: 'page1/page1.html',
      controller: 'page1Ctrl',
      /* Now you can bind css to routes */
      css: 'page1/page1.css'
    })
    .when('/page2', {
      templateUrl: 'page2/page2.html',
      controller: 'page2Ctrl',
      /* You can also enable features like bust cache, persist and preload */
      css: {
        href: 'page2/page2.css',
        bustCache: true
      }
    })
    .when('/page3', {
      templateUrl: 'page3/page3.html',
      controller: 'page3Ctrl',
      /* This is how you can include multiple stylesheets */
      css: ['page3/page3.css','page3/page3-2.css']
    })
    .when('/page4', {
      templateUrl: 'page4/page4.html',
      controller: 'page4Ctrl',
      css: [
        {
          href: 'page4/page4.css',
          persist: true
        }, {
          href: 'page4/page4.mobile.css',
          /* Media Query support via window.matchMedia API
           * This will only add the stylesheet if the breakpoint matches */
          media: 'screen and (max-width : 768px)'
        }, {
          href: 'page4/page4.print.css',
          media: 'print'
        }
      ]
    });

Directives

myApp.directive('myDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'my-directive/my-directive.html',
    css: 'my-directive/my-directive.css'
  }
});

Additionally, you can use the $css service for edge cases:

myApp.controller('pageCtrl', function ($scope, $css) {

  // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
  $css.bind({ 
    href: 'my-page/my-page.css'
  }, $scope);

  // Simply add stylesheet(s)
  $css.add('my-page/my-page.css');

  // Simply remove stylesheet(s)
  $css.remove(['my-page/my-page.css','my-page/my-page2.css']);

  // Remove all stylesheets
  $css.removeAll();

});

You can read more about AngularCSS here:

http://door3.com/insights/introducing-angularcss-css-demand-angularjs

adb remount permission denied, but able to access super user in shell -- android

@echo off
color 0B
echo =============================================================================
echo.
echo              ClockworkMod Recovery for SAMSUNG GALAXY SIII E210L
echo.
echo                  ClockworkMod Recovery (v6.0.1.2 Touch)
echo.
echo     ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo     ¨U                                                                  ¨U
echo     ¨U SAMSUNG GALAXY SIII E210L                                        ¨U
echo     ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo.
echo  1) (Settings\Developer options©¥ USB debugging)
echo.
echo  2) CWM SAMSUNG GALAXY SIII E210L 
echo.
echo  3) THANK!!!!!!
echo.
echo =============================================================================
echo                           ARE YOU READY? GO! ¡·¡·¡·
@pause
echo.
echo adb...
adb.exe kill-server
adb.exe wait-for-device
echo wiat¸!
echo.
echo conect...
adb.exe push IMG /data/local/tmp/
adb.exe shell su -c "dd if=/data/local/tmp/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk of=/mnt/sdcard/Android/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk
adb.exe shell su -c "rm /data/local/tmp/bootloader.img"
adb.exe shell su -c "rm /data/local/tmp/recovery.img"


echo ===============================================================
echo     ClockworkMod Recovery!
echo.
@pause

What causes a java.lang.StackOverflowError

In my case I have two activities. In the second activity I forgot to put super on the onCreate method.

super.onCreate(savedInstanceState);

C# How to determine if a number is a multiple of another?

I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....

What's the simplest way to print a Java array?

Arrays.toString

As a direct answer, the solution provided by several, including @Esko, using the Arrays.toString and Arrays.deepToString methods, is simply the best.

Java 8 - Stream.collect(joining()), Stream.forEach

Below I try to list some of the other methods suggested, attempting to improve a little, with the most notable addition being the use of the Stream.collect operator, using a joining Collector, to mimic what the String.join is doing.

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

Difference between using Throwable and Exception in a try catch

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

@HostBinding and @HostListener: what do they do and what are they for?

One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }

It works, because it is a get accessor. You couldn't use a function equivalent:

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }

Otherwise, the benefit of using @HostBinding is it assures change detection is run when the bound value changes.

try/catch with InputMismatchException creates infinite loop

To follow debobroto das's answer you can also put after

input.reset();
input.next(); 

I had the same problem and when I tried this. It completely fixed it.

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

Go to the preview version of tomcat e.g. : tomcat 8.3 and copy catalina.jar file and paste into the existing tomcat which you have facing the issue

NOW() function in PHP

You might find this helpful

new \DateTime()

Rounding a variable to two decimal places C#

Pay attention on fact that Round rounds.

So (I don't know if it matters in your industry or not), but:

float a = 12.345f;
Math.Round(a,2);

//result:12,35, and NOT 12.34 !

To make it more precise for your case we can do something like this:

int aInt = (int)(a*100);
float aFloat= aInt /100.0f;
//result:12,34 

MVC3 EditorFor readOnly

Try using:

@Html.DisplayFor(model => model.userName) <br/>
@Html.HiddenFor(model => model.userName)

Why does the Google Play store say my Android app is incompatible with my own device?

In Android some permissions <uses-permission> will imply <uses-feature> requirements to the app.

For example <uses-permission android:name="android.permission.BLUETOOTH" />
Will imply <uses-feature android:name="android.hardware.bluetooth"/>

You can check the whole list here https://developer.android.com/guide/topics/manifest/uses-feature-element#permissions

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Testing Private method using mockito

You're not suppose to test private methods. Only non-private methods needs to be tested as these should call the private methods anyway. If you "want" to test private methods, it may indicate that you need to rethink your design:

Am I using proper dependency injection? Do I possibly needs to move the private methods into a separate class and rather test that? Must these methods be private? ...can't they be default or protected rather?

In the above instance, the two methods that are called "randomly" may actually need to be placed in a class of their own, tested and then injected into the class above.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Stretch child div height to fill parent that has dynamic height

Use display: flex to stretch your divs:

div#container {
    padding:20px;
    background:#F1F1F1;
    display: flex;
}

.content {
    width:150px;
    background:#ddd;
    padding:10px;
    margin-left: 10px;
}

JSFIDDLE

Using union and count(*) together in SQL query

select T1.name, count (*)
from (select name from Results 
      union 
      select name from Archive_Results) as T1
group by T1.name order by T1.name

Including JavaScript class definition from another file in Node.js

Modify your class definition to read like this:

exports.User = function (socket) {
  ...
};

Then rename the file to user.js. Assuming it's in the root directory of your main script, you can include it like this:

var user = require('./user');
var someUser = new user.User();

That's the quick and dirty version. Read about CommonJS Modules if you'd like to learn more.

How to do a non-greedy match in grep?

Sorry I am 9 years late, but this might work for the viewers in 2020.

So suppose you have a line like "Hello my name is Jello". Now you want to find the words that start with 'H' and end with 'o', with any number of characters in between. And we don't want lines we just want words. So for that we can use the expression:

grep "H[^ ]*o" file

This will return all the words. The way this works is that: It will allow all the characters instead of space character in between, this way we can avoid multiple words in the same line.

Now you can replace the space character with any other character you want. Suppose the initial line was "Hello-my-name-is-Jello", then you can get words using the expression:

grep "H[^-]*o" file

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

What is the right way to check for a null string in Objective-C?

@interface NSString (StringFunctions)
- (BOOL) hasCharacters;
@end

@implementation NSString (StringFunctions)
- (BOOL) hasCharacters {
    if(self == (id)[NSNull null]) {
        return NO;
    }else {
        if([self length] == 0) {
            return NO;
        }
    }
    return YES;
}
@end

NSString *strOne = nil;
if([strOne hasCharacters]) {
    NSLog(@"%@",strOne);
}else {
    NSLog(@"String is Empty");
}

This would work with the following cases, NSString *strOne = @"" OR NSString *strOne = @"StackOverflow" OR NSString *strOne = [NSNull null] OR NSString *strOne.

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

Cross browser method to fit a child div to its parent's width

In case you want to use that padding space... then here's something:

http://jsfiddle.net/qD4zd/

All the colors are background colors.

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

Rank function in MySQL

Here is a generic solution that assigns dense rank over partition to rows. It uses user variables:

CREATE TABLE person (
    id INT NOT NULL PRIMARY KEY,
    firstname VARCHAR(10),
    gender VARCHAR(1),
    age INT
);

INSERT INTO person (id, firstname, gender, age) VALUES
(1,  'Adams',  'M', 33),
(2,  'Matt',   'M', 31),
(3,  'Grace',  'F', 25),
(4,  'Harry',  'M', 20),
(5,  'Scott',  'M', 30),
(6,  'Sarah',  'F', 30),
(7,  'Tony',   'M', 30),
(8,  'Lucy',   'F', 27),
(9,  'Zoe',    'F', 30),
(10, 'Megan',  'F', 26),
(11, 'Emily',  'F', 20),
(12, 'Peter',  'M', 20),
(13, 'John',   'M', 21),
(14, 'Kate',   'F', 35),
(15, 'James',  'M', 32),
(16, 'Cole',   'M', 25),
(17, 'Dennis', 'M', 27),
(18, 'Smith',  'M', 35),
(19, 'Zack',   'M', 35),
(20, 'Jill',   'F', 25);

SELECT person.*, @rank := CASE
    WHEN @partval = gender AND @rankval = age THEN @rank
    WHEN @partval = gender AND (@rankval := age) IS NOT NULL THEN @rank + 1
    WHEN (@partval := gender) IS NOT NULL AND (@rankval := age) IS NOT NULL THEN 1
END AS rnk
FROM person, (SELECT @rank := NULL, @partval := NULL, @rankval := NULL) AS x
ORDER BY gender, age;

Notice that the variable assignments are placed inside the CASE expression. This (in theory) takes care of order of evaluation issue. The IS NOT NULL is added to handle datatype conversion and short circuiting issues.

PS: It can easily be converted to row number over partition by by removing all conditions that check for tie.

| id | firstname | gender | age | rank |
|----|-----------|--------|-----|------|
| 11 | Emily     | F      | 20  | 1    |
| 20 | Jill      | F      | 25  | 2    |
| 3  | Grace     | F      | 25  | 2    |
| 10 | Megan     | F      | 26  | 3    |
| 8  | Lucy      | F      | 27  | 4    |
| 6  | Sarah     | F      | 30  | 5    |
| 9  | Zoe       | F      | 30  | 5    |
| 14 | Kate      | F      | 35  | 6    |
| 4  | Harry     | M      | 20  | 1    |
| 12 | Peter     | M      | 20  | 1    |
| 13 | John      | M      | 21  | 2    |
| 16 | Cole      | M      | 25  | 3    |
| 17 | Dennis    | M      | 27  | 4    |
| 7  | Tony      | M      | 30  | 5    |
| 5  | Scott     | M      | 30  | 5    |
| 2  | Matt      | M      | 31  | 6    |
| 15 | James     | M      | 32  | 7    |
| 1  | Adams     | M      | 33  | 8    |
| 18 | Smith     | M      | 35  | 9    |
| 19 | Zack      | M      | 35  | 9    |

Demo on db<>fiddle

What is a void pointer in C++?

Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

General Syntax:

void* pointer_variable;

void *pVoid; // pVoid is a void pointer

A void pointer can point to objects of any data type:

int nValue;
float fValue;

struct Something
{
    int nValue;
    float fValue;
};

Something sValue;

void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid

However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

int nValue = 5;
void *pVoid = &nValue;

// can not dereference pVoid because it is a void pointer

int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Source: link

How do you add swap to an EC2 instance?

After applying the steps mentioned by ajtrichards you can check if your amazon free tier instance is using swap using this command

cat /proc/meminfo

result:

ubuntu@ip-172-31-24-245:/$ cat /proc/meminfo
MemTotal:         604340 kB
MemFree:            8524 kB
Buffers:            3380 kB
Cached:           398316 kB
SwapCached:            0 kB
Active:           165476 kB
Inactive:         384556 kB
Active(anon):     141344 kB
Inactive(anon):     7248 kB
Active(file):      24132 kB
Inactive(file):   377308 kB
Unevictable:           0 kB
Mlocked:               0 kB

SwapTotal: 1048572 kB

SwapFree: 1048572 kB

Dirty:                 0 kB
Writeback:             0 kB
AnonPages:        148368 kB
Mapped:            14304 kB
Shmem:               256 kB
Slab:              26392 kB
SReclaimable:      18648 kB
SUnreclaim:         7744 kB
KernelStack:         736 kB
PageTables:         5060 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1350740 kB
Committed_AS:     623908 kB
VmallocTotal:   34359738367 kB
VmallocUsed:        7420 kB
VmallocChunk:   34359728748 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:      637952 kB
DirectMap2M:           0 kB

Reading Properties file in Java

Make sure that the file name is correct and that the file is actually in the class path. getResourceAsStream() will return null if this is not the case which causes the last line to throw the exception.

If myProp.properties is in the root directory of your project, use /myProp.properties instead.

jQuery/Javascript function to clear all the fields of a form

HTML

<form id="contactform"></form>

JavaScript

 var $contactform = $('#contactform')
    $($contactform).find("input[type=text] , textarea ").each(function(){
                $(this).val('');            
    });

Simple and short function to clear all fields

Use a JSON array with objects with javascript

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

Static image src in Vue.js template

If you want to bind a string to the src attribute, you should wrap it on single quotes:

<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">

IMO you do not need to bind a string, you could use the simple way:

<img src="/static/img/clear.gif">

Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL

How to convert index of a pandas dataframe into a column?

df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123

Escape dot in a regex range

Because the dot is inside character class (square brackets []).

Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):

Any character except ^-]\ add that character to the possible matches for the character class.

Clearing _POST array fully

To unset the $_POST variable, redeclare it as an empty array:

$_POST = array();

PHP Call to undefined function

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload['helper'] = array('common','security','url');

common is the name of my controller.

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

How to delete file from public folder in laravel 5.1

If you store your image in folder public, try this steps:

For example your image is sample.jpg and your path is public/img/sample.jpg so this codes will delete your image

use Illuminate\Support\Facades\File;
.
.
.


public function deleteImage(){

   $imgWillDelete = public_path() . '/img/sample.jpg';
   File::delete($imgWillDelete);
}

How to pass html string to webview on android

I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.

String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");

Find details on WebView

Copy values from one column to another in the same table

Short answer for the code in question is:

UPDATE `table` SET test=number

Here table is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE is a keyword in that case).

BEWARE, that this is pretty dangerous query which will wipe everything in column test in every row of your table replacing it by the number (regardless of it's value)

It is more common to use WHERE clause to limit your query to only specific set of rows:

UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10

Composer: The requested PHP extension ext-intl * is missing from your system

I encountered this using it in Mac, resolved it by using --ignore-platform-reqs option.

composer install --ignore-platform-reqs

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

List<String> collectionOfStrings = // List of string to concat
String csvStrings = StringUtils.collectionToDelimitedString(collectionOfStrings, ",");

StringUtils from springframeowrk:spring-core

Endless loop in C/C++

The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.

Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.

The while(1), while(true) and for(;;) are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.


for(;;)

  • This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:

    K&R 2nd ed 3.5:

    for (;;) {
    ...
    }
    

    is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.

    For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;), this would have been regarded as the most correct form at least up until the C standardization in 1990.

    However, K&R themselves already stated that it was a matter of preference.

    And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.

    But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;).

  • The argument against the for(;;) loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:

    ISO 9899:2011 6.8.5.3:

    for ( clause-1 ; expression-2 ; expression-3 ) statement
    

    /--/

    Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

    Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.


while(1)

  • This is supposedly a more readable form than for(;;). However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.

  • There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1), when the programmer intended to write while(i == 1).

    Also, external static code analysers are likely to whine about "condition is always true".


while(true)

  • To make while(1) even more readable, some use while(true) instead. The consensus among programmers seem to be that this is the most readable form.

  • However, this form has the same problem as while(1), as described above: "condition is always true" warnings.

  • When it comes to C, this form has another disadvantage, namely that it uses the macro true from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool exists as a primitive data type and true is a language keyword.

  • Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.


So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.

Personally, I always use for(;;) just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:

If even a C beginner knows that for(;;) means an eternal loop, then who are you trying to make the code more readable for?

I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.

And since everyone who should be reading your code already knows what for(;;) means, there is no point in making it further readable - it is already as readable as it gets.

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

Is there a css cross-browser value for "width: -moz-fit-content;"?

I use these:

.right {display:table; margin:-18px 0 0 auto;}
.center {display:table; margin:-18px auto 0 auto;}

AngularJS ngClass conditional

Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.

Type 1

<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>

In this code class will be apply according to value of status value

if status value is 0 then apply class one

if status value is 1 then apply class two

if status value is 2 then apply class three


Type 2

<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>

In which class will be apply by value of status

if status value is 1 or true then it will add class test_yes

if status value is 0 or false then it will add class test_no

How do I search for an object by its ObjectId in the mongo console?

Once you opened the mongo CLI, connected and authorized on the right database.

The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:

db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})