Programs & Examples On #Rewritepath

Redirects a request for a resource to a different path than the one that is indicated by the requested URL. One of the uses of `RewritePath` is to strip session IDs from URLs.

ASP.NET MVC: No parameterless constructor defined for this object

So I have gotten that message before as well, when doing an ajax call. So what it's basically asking for is a constructor in that model class that is being called by the contoller, doesn't have any parameter.

Here is an example

public class MyClass{

     public MyClass(){} // so here would be your parameterless constructor

 }

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

javascript functions to show and hide divs

<script> 
    function show() { 
        if(document.getElementById('benefits').style.display=='none') { 
            document.getElementById('benefits').style.display='block'; 
        } 
        return false;
    } 
    function hide() { 
        if(document.getElementById('benefits').style.display=='block') { 
            document.getElementById('benefits').style.display='none'; 
        } 
        return false;
    }   
</script> 


 <div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div> 
    <div id="benefits" style="display:none;">some input in here plus the close button 
           <div id="upbutton"><a onclick="return hide();">click here</a></div> 
    </div> 

Notepad++ Multi editing

Notepad++ also handles multiple cursors now.

Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.

Feature demo on official website here : https://npp-user-manual.org/docs/editing/

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

How to set a parameter in a HttpServletRequest?

As mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that apart from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.g. the value of a param added by the custom request wrapper should also be included in the parameters map returned by the method getParameterMap(). Here is an example:

   public class AddableHttpRequest extends HttpServletRequestWrapper {

    /** A map containing additional request params this wrapper adds to the wrapped request */
    private final Map<String, String> params = new HashMap<>();

    /**
     * Constructs a request object wrapping the given request.
     * @throws java.lang.IllegalArgumentException if the request is null
     */
    AddableHttpRequest(final HttpServletRequest request) {
        super(request)
    }

    @Override
    public String getParameter(final String name) {
        // if we added one with the given name, return that one
        if ( params.get( name ) != null ) {
            return params.get( name );
        } else {
            // otherwise return what's in the original request
            return super.getParameter(name);
        }
    }


    /**
     * *** OVERRIDE THE METHODS BELOW TO REFLECT PARAMETERS ADDED BY THIS WRAPPER ****
     */

    @Override
    public Map<String, String> getParameterMap() {
        // defaulf impl, should be overridden for an approprivate map of request params
        return super.getParameterMap();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        // defaulf impl, should be overridden for an approprivate map of request params names
        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(final String name) {
        // defaulf impl, should be overridden for an approprivate map of request params values
        return super.getParameterValues(name);
    }
}

Why does DEBUG=False setting make my django Static Files Access fail?

Although it's not safest, but you can change in the source code. navigate to Python/2.7/site-packages/django/conf/urls/static.py

Then edit like following:

if settings.DEBUG or (prefix and '://' in prefix):

So then if settings.debug==False it won't effect on the code, also after running try python manage.py runserver --runserver to run static files.

NOTE: Information should only be used for testing only

Get int value from enum in C#

Use:

Question question = Question.Role;
int value = Convert.ToInt32(question);

Redirect to specified URL on PHP script completion?

<?
ob_start(); // ensures anything dumped out will be caught

// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever

// clear out the output buffer
while (ob_get_status()) 
{
    ob_end_clean();
}

// no redirect
header( "Location: $url" );
?>

UIWebView open links in Safari

Here's the Xamarin iOS equivalent of drawnonward's answer.

class WebviewDelegate : UIWebViewDelegate {
    public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
        if (navigationType == UIWebViewNavigationType.LinkClicked) {
            UIApplication.SharedApplication.OpenUrl (request.Url);
            return false;
        }
        return true;
    }
}

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

Have bash script answer interactive prompts

There is a special build-in util for this - 'yes'.

To answer all questions with the same answer, you can run

yes [answer] |./your_script

Or you can put it inside your script have specific answer to each question

How to count no of lines in text file and store the value into a variable using batch script?

I usually use something more like this for /f %%a in (%_file%) do (set /a Lines+=1)

Where do I find the Instagram media ID of a image

Here is python solution to do this without api call.

def media_id_to_code(media_id):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    short_code = ''
    while media_id > 0:
        remainder = media_id % 64
        media_id = (media_id-remainder)/64
        short_code = alphabet[remainder] + short_code
    return short_code


def code_to_media_id(short_code):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    media_id = 0;
    for letter in short_code:
        media_id = (media_id*64) + alphabet.index(letter)

    return media_id

How to get the Android Emulator's IP address?

Like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Check the docs for more info: NetworkInterface.

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

Array versus List<T>: When to use which?

It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.

Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

When tree width is very large and depth is low use DFS as recursion stack will not overflow.Use BFS when width is low and depth is very large to traverse the tree.

Is a LINQ statement faster than a 'foreach' loop?

It should probably be noted that the for loop is faster than the foreach. So for the original post, if you are worried about performance on a critical component like a renderer, use a for loop.

Reference: In .NET, which loop runs faster, 'for' or 'foreach'?

Using curl POST with variables defined in bash script functions

Solution tested with https://httpbin.org/ and inline bash script
1. For variables without spaces in it i.e. 1:
Simply add ' before and after $variable when replacing desired string

for i in {1..3}; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"number":"'$i'"}' "https://httpbin.org/post"; \
done

2. For input with spaces:
Wrap variable with additional " i.e. "el a":

declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
  curl -X POST -H "Content-Type: application/json" -d \
    '{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done

Wow works :)

Parameter in like clause JPQL

Just leave out the ''

LIKE %:code%

How to get a value inside an ArrayList java

The list may contain several elements, so the get method takes an argument : the index of the element you want to retrieve. If you want the first one, then it's 0.

The list contains Car instances, so you just have to do

Car firstCar = car.get(0);
String price = firstCar.getPrice();

or just

String price = car.get(0).getPrice();

The car variable should be named cars, since it's a list and thus contains several cars.

Read the tutorial about collections. And learn to use the javadoc: all the classes and methods are documented.

Print JSON parsed object?

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

How to config Tomcat to serve images from an external folder outside webapps?

This is very simple and straight forward to server the static content from outside webapps folder in tomcat.

Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        **<Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />**

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

Add the context element inside the host element with two attribute docBase and path.

1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.

For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:

http://localhost:8081/companyLogo/7.png

For more details, check the blog

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

What's the difference between <b> and <strong>, <i> and <em>?

b or i means you want the text to be rendered as bold or italics. strong or em means you want the text to be rendered in a way that the user understands as "important". The default is to render strong as bold and em as italics, but some other cultures might use a different mapping.

Like strings in a program, b and i would be "hard coded" while strong and em would be "localized".

Jackson JSON custom serialization for certain fields

jackson-annotations provides @JsonFormat which can handle a lot of customizations without the need to write the custom serializer.

For example, requesting a STRING shape for a field with numeric type will output the numeric value as string

public class Person {
    public String name;
    public int age;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public int favoriteNumber;
}

will result in the desired output

{"name":"Joe","age":25,"favoriteNumber":"123"}

What exactly are DLL files, and how do they work?

According to Microsoft

(DLL) Dynamic link libraries are files that contain data, code, or resources needed for the running of applications. These are files that are created by the windows ecosystem and can be shared between two or more applications.

When a program or software runs on Windows, much of how the application works depends on the DLL files of the program. For instance, if a particular application had several modules, then how each module interacts with each other is determined by the Windows DLL files.

If you want detailed explanation, check these useful resources

What are dll files , About Dll files

how to draw smooth curve through N points using javascript HTML5 canvas?

This code is perfect for me:

this.context.beginPath();
this.context.moveTo(data[0].x, data[0].y);
for (let i = 1; i < data.length; i++) {
  this.context.bezierCurveTo(
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i - 1].y,
    data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
    data[i].y,
    data[i].x,
    data[i].y);
}

you have correct smooth line and correct endPoints NOTICE! (y = "canvas height" - y);

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

select certain columns of a data table

Also we can try like this,

 string[] selectedColumns = new[] { "Column1","Column2"};

 DataTable dt= new DataView(fromDataTable).ToTable(false, selectedColumns);

Converting Dictionary to List?

Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.

To fix your code, try something like:

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.

Or just use dict.items() as has been suggested.

Use latest version of Internet Explorer in the webbrowser control

I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion


    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}

What's the difference between 'int?' and 'int' in C#?

the symbol ? after the int means that it can be nullable.

The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.

Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.

What is the garbage collector in Java?

The garbage collector allows your computer to simulate a computer with infinite memory. The rest is just mechanism.

It does this by detecting when chunks of memory are no longer accessible from your code, and returning those chunks to the free store.

EDIT: Yes, the link is for C#, but C# and Java are identical in this regard.

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Moving items around in an ArrayList

Applying recursion to reorder items in an arraylist

public class ArrayListUtils {
            public static <T> void reArrange(List<T> list,int from, int to){
                if(from != to){
                     if(from > to)
                        reArrange(list,from -1, to);
                      else
                        reArrange(list,from +1, to);

                     Collections.swap(list, from, to);
                }
            }
    }

Storing WPF Image Resources

Full description how to use resources: WPF Application Resource, Content, and Data Files

And how to reference them, read "Pack URIs in WPF".

In short, there is even means to reference resources from referenced/referencing assemblies.

How to automatically reload a page after a given period of inactivity

This task is very easy use following code in html header section

<head> <meta http-equiv="refresh" content="30" /> </head>

It will refresh your page after 30 seconds.

Calculate last day of month in JavaScript

Try this:

function _getEndOfMonth(time_stamp) {
    let time = new Date(time_stamp * 1000);
    let month = time.getMonth() + 1;
    let year = time.getFullYear();
    let day = time.getDate();
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        case 2:
            if (_leapyear(year))
                day = 29;
            else
                day = 28;
            break
    }
    let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
    return m.unix() + constants.DAY - 1;
}

function _leapyear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}

How to change the docker image installation directory?

On openSUSE Leap 42.1

$cat /etc/sysconfig/docker 
## Path           : System/Management
## Description    : Extra cli switches for docker daemon
## Type           : string
## Default        : ""
## ServiceRestart : docker
#
DOCKER_OPTS="-g /media/data/installed/docker"

Note that DOCKER_OPTS was initially empty and all I did was add in the argument to make docker use my new directory

How to correct TypeError: Unicode-objects must be encoded before hashing?

The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes, e.g. with line.encode('utf-8').

How do I load a PHP file into a variable?

ob_start();
include "yourfile.php";
$myvar = ob_get_clean();

ob_get_clean()

How can I convert a comma-separated string to an array?

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.

How to access model hasMany Relation with where condition?

I have fixed the similar issue by passing associative array as the first argument inside Builder::with method.

Imagine you want to include child relations by some dynamic parameters but don't want to filter parent results.

Model.php

public function child ()
{
    return $this->hasMany(ChildModel::class);
}

Then, in other place, when your logic is placed you can do something like filtering relation by HasMany class. For example (very similar to my case):

$search = 'Some search string';
$result = Model::query()->with(
    [
        'child' => function (HasMany $query) use ($search) {
            $query->where('name', 'like', "%{$search}%");
        }
    ]
);

Then you will filter all the child results but parent models will not filter. Thank you for attention.

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

How to extract IP Address in Spring MVC Controller get call?

I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr() works.

In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.

So you should access the X-Forwarded-For http header in such a case to get the user's IP address.

e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");

Hope this helps.

Display curl output in readable JSON format in Unix shell script

This is to add to of Gilles' Answer. There are many ways to get this done but personally I prefer something lightweight, easy to remember and universally available (e.g. come with standard LTS installations of your preferred Linux flavor or easy to install) on common *nix systems.

Here are the options in their preferred order:

Python Json.tool module

echo '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool

pros: almost available everywhere; cons: no color coding


jq (may require one time installation)

echo '{"foo": "lorem", "bar": "ipsum"}' | jq

cons: needs to install jq; pros: color coding and versatile


json_pp (available in Ubuntu 16.04 LTS)

echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp

For Ruby users

gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty

Android Studio shortcuts like Eclipse

You can change your keymap to use eclipse shortcuts. You can see here how to change keymap. https://stackoverflow.com/a/25419358

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

How to get Bitmap from an Uri?

This is the easiest solution:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

Error while installing json gem 'mkmf.rb can't find header files for ruby'

Most voted solution didn't work on my machine (linux mint 18.04). After a careful look, i found that g++ was missing. Solved with

sudo apt-get install g++

Copy files from one directory into an existing directory

cp -R t1/ t2

The trailing slash on the source directory changes the semantics slightly, so it copies the contents but not the directory itself. It also avoids the problems with globbing and invisible files that Bertrand's answer has (copying t1/* misses invisible files, copying `t1/* t1/.*' copies t1/. and t1/.., which you don't want).

Convert timestamp in milliseconds to string formatted time in Java

I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses java.util.Calendar, another uses Joda-Time, and the last uses the java.time framework built into Java 8 and later.

The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

java.util.Date & .Calendar

final long timestamp = new Date().getTime();

// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

Joda-Time

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);

Output:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );

System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771

How to concatenate a std::string and an int?

If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).

Another way is to use stringstreams:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

A third approach would be to use sprintf or snprintf from the C library.

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

Different font size of strings in the same TextView

Just in case you're wondering how you can set multiple different sizes in the same textview, but using an absolute size and not a relative one, you can achieve that using AbsoluteSizeSpan instead of a RelativeSizeSpan.

Just get the dimension in pixels of the desired text size

int textSize1 = getResources().getDimensionPixelSize(R.dimen.text_size_1);
int textSize2 = getResources().getDimensionPixelSize(R.dimen.text_size_2);

and then create a new AbsoluteSpan based on the text

String text1 = "Hi";
String text2 = "there";

SpannableString span1 = new SpannableString(text1);
span1.setSpan(new AbsoluteSizeSpan(textSize1), 0, text1.length(), SPAN_INCLUSIVE_INCLUSIVE);

SpannableString span2 = new SpannableString(text2);
span2.setSpan(new AbsoluteSizeSpan(textSize2), 0, text2.length(), SPAN_INCLUSIVE_INCLUSIVE);

// let's put both spans together with a separator and all
CharSequence finalText = TextUtils.concat(span1, " ", span2);

jQuery ajax error function

From jquery.com:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual 
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want global handlers you can use:

.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()

How can I get the number of records affected by a stored procedure?

WARNING: @@ROWCOUNT may return bogus data if the table being altered has triggers attached to it!

The @@ROWCOUNT will return the number of records affected by the TRIGGER, not the actual statement!

Objective-C Static Class Level variables

As pgb said, there are no "class variables," only "instance variables." The objective-c way of doing class variables is a static global variable inside the .m file of the class. The "static" ensures that the variable can not be used outside of that file (i.e. it can't be extern).

custom facebook share button

You can use facebook javascript sdk. First add FB Js SDK to your code (please refer to https://developers.facebook.com/docs/javascript)

window.fbAsyncInit = function(){
FB.init({
    appId: 'xxxxx', status: true, cookie: true, xfbml: true }); 
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if(d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; 
    js.async = true;js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}

So when you want to share something

<a href="someurl.com/some-article" data-image="article-1.jpg" data-title="Article Title" data-desc="Some description for this article" class="btnShare">Share</a>

And finally JS to handle click:

$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));

return false;
});

Declare a dictionary inside a static class

public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };             
    }
}

Probably initialise in the constructor.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

It's a Windows permissions issue. If you connected to your server using Windows Authentication then that Windows user needs permissions to the file. If you connected to your server using SQL Server authentication then the SQL Server instance account (MSSQL$, e.g. MSSQL$SQLEXPRESS) needs permissions to the file. The other solutions suggesting logging in as an administrator essentially accomplish the same thing (with a bit of a sledgehammer :).

If the database file is in your SQL Server's data folder then it should have inherited the user rights for the SQL Server account from that folder so the SQL Server authentication should have worked. I would recommend fixing the SQL Server instance's account's rights for that folder. If the data file is somewhere else and the SQL Server account does not have permissions then you will likely encounter other problems later. Again, the better solution is to fix the SS account rights. Unless you are always going to log in as administrator...

CSS Child vs Descendant selectors

Be aware that the child selector is not supported in Internet Explorer 6. (If you use the selector in a jQuery/Prototype/YUI etc selector rather than in a style sheet it still works though)

Merge (Concat) Multiple JSONObjects in Java

If you want a new object with two keys, Object1 and Object2, you can do:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

If you want to merge them, so e.g. a top level object has 5 keys (Stringkey1, ArrayKey, StringKey2, StringKey3, StringKey4), I think you have to do that manually:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

This would be a lot easier if JSONObject implemented Map, and supported putAll.

Content-Disposition:What are the differences between "inline" and "attachment"?

It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.

see this link:

http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server

somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...

If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.

Installing Google Protocol Buffers on mac

There are some issues with building protobuf 2.4.1 from source on a Mac. There is a patch that also has to be applied. All this is contained within the homebrew protobuf241 formula, so I would advise using it.

To install protocol buffer version 2.4.1 type the following into a terminal:

brew tap homebrew/versions
brew install protobuf241

If you already have a protocol buffer version that you tried to install from source, you can type the following into a terminal to have the source code overwritten by the homebrew version:

brew link --force --overwrite protobuf241

Check that you now have the correct version installed by typing:

protoc --version

It should display 2.4.1

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

You need to set utf8mb4 in meta html and also in your server alter tabel and set collation to utf8mb4

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

How to check if a Constraint exists in Sql server?

IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
BEGIN
    DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
END
GO

How do I list all the columns in a table?

Microsoft SQL Server Management Studio 2008 R2:

In a query editor, if you highlight the text of table name (ex dbo.MyTable) and hit ALT+F1, you'll get a list of column names, type, length, etc.

ALT+F1 while you've highlighted dbo.MyTable is the equivalent of running EXEC sp_help 'dbo.MyTable' according to this site

I can't get the variations on querying INFORMATION_SCHEMA.COLUMNS to work, so I use this instead.

How can I use optional parameters in a T-SQL stored procedure?

You can do in the following case,

CREATE PROCEDURE spDoSearch
   @FirstName varchar(25) = null,
   @LastName varchar(25) = null,
   @Title varchar(25) = null
AS
  BEGIN
      SELECT ID, FirstName, LastName, Title
      FROM tblUsers
      WHERE
        (@FirstName IS NULL OR FirstName = @FirstName) AND
        (@LastNameName IS NULL OR LastName = @LastName) AND
        (@Title IS NULL OR Title = @Title)
END

however depend on data sometimes better create dynamic query and execute them.

How can I override the OnBeforeUnload dialog and replace it with my own?

I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was : 1) It was giving message on all navigations I want it only for close click. 2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.

Following is the solutions code I found, which I wrote on my Master page.

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event; }
    if (evt && evt.clientX >= (window.event.screenX - 150) &&
        evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}
window.onbeforeunload = closeMe;

What does the symbol \0 mean in a string-literal?

Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:

$ cat junk.c
#include <stdio.h>

char* string = "Hello\0";

int main(int argv, char** argc)
{
    printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s

... eliding the unnecessary parts ...

.LC0:
    .string "Hello"
    .string ""

...

.LC1:
    .string "-->%s<--\n"

...

Note here how the string I used for printf is just "-->%s<---\n" while the global string is in two parts: "Hello" and "". The GNU assembler also terminates strings with an implicit NUL character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NULs. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S (for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

What is mutex and semaphore in Java ? What is the main difference?

The object of synchronization Semaphore implements a classical traffic light. A traffic light controls access to a resource shared by a counter. If the counter is greater than zero, access is granted; If it is zero, access is denied. The counter counts the permissions that allow access to the shared resource. Then, to access the resource, a thread must receive permission from the traffic light. In general, to use a traffic light, the thread that wants to access the shared resource tries to acquire a permit. If the traffic light count is greater than zero, the thread acquires a permit, and the traffic light count is decremented. Otherwise the thread is locked until it can get a permission. When the thread no longer needs to access the shared resource, it releases the permission, so the traffic light count is increased. If there is another thread waiting for a permit, it acquires a permit at that time. The Semaphore class of Java implements this mechanism.

Semaphore has two builders:

Semaphore(int num)
Semaphore(int num, boolean come)

num specifies the initial count of the permit. Then num specifies the number of threads that can access a shared resource at a given time. If num is one, it can access the resource one thread at a time. By setting come as true, you can guarantee that the threads you are waiting for are granted permission in the order they requested.

Argparse: Required arguments listed under "optional arguments"?

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name

PHP send mail to multiple email addresses

Try this. It works for me.

$to = $email1 .','. $email2 .','. $email3;

Passing an array as a function parameter in JavaScript

Why don't you pass the entire array and process it as needed inside the function?

var x = [ 'p0', 'p1', 'p2' ]; 
call_me(x);

function call_me(params) {
  for (i=0; i<params.length; i++) {
    alert(params[i])
  }
}

Status bar and navigation bar appear over my view's bounds in iOS 7

I have a scenario where I use the BannerViewController written by Apple to display my ads and a ScrollViewController embedded in the BannerViewController.

To prevent the navigation bar from hiding my content, I had to make two changes.

1) Modify BannerViewController.m

- (void)viewDidLoad
{
   [super viewDidLoad];
   float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
   if (systemVersion >= 7.0) {
      self.edgesForExtendedLayout = UIRectEdgeNone;
   }
}

2) Modify my ScrollViewContoller

- (void)viewDidLoad
{
    [super viewDidLoad];
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

Now the ads show up correctly at the bottom of the view instead of being covered by the Navigation bar and the content on the top is not cut off.

How to open VMDK File of the Google-Chrome-OS bundle 2012?

For me my vmdk file was accompanied by a vmx file. Opening the vmx file worked for vmware player.

How to use Google fonts in React.js?

Had the same issue. Turns out I was using " instead of '.

use @import url('within single quotes'); like this

not @import url("within double quotes"); like this

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

//In the Application_OnBeginRequest method in GLOBAL.ASX add the following:-  

var res = HttpContext.Current.Response;  
var req = HttpContext.Current.Request;  
res.AppendHeader("Access-Control-Allow-Origin", "*");  
res.AppendHeader("Access-Control-Allow-Credentials", "true");  
res.AppendHeader("Access-Control-Allow-Headers", "Authorization");  
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");  

    // ==== Respond to the OPTIONS verb =====
    if (req.HttpMethod == "OPTIONS")
    {
        res.StatusCode = 200;
        res.End();
    }

//Remove any entries in the custom headers as this will throw an error that there's to  
//many values in the header.  

<httpProtocol>
    <customHeaders>
    </customHeaders>
</httpProtocol>

How to represent multiple conditions in a shell if statement?

$ g=3
$ c=133
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
efg
$ g=1
$ c=123
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
abc

How to detect a docker daemon port

  1. Prepare extra configuration file. Create a file named /etc/systemd/system/docker.service.d/docker.conf. Inside the file docker.conf, paste below content:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock

Note that if there is no directory like docker.service.d or a file named docker.conf then you should create it.

  1. Restart Docker. After saving this file, reload the configuration by systemctl daemon-reload and restart Docker by systemctl restart docker.service.

  2. Check your Docker daemon. After restarting docker service, you can see the port in the output of systemctl status docker.service like /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock.

Hope this may help

Thank you!

In what cases will HTTP_REFERER be empty

I have found the browser referer implementation to be really inconsistent.

For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.

<a href="http://foo.com/foo" download="bar">click to download</a>

Is broken in Chrome - no referer sent.

Monitor network activity in Android Phones

Without root, you can use debug proxies like Charlesproxy&Co.

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I solved this problem by starting Visual Studio with Run as administrator. This is also required if you want to publish your project to the local IIS.

To set this permanently:-

  1. Right-click on the Visual Studio icon
  2. Select Properties
  3. Click Advanced
  4. Ensure Run as administrator is checked-on
  5. Click on OK all the way out.
  6. Start Visual Studio, load your project and start debugging

How can I center text (horizontally and vertically) inside a div block?

You can try the following methods:

  1. If you have a single word or one line sentence, then the following code can do the trick.

    Have a text inside a div tag and give it an id. Define the following properties for that id.

    id-name {
      height: 90px;
      line-height: 90px;
      text-align: center;
      border: 2px dashed red;
    }
    

    Note: Make sure the line-height property is same as the height of the division.

    Image

    But, if the content is more than one single word or a line then this doesn’t work. Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle).

  2. To solve this issue, we can try the following combination of properties.

    id-name {
      display: flex;
      justify-content: center;
      align-items: center;
      border: 2px dashed red;
    }
    

    Image

    These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display). The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered.

    Note: Flex does not work in all browsers. Make sure you add appropriate vendor prefixes for additional browser support.

angular2: how to copy object into another object

Object.assign will only work in single level of object reference.

To do a copy in any depth use as below:

let x = {'a':'a','b':{'c':'c'}};
let y = JSON.parse(JSON.stringify(x));

If want to use any library instead then go with the loadash.js library.

Import file size limit in PHPMyAdmin

I had the same problem. My Solution: go to /etc/phpmyadmin and edit apache.conf in the <Directory>[...]</Directory> section you can add

php_value upload_max_filesize 10M
php_value post_max_size 10M

Solved the problem for me!

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

How to center a (background) image within a div?

This works for me :

<style>
   .WidgetBody
        {   
            background: #F0F0F0;
            background-image:url('images/mini-loader.gif');
            background-position: 50% 50%;            
            background-repeat:no-repeat;            
        }
</style>        

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After a recent update on my Ubuntu 16.04 system I have also started getting this error when trying to run convert on .ps files to convert them into pdfs.

This fix worked for me:

In a terminal run:

sudo gedit /etc/ImageMagick-6/policy.xml

This should open the policy.xml file in the gedit text editor. If it doesn't, your image magick might be installed in a different place. Then change

rights="none" 

to

rights="read | write" 

for PDF, EPS and PS lines near the bottom of the file. Save and exit, and image magick should then work again.

How to embed a YouTube channel into a webpage

YouTube supports a fairly easy to use iframe and url interface to embed videos, playlists and all user uploads to your channel: https://developers.google.com/youtube/player_parameters

For example this HTML will embed a player loaded with a playlist of all the videos uploaded to your channel. Replace YOURCHANNELNAME with the actual name of your channel:

<iframe src="http://www.youtube.com/embed/?listType=user_uploads&list=YOURCHANNELNAME" width="480" height="400"></iframe>

Create thumbnail image

Here is a complete example of how to create a smaller image (thumbnail). This snippet resizes the Image, rotates it when needed (if a phone was held vertically) and pads the image if you want to create square thumbs. This snippet creates a JPEG, but it can easily be modified for other file types. Even if the image would be smaller than the max allowed size the image will still be compressed and it's resolution altered to create images of the same dpi and compression level.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

//set the resolution, 72 is usually good enough for displaying images on monitors
float imageResolution = 72;

//set the compression level. higher compression = better quality = bigger images
long compressionLevel = 80L;


public Image resizeImage(Image image, int maxWidth, int maxHeight, bool padImage)
{
    int newWidth;
    int newHeight;

    //first we check if the image needs rotating (eg phone held vertical when taking a picture for example)
    foreach (var prop in image.PropertyItems)
    {
        if (prop.Id == 0x0112)
        {
            int orientationValue = image.GetPropertyItem(prop.Id).Value[0];
            RotateFlipType rotateFlipType = getRotateFlipType(orientationValue);
            image.RotateFlip(rotateFlipType);
            break;
        }
    }

    //apply the padding to make a square image
    if (padImage == true)
    {
        image = applyPaddingToImage(image, Color.Red);
    }

    //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
    if (image.Width > maxWidth || image.Height > maxHeight)
    {
        double ratioX = (double)maxWidth / image.Width;
        double ratioY = (double)maxHeight / image.Height;
        double ratio = Math.Min(ratioX, ratioY);

        newWidth = (int)(image.Width * ratio);
        newHeight = (int)(image.Height * ratio);
    }
    else
    {
        newWidth = image.Width;
        newHeight = image.Height;
    }

    //start the resize with a new image
    Bitmap newImage = new Bitmap(newWidth, newHeight);

    //set the new resolution
    newImage.SetResolution(imageResolution, imageResolution);

    //start the resizing
    using (var graphics = Graphics.FromImage(newImage))
    {
        //set some encoding specs
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        graphics.DrawImage(image, 0, 0, newWidth, newHeight);
    }

    //save the image to a memorystream to apply the compression level
    using (MemoryStream ms = new MemoryStream())
    {
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compressionLevel);

        newImage.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);

        //save the image as byte array here if you want the return type to be a Byte Array instead of Image
        //byte[] imageAsByteArray = ms.ToArray();
    }

    //return the image
    return newImage;
}


//=== image padding
public Image applyPaddingToImage(Image image, Color backColor)
{
    //get the maximum size of the image dimensions
    int maxSize = Math.Max(image.Height, image.Width);
    Size squareSize = new Size(maxSize, maxSize);

    //create a new square image
    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);

    using (Graphics graphics = Graphics.FromImage(squareImage))
    {
        //fill the new square with a color
        graphics.FillRectangle(new SolidBrush(backColor), 0, 0, squareSize.Width, squareSize.Height);

        //put the original image on top of the new square
        graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
    }

    //return the image
    return squareImage;
}


//=== get encoder info
private ImageCodecInfo getEncoderInfo(string mimeType)
{
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

    for (int j = 0; j < encoders.Length; ++j)
    {
        if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
        {
            return encoders[j];
        }
    }

    return null;
}


//=== determine image rotation
private RotateFlipType getRotateFlipType(int rotateValue)
{
    RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;

    switch (rotateValue)
    {
        case 1:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
        case 2:
            flipType = RotateFlipType.RotateNoneFlipX;
            break;
        case 3:
            flipType = RotateFlipType.Rotate180FlipNone;
            break;
        case 4:
            flipType = RotateFlipType.Rotate180FlipX;
            break;
        case 5:
            flipType = RotateFlipType.Rotate90FlipX;
            break;
        case 6:
            flipType = RotateFlipType.Rotate90FlipNone;
            break;
        case 7:
            flipType = RotateFlipType.Rotate270FlipX;
            break;
        case 8:
            flipType = RotateFlipType.Rotate270FlipNone;
            break;
        default:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
    }

    return flipType;
}


//== convert image to base64
public string convertImageToBase64(Image image)
{
    using (MemoryStream ms = new MemoryStream())
    {
        //convert the image to byte array
        image.Save(ms, ImageFormat.Jpeg);
        byte[] bin = ms.ToArray();

        //convert byte array to base64 string
        return Convert.ToBase64String(bin);
    }
}

For the asp.net users a little example of how to upload a file, resize it and display the result on the page.

//== the button click method
protected void Button1_Click(object sender, EventArgs e)
{
    //check if there is an actual file being uploaded
    if (FileUpload1.HasFile == false)
    {
        return;
    }

    using (Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream))
    {
        try
        {
            //start the resize
            Image image = resizeImage(bitmap, 256, 256, true);

            //to visualize the result, display as base64 image
            Label1.Text = "<img src=\"data:image/jpg;base64," + convertImageToBase64(image) + "\">";

            //save your image to file sytem, database etc here
        }
        catch (Exception ex)
        {
            Label1.Text = "Oops! There was an error when resizing the Image.<br>Error: " + ex.Message;
        }
    }
}

Get URL of ASP.Net Page in code-behind

Use this:

Request.Url.AbsoluteUri

That will get you the full path (including http://...)

How to use table variable in a dynamic sql statement?

Well, I figured out the way and thought to share with the people out there who might run into the same problem.

Let me start with the problem I had been facing,

I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.

Solution:

I simply changed them to Global Temporary Variables and they worked.

Find my stored procedure underneath.

CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null

AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##RelPro
END

Create Table ##RelPro
(
    RowID int identity(1,1),
    ID int,
    Item_Name nvarchar(max),
    SKU nvarchar(max),
    Vendor nvarchar(max),
    Product_Img_180 nvarchar(max),
    rpGroup int,
    Assoc_Item_1 nvarchar(max),
    Assoc_Item_2 nvarchar(max),
    Assoc_Item_3 nvarchar(max),
    Assoc_Item_4 nvarchar(max),
    Assoc_Item_5 nvarchar(max),
    Assoc_Item_6 nvarchar(max),
    Assoc_Item_7 nvarchar(max),
    Assoc_Item_8 nvarchar(max),
    Assoc_Item_9 nvarchar(max),
    Assoc_Item_10 nvarchar(max)
);

Begin
    Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)

    Select distinct zp.ProductID, zp.Name, zp.SKU,
        (Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
        'http://s0001.server.com/is/sw11/DG/' + 
        (Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
        '_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
    From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
    Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End

declare @curr_row int = 0,
        @tot_rows int= 0,
        @sku nvarchar(15) = null;

IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));

Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);

while @curr_row <= @tot_rows
Begin
    select @sku = SKU from ##RelPro where RowID = @curr_row;

    truncate table ##TSku;

    Insert ##TSku(relsku)
    Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN 
    [INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
    Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)

    declare @curr_row1 int = (Select Min(tid) From ##TSku),
            @tot_rows1 int = (Select Max(tid) From ##TSku);

    If(@tot_rows1 <> 0)
    Begin
        While @curr_row1 <= @tot_rows1
        Begin
            declare @col_name nvarchar(15) = null,
                    @sqlstat nvarchar(500) = null;
            set @col_name =  'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
            set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
            Exec(@sqlstat);
            set @curr_row1 = @curr_row1 + 1;
        End
    End
    set @curr_row = @curr_row + 1;
End

Select * From ##RelPro;

END GO

How to remove empty cells in UITableView?

Using UITableViewController

The solution accepted will change the height of the TableViewCell. To fix that, perform following steps:

  1. Write code snippet given below in ViewDidLoad method.

    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

  2. Add following method in the TableViewClass.m file.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
    {
        return (cell height set on storyboard); 
    }
    

That's it. You can build and run your project.

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

Query to get all rows from previous month

Here is the query to get the records of the last month:

SELECT *
FROM `tablename`
WHERE `datefiled`
BETWEEN DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH )
AND 
LAST_DAY( DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH ) )

Regards - saqib

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

setTimeout / clearTimeout problems

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

ld: framework not found Pods

In my case I can build it on devices and simulator but has the same errors when archiving. To solve it, I have to

  • remove Pods.framework
  • make sure Pods-<project-name>.framework is embedded

You will find the settings in TARGETS-->Linked Frameworks and Libraries.

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Reinitialize Slick js after successful ajax call

$('#slick-slider').slick('refresh'); //Working for slick 1.8.1

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

An established connection was aborted by the software in your host machine

  1. Close Eclipse
  2. Open Task Manager and kill adb.exe
  3. Start Eclipse It should work.

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

ORA-00972 identifier is too long alias column name

The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --

 DBA_ALL_TABLES         ALL_ALL_TABLES        USER_ALL_TABLES
 DBA_PARTIAL_DROP_TABS  ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
 DBA_PART_TABLES        ALL_PART_TABLES       USER_PART_TABLES 
 DBA_TABLES             ALL_TABLES            USER_TABLES           
 DBA_TABLESPACES        USER_TABLESPACES      TAB
 DBA_TAB_COLUMNS      ALL_TAB_COLUMNS         USER_TAB_COLUMNS 
 DBA_TAB_COLS         ALL_TAB_COLS            USER_TAB_COLS 
 DBA_TAB_COMMENTS     ALL_TAB_COMMENTS        USER_TAB_COMMENTS 
 DBA_TAB_HISTOGRAMS   ALL_TAB_HISTOGRAMS      USER_TAB_HISTOGRAMS 
 DBA_TAB_MODIFICATIONS  ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS 
 DBA_TAB_PARTITIONS   ALL_TAB_PARTITIONS      USER_TAB_PARTITIONS

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

How to find index of STRING array in Java from a given value?

Try this Function :

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }

What is inf and nan?

Inf is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf. -Inf is similar, but smaller than everything.

NaN means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN. Inf - Inf is one such computation. Usually NaN is used to just mean that some data is missing.

How can I create directory tree in C++/Linux?

This is similar to the previous but works forward through the string instead of recursively backwards. Leaves errno with the right value for last failure. If there's a leading slash, there's an extra time through the loop which could have been avoided via one find_first_of() outside the loop or by detecting the leading / and setting pre to 1. The efficiency is the same whether we get set up by a first loop or a pre loop call, and the complexity would be (slightly) higher when using the pre-loop call.

#include <iostream>
#include <string>
#include <sys/stat.h>

int
mkpath(std::string s,mode_t mode)
{
    size_t pos=0;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        // force trailing / so we can handle everything in loop
        s+='/';
    }

    while((pos=s.find_first_of('/',pos))!=std::string::npos){
        dir=s.substr(0,pos++);
        if(dir.size()==0) continue; // if leading / first time is 0 length
        if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

int main()
{
    int mkdirretval;
    mkdirretval=mkpath("./foo/bar",0755);
    std::cout << mkdirretval << '\n';

}

How to write a basic swap function in Java

Java uses pass-by-value. It is not possible to swap two primitives or objects using a method.

Although it is possible to swap two elements in an integer array.

Difference between Method and Function?

There is no functions in c#. There is methods (typical method:public void UpdateLeaveStatus(EmployeeLeave objUpdateLeaveStatus)) link to msdn and functors - variable of type Func<>

Batch file to delete files older than N days

Ok was bored a bit and came up with this, which contains my version of a poor man's Linux epoch replacement limited for daily usage (no time retention):

7daysclean.cmd

@echo off
setlocal ENABLEDELAYEDEXPANSION
set day=86400
set /a year=day*365
set /a strip=day*7
set dSource=C:\temp

call :epoch %date%
set /a slice=epoch-strip

for /f "delims=" %%f in ('dir /a-d-h-s /b /s %dSource%') do (
    call :epoch %%~tf
    if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)
)
exit /b 0

rem Args[1]: Year-Month-Day
:epoch
    setlocal ENABLEDELAYEDEXPANSION
    for /f "tokens=1,2,3 delims=-" %%d in ('echo %1') do set Years=%%d& set Months=%%e& set Days=%%f
    if "!Months:~0,1!"=="0" set Months=!Months:~1,1!
    if "!Days:~0,1!"=="0" set Days=!Days:~1,1!
    set /a Days=Days*day
    set /a _months=0
    set i=1&& for %%m in (31 28 31 30 31 30 31 31 30 31 30 31) do if !i! LSS !Months! (set /a _months=!_months! + %%m*day&& set /a i+=1)
    set /a Months=!_months!
    set /a Years=(Years-1970)*year
    set /a Epoch=Years+Months+Days
    endlocal& set Epoch=%Epoch%
    exit /b 0

USAGE

set /a strip=day*7 : Change 7 for the number of days to keep.

set dSource=C:\temp : This is the starting directory to check for files.

NOTES

This is non-destructive code, it will display what would have happened.

Change :

if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)

to something like :

if !epoch! LEQ %slice% del /f %%f

so files actually get deleted

February: is hard-coded to 28 days. Bissextile years is a hell to add, really. if someone has an idea that would not add 10 lines of code, go ahead and post so I add it to my code.

epoch: I did not take time into consideration, as the need is to delete files older than a certain date, taking hours/minutes would have deleted files from a day that was meant for keeping.

LIMITATION

epoch takes for granted your short date format is YYYY-MM-DD. It would need to be adapted for other settings or a run-time evaluation (read sShortTime, user-bound configuration, configure proper field order in a filter and use the filter to extract the correct data from the argument).

Did I mention I hate this editor's auto-formating? it removes the blank lines and the copy-paste is a hell.

I hope this helps.

How to permanently set $PATH on Linux/Unix?

Zues77 has the right idea. The OP didn't say "how can i hack my way through this". OP wanted to know how to permanently append to $PATH:

sudo nano /etc/profile

This is where it is set for everything and is the best place to change it for all things needing $PATH

Avoid line break between html elements

In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:

_x000D_
_x000D_
.wrapper{_x000D_
  width: 290px;   _x000D_
  white-space: no-wrap;_x000D_
  resize:both;_x000D_
  overflow:auto; _x000D_
  border: 1px solid gray;_x000D_
}_x000D_
_x000D_
.breakable-text{_x000D_
  display: inline;_x000D_
  white-space: no-wrap;_x000D_
}_x000D_
_x000D_
.no-break-before {_x000D_
  padding-left: 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>&#8205;<span class="no-break-before">TOGETHER</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

Why do I get a "permission denied" error while installing a gem?

After setting the gems directory to the user directory that runs the gem install, using export GEM_HOME=/home/<user>/gems, the issue has been solved.

How to align content of a div to the bottom

try with:

div.myclass { margin-top: 100%; }

try changing the % to fix it. Example: 120% or 90% ...etc.

What is the meaning of <> in mysql query?

In MySQL, I use <> to preferentially place specific rows at the front of a sort request.

For instance, under the column topic, I have the classifications of 'Chair', 'Metabolomics', 'Proteomics', and 'Endocrine'. I always want to list any individual(s) with the topic 'Chair', first, and then list the other members in alphabetical order based on their topic and then their name_last.

I do this with:

SELECT scicom_list ORDER BY topic <> 'Chair',topic,name_last;

This outputs the rows in the order of:
Chair
Endocrine
Metabolomics
Proteomics

Notice that topic <> 'Chair' is used to select all the rows with 'Chair' first. It then sorts the rows where topic = Chair by name_last.*

*This is a bit counterintuitive since <> equals != based on other feedback in this post.

This syntax can also be used to prioritize multiple categories. For instance, if I want to have "Chair" and then "Vice Chair" listed before the rest of the topics, I use the following

SELECT scicom_list ORDER BY topic <> 'Chair',topic <> 'Vice Chair',topic,name_last;

This outputs the rows in the order of:
Chair
Vice Chair
Endocrine
Metabolomics
Proteomics

Check if string contains only digits

This is what you want

function isANumber(str){
  return !/\D/.test(str);
}

JavaFX 2.1 TableView refresh items

Following the answer of Daniel De León ...

  • I introduced a dummy property "modelChangedProperty" in my model and
  • created a method refresh() in my model that changes the value of that property.
  • In my controller I added a Listener to the dummy property that updates the table view.

-

/**
 * Adds a listener to the modelChangedProperty to update the table view
 */
private void createUpdateWorkAroundListener() {

    model.modelChangedProperty.addListener(
            (ObservableValue<? extends Boolean> arg0, final Boolean oldValue, final Boolean newValue) -> updateTableView()
            );
}

/**
 * Work around to update table view
 */
private void updateTableView() {
    TableColumn<?, ?> firstColumn = scenarioTable.getColumns().get(0);
    firstColumn.setVisible(false);
    firstColumn.setVisible(true);
}

The equivalent of wrap_content and match_parent in flutter?

Use the widget Wrap.

For Column like behavior try:

  return Wrap(
          direction: Axis.vertical,
          spacing: 10,
          children: <Widget>[...],);

For Row like behavior try:

  return Wrap(
          direction: Axis.horizontal,
          spacing: 10,
          children: <Widget>[...],);

For more information: Wrap (Flutter Widget)

ExpressionChangedAfterItHasBeenCheckedError Explained

Update

I highly recommend starting with the OP's self response first: properly think about what can be done in the constructor vs what should be done in ngOnChanges().

Original

This is more a side note than an answer, but it might help someone. I stumbled upon this problem when trying to make the presence of a button depend on the state of the form:

<button *ngIf="form.pristine">Yo</button>

As far as I know, this syntax leads to the button being added and removed from the DOM based on the condition. Which in turn leads to the ExpressionChangedAfterItHasBeenCheckedError.

The fix in my case (although I don't claim to grasp the full implications of the difference), was to use display: none instead:

<button [style.display]="form.pristine ? 'inline' : 'none'">Yo</button>

All com.android.support libraries must use the exact same version specification

After searching and combining answers, 2018 version of this question and it worked for me:

1) On navigation tab change it to project view

2) Navigate to [YourProjectName]/.idea/libraries/

3) Delete all files starting with Gradle__com_android_support_[libraryName]

E.g: Gradle__com_android_support_animated_vector_drawable_26_0_0.xml

4) In your gradle file define a variable and use it to replace version number like ${variableName}

Def variable:

ext {
    support_library_version = '28.0.0' //use the version of choice
}

Use variable:

implementation "com.android.support:cardview-v7:${support_library_version}"

example gradle:

dependencies {
    ext {
        support_library_version = '28.0.0' //use the version of choice
    }

    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation "com.android.support:animated-vector-drawable:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:customtabs:${support_library_version}"
    implementation "com.android.support:cardview-v7:${support_library_version}"
    implementation "com.android.support:support-compat:${support_library_version}"
    implementation "com.android.support:support-v4:${support_library_version}"
    implementation "com.android.support:support-core-utils:${support_library_version}"
    implementation "com.android.support:support-core-ui:${support_library_version}"
    implementation "com.android.support:support-fragment:${support_library_version}"
    implementation "com.android.support:support-media-compat:${support_library_version}"
    implementation "com.android.support:appcompat-v7:${support_library_version}"
    implementation "com.android.support:recyclerview-v7:${support_library_version}"
    implementation "com.android.support:design:${support_library_version}"

}

What is the worst real-world macros/pre-processor abuse you've ever come across?

This is taken from a popular open source program. In fact it makes some parts of the code more readable by hiding the ugly legacy.

#define EP_STATUS    CASTLING][(BOARD_FILES-2)
#define HOLDINGS_SET CASTLING][(BOARD_FILES-1)

I guess there is nothing really bad here, I just find it funny.

http://git.savannah.gnu.org/cgit/xboard.git/tree/common.h

How can I remove space (margin) above HTML header?

It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:

* { margin: 0, padding: 0 }

This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.

TypeScript: Property does not exist on type '{}'

You can assign the any type to the object:

let bar: any = {};
bar.foo = "foobar"; 

How to add conditional attribute in Angular 2?

Inline-Maps are handy, too.

They're a little more explicit & readable as well.

[class]="{ 'true': 'active', 'false': 'inactive', 'true&false': 'some-other-class' }[ trinaryBoolean ]"

Just another way of accomplishing the same thing, in case you don't like the ternary syntax or ngIfs (etc).

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

  • With Jenkins CLI you do not have to reload everything - you just can load the job (update-job command). You can't use tokens with CLI, AFAIK - you have to use password or password file.

  • Token name for user can be obtained via http://<jenkins-server>/user/<username>/configure - push on 'Show API token' button.

  • Here's a link on how to use API tokens (it uses wget, but curl is very similar).

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I had exactly the same issue: After updating to Android Studio 3.1.2 my project wouldn't compile with an AAPT2 error telling me some of my drawables which are referenced by styles.xml could not be found. Disabling AAPT2 isn't a solution anymore, since the setting is deprecated and will be removed at the end of 2018.

Culprit was an empty line just before the xml decleration in a totally unrelated layout.xml file... So the layout.xml file started like this:

//empty line//
<?xml version="1.0" encoding="utf-8"?>

Removed the empty line and everything worked like a charm again. Unbelievable and unlikely, but true.

Android Studio actually gave a warning because the file didn't start with the xml decleration (because of the empty line). But the warning is only visible when the file is opened in the editor.

C# Numeric Only TextBox Control

I used the TryParse that @fjdumont mentioned but in the validating event instead.

private void Number_Validating(object sender, CancelEventArgs e) {
    int val;
    TextBox tb = sender as TextBox;
    if (!int.TryParse(tb.Text, out val)) {
        MessageBox.Show(tb.Tag +  " must be numeric.");
        tb.Undo();
        e.Cancel = true;
    }
}

I attached this to two different text boxes with in my form initializing code.

    public Form1() {
        InitializeComponent();
        textBox1.Validating+=new CancelEventHandler(Number_Validating);
        textBox2.Validating+=new CancelEventHandler(Number_Validating);
    }

I also added the tb.Undo() to back out invalid changes.

How to create dictionary and add key–value pairs dynamically?

You can use maps with Map, like this:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

PHP Get all subdirectories of a given directory

<?php
    /*this will do what you asked for, it only returns the subdirectory names in a given
      path, and you can make hyperlinks and use them:
    */

    $yourStartingPath = "photos\\";
    $iterator = new RecursiveIteratorIterator( 
        new RecursiveDirectoryIterator($yourStartingPath),  
        RecursiveIteratorIterator::SELF_FIRST);

    foreach($iterator as $file) { 
        if($file->isDir()) { 
            $path = strtoupper($file->getRealpath()) ; 
            $path2 = PHP_EOL;
            $path3 = $path.$path2;

            $result = end(explode('/', $path3)); 

            echo "<br />". basename($result );
        } 
    } 

    /* best regards,
        Sanaan Barzinji
        Erbil
    */
?>

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

How can I compare two time strings in the format HH:MM:SS?

I improved this function from @kamil-p solution. I ignored seconds compare . You can add seconds logic to this function by attention your using.

Work only for "HH:mm" time format.

function compareTime(str1, str2){
    if(str1 === str2){
        return 0;
    }
    var time1 = str1.split(':');
    var time2 = str2.split(':');
    if(eval(time1[0]) > eval(time2[0])){
        return 1;
    } else if(eval(time1[0]) == eval(time2[0]) && eval(time1[1]) > eval(time2[1])) {
        return 1;
    } else {
        return -1;
    }
}

example

alert(compareTime('8:30','11:20'));

Thanks to @kamil-p

How can I convert radians to degrees with Python?

Python convert radians to degrees or degrees to radians:

What are Radians and what problem does it solve?:

Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

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

Conversion from radians to degrees

Python examples using libraries calculating degrees from radians:

>>> import math
>>> math.degrees(0)                       #0 radians == 0 degrees
0.0
>>> math.degrees(math.pi/2)               #pi/2 radians is 90 degrees
90.0
>>> math.degrees(math.pi)                 #pi radians is 180 degrees
180.0      
>>> math.degrees(math.pi+(math.pi/2))     #pi+pi/2 radians is 270 degrees
270.0 
>>> math.degrees(math.pi+math.pi)         #2*pi radians is 360 degrees
360.0      

Python examples using libraries calculating radians from degrees:

>>> import math
>>> math.radians(0)           #0 degrees == 0 radians
0.0
>>> math.radians(90)          #90 degrees is pi/2 radians
1.5707963267948966
>>> math.radians(180)         #180 degrees is pi radians
3.141592653589793
>>> math.radians(270)         #270 degrees is pi+(pi/2) radians
4.71238898038469
>>> math.radians(360)         #360 degrees is 2*pi radians
6.283185307179586

Source: https://docs.python.org/3/library/math.html#angular-conversion

The mathematical notation:

Mathematical notation of degrees and radians

You can do degree/radian conversion without libraries:

If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.

Lets crash that orbiter and Roll our own Radians to Degrees:

Invalid radians as input return garbage output.

>>> 0 * 180.0 / math.pi                         #0 radians is 0 degrees
0.0
>>> (math.pi/2) * 180.0 / math.pi               #pi/2 radians is 90 degrees
90.0
>>> (math.pi) * 180.0 / math.pi                 #pi radians is 180 degrees
180.0
>>> (math.pi+(math.pi/2)) * 180.0 / math.pi     #pi+(pi/2) radians is 270 degrees
270.0
>>> (2 * math.pi) * 180.0 / math.pi             #2*pi radians is 360 degrees
360.0

Degrees to radians:

>>> 0 * math.pi / 180.0              #0 degrees in radians
0.0
>>> 90 * math.pi / 180.0             #90 degrees in radians
1.5707963267948966
>>> 180 * math.pi / 180.0            #180 degrees in radians
3.141592653589793
>>> 270 * math.pi / 180.0            #270 degrees in radians
4.71238898038469
>>> 360 * math.pi / 180.0            #360 degrees in radians
6.283185307179586

Expressing multiple rotations with degrees and radians

Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

>>> import math
>>> math.radians(360)                 #one complete rotation
6.283185307179586
>>> math.radians(360+360)             #two rotations
12.566370614359172
>>> math.degrees(12.566370614359172)  #math.degrees and math.radians preserve the
720.0                                 #number of rotations

Collapsing multiple rotations:

You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

>>> import math
>>> math.radians(720+90)        #2 whole rotations plus 90 is 14.14 radians
14.137166941154069
>>> math.radians((720+90)%360)  #14.1 radians brings you to 
1.5707963267948966              #the end point as 1.57 radians.

>>> math.degrees((2*math.pi)+(math.pi/2))            #one rotation plus a quarter 
450.0                                                #rotation is 450 degrees.
>>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
90.0                                                    #rotation brings you to 90.

Protip

Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics: https://www.khanacademy.org/math/algebra2/trig-functions/intro-to-radians-alg2/v/introduction-to-radians

How to switch between frames in Selenium WebDriver using Java

This code is in groovy, so most likely you will need to do some rework. The first param is a url, the second is a counter to limit the tries.

public boolean selectWindow(window, maxTries) {
    def handles
    int tries = 0
    while (true) {
        try {
            handles = driver.getWindowHandles().toArray()
            for (int a = handles.size() - 1; a >= 0 ; a--) { // Backwards is faster with FF since it requires two windows
                try {
                    Log.logger.info("Attempting to select window: " + window)
                    driver.switchTo().window(handles[a]);
                    if (driver.getCurrentUrl().equals(window))
                        return true;
                    else {
                        Thread.sleep(2000)
                        tries++
                    }
                    if (tries > maxTries) {
                        Log.logger.warn("Cannot select page")
                        return false
                    }
                } catch (Exception ex) {
                    Thread.sleep(2000)
                    tries++
                }
            }
        } catch (Exception ex2) {
            Thread.sleep(2000)
            tries++
        }
    }
    return false;
}

Python send UDP packet

Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more

full code:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

Convert InputStream to JSONObject

This worked for me:

JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

Reference jars inside a jar

in eclipse, right click project, select RunAs -> Run Configuration and save your run configuration, this will be used when you next export as Runnable JARs

Android Studio Rendering Problems : The following classes could not be found

You have to do two things:

  • be sure to have imported right appcompat-v7 library in your project structure -> dependencies
  • change the theme in the preview window to not an AppCompat theme. Try with Holo.light or Holo.dark for example.

What do these three dots in React do?

Spread Attributes used to Pass the multiple Properties in a Simple Way

{ ... this.props } is Holding the property of this.props

Use of the { ... } Spread Operator with below props

this.props = 
 { 
    firstName: 'Dan', 
    lastName: 'Abramov', 
    city: 'New York',
    country: 'USA' 
}

Without { ... } Spread

<Child 
  firstName={this.props.firstName}
  lastName={this.props.lastName}
  city={this.props.city}
  country={this.props.country}

> 

With { ... } Spread

<Child { ...this.props } />

Dan Abramov's Tweet about Spread operator (Creator of Redux)

Case insensitive regular expression without re.compile?

In imports

import re

In run time processing:

RE_TEST = r'test'
if re.match(RE_TEST, 'TeSt', re.IGNORECASE):

It should be mentioned that not using re.compile is wasteful. Every time the above match method is called, the regular expression will be compiled. This is also faulty practice in other programming languages. The below is the better practice.

In app initialization:

self.RE_TEST = re.compile('test', re.IGNORECASE)

In run time processing:

if self.RE_TEST.match('TeSt'):

Custom CSS Scrollbar for Firefox

As of late 2018, there is now limited customization available in Firefox!

See these answers:

And this for background info: https://bugzilla.mozilla.org/show_bug.cgi?id=1460109


There's no Firefox equivalent to ::-webkit-scrollbar and friends.

You'll have to stick with JavaScript.

Plenty of people would like this feature, see: https://bugzilla.mozilla.org/show_bug.cgi?id=77790


As far as JavaScript replacements go, you can try:

Path of currently executing powershell script

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}

Complex CSS selector for parent of active child

Another thought occurred to me just now that could be a pure CSS solution. Display your active class as an absolutely positioned block and set its style to cover up the parent li.

a.active {
   position:absolute;
   display:block;
   width:100%;
   height:100%;
   top:0em;
   left:0em;
   background-color: whatever;
   border: whatever;
}
/* will also need to make sure the parent li is a positioned element so... */
ul.menu li {
    position:relative;
}    

For those of you who want to use javascript without jquery...

Selecting the parent is trivial. You need a getElementsByClass function of some sort, unless you can get your drupal plugin to assign the active item an ID instead of Class. The function I provided I grabbed from some other genius on SO. It works well, just keep in mind when you're debugging that the function will always return an array of nodes, not just a single node.

active_li = getElementsByClass("active","a");
active_li[0].parentNode.style.whatever="whatever";

function getElementsByClass(node,searchClass,tag) {
    var classElements = new Array();
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b"+searchClass+"\\b");
    for (i = 0, j = 0; i < elsLen; i++) {
       if ( pattern.test(els[i].className) ) {
       classElements[j] = els[i];
       j++;
   }
}
return classElements;
}

Adding to a vector of pair

revenue.pushback("string",map[i].second);

But that says cannot take two arguments. So how can I add to this vector pair?

You're on the right path, but think about it; what does your vector hold? It certainly doesn't hold a string and an int in one position, it holds a Pair. So...

revenue.push_back( std::make_pair( "string", map[i].second ) );     

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

npm install private github repositories by dependency in package.json

"dependencies": {
  "some-package": "github:github_username/some-package"
}

or just

"dependencies": {
  "some-package": "github_username/some-package"
}

https://docs.npmjs.com/files/package.json#github-urls

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:

jqGrid

DataTables.net

UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

PHP $_POST not working?

A few thing you could do:

  1. Make sure that the "action" attribute on your form leads to the correct destination.
  2. Try using $_REQUEST[] instead of $_POST, see if there is any change.
  3. [Optional] Try including both a 'name' and an 'id' attribute e.g.

    <input type="text" name="firstname" id="firstname">
    

  4. If you are in a Linux environment, check that you have both Read/Write permissions to the file.

In addition, this link might also help.

EDIT:

You could also substitute

<code>if(isset($_POST['submit'])){</code>

with this:

<code>if($_SERVER['REQUEST_METHOD'] == "POST"){ </code>

This is always the best way of checking whether or not a form has been submitted

How to convert a Collection to List?

Java 10 introduced List#copyOf which returns unmodifiable List while preserving the order:

List<Integer> list = List.copyOf(coll);

Array inside a JavaScript Object?

var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

Find the index of a dict within a list, by matching the dict's value

It won't be efficient, as you need to walk the list checking every item in it (O(n)). If you want efficiency, you can use dict of dicts. On the question, here's one possible way to find it (though, if you want to stick to this data structure, it's actually more efficient to use a generator as Brent Newey has written in the comments; see also tokland's answer):

>>> L = [{'id':'1234','name':'Jason'},
...         {'id':'2345','name':'Tom'},
...         {'id':'3456','name':'Art'}]
>>> [i for i,_ in enumerate(L) if _['name'] == 'Tom'][0]
1

How to add manifest permission to an application?

Permission name is CASE-SENSITIVE

In case somebody will struggle with same issue, it is case sensitive statement, so wrong case means your application won't get the permission.

WRONG

<uses-permission android:name="ANDROID.PERMISSION.INTERNET" />

CORRECT

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

This issue may happen ie. on autocomplete in IDE

mysqli::query(): Couldn't fetch mysqli

Check if db name do not have "_" or "-" that helps in my case

Assign an initial value to radio button as checked

You can use the checked attribute for this:

<input type="radio" checked="checked">

How to grant all privileges to root user in MySQL 8.0

I see a lot of (wrong) answers, it is just as simple as this:

USE mysql;
CREATE USER 'user'@'localhost' IDENTIFIED BY 'P@ssW0rd';
GRANT ALL ON *.* TO 'user'@'localhost';
FLUSH PRIVILEGES;

Note: instead of a self-created user you can use root to connect to the database. However, using the default root account to let an application connect to the database is not the preferred way.

Alternative privileges (be careful and remember the least-privilege principle):

-- Grant user permissions to all tables in my_database from localhost --
GRANT ALL ON my_database.* TO 'user'@'localhost';

-- Grant user permissions to my_table in my_database from localhost --
GRANT ALL ON my_database.my_table TO 'user'@'localhost';

-- Grant user permissions to all tables and databases from all hosts --
GRANT ALL ON *.* TO 'user'@'*';

If you would somehow run into the following error:

ERROR 1130 (HY000): Host ‘1.2.3.4’ is not allowed to connect to this MySQL server

You need add/change the following two lines in /etc/mysql/my.cnf and restart mysql:

bind-address           = 0.0.0.0
skip-networking

What is the recommended way to delete a large number of items from DynamoDB?

The answer of this question depends on the number of items and their size and your budget. Depends on that we have following 3 cases:

1- The number of items and size of items in the table are not very much. then as Steffen Opel said you can Use Query rather than Scan to retrieve all items for user_id and then loop over all returned items and either facilitate DeleteItem or BatchWriteItem. But keep in mind you may burn a lot of throughput capacity here. For example, consider a situation where you need delete 1000 items from a DynamoDB table. Assume that each item is 1 KB in size, resulting in Around 1MB of data. This bulk-deleting task will require a total of 2000 write capacity units for query and delete. To perform this data load within 10 seconds (which is not even considered as fast in some applications), you would need to set the provisioned write throughput of the table to 200 write capacity units. As you can see its doable to use this way if its for less number of items or small size items.

2- We have a lot of items or very large items in the table and we can store them according to the time into different tables. Then as jonathan Said you can just delete the table. this is much better but I don't think it is matched with your case. As you want to delete all of users data no matter what is the time of creation of logs, so in this case you can't delete a particular table. if you wanna have a separate table for each user then I guess if number of users are high then its so expensive and it is not practical for your case.

3- If you have a lot of data and you can't divide your hot and cold data into different tables and you need to do large scale delete frequently then unfortunately DynamoDB is not a good option for you at all. It may become more expensive or very slow(depends on your budget). In these cases I recommend to find another database for your data.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

how to draw a rectangle in HTML or CSS?

css:

.example {
    display: table;
    width: 200px;
    height: 200px;
    background: #4679BD;
}

html:

<div class="retangulo">
   
</div>

Ternary operator (?:) in Bash

to answer to : int a = (b == 5) ? c : d;

just write:

b=5
c=1
d=2
let a="(b==5)?c:d"

echo $a # 1

b=6;
c=1;
d=2;
let a="(b==5)?c:d"

echo $a # 2

remember that " expression " is equivalent to $(( expression ))

Chrome - ERR_CACHE_MISS

This is an issue distinct to Chrome, but there are two paths you can take to fix it.

I noticed the error once I added this specific header to my PHP script.

header('Content-Type: application/json');

The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).

Run function from the command line

With the -c (command) argument (assuming your file is named foo.py):

$ python -c 'import foo; print foo.hello()'

Alternatively, if you don't care about namespace pollution:

$ python -c 'from foo import *; print hello()'

And the middle ground:

$ python -c 'from foo import hello; print hello()'

Check if a variable is of function type

Underscore.js uses a more elaborate but highly performant test:

_.isFunction = function(obj) {
  return !!(obj && obj.constructor && obj.call && obj.apply);
};

See: http://jsperf.com/alternative-isfunction-implementations

EDIT: updated tests suggest that typeof might be faster, see http://jsperf.com/alternative-isfunction-implementations/4

Apply jQuery datepicker to multiple instances

I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js

// this.element.on('click', $.proxy(this.show, this));

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

How to open a website when a Button is clicked in Android application?

Import import android.net.Uri;

Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);

or it can be done using,

TextView textView = (TextView)findViewById(R.id.yourID);

textView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://www.typeyourURL.com"));
        startActivity(intent);
    } });

Add Keypair to existing EC2 instance

On your local machine, run command:

ssh-keygen -t rsa -C "SomeAlias"

After that command runs, a file ending in *.pub will be generated. Copy the contents of that file.

On the Amazon machine, edit ~/.ssh/authorized_keys and paste the contents of the *.pub file (and remove any existing contents first).

You can then SSH using the other file that was generated from the ssh-keygen command (the private key).

How to hide Bootstrap modal with javascript?

$('#modal').modal('hide'); 
//hide the modal

$('body').removeClass('modal-open'); 
//modal-open class is added on body so it has to be removed

$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class

What does it mean by select 1 from table?

it does what it says - it will always return the integer 1. It's used to check whether a record matching your where clause exists.

How to fix committing to the wrong Git branch?

For me, this was solved by reverting the commit I had pushed, then cherry-picking that commit to the other branch.

git checkout branch_that_had_the_commit_originally
git revert COMMIT-HASH
git checkout branch_that_was_supposed_to_have_the_commit
git cherry pick COMMIT-HASH

You can use git log to find the correct hash, and you can push these changes whenever you like!

Show dialog from fragment?

I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.

I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.

Iterate over object keys in node.js

adjust his code:

Object.prototype.each = function(iterateFunc) {
        var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
        var that = this;
        var next = function() {

            if (counter < len) {
                currentKey = keys[counter++];
                iterateFunc(currentKey, that[currentKey]);

                next();
            } else {
                that = counter = keys = currentKey = len = next = undefined;
            }
        };
        next();
    };

    ({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
        // do things
        console.log(key);
    });

ORA-01438: value larger than specified precision allows for this column

One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g

How do I rename both a Git local and remote branch name?

Attaching a Simple Snippet for renaming your current branch (local and on origin):

git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>

Explanation from git docs:

git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.

The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.

--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

I tried all the solutions but it still wasn't sufficient. After some more digging I eventually found I had also to set the 'file_priv' flag, and restart mysql.

To resume :

Grant the privileges :

> GRANT ALL PRIVILEGES
  ON my_database.* 
  to 'my_user'@'localhost';

> GRANT FILE ON *.* TO my_user;

> FLUSH PRIVILEGES; 

Set the flag :

> UPDATE mysql.user SET File_priv = 'Y' WHERE user='my_user' AND host='localhost';

Finally restart the mysql server:

$ sudo service mysql restart

After that, I could write into the secure_file_priv directory. For me it was /var/lib/mysql-files/, but you can check it with the following command :

> SHOW VARIABLES LIKE "secure_file_priv";

Matrix Transpose in Python

#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
    matrix.append([])
    for j in range(n):
        elem=input('enter element: ')
        matrix[i].append(elem)

#print matrix
for i in range(m):
    for j in range(n):
        print matrix[i][j],
    print '\n'

#generate transpose
transpose=[]
for j in range(n):
    transpose.append([])
    for i in range (m):
        ent=matrix[i][j]
        transpose[j].append(ent)

#print transpose
for i in range (n):
    for j in range (m):
        print transpose[i][j],
    print '\n'