Programs & Examples On #Spquery

SPQuery represents a query in a SharePoint list view

Center button under form in bootstrap

Remove that <p> tag and add the button inside a <div class="form-actions"> like this:

<div class="form-actions">
    <button type="submit" class="btn">Confirm</button>
</div>

an then augment the CSS class with:

.form-actions {
    margin: 0;
    background-color: transparent;
    text-align: center;
}

Here's a JS Bin demo: http://jsbin.com/ijozof/2


Look for form-actions at the Bootstrap doc here:

http://twitter.github.io/bootstrap/base-css.html#buttons

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

Python data structure sort list alphabetically

>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a =  ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'] 
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>> 

printf format specifiers for uint32_t and size_t

If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t or uintmax_t and use "%jd" or %ju, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t.

PHP Try and Catch for SQL Insert

    $sql = "INSERT INTO   customer(FIELDS)VALUES(VALUES)";
    mysql_query($sql);
    if (mysql_errno())
    {
            echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
    }   

Is it possible to GROUP BY multiple columns using MySQL?

If you prefer (I need to apply this) group by two columns at same time, I just saw this point:

SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1

Mapping over values in a python dictionary

These toolz are great for this kind of simple yet repetitive logic.

http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap

Gets you right where you want to be.

import toolz
def f(x):
  return x+1

toolz.valmap(f, my_list)

What does the Ellipsis object do?

You can also use the Ellipsis when specifying expected doctest output:

class MyClass(object):
    """Example of a doctest Ellipsis

    >>> thing = MyClass()
    >>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'>
    >>> type(thing)           # doctest:+ELLIPSIS
    <class '....MyClass'>
    """
    pass

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

Better naming in Tuple classes than "Item1", "Item2"

Here is an overly complicated version of what you are asking:

class MyTuple : Tuple<int, int>
{
    public MyTuple(int one, int two)
        :base(one, two)
    {

    }

    public int OrderGroupId { get{ return this.Item1; } }
    public int OrderTypeId { get{ return this.Item2; } }

}

Why not just make a class?

Difference between String replace() and replaceAll()

The replace() method is overloaded to accept both a primitive char and a CharSequence as arguments.

Now as far as the performance is concerned, the replace() method is a bit faster than replaceAll() because the latter first compiles the regex pattern and then matches before finally replacing whereas the former simply matches for the provided argument and replaces.

Since we know the regex pattern matching is a bit more complex and consequently slower, then preferring replace() over replaceAll() is suggested whenever possible.

For example, for simple substitutions like you mentioned, it is better to use:

replace('.', '\\');

instead of:

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

Note: the above conversion method arguments are system-dependent.

Uncaught TypeError: Cannot read property 'top' of undefined

I know this is extremely old, but I understand that this error type is a common mistake for beginners to make since most beginners will call their functions upon their header element being loaded. Seeing as this solution is not addressed at all in this thread, I'll add it. It is very likely that this javascript function was placed before the actual html was loaded. Remember, if you immediately call your javascript before the document is ready then elements requiring an element from the document might find an undefined value.

Eclipse IDE for Java - Full Dark Theme

Instead if finding a night theme I found a utility that puts my entire desktop into night mode NegativeScreen.

eclipse ide night mode

I use the below adjusted 'Smart Inversion Alt 2' matrix where the black is lightened a little.

Smart Inversion Alt 2b (danielsokolowski)=
{  0.390, -0.620, -0.620,  0.000,  0.000 }
{ -1.210, -0.220, -1.220,  0.000,  0.000 }
{ -0.160, -0.160,  0.840,  0.000,  0.000 }
{  0.075,  0.075,  0.075,  1.000,  0.000 }
{  1,  1,  1,  0.000,  1.000 }

Differences between Lodash and Underscore.js

For the most part Underscore.js is subset of Lodash.

At times, like presently, Underscore.js will have cool little functions Lodash doesn't have, like mapObject. This one saved me a lot of time in the development of my project.

Download JSON object as a file from browser

    downloadJsonFile(data, filename: string){
        // Creating a blob object from non-blob data using the Blob constructor
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        // Create a new anchor element
        const a = document.createElement('a');
        a.href = url;
        a.download = filename || 'download';
        a.click();
        a.remove();
      }

You can easily auto download file with using Blob and transfer it in first param downloadJsonFile. filename is name of file you wanna set.

jquery to change style attribute of a div class

You can't use $('#Id').attr('style',' color:red'); and $('#Id').css('padding-left','20%');
at the same time.
You can either use attr or css but both only works when they are used alone.

How to uninstall Apache with command line

On Windows 8.1 I had to run cmd.exe as administrator (even though I was logged in as admin). Otherwise I got an error when trying to execute: httpd.exe -k uninstall

Error: C:\Program Files\Apache\bin>(OS 5)Access is denied. : AH00373: Apache2.4: OpenS ervice failed

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

AngularJS ng-click to go to another page (with Ionic framework)

app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
    $scope.post = {url: 'http://', title: ''};

    $scope.createVariable = function(url) {
      $window.location.href = url;
    };
    $scope.createFixed = function() {
      $window.location.href = '/tab/newpost';
    };
});

HTML

<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>

How do I get the resource id of an image if I know its name?

One other scenario which I encountered.

String imageName ="Hello" and then when it is passed into getIdentifier function as first argument, it will pass the name with string null termination and will always return zero. Pass this imageName.substring(0, imageName.length()-1)

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Bootstrap.yml is the first file loaded when you start spring boot application and application.property is loaded when application starts. So, you keep, may be your config server's credentials etc., in bootstrap.yml which is required during loading application and then in application.properties you keep may be database URL etc.

How would I extract a single file (or changes to a file) from a git stash?

The simplest concept to understand, although maybe not the best, is you have three files changed and you want to stash one file.

If you do git stash to stash them all, git stash apply to bring them back again and then git checkout f.c on the file in question to effectively reset it.

When you want to unstash that file run do a git reset --hard and then run git stash apply again, taking advantage ofthe fact that git stash apply doesn't clear the diff from the stash stack.

JAVA_HOME does not point to the JDK

for centos yum -y install java-1.7.0-openjdk-devel.x86_64

and update JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk.x86-64

python list by value not by reference

Also, you can do:

b = list(a)

This will work for any sequence, even those that don't support indexers and slices...

Why does JPA have a @Transient annotation?

I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

Simulate string split function in Excel formula

Some great worksheet-fu in the other answers but I think they've overlooked that you can define a user-defined function (udf) and call this from the sheet or a formula.

The next problem you have is to decide either to work with a whole array or with element.

For example this UDF function code

Public Function UdfSplit(ByVal sText As String, Optional ByVal sDelimiter As String = " ", Optional ByVal lIndex As Long = -1) As Variant
    Dim vSplit As Variant
    vSplit = VBA.Split(sText, sDelimiter)
    If lIndex > -1 Then
        UdfSplit = vSplit(lIndex)
    Else
        UdfSplit = vSplit
    End If
End Function

allows single elements with the following in one cell

=UdfSplit("EUR/USD","/",0)

or one can use a blocks of cells with

=UdfSplit("EUR/USD","/")

What is the correct way to create a single-instance WPF application?

The code C# .NET Single Instance Application that is the reference for the marked answer is a great start.

However, I found it doesn't handle very well the cases when the instance that already exist has a modal dialog open, whether that dialog is a managed one (like another Form such as an about box), or an unmanaged one (like the OpenFileDialog even when using the standard .NET class). With the original code, the main form is activated, but the modal one stays unactive, which looks strange, plus the user must click on it to keep using the app.

So, I have create a SingleInstance utility class to handle all this quite automatically for Winforms and WPF applications.

Winforms:

1) modify the Program class like this:

static class Program
{
    public static readonly SingleInstance Singleton = new SingleInstance(typeof(Program).FullName);

    [STAThread]
    static void Main(string[] args)
    {
        // NOTE: if this always return false, close & restart Visual Studio
        // this is probably due to the vshost.exe thing
        Singleton.RunFirstInstance(() =>
        {
            SingleInstanceMain(args);
        });
    }

    public static void SingleInstanceMain(string[] args)
    {
        // standard code that was in Main now goes here
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

2) modify the main window class like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override void WndProc(ref Message m)
    {
        // if needed, the singleton will restore this window
        Program.Singleton.OnWndProc(this, m, true);

        // TODO: handle specific messages here if needed
        base.WndProc(ref m);
    }
}

WPF:

1) modify the App page like this (and make sure you set its build action to page to be able to redefine the Main method):

public partial class App : Application
{
    public static readonly SingleInstance Singleton = new SingleInstance(typeof(App).FullName);

    [STAThread]
    public static void Main(string[] args)
    {
        // NOTE: if this always return false, close & restart Visual Studio
        // this is probably due to the vshost.exe thing
        Singleton.RunFirstInstance(() =>
        {
            SingleInstanceMain(args);
        });
    }

    public static void SingleInstanceMain(string[] args)
    {
        // standard code that was in Main now goes here
        App app = new App();
        app.InitializeComponent();
        app.Run();
    }
}

2) modify the main window class like this:

public partial class MainWindow : Window
{
    private HwndSource _source;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        _source = (HwndSource)PresentationSource.FromVisual(this);
        _source.AddHook(HwndSourceHook);
    }

    protected virtual IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        // if needed, the singleton will restore this window
        App.Singleton.OnWndProc(hwnd, msg, wParam, lParam, true, true);

        // TODO: handle other specific message
        return IntPtr.Zero;
    }

And here is the utility class:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;

namespace SingleInstanceUtilities
{
    public sealed class SingleInstance
    {
        private const int HWND_BROADCAST = 0xFFFF;

        [DllImport("user32.dll")]
        private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern int RegisterWindowMessage(string message);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        public SingleInstance(string uniqueName)
        {
            if (uniqueName == null)
                throw new ArgumentNullException("uniqueName");

            Mutex = new Mutex(true, uniqueName);
            Message = RegisterWindowMessage("WM_" + uniqueName);
        }

        public Mutex Mutex { get; private set; }
        public int Message { get; private set; }

        public void RunFirstInstance(Action action)
        {
            RunFirstInstance(action, IntPtr.Zero, IntPtr.Zero);
        }

        // NOTE: if this always return false, close & restart Visual Studio
        // this is probably due to the vshost.exe thing
        public void RunFirstInstance(Action action, IntPtr wParam, IntPtr lParam)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            if (WaitForMutext(wParam, lParam))
            {
                try
                {
                    action();
                }
                finally
                {
                    ReleaseMutex();
                }
            }
        }

        public static void ActivateWindow(IntPtr hwnd)
        {
            if (hwnd == IntPtr.Zero)
                return;

            FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));
        }

        public void OnWndProc(IntPtr hwnd, int m, IntPtr wParam, IntPtr lParam, bool restorePlacement, bool activate)
        {
            if (m == Message)
            {
                if (restorePlacement)
                {
                    WindowPlacement placement = WindowPlacement.GetPlacement(hwnd, false);
                    if (placement.IsValid && placement.IsMinimized)
                    {
                        const int SW_SHOWNORMAL = 1;
                        placement.ShowCmd = SW_SHOWNORMAL;
                        placement.SetPlacement(hwnd);
                    }
                }

                if (activate)
                {
                    SetForegroundWindow(hwnd);
                    FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(hwnd));
                }
            }
        }

#if WINFORMS // define this for Winforms apps
        public void OnWndProc(System.Windows.Forms.Form form, int m, IntPtr wParam, IntPtr lParam, bool activate)
        {
            if (form == null)
                throw new ArgumentNullException("form");

            if (m == Message)
            {
                if (activate)
                {
                    if (form.WindowState == System.Windows.Forms.FormWindowState.Minimized)
                    {
                        form.WindowState = System.Windows.Forms.FormWindowState.Normal;
                    }

                    form.Activate();
                    FormUtilities.ActivateWindow(FormUtilities.GetModalWindow(form.Handle));
                }
            }
        }

        public void OnWndProc(System.Windows.Forms.Form form, System.Windows.Forms.Message m, bool activate)
        {
            if (form == null)
                throw new ArgumentNullException("form");

            OnWndProc(form, m.Msg, m.WParam, m.LParam, activate);
        }
#endif

        public void ReleaseMutex()
        {
            Mutex.ReleaseMutex();
        }

        public bool WaitForMutext(bool force, IntPtr wParam, IntPtr lParam)
        {
            bool b = PrivateWaitForMutext(force);
            if (!b)
            {
                PostMessage((IntPtr)HWND_BROADCAST, Message, wParam, lParam);
            }
            return b;
        }

        public bool WaitForMutext(IntPtr wParam, IntPtr lParam)
        {
            return WaitForMutext(false, wParam, lParam);
        }

        private bool PrivateWaitForMutext(bool force)
        {
            if (force)
                return true;

            try
            {
                return Mutex.WaitOne(TimeSpan.Zero, true);
            }
            catch (AbandonedMutexException)
            {
                return true;
            }
        }
    }

    // NOTE: don't add any field or public get/set property, as this must exactly map to Windows' WINDOWPLACEMENT structure
    [StructLayout(LayoutKind.Sequential)]
    public struct WindowPlacement
    {
        public int Length { get; set; }
        public int Flags { get; set; }
        public int ShowCmd { get; set; }
        public int MinPositionX { get; set; }
        public int MinPositionY { get; set; }
        public int MaxPositionX { get; set; }
        public int MaxPositionY { get; set; }
        public int NormalPositionLeft { get; set; }
        public int NormalPositionTop { get; set; }
        public int NormalPositionRight { get; set; }
        public int NormalPositionBottom { get; set; }

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool SetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);

        private const int SW_SHOWMINIMIZED = 2;

        public bool IsMinimized
        {
            get
            {
                return ShowCmd == SW_SHOWMINIMIZED;
            }
        }

        public bool IsValid
        {
            get
            {
                return Length == Marshal.SizeOf(typeof(WindowPlacement));
            }
        }

        public void SetPlacement(IntPtr windowHandle)
        {
            SetWindowPlacement(windowHandle, ref this);
        }

        public static WindowPlacement GetPlacement(IntPtr windowHandle, bool throwOnError)
        {
            WindowPlacement placement = new WindowPlacement();
            if (windowHandle == IntPtr.Zero)
                return placement;

            placement.Length = Marshal.SizeOf(typeof(WindowPlacement));
            if (!GetWindowPlacement(windowHandle, ref placement))
            {
                if (throwOnError)
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                return new WindowPlacement();
            }
            return placement;
        }
    }

    public static class FormUtilities
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetActiveWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("kernel32.dll")]
        public static extern int GetCurrentThreadId();

        private delegate bool EnumChildrenCallback(IntPtr hwnd, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern bool EnumThreadWindows(int dwThreadId, EnumChildrenCallback lpEnumFunc, IntPtr lParam);

        private class ModalWindowUtil
        {
            private const int GW_OWNER = 4;
            private int _maxOwnershipLevel;
            private IntPtr _maxOwnershipHandle;

            private bool EnumChildren(IntPtr hwnd, IntPtr lParam)
            {
                int level = 1;
                if (IsWindowVisible(hwnd) && IsOwned(lParam, hwnd, ref level))
                {
                    if (level > _maxOwnershipLevel)
                    {
                        _maxOwnershipHandle = hwnd;
                        _maxOwnershipLevel = level;
                    }
                }
                return true;
            }

            private static bool IsOwned(IntPtr owner, IntPtr hwnd, ref int level)
            {
                IntPtr o = GetWindow(hwnd, GW_OWNER);
                if (o == IntPtr.Zero)
                    return false;

                if (o == owner)
                    return true;

                level++;
                return IsOwned(owner, o, ref level);
            }

            public static void ActivateWindow(IntPtr hwnd)
            {
                if (hwnd != IntPtr.Zero)
                {
                    SetActiveWindow(hwnd);
                }
            }

            public static IntPtr GetModalWindow(IntPtr owner)
            {
                ModalWindowUtil util = new ModalWindowUtil();
                EnumThreadWindows(GetCurrentThreadId(), util.EnumChildren, owner);
                return util._maxOwnershipHandle; // may be IntPtr.Zero
            }
        }

        public static void ActivateWindow(IntPtr hwnd)
        {
            ModalWindowUtil.ActivateWindow(hwnd);
        }

        public static IntPtr GetModalWindow(IntPtr owner)
        {
            return ModalWindowUtil.GetModalWindow(owner);
        }
    }
}

How do you properly determine the current script directory?

The os.path... approach was the 'done thing' in Python 2.

In Python 3, you can find directory of script as follows:

from pathlib import Path
cwd = Path(__file__).parents[0]

select2 changing items dynamically

In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.

Smart way to truncate long strings

Best function I have found. Credit to text-ellipsis.

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}

Examples:

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"

Firebase FCM force onTokenRefresh() to be called

FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new 
OnSuccessListener<String>() {
    @Override
    public void onSuccess(String newToken) {
        ....
    }
});

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

How to install Intellij IDEA on Ubuntu?

JetBrains has a new application called the Toolbox App which quickly and easily installs any JetBrains software you want, assuming you have the license. It also manages your login once to apply across all JetBrains software, a very useful feature.

To use it, download the tar.gz file here, then extract it and run the included executable jetbrains-toolbox. Then sign in, and press install next to IntelliJ IDEA:

enter image description here

If you want to move the executable to /usr/bin/ feel free, however it works fine out of the box wherever you extract it to.

This will also make the appropriate desktop entries upon install.

Check for a substring in a string in Oracle without LIKE

Bear in mind that it is only worth using anything other than a full table scan to find these values if the number of blocks that contain a row that matches the predicate is significantly smaller than the total number of blocks in the table. That is why Oracle will often decline the use of an index in order to full scan when you use LIKE '%x%' where x is a very small string. For example if the optimizer believes that using an index would still require single-block reads on (say) 20% of the table blocks then a full table scan is probably a better option than an index scan.

Sometimes you know that your predicate is much more selective than the optimizer can estimate. In such a case you can look into supplying an optimizer hint to perform an index fast full scan on the relevant column (particularly if the index is a much smaller segment than the table).

SELECT /*+ index_ffs(users (users.last_name)) */
       * 
FROM   users
WHERE  last_name LIKE "%z%"

Usage of MySQL's "IF EXISTS"

if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1 
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1 
end
else
begin
print 'the record does not exits'
end

Binding multiple events to a listener (without JQuery)?

Cleaning up Isaac's answer:

['mousemove', 'touchmove'].forEach(function(e) {
  window.addEventListener(e, mouseMoveHandler);
});

EDIT

ES6 helper function:

function addMultipleEventListener(element, events, handler) {
  events.forEach(e => element.addEventListener(e, handler))
}

php: check if an array has duplicates

Two ways to do it efficiently that I can think of:

  1. inserting all the values into some sort of hashtable and checking whether the value you're inserting is already in it(expected O(n) time and O(n) space)

  2. sorting the array and then checking whether adjacent cells are equal( O(nlogn) time and O(1) or O(n) space depending on the sorting algorithm)

stormdrain's solution would probably be O(n^2), as would any solution which involves scanning the array for each element searching for a duplicate

Looping through all rows in a table column, Excel-VBA

Since none of the above answers helped me with my problem, here my solution to extract a certain (named) column from each row.

I convert a table into text using the values of some named columns (Yes, No, Maybe) within the named Excel table myTable on the tab mySheet using the following (Excel) VBA snippet:

Function Table2text()
    Dim NumRows, i As Integer
    Dim rngTab As Range
    Set rngTab = ThisWorkbook.Worksheets("mySheet").Range("myTable")
    ' For each row, convert the named columns into an enumeration
    For i = 1 To rngTab.Rows.Count
        Table2text= Table2text & "- Yes:"   & Range("myTable[Yes]")(i).Value & Chr(10)
        Table2text= Table2text & "- No: "   & Range("myTable[No]")(i).Value & Chr(10)
        Table2text= Table2text & "- Maybe: "& Range("myTable[Maybe]")(i).Value & Chr(10) & Chr(10)
    Next i
  ' Finalize return value 
  Table2text = Table2text & Chr(10)  
End Function

We define a range rngTab over which we loop. The trick is to use Range("myTable[col]")(i) to extract the entry of column col in row i.

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

Clicking a checkbox with ng-click does not update the model

Why dont you use

$watch('todo',function(.....

Or another solution would be to set the todo.done inside the ng-click callback and only use ng-click

<div ng-app="myApp" ng-controller="Ctrl">
<li  ng-repeat="todo in todos">
<input type='checkbox' ng-click='onCompleteTodo(todo)'>
    {{todo.text}} {{todo.done}}

and

$scope.onCompleteTodo = function(todo) {
        todo.done = !todo.done; //toggle value
        console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
        $scope.current = todo;
}

Append to the end of a Char array in C++

If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.

In C++, You are much better off using std::string and then you can use std::string::append()

How to remove specific object from ArrayList in Java?

AValchev is right. A quicker solution would be to parse all elements and compare by an unique property.

String property = "property to delete";

for(int j = 0; j < i.size(); j++)
{
    Student obj = i.get(j);

    if(obj.getProperty().equals(property)){
       //found, delete.
        i.remove(j);
        break;
    }

}

THis is a quick solution. You'd better implement object comparison for larger projects.

What does the function then() mean in JavaScript?

Here is a small JS_Fiddle.

then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works

You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.

I forked and Edited from MSDN Docs on Battery charging status..

What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.

navigator
    .getBattery()
    .then(function(battery) {
       var charging = battery.charging;
       alert(charging);
    })
    .then(function(){alert("YeoMan : SINGH is King !!");});

Another es6 Example

function fetchAsync (url, timeout, onData, onError) {
    …
}
let fetchPromised = (url, timeout) => {
    return new Promise((resolve, reject) => {
        fetchAsync(url, timeout, resolve, reject)
    })
}
Promise.all([
    fetchPromised("http://backend/foo.txt", 500),
    fetchPromised("http://backend/bar.txt", 500),
    fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
    let [ foo, bar, baz ] = data
    console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
    console.log(`error: ${err}`)
})

Definition :: then is a method used to solve Asynchronous callbacks

this is introduced in ES6

Please find the proper documentation here Es6 Promises

Convert double to string C++?

Use std::stringstream. Its operator << is overloaded for all built-in types.

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();

This works like you'd expect - the same way you print to the screen with std::cout. You're simply "printing" to a string instead. The internals of operator << take care of making sure there's enough space and doing any necessary conversions (e.g., double to string).

Also, if you have the Boost library available, you might consider looking into lexical_cast. The syntax looks much like the normal C++-style casts:

#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;

storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
                       "," + lexical_cast<std::string>(c2) + ")";

Under the hood, boost::lexical_cast is basically doing the same thing we did with std::stringstream. A key advantage to using the Boost library is you can go the other way (e.g., string to double) just as easily. No more messing with atof() or strtod() and raw C-style strings.

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

Alternate output format for psql

I just needed to spend more time staring at the documentation. This command:

\x on

will do exactly what I wanted. Here is some sample output:

select * from dda where u_id=24 and dda_is_deleted='f';
-[ RECORD 1 ]------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
dda_id             | 1121
u_id               | 24
ab_id              | 10304
dda_type           | CHECKING
dda_status         | PENDING_VERIFICATION
dda_is_deleted     | f
dda_verify_op_id   | 44938
version            | 2
created            | 2012-03-06 21:37:50.585845
modified           | 2012-03-06 21:37:50.593425
c_id               | 
dda_nickname       | 
dda_account_name   | 
cu_id              | 1
abd_id             | 

How do you use a variable in a regular expression?

None of these answers were clear to me. I eventually found a good explanation at http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/

The simple answer is:

var search_term = new RegExp(search_term, "g");    
text = text.replace(search_term, replace_term);

For example:

_x000D_
_x000D_
$("button").click(function() {_x000D_
  Find_and_replace("Lorem", "Chocolate");_x000D_
  Find_and_replace("ipsum", "ice-cream");_x000D_
});_x000D_
_x000D_
function Find_and_replace(search_term, replace_term) {_x000D_
  text = $("textbox").html();_x000D_
  var search_term = new RegExp(search_term, "g");_x000D_
  text = text.replace(search_term, replace_term);_x000D_
  $("textbox").html(text);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textbox>_x000D_
  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum_x000D_
</textbox>_x000D_
<button>Click me</button>
_x000D_
_x000D_
_x000D_

UIImage resize (Scale proportion)

Try to make the bounds's size integer.

#include <math.h>
....

    if (ratio > 1) {
        bounds.size.width = resolution;
        bounds.size.height = round(bounds.size.width / ratio);
    } else {
        bounds.size.height = resolution;
        bounds.size.width = round(bounds.size.height * ratio);
    }

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

Find a line in a file and remove it

package com.ncs.cache;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

    public void removeLineFromFile(String file, String lineToRemove) {

        try {

            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        util.removeLineFromFile("test.txt", "bbbbb");
    }
}

src : http://www.javadb.com/remove-a-line-from-a-text-file/

How do I fix twitter-bootstrap on IE?

Need to include these two scripts for IE

<script src="http://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="http://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

How to execute my SQL query in CodeIgniter

 return $this->db->select('(CASE 
            enter code hereWHEN orderdetails.ProductID = 0   THEN dealmaster.deal_name
            WHEN orderdetails.DealID = 0 THEN products.name
            END) as product_name')

Convert a string to an enum in C#

Try this sample:

 public static T GetEnum<T>(string model)
    {
        var newModel = GetStringForEnum(model);

        if (!Enum.IsDefined(typeof(T), newModel))
        {
            return (T)Enum.Parse(typeof(T), "None", true);
        }

        return (T)Enum.Parse(typeof(T), newModel.Result, true);
    }

    private static Task<string> GetStringForEnum(string model)
    {
        return Task.Run(() =>
        {
            Regex rgx = new Regex("[^a-zA-Z0-9 -]");
            var nonAlphanumericData = rgx.Matches(model);
            if (nonAlphanumericData.Count < 1)
            {
                return model;
            }
            foreach (var item in nonAlphanumericData)
            {
                model = model.Replace((string)item, "");
            }
            return model;
        });
    }

In this sample you can send every string, and set your Enum. If your Enum had data that you wanted, return that as your Enum type.

how to get the first and last days of a given month

Try this , if you are using PHP 5.3+, in php

$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');

For finding next month last date, modify as follows,

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

and so on..

sorting a List of Map<String, String>

Bit out of topic
this is a little util for watching sharedpreferences
based on upper answers
may be for someone this will be helpful

@SuppressWarnings("unused")
public void printAll() {
    Map<String, ?> prefAll = PreferenceManager
        .getDefaultSharedPreferences(context).getAll();
    if (prefAll == null) {
        return;
    }
    List<Map.Entry<String, ?>> list = new ArrayList<>();
    list.addAll(prefAll.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, ?>>() {
        public int compare(final Map.Entry<String, ?> entry1, final Map.Entry<String, ?> entry2) {
            return entry1.getKey().compareTo(entry2.getKey());
        }
    });
    Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    Timber.i("Printing all sharedPreferences");
    for(Map.Entry<String, ?> entry : list) {
        Timber.i("%s: %s", entry.getKey(), entry.getValue());
    }
    Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}

What languages are Windows, Mac OS X and Linux written in?

See under the heading One Operating System Running On Multiple Platforms where it states:

Most of the source code for Windows NT is written in C or C++.

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Additional to the main answer I needed to remove all npm instances found in:

rm -rf /usr/local/share/man/man1/npm*

How to start nginx via different port(other than 80)

You will need to change the configure port of either Apache or Nginx. After you do this you will need to restart the reconfigured servers, using the 'service' command you used.


Apache

Edit

sudo subl /etc/apache2/ports.conf 

and change the 80 on the following line to something different :

Listen 80

If you just change the port or add more ports here, you will likely also have to change the VirtualHost statement in

sudo subl /etc/apache2/sites-enabled/000-default.conf

and change the 80 on the following line to something different :

<VirtualHost *:80>

then restart by :

sudo service apache2 restart

Nginx

Edit

/etc/nginx/sites-enabled/default

and change the 80 on the following line :

listen 80;

then restart by :

sudo service nginx restart

Simplest code for array intersection in javascript

If your environment supports ECMAScript 6 Set, one simple and supposedly efficient (see specification link) way:

function intersect(a, b) {
  var setA = new Set(a);
  var setB = new Set(b);
  var intersection = new Set([...setA].filter(x => setB.has(x)));
  return Array.from(intersection);
}

Shorter, but less readable (also without creating the additional intersection Set):

function intersect(a, b) {
  var setB = new Set(b);
  return [...new Set(a)].filter(x => setB.has(x));
}

Note that when using sets you will only get distinct values, thus new Set([1, 2, 3, 3]).size evaluates to 3.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

How to enable mod_rewrite for Apache 2.2

For my situation, I had

RewriteEngine On

in my .htaccess, along with the module being loaded, and it was not working.

The solution to my problem was to edit my vhost entry to inlcude

AllowOverride all

in the <Directory> section for the site in question.

Using iText to convert HTML to PDF

The answer to your question is actually two-fold. First of all you need to specify what you intend to do with the rendered HTML: save it to a new PDF file, or use it within another rendering context (i.e. add it to some other document you are generating).

The former is relatively easily accomplished using the Flying Saucer framework, which can be found here: https://github.com/flyingsaucerproject/flyingsaucer

The latter is actually a much more comprehensive problem that needs to be categorized further. Using iText you won't be able to (trivially, at least) combine iText elements (i.e. Paragraph, Phrase, Chunk and so on) with the generated HTML. You can hack your way out of this by using the ContentByte's addTemplate method and generating the HTML to this template.

If you on the other hand want to stamp the generated HTML with something like watermarks, dates or the like, you can do this using iText.

So bottom line: You can't trivially integrate the rendered HTML in other pdf generating contexts, but you can render HTML directly to a blank PDF document.

Xampp-mysql - "Table doesn't exist in engine" #1932

I have faced same issue and sorted using below step.

  1. Go to MySQL config file (my file at C:\xampp\mysql\bin\my.ini)
  2. Check for the line innodb_data_file_path = ibdata1:10M:autoextend
  3. Next check the ibdata1 file exist under C:/xampp/mysql/data/
  4. If file does not exist copy the ibdata1 file from location C:\xampp\mysql\backup\ibdata1

hope it helps to someone.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I found a solution to solve this problem in Python.

go to c:\python27\ directory and rigtlcick python.exe and tab to compaitbility and select the admin privilege option and apply the changes. Now you issue the command it allows to create the socket connection.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

Windows-1252 to UTF-8 encoding

iconv -f WINDOWS-1252 -t UTF-8 filename.txt

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

You can do the thing with T-SQL in the following way.

 ALTER TABLE {TABLENAME}
 ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
 CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}

As well as you can use SQL Server Management Studio also by right clicking table in the Design menu, setting the default value to table.

And furthermore, if you want to add the same column (if it does not exists) to all tables in database, then use:

 USE AdventureWorks;
 EXEC sp_msforeachtable
'PRINT ''ALTER TABLE ? ADD Date_Created DATETIME DEFAULT GETDATE();''' ;

Global variables in Java

To define Global Variable you can make use of static Keyword

public class Example {
    public static int a;
    public static int b;
}

now you can access a and b from anywhere by calling

Example.a;

Example.b;

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Use DateTime.TryParseExact() if you want to match against a specific date format

   string format = "yyyyMMdd"; 
    DateTime dateTime;
    DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                             DateTimeStyles.None, out dateTime);

Regular expression to get a string between two strings in Javascript

You can use destructuring to only focus on the part of your interest.

So you can do:

_x000D_
_x000D_
let str = "My cow always gives milk";

let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];

console.log(result);
_x000D_
_x000D_
_x000D_

In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || [] may be interesting if you are not sure there will be a match at all. In that case match would return null which cannot be destructured, and so we return [] instead in that case, and then result will be null.

The additional \b ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+ is needed to avoid that the match includes some outer spacing.

How to apply color in Markdown?

I have started using Markdown to post some of my documents to an internal web site for in-house users. It is an easy way to have a document shared but not able to be edited by the viewer.

So, this marking of text in color is “Great”. I have use several like this and works wonderful.

<span style="color:blue">some *This is Blue italic.* text</span>

Turns into This is Blue italic.

And

<span style="color:red">some **This is Red Bold.** text</span>

Turns into This is Red Bold.

I love the flexibility and ease of use.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Good. I suggest creating a Value Object (Vo) that contains the fields you need. The code is simpler, we do not change the functioning of Jackson and it is even easier to understand. Regards!

A function to convert null to string

Convert.ToString(object) converts to string. If the object is null, Convert.ToString converts it to an empty string.

Calling .ToString() on an object with a null value throws a System.NullReferenceException.

EDIT:

Two exceptions to the rules:

1) ConvertToString(string) on a null string will always return null.

2) ToString(Nullable<T>) on a null value will return "" .

Code Sample:

// 1) Objects:

object obj = null;

//string valX1 = obj.ToString();           // throws System.NullReferenceException !!!
string val1 = Convert.ToString(obj);    

Console.WriteLine(val1 == ""); // True
Console.WriteLine(val1 == null); // False


// 2) Strings

String str = null;
//string valX2 = str.ToString();    // throws System.NullReferenceException !!!
string val2 = Convert.ToString(str); 

Console.WriteLine(val2 == ""); // False
Console.WriteLine(val2 == null); // True            


// 3) Nullable types:

long? num = null;
string val3 = num.ToString();  // ok, no error

Console.WriteLine(num == null); // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False 

val3 = Convert.ToString(num);  

Console.WriteLine(num == null);  // True
Console.WriteLine(val3 == "");  // True
Console.WriteLine(val3 == null); // False

Shell script to get the process ID on Linux

This works in Cygwin but it should be effective in Linux as well.

ps -W | awk '/ruby/,NF=1' | xargs kill -f

or

ps -W | awk '$0~z,NF=1' z=ruby | xargs kill -f

Bash Pitfalls

Play/pause HTML 5 video using JQuery

This is the easy methods we can use

on jquery button click function

$("#button").click(function(event){
    $('video').trigger('play');
    $('video').trigger('pause');
}

Thanks

Dynamically display a CSV file as an HTML table on a web page

phihag's answer puts each row in a single cell, while you are asking for each value to be in a separate cell. This seems to do it:

<?php
// Create a table from a csv file 
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        $row = $line[0];    // We need to get the actual row (it is the first element in a 1-element array)
        $cells = explode(";",$row);
        echo "<tr>";
        foreach ($cells as $cell) {
            echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>

Find the directory part (minus the filename) of a full path in access 97

I always used the FileSystemObject for this sort of thing. Here's a little wrapper function I used. Be sure to reference the Microsoft Scripting Runtime.

Function StripFilename(sPathFile As String) As String

'given a full path and file, strip the filename off the end and return the path

Dim filesystem As New FileSystemObject

StripFilename = filesystem.GetParentFolderName(sPathFile) & "\"

Exit Function

End Function

How to check if a file is empty in Bash?

[[ -f filename && ! -s filename ]] && echo "filename exists and is empty"

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

New -> Batch Drawable Import -> Click on Add button -> Select image -> Select Target Resolution, Target Name, Format -> Ok

Is it possible to sort a ES6 map object?

2 hours spent to get into details.

Note that the answer for question is already given at https://stackoverflow.com/a/31159284/984471

However, the question has keys that are not usual ones,
A clear & general example with explanation, is below that provides some more clarity:

.

let m1 = new Map();

m1.set(6,1); // key 6 is number and type is preserved (can be strings too)
m1.set(10,1);
m1.set(100,1);
m1.set(1,1);
console.log(m1);

// "string" sorted (even if keys are numbers) - default behaviour
let m2 = new Map( [...m1].sort() );
//      ...is destructuring into individual elements
//      then [] will catch elements in an array
//      then sort() sorts the array
//      since Map can take array as parameter to its constructor, a new Map is created
console.log('m2', m2);

// number sorted
let m3 = new Map([...m1].sort((a, b) => {
  if (a[0] > b[0]) return 1;
  if (a[0] == b[0]) return 0;
  if (a[0] < b[0]) return -1;
}));
console.log('m3', m3);

// Output
//    Map { 6 => 1, 10 => 1, 100 => 1, 1 => 1 }
// m2 Map { 1 => 1, 10 => 1, 100 => 1, 6 => 1 }
//           Note:  1,10,100,6  sorted as strings, default.
//           Note:  if the keys were string the sort behavior will be same as this
// m3 Map { 1 => 1, 6 => 1, 10 => 1, 100 => 1 }
//           Note:  1,6,10,100  sorted as number, looks correct for number keys

Hope that helps.

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Multiple select in Visual Studio?

For Visual Studio Code

Got to this question because I was looking for a way to select multiple words with mouse click on VS Code, which should be achieved by using alt+click, but this keybinding wasn't working (I think it is something related to my OS, Ubuntu).

For anyone looking for something similar, try changing the key to ctrl+click.

Go to Selection > Switch to Ctrl+Click for Multi Cursor

Replace invalid values with None in Pandas DataFrame

I prefer the solution using replace with a dict because of its simplicity and elegance:

df.replace({'-': None})

You can also have more replacements:

df.replace({'-': None, 'None': None})

And even for larger replacements, it is always obvious and clear what is replaced by what - which is way harder for long lists, in my opinion.

getting the index of a row in a pandas apply function

To access the index in this case you access the name attribute:

In [182]:

df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
    return row['a'] + row['b'] * row['c']

def rowIndex(row):
    return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
   a  b  c   d  rowIndex
0  1  2  3   7         0
1  4  5  6  34         1

Note that if this is really what you are trying to do that the following works and is much faster:

In [198]:

df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
   a  b  c   d
0  1  2  3   7
1  4  5  6  34

In [199]:

%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop

EDIT

Looking at this question 3+ years later, you could just do:

In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df

Out[15]: 
   a  b  c   d  rowIndex
0  1  2  3   7         0
1  4  5  6  34         1

but assuming it isn't as trivial as this, whatever your rowFunc is really doing, you should look to use the vectorised functions, and then use them against the df index:

In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df

Out[16]: 
   a  b  c   d  rowIndex  newCol
0  1  2  3   7         0       6
1  4  5  6  34         1      16

Java synchronized method lock on object, or method?

The lock accessed is on the object, not on the method. Which variables are accessed within the method is irrelevant.

Adding "synchronized" to the method means the thread running the code must acquire the lock on the object before proceeding. Adding "static synchronized" means the thread running the code must acquire the lock on the class object before proceeding. Alternatively you can wrap code in a block like this:

public void addA() {
    synchronized(this) {
        a++;
    }
}

so that you can specify the object whose lock must be acquired.

If you want to avoid locking on the containing object you can choose between:

Drawing an image from a data URL to a canvas

Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.

(function (doc) {
    var oError = null;
    var oFileIn = doc.getElementById('fileIn');
    var oFileReader = new FileReader();
    var oImage = new Image();
    oFileIn.addEventListener('change', function () {
        var oFile = this.files[0];
        var oLogInfo = doc.getElementById('logInfo');
        var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
        try {
            if (rFltr.test(oFile.type)) {
                oFileReader.readAsDataURL(oFile);
                oLogInfo.setAttribute('class', 'message info');
                throw 'Preview for ' + oFile.name;
            } else {
                oLogInfo.setAttribute('class', 'message error');
                throw oFile.name + ' is not a valid image';
            }
        } catch (err) {
            if (oError) {
                oLogInfo.removeChild(oError);
                oError = null;
                $('#logInfo').fadeOut();
                $('#imgThumb').fadeOut();
            }
            oError = doc.createTextNode(err);
            oLogInfo.appendChild(oError);
            $('#logInfo').fadeIn();
        }
    }, false);
    oFileReader.addEventListener('load', function (e) {
        oImage.src = e.target.result;
    }, false);
    oImage.addEventListener('load', function () {
        if (oCanvas) {
            oCanvas = null;
            oContext = null;
            $('#imgThumb').fadeOut();
        }
        var oCanvas = doc.getElementById('imgThumb');
        var oContext = oCanvas.getContext('2d');
        var nWidth = (this.width > 500) ? this.width / 4 : this.width;
        var nHeight = (this.height > 500) ? this.height / 4 : this.height;
        oCanvas.setAttribute('width', nWidth);
        oCanvas.setAttribute('height', nHeight);
        oContext.drawImage(this, 0, 0, nWidth, nHeight);
        $('#imgThumb').fadeIn();
    }, false);
})(document);

Replacing Numpy elements if condition is met

>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[0, 3, 3, 2],
       [4, 1, 1, 2],
       [3, 4, 2, 4],
       [2, 4, 3, 0],
       [1, 2, 3, 4]])
>>> 
>>> a[a > 3] = -101
>>> a
array([[   0,    3,    3,    2],
       [-101,    1,    1,    2],
       [   3, -101,    2, -101],
       [   2, -101,    3,    0],
       [   1,    2,    3, -101]])
>>>

See, eg, Indexing with boolean arrays.

How to make join queries using Sequelize on Node.js

While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.

If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:

SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id

Which is semantically the same thing as the OP's original SQL:

SELECT * FROM posts, users WHERE posts.user_id = users.id

then this is what you want:

Posts.findAll({
  include: [{
    model: User,
    required: true
   }]
}).then(posts => {
  /* ... */
});

Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:

Posts.findAll({
  include: [{
    model: User,
//  required: false
   }]
}).then(posts => {
  /* ... */
});

If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

Note that required is true by default as soon as you add a where clause in.

If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
    required: false,
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: ["year_birth = post_year"]
   }]
}).then(posts => {
  /* ... */
});

I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)

I figured this out (mostly) from this doc:

jQuery UI Dialog OnBeforeUnload

You can also make an exception for leaving the page via submitting a particular form:

$(window).bind('beforeunload', function(){
    return "Do you really want to leave now?";
});

$("#form_id").submit(function(){
    $(window).unbind("beforeunload");
});

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

"Multiple definition", "first defined here" errors

I had a similar issue when not using inline for my global function that was included in two places.

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

How to trigger a phone call when clicking a link in a web page on mobile phone

The proper URL scheme is tel:[number] so you would do

_x000D_
_x000D_
<a href="tel:5551234567"><img src="callme.jpg" /></a>
_x000D_
_x000D_
_x000D_

How do I get the name of a Ruby class?

Both result.class.to_s and result.class.name work.

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

How do I update a Python package?

pip install -U $(pip list --outdated | awk 'NR>2 {print $1}')

read word by word from file in C++

I have edited the function for you,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

How to detect chrome and safari browser (webkit)

Many answers here. Here is my first consideration.

Without JavaScript, including the possibility Javascript is initially disabled by the user in his browser for security purposes, to be white listed by the user if the user trusts the site, DOM will not be usable because Javascript is off.

Programmatically, you are left with a backend server-side or frontend client-side consideration.

With the backend, you can use common denominator HTTP "User-Agent" request header and/or any possible proprietary HTTP request header issued by the browser to output browser specific HTML stuff.

With the client site, you may want to enforce Javascript to allow you to use DOM. If so, then you probably will want to first use the following in your HTML page:

<noscript>This site requires Javascript. Please turn on Javascript.</noscript>

While we are heading to a day with every web coder will be dependent on Javascript in some way (or not), today, to presume every user has javascript enabled would be design and product development QA mistake.

I've seen far too may sites who end up with a blank page or the site breaks down because it presumed every user has javascript enabled. No. For security purposes, they may have Javascript initially off and some browsers, like Chrome, will allow the user to white list the web site on a domain by domain basis. Edge is the only browser I am aware of where Microsoft made the decision to completely disable the user's ability to turn off Javascript. Edge doesn't offer a white listing concept hence it is one reason I don't personally use Edge.

Using the tag is a simple way to inform the user your site won't work without Javascript. Once the user turns it on and refreshes/reload the page, DOM is now available to use the techniques cited by the thread replies to detect chrome vs safari.

Ironically, I got here because I was updating by platform and google the same basic question; chrome vs sarafi. I didn't know Chrome creates a DOM object named "chrome" which is really all you need to detect "chrome" vs everything else.

var isChrome = typeof(chrome) === "object";

If true, you got Chrome, if false, you got some other browser.

Check to see if Safari create its own DOM object as well, if so, get the object name and do the same thing, for example:

var isSafari = (typeof(safari) === "object");

Hope these tips help.

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

I'm responding to this question because I had a different way of fixing this problem than the other answers had. I had this problem when I refactored the name of the plugins that I was exporting. Eventually I had to make sure to fix/change the following.

  1. The product file's dependencies,
  2. The plugin.xml dependencies (and make sure it is not implicitly imported using the imported packages dialog).
  3. The run configuration plug-ins tab. Run As..->Run Configurations->Plug-ins tab. Uncheck the old plugins and then click Add Required Plug-ins.

This worked for me, but your mileage may vary.

Oracle listener not running and won't start

I encounter similar problem when installing oracle 11gR2 on Windows 2012 server. the problem is solved when I run cmd.exe as Admistrator privilege and run "lsnrctl start LISTENER".

"Correct" way to specifiy optional arguments in R functions

I would tend to prefer using NULL for the clarity of what is required and what is optional. One word of warning about using default values that depend on other arguments, as suggested by Jthorpe. The value is not set when the function is called, but when the argument is first referenced! For instance:

foo <- function(x,y=length(x)){
    x <- x[1:10]
    print(y)
}
foo(1:20) 
#[1] 10

On the other hand, if you reference y before changing x:

foo <- function(x,y=length(x)){
    print(y)
    x <- x[1:10]
}
foo(1:20) 
#[1] 20

This is a bit dangerous, because it makes it hard to keep track of what "y" is being initialized as if it's not called early on in the function.

Pip install - Python 2.7 - Windows 7

Add the following to you environment variable PATH.

C:\Python27\Scripts

This path will contain the pip executable file. Make sure it exist. If it doesn't then you'll need to install it using the get-pip.py script.

Additonally, you can read the following link to get a better understanding.

Where to put Gradle configuration (i.e. credentials) that should not be committed?

You could also supply variables on the command line with -PmavenUser=user -PmavenPassword=password.

This might be useful you can't use a gradle.properties file for some reason. E.g. on a build server we're using Gradle with the -g option so that each build plan has it's own GRADLE_HOME.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Already defined in .obj - no double inclusions

I do recomend doing it in 2 filles (.h .cpp) But if u lazy just add inline before the function So it will look something like this

inline void functionX() 
{ }

more about inline functions:

The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.

more info here

How to install a private NPM module without my own registry?

This was what I was looking for:

# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master

# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev

How to define a default value for "input type=text" without using attribute 'value'?

You can set the value property using client script after the element is created:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

Send Mail to multiple Recipients in java

So ... it took many months, but still ... You can send email to multiple recipients by using the ',' as separator and

message.setRecipients(Message.RecipientType.CC, "[email protected],[email protected],[email protected]");

is ok. At least in JavaMail 1.4.5

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

Angular 4 checkbox change value

try this worked for me :

checkValue(event: any) {
    this.siteSelected.majeur = event;
}

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

There are two things to remember here. One is to add the -PassThru argument and two is to add the -Wait argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property

-PassThru [<SwitchParameter>]
    Returns a process object for each process that the cmdlet started. By d
    efault, this cmdlet does not generate any output.

Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:

$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode

# This will print 1

If you run it without -PassThru or -Wait, it will print out nothing.

The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?

How to find day of week in php in a specific timezone

My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue

Progress during large file copy (Copy-Item & Write-Progress?)

cmd /c copy /z src dest

not pure PowerShell, but executable in PowerShell and it displays progress in percents

Adding values to a C# array

Answers on how to do it using an array are provided here.

However, C# has a very handy thing called System.Collections :)

Collections are fancy alternatives to using an array, though many of them use an array internally.

For example, C# has a collection called List that functions very similar to the PHP array.

using System.Collections.Generic;

// Create a List, and it can only contain integers.
List<int> list = new List<int>();

for (int i = 0; i < 400; i++)
{
   list.Add(i);
}

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can create table variable instead of tamp table in procedure A and execute procedure B and insert into temp table by below query.

DECLARE @T TABLE
(
TABLE DEFINITION
)
.
.
.
INSERT INTO @T
EXEC B @MYDATE

and you continue operation.

Selenium WebDriver.get(url) does not open the URL

I was having the save issue when trying with Chrome. I finally placed my chromedrivers.exe in the same location as my project. This fixed it for me.

How does the ARM architecture differ from x86?

The ARM is like an Italian sports car:

  • Well balanced, well tuned, engine. Gives good acceleration, and top speed.
  • Excellent chases, brakes and suspension. Can stop quickly, can corner without slowing down.

The x86 is like an American muscle car:

  • Big engine, big fuel pump. Gives excellent top speed, and acceleration, but uses a lot of fuel.
  • Dreadful brakes, you need to put an appointment in your diary, if you want to slowdown.
  • Terrible steering, you have to slow down to corner.

In summary: the x86 is based on a design from 1974 and is good in a straight line (but uses a lot of fuel). The arm uses little fuel, does not slowdown for corners (branches).


Metaphor over, here are some real differences.

  • Arm has more registers.
  • Arm has few special purpose registers, x86 is all special purpose registers (so less moving stuff around).
  • Arm has few memory access commands, only load/store register.
  • Arm is internally Harvard architecture my design.
  • Arm is simple and fast.
  • Arm instructions are architecturally single cycle (except load/store multiple).
  • Arm instructions often do more than one thing (in a single cycle).
  • Where more that one Arm instruction is needed, such as the x86's looping store & auto-increment, the Arm still does it in less clock cycles.
  • Arm has more conditional instructions.
  • Arm's branch predictor is trivially simple (if unconditional or backwards then assume branch, else assume not-branch), and performs better that the very very very complex one in the x86 (there is not enough space here to explain it, not that I could).
  • Arm has a simple consistent instruction set (you could compile by hand, and learn the instruction set quickly).

How to use FormData in react-native?

I was looking for a long time an answer that solve the problem and this is the way I did it

I take the file with expo-document-picker

const pickDocument = async (tDocument) => {
    let result = await DocumentPicker.getDocumentAsync();
    result.type = mimetype(result.name);
    if (result.type === undefined){
      alert("not allowed extention");
      return null;
    }
    let formDat = new FormData();
    formDat.append("file", result);
    uploadDoc(formDat);
  };

  const mimetype = (name) => {
    let allow =  {"png":"image/png","pdf":"application/json","jpeg":"image/jpeg", "jpg":"image/jpg"};
    let extention = name.split(".")[1];
    if (allow[extention] !== undefined){
      return allow[extention]
    }
    else {
      return undefined
    }
  }

const uploadDoc = (data) =>  {
    fetch("MyApi", {
      method: "POST",
      body: data
    }).then(res => res.json())
    .then(response =>{
      if (response.result === 1) {
        //somecode
      } else {
        //somecode
      }
    });
  }

this is because android doesn't manage the mime-type of your file so if you put away the header "Content-type" and instead you put the mime-type on the file it gonna send the correct header

works on IOS an Android

How to add a new line in textarea element?

T.innerText = "Position of LF: " + t.value.indexOf("\n");

p3.innerText = t.value.replace("\n", "");

<textarea id="t">Line 1&#10;Line 2</textarea>

<p id='p3'></p>

How to access POST form fields

Note for Express 4 users:

If you try and put app.use(express.bodyParser()); into your app, you'll get the following error when you try to start your Express server:

Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

You'll have to install the package body-parser separately from npm, then use something like the following (example taken from the GitHub page):

var express    = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

Omit rows containing specific column of NA

Use is.na

DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
DF[!is.na(DF$y),]

How to set the color of "placeholder" text?

Try this

textarea::-webkit-input-placeholder {  color: #999;}

How do I make a burn down chart in Excel?

No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.

Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.

Burndown Chart of Pages Read

PHP's array_map including keys

I always like the javascript variant of array map. The most simple version of it would be:

/**
 * @param  array    $array
 * @param  callable $callback
 * @return array
 */
function arrayMap(array $array, callable $callback)
{
    $newArray = [];

    foreach( $array as $key => $value )
    {
        $newArray[] = call_user_func($callback, $value, $key, $array);
    }

    return $newArray;
}

So now you can just pass it a callback function how to construct the values.

$testArray = [
    "first_key" => "first_value", 
    "second_key" => "second_value"
];

var_dump(
    arrayMap($testArray, function($value, $key) {
        return $key . ' loves ' . $value;
    });
);

Find a file in python

I used a version of os.walk and on a larger directory got times around 3.5 sec. I tried two random solutions with no great improvement, then just did:

paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()]

While it's POSIX-only, I got 0.25 sec.

From this, I believe it's entirely possible to optimise whole searching a lot in a platform-independent way, but this is where I stopped the research.

How to open html file?

you can make use of the following code:

from __future__ import division, unicode_literals 
import codecs
from bs4 import BeautifulSoup

f=codecs.open("test.html", 'r', 'utf-8')
document= BeautifulSoup(f.read()).get_text()
print document

If you want to delete all the blank lines in between and get all the words as a string (also avoid special characters, numbers) then also include:

import nltk
from nltk.tokenize import word_tokenize
docwords=word_tokenize(document)
for line in docwords:
    line = (line.rstrip())
    if line:
        if re.match("^[A-Za-z]*$",line):
            if (line not in stop and len(line)>1):
                st=st+" "+line
print st

*define st as a string initially, like st=""

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

A formal analysis has been done by Phil Rogaway in 2011, here. Section 1.6 gives a summary that I transcribe here, adding my own emphasis in bold (if you are impatient, then his recommendation is use CTR mode, but I suggest that you read my paragraphs about message integrity versus encryption below).

Note that most of these require the IV to be random, which means non-predictable and therefore should be generated with cryptographic security. However, some require only a "nonce", which does not demand that property but instead only requires that it is not re-used. Therefore designs that rely on a nonce are less error prone than designs that do not (and believe me, I have seen many cases where CBC is not implemented with proper IV selection). So you will see that I have added bold when Rogaway says something like "confidentiality is not achieved when the IV is a nonce", it means that if you choose your IV cryptographically secure (unpredictable), then no problem. But if you do not, then you are losing the good security properties. Never re-use an IV for any of these modes.

Also, it is important to understand the difference between message integrity and encryption. Encryption hides data, but an attacker might be able to modify the encrypted data, and the results can potentially be accepted by your software if you do not check message integrity. While the developer will say "but the modified data will come back as garbage after decryption", a good security engineer will find the probability that the garbage causes adverse behaviour in the software, and then he will turn that analysis into a real attack. I have seen many cases where encryption was used but message integrity was really needed more than the encryption. Understand what you need.

I should say that although GCM has both encryption and message integrity, it is a very fragile design: if you re-use an IV, you are screwed -- the attacker can recover your key. Other designs are less fragile, so I personally am afraid to recommend GCM based upon the amount of poor encryption code that I have seen in practice.

If you need both, message integrity and encryption, you can combine two algorithms: usually we see CBC with HMAC, but no reason to tie yourself to CBC. The important thing to know is encrypt first, then MAC the encrypted content, not the other way around. Also, the IV needs to be part of the MAC calculation.

I am not aware of IP issues.

Now to the good stuff from Professor Rogaway:

Block ciphers modes, encryption but not message integrity

ECB: A blockcipher, the mode enciphers messages that are a multiple of n bits by separately enciphering each n-bit piece. The security properties are weak, the method leaking equality of blocks across both block positions and time. Of considerable legacy value, and of value as a building block for other schemes, but the mode does not achieve any generally desirable security goal in its own right and must be used with considerable caution; ECB should not be regarded as a “general-purpose” confidentiality mode.

CBC: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is merely a nonce, nor if it is a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are highly malleable. No chosen ciphertext attack (CCA) security. Confidentiality is forfeit in the presence of a correct-padding oracle for many padding methods. Encryption inefficient from being inherently serial. Widely used, the mode’s privacy-only security properties result in frequent misuse. Can be used as a building block for CBC-MAC algorithms. I can identify no important advantages over CTR mode.

CFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is predictable, nor if it is made by a nonce enciphered under the same key used by the scheme, as the standard incorrectly suggests to do. Ciphertexts are malleable. No CCA-security. Encryption inefficient from being inherently serial. Scheme depends on a parameter s, 1 = s = n, typically s = 1 or s = 8. Inefficient for needing one blockcipher call to process only s bits . The mode achieves an interesting “self-synchronization” property; insertion or deletion of any number of s-bit characters into the ciphertext only temporarily disrupts correct decryption.

OFB: An IV-based encryption scheme, the mode is secure as a probabilistic encryption scheme, achieving indistinguishability from random bits, assuming a random IV. Confidentiality is not achieved if the IV is a nonce, although a fixed sequence of IVs (eg, a counter) does work fine. Ciphertexts are highly malleable. No CCA security. Encryption and decryption inefficient from being inherently serial. Natively encrypts strings of any bit length (no padding needed). I can identify no important advantages over CTR mode.

CTR: An IV-based encryption scheme, the mode achieves indistinguishability from random bits assuming a nonce IV. As a secure nonce-based scheme, the mode can also be used as a probabilistic encryption scheme, with a random IV. Complete failure of privacy if a nonce gets reused on encryption or decryption. The parallelizability of the mode often makes it faster, in some settings much faster, than other confidentiality modes. An important building block for authenticated-encryption schemes. Overall, usually the best and most modern way to achieve privacy-only encryption.

XTS: An IV-based encryption scheme, the mode works by applying a tweakable blockcipher (secure as a strong-PRP) to each n-bit chunk. For messages with lengths not divisible by n, the last two blocks are treated specially. The only allowed use of the mode is for encrypting data on a block-structured storage device. The narrow width of the underlying PRP and the poor treatment of fractional final blocks are problems. More efficient but less desirable than a (wide-block) PRP-secure blockcipher would be.

MACs (message integrity but not encryption)

ALG1–6: A collection of MACs, all of them based on the CBC-MAC. Too many schemes. Some are provably secure as VIL PRFs, some as FIL PRFs, and some have no provable security. Some of the schemes admit damaging attacks. Some of the modes are dated. Key-separation is inadequately attended to for the modes that have it. Should not be adopted en masse, but selectively choosing the “best” schemes is possible. It would also be fine to adopt none of these modes, in favor of CMAC. Some of the ISO 9797-1 MACs are widely standardized and used, especially in banking. A revised version of the standard (ISO/IEC FDIS 9797-1:2010) will soon be released [93].

CMAC: A MAC based on the CBC-MAC, the mode is provably secure (up to the birthday bound) as a (VIL) PRF (assuming the underlying blockcipher is a good PRP). Essentially minimal overhead for a CBCMAC-based scheme. Inherently serial nature a problem in some application domains, and use with a 64-bit blockcipher would necessitate occasional re-keying. Cleaner than the ISO 9797-1 collection of MACs.

HMAC: A MAC based on a cryptographic hash function rather than a blockcipher (although most cryptographic hash functions are themselves based on blockciphers). Mechanism enjoys strong provable-security bounds, albeit not from preferred assumptions. Multiple closely-related variants in the literature complicate gaining an understanding of what is known. No damaging attacks have ever been suggested. Widely standardized and used.

GMAC: A nonce-based MAC that is a special case of GCM. Inherits many of the good and bad characteristics of GCM. But nonce-requirement is unnecessary for a MAC, and here it buys little benefit. Practical attacks if tags are truncated to = 64 bits and extent of decryption is not monitored and curtailed. Complete failure on nonce-reuse. Use is implicit anyway if GCM is adopted. Not recommended for separate standardization.

authenticated encryption (both encryption and message integrity)

CCM: A nonce-based AEAD scheme that combines CTR mode encryption and the raw CBC-MAC. Inherently serial, limiting speed in some contexts. Provably secure, with good bounds, assuming the underlying blockcipher is a good PRP. Ungainly construction that demonstrably does the job. Simpler to implement than GCM. Can be used as a nonce-based MAC. Widely standardized and used.

GCM: A nonce-based AEAD scheme that combines CTR mode encryption and a GF(2128)-based universal hash function. Good efficiency characteristics for some implementation environments. Good provably-secure results assuming minimal tag truncation. Attacks and poor provable-security bounds in the presence of substantial tag truncation. Can be used as a nonce-based MAC, which is then called GMAC. Questionable choice to allow nonces other than 96-bits. Recommend restricting nonces to 96-bits and tags to at least 96 bits. Widely standardized and used.

How can I check whether an array is null / empty?

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];
        System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
        for (Integer integer : integers1) {
            System.out.println(integer); //prints all 0s
        }

//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
//        integers1[2] = 0;
        for (Integer integer : integers1) {
            System.out.println(integer); //Still it prints all 0s but it is not empty
            //but that manually added 0 is different
        }

//Even we manually add 0, still we need to treat it as null. This is semantic logic.

        Integer[] integers2 = new Integer[20];
        integers2 = null; //array is nullified
//        integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line. 
        if (integers2 == null) {
            System.out.println("null Array");
        }   

How to create a GUID / UUID

Because i can, i thought i should share my solution, since it is a very fascinating problem and it has so many solutions.

It works for nodejs too, if you replace let buffer = new Uint8Array(); crypto.getRandomValues with let buffer = crypto.randomBytes(16)

I hope it helps somebody. It should beat most regex solutions in performance.

_x000D_
_x000D_
const hex = '0123456789ABCDEF'

let generateToken = function() {
    let buffer = new Uint8Array(16)
    
    crypto.getRandomValues(buffer)

    buffer[6] = 0x40 | (buffer[6] & 0xF)
    buffer[8] = 0x80 | (buffer[8] & 0xF)

    let segments = []

    for (let i = 0; i < 16; ++i) {
        segments.push(hex[(buffer[i] >> 4 & 0xF)])
        segments.push(hex[(buffer[i] >> 0 & 0xF)])

        if (i == 3 || i == 5 || i == 7 || i == 9) {
            segments.push('-')
        }
    }

    return segments.join('')
}

for (let i = 0; i < 100; ++i) {
  console.log(generateToken())
}
_x000D_
_x000D_
_x000D_

Performance charts, everybody loves them: jsbench

Have fun and thank you for all the other solutions, some served my quite long.

MySQL WHERE IN ()

You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).

I assume your table looks somewhat like this

TABLE
================================
| group_id | user_ids | name   |
--------------------------------
| 1        | 1,4,6    | group1 |
--------------------------------
| 2        | 4,5,1    | group2 |    

so in your table of user groups, each row represents one group and in user_ids column you have set of user ids assigned to that group.

Normalized version of this table would look like this

GROUP
=====================
| id       | name   |
---------------------
| 1        | group1 |
---------------------
| 2        | group2 |    

GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1        | 1       |
----------------------
| 1        | 4       |
----------------------
| 1        | 6       |
----------------------
| 2        | 4       |
----------------------
| ...      

Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:

/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);

/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);

/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;

/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;

/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;

/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;

This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment, when you want to remove assignment you just delete row in group_user_assignment.

In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.

Here is sqlFiddle to play with.

AttributeError: Can only use .dt accessor with datetimelike values

Your problem here is that the dtype of 'Date' remained as str/object. You can use the parse_dates parameter when using read_csv

import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', parse_dates= [col],encoding='utf-8-sig', usecols= ['Date', 'ids'],)    
df['Month'] = df['Date'].dt.month

From the documentation for the parse_dates parameter

parse_dates : bool or list of int or names or list of lists or dict, default False

The behavior is as follows:

  • boolean. If True -> try parsing the index.
  • list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
  • list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
  • dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use pd.to_datetime after pd.read_csv. To parse an index or column with a mixture of timezones, specify date_parser to be a partially-applied pandas.to_datetime() with utc=True. See Parsing a CSV with mixed timezones for more.

Note: A fast-path exists for iso8601-formatted dates.

The relevant case for this question is the "list of int or names" one.

col is the columns index of 'Date' which parses as a separate date column.

How can I load Partial view inside the view?

If you want to load the partial view directly inside the main view you could use the Html.Action helper:

@Html.Action("Load", "Home")

or if you don't want to go through the Load action use the HtmlPartialAsync helper:

@await Html.PartialAsync("_LoadView")

If you want to use Ajax.ActionLink, replace your Html.ActionLink with:

@Ajax.ActionLink(
    "load partial view", 
    "Load", 
    "Home", 
    new AjaxOptions { UpdateTargetId = "result" }
)

and of course you need to include a holder in your page where the partial will be displayed:

<div id="result"></div>

Also don't forget to include:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

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

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.

Align items in a stack panel?

Maybe not what you want if you need to avoid hard-coding size values, but sometimes I use a "shim" (Separator) for this:

<Separator Width="42"></Separator>

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Changing the color of a clicked table row using jQuery

.highlight { background-color: red; }

If you want multiple selections

$("#data tr").click(function() {
    $(this).toggleClass("highlight");
});

If you want only 1 row in the table to be selected at a time

$("#data tr").click(function() {
    var selected = $(this).hasClass("highlight");
    $("#data tr").removeClass("highlight");
    if(!selected)
            $(this).addClass("highlight");
});

Also note your TABLE tag has 2 ID attributes, you can't do that.

How can I replace newline or \r\n with <br/>?

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);

Angularjs loading screen on ajax request

You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

angular.module('directive.loading', [])
        .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isNoLoadingForced = false;
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                    };

                    $rootScope.$on('stopLoader', function(){
                        scope.isNoLoadingForced = true;
                    })

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);

This is definatly not the best solution but it would still works.

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

Should I write script in the body or the head of the html?

I always put my scripts in the header. My reasons:

  1. I like to separate code and (static) text
  2. I usually load my script from external sources
  3. The same script is used from several pages, so it feels like an include file (which also goes in the header)

react native get TextInput value

Every thing is OK for me by this procedure:

<Input onChangeText={this.inputOnChangeText} />

and also:

inputOnChangeText = (e) => {
  this.setState({
    username: e
  })
}

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

Content Type application/soap+xml; charset=utf-8 was not supported by service

I run into naming problem. Service name has to be exactly name of your implementation. If mismatched, it uses by default basicHttpBinding resulting in text/xml content type.

Name of your class is on two places - SVC markup and CS file.

Check endpoint contract too - again exact name of your interface, nothing more. I've added assembly name which just can't be there.

<service name="MyNamespace.MyService">
    <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.IMyService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

How to view data saved in android database(SQLite)?

Open DDMS than in DATA>DATA>"Select your package like com.example.foo"> than select your database folder than pull that data in eclipse you can see the pull an push icon on top right side ...

What are the differences in die() and exit() in PHP?

DIFFERENCE IN ORIGIN

The difference between die() and exit() in PHP is their origin.


FUNCTIONALLY EQUIVALENT

die() and exit() are equivalent functions.

PHP Manual

PHP Manual for die:

This language construct is equivalent to exit().

PHP Manual for exit:

Note: This language construct is equivalent to die().

PHP Manual for List of Function Aliases:

die is an alias for master function exit()


DIFFERENT IN OTHER LANGUAGES

die() and exit() are different in other languages but in PHP they are identical.

From Yet another PHP rant:

...As a C and Perl coder, I was ready to answer, "Why, exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status." But then I remembered we're in messy-syntax-land of PHP.

In PHP, exit() and die() are identical.

The designers obviously thought "Hmm, let's borrow exit() from C. And Perl folks probably will like it if we take die() as is from Perl too. Oops! We have two exit functions now! Let's make it so that they both can take a string or integer as an argument and make them identical!"

The end result is that this didn't really make things any "easier", just more confusing. C and Perl coders will continue to use exit() to toss an integer exit value only, and die() to toss an error message and exit with a failure. Newbies and PHP-as-a-first-language people will probably wonder "umm, two exit functions, which one should I use?" The manual doesn't explain why there's exit() and die().

In general, PHP has a lot of weird redundancy like this - it tries to be friendly to people who come from different language backgrounds, but while doing so, it creates confusing redundancy.

How do I create a sequence in MySQL?

Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.

In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.

Without additional details on the specific error, it is difficult to provide more specific help.

UPDATE

CREATE TABLE ORD (
  ORDID INT NOT NULL AUTO_INCREMENT,
  //Rest of table code
  PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;

This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.

Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.

ALTER TABLE ORD AUTO_INCREMENT = 622;

UPDATE 2 Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.

Determine what attributes were changed in Rails after_save callback?

you can add a condition to the after_update like so:

class SomeModel < ActiveRecord::Base
  after_update :send_notification, if: :published_changed?

  ...
end

there's no need to add a condition within the send_notification method itself.

How to create a new branch from a tag?

I used the following steps to create a new hot fix branch from a Tag.

Syntax

git checkout -b <New Branch Name> <TAG Name>

Steps to do it.

  1. git checkout -b NewBranchName v1.0
  2. Make changes to pom / release versions
  3. Stage changes
  4. git commit -m "Update pom versions for Hotfix branch"
  5. Finally push your newly created branch to remote repository.
git push -u origin NewBranchName

I hope this would help.

MySQL Trigger after update only if row has changed

Use the following query to see which rows have changes:

(select * from inserted) except (select * from deleted)

The results of this query should consist of all the new records that are different from the old ones.

What is the best collation to use for MySQL with PHP?

Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.

Example from the documentation for charset unicode:

utf8_general_ci also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should use utf8_general_ci because it is faster. Otherwise, use utf8_unicode_ci because it is more accurate.

So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci should suffice, for other languages, like Swedish, special collations have been created.

Get the value of input text when enter key pressed

Try this:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>  
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

JS Code

function search(ele) {
    if(event.key === 'Enter') {
        alert(ele.value);        
    }
}

DEMO Link

How can you make a custom keyboard in Android?

I came across this post recently when I was trying to decide what method to use to create my own custom keyboard. I found the Android system API to be very limited, so I decided to make my own in-app keyboard. Using Suragch's answer as the basis for my research, I went on to design my own keyboard component. It's posted on GitHub with an MIT license. Hopefully this will save somebody else a lot of time and headache.

The architecture is pretty flexible. There is one main view (CustomKeyboardView) that you can inject with whatever keyboard layout and controller you want.

You just have to declare the CustomKeyboardView in you activity xml (you can do it programmatically as well):

    <com.donbrody.customkeyboard.components.keyboard.CustomKeyboardView
    android:id="@+id/customKeyboardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

Then register your EditText's with it and tell it what type of keyboard they should use:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val numberField: EditText = findViewById(R.id.testNumberField)
    val numberDecimalField: EditText = findViewById(R.id.testNumberDecimalField)
    val qwertyField: EditText = findViewById(R.id.testQwertyField)

    keyboard = findViewById(R.id.customKeyboardView)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER, numberField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER_DECIMAL, numberDecimalField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.QWERTY, qwertyField)
}

The CustomKeyboardView handles the rest!

I've got the ball rolling with a Number, NumberDecimal, and QWERTY keyboard. Feel free to download it and create your own layouts and controllers. It looks like this:

android custom keyboard gif landscape

enter image description here

Even if this is not the architecture you decide to go with, hopefully it'll be helpful to see the source code for a working in-app keyboard.

Again, here's the link to the project: Custom In-App Keyboard

EDIT: I'm no longer an Android developer, and I no longer maintain this GitHub project. There are probably more modern approaches and architectures at this point, but please feel free to reference the GitHub project if you'd like and fork it.

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

How can I give the Intellij compiler more heap space?

To resolve this issue follow the below given steps-

1). In inteli Go to File> Setting Option and Search for Vm Option In the field of Vm Option for Importer give value -Xmx512m. Intelij Setting Options

2). Go to Control Pannel Select View by :Large icons then Go to Java one promp window will appear with name java control pannel then go to java Java VM Options

select view option. java view options

In Java Run time Environment Setting pass Run time Parameters as -Xmx1024m.

3). If above given options does not work then change the size of pom.xml

How to return an array from an AJAX call?

@Xeon06, nice but just as a fyi for those that read this thread and tried like me... when returning the array from php => json_encode($theArray). converts to a string which to me isn't easy to manipulate esp for soft js users like myself.

Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data) where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.

e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse

for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) } - prints to ur firebug console. voila!

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"]}, //                 
           ]
};

Loading local JSON file

What I did was editing the JSON file little bit.

myfile.json => myfile.js

In the JSON file, (make it a JS variable)

{name: "Whatever"} => var x = {name: "Whatever"}

At the end,

export default x;

Then,

import JsonObj from './myfile.js';

How to update primary key

When you find it necessary to update a primary key value as well as all matching foreign keys, then the entire design needs to be fixed.

It is tricky to cascade all the necessary foreign keys changes. It is a best practice to never update the primary key, and if you find it necessary, you should use a Surrogate Primary Key, which is a key not derived from application data. As a result its value is unrelated to the business logic and never needs to change (and should be invisible to the end user). You can then update and display some other column.

for example:

BadUserTable
UserID     varchar(20) primary key --user last name
other columns...

when you create many tables that have a FK to UserID, to track everything that the user has worked on, but that user then gets married and wants a ID to match their new last name, you are out of luck.

GoodUserTable
UserID    int identity(1,1) primary key
UserLogin varchar(20) 
other columns....

you now FK the Surrogate Primary Key to all the other tables, and display UserLogin when necessary, allow them to login using that value, and when they need to change it, you change it in one column of one row only.

calling parent class method from child class object in java

Say the hierarchy is C->B->A with A being the base class.

I think there's more to fixing this than renaming a method. That will work but is that a fix?

One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

Recyclerview inside ScrollView not scrolling smoothly

Or you can just set android:focusableInTouchMode="true" in your recycler view

How to Convert JSON object to Custom C# object?

A good way to use JSON in C# is with JSON.NET

Quick Starts & API Documentation from JSON.NET - Official site help you work with it.

An example of how to use it:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

"Large data" workflows using pandas

There is now, two years after the question, an 'out-of-core' pandas equivalent: dask. It is excellent! Though it does not support all of pandas functionality, you can get really far with it. Update: in the past two years it has been consistently maintained and there is substantial user community working with Dask.

And now, four years after the question, there is another high-performance 'out-of-core' pandas equivalent in Vaex. It "uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted)." It can handle data sets of billions of rows and does not store them into memory (making it even possible to do analysis on suboptimal hardware).

Android - Pulling SQlite database android device

you can easily extract the sqlite file from your device(root no necessary)

  1. Go to SDK Folder
  2. cd platform-tools
  3. start adb

    cd /sdk/platform-tools ./adb shell

    Then type in the following command in terminal

    ./adb -d shell "run-as com.your_packagename cat /data/data/com.your_packagename/databases/jokhanaNepal > /sdcard/jokhana.sqlite"

    For eg

    ./adb -d shell "run-as com.yuvii.app cat /data/data/com.yuvii.app/databases/jokhanaNepal > /sdcard/jokhana.sqlite"

Eclipse interface icons very small on high resolution screen in Windows 8.1

Thank you Sigh David Levy. I could not develop on Eclipse w/out your sol'n. I had to add a coupla catch (exceptions) to your code to get it to work:

            while (srcEntries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) srcEntries.nextElement();
                    logger.info("Processing zip entry ["+ entry.getName() + "]");

                    ZipEntry newEntry = new ZipEntry(entry.getName());


                    try { outStream.putNextEntry(newEntry); } 
                    ***catch (Exception e) { 
                        logger.error("error: ", e);
                        outStream.closeEntry();
                        continue;*
                    }**

Spring Boot Remove Whitelabel Error Page

You need to change your code to the following:

@RestController
public class IndexController implements ErrorController{

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "Error handling";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

Your code did not work, because Spring Boot automatically registers the BasicErrorController as a Spring Bean when you have not specified an implementation of ErrorController.

To see that fact just navigate to ErrorMvcAutoConfiguration.basicErrorController here.

Deleting an SVN branch

Sure: svn rm the unwanted folder, and commit.

To avoid this situation in the future, I would follow the recommended layout for SVN projects:

  • Put your code in the /someproject/trunk folder (or just /trunk if you want to put only one project in the repository)
  • Created branches as /someproject/branches/somebranch
  • Put tags under /someproject/tags

Now when you check out a working copy, be sure to check out only trunk or some individual branch. Don't check everything out in one huge working copy containing all branches.1

1Unless you know what you're doing, in which case you know how to create shallow working copies.

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Tracing XML request/responses with JAX-WS

Here is the solution in raw code (put together thanks to stjohnroe and Shamik):

Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);

Where SOAPLoggingHandler is (ripped from linked examples):

package com.myfirm.util.logging.ws;

import java.io.PrintStream;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/*
 * This simple SOAPHandler will output the contents of incoming
 * and outgoing messages.
 */
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {

    // change this to redirect output if desired
    private static PrintStream out = System.out;

    public Set<QName> getHeaders() {
        return null;
    }

    public boolean handleMessage(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    public boolean handleFault(SOAPMessageContext smc) {
        logToSystemOut(smc);
        return true;
    }

    // nothing to clean up
    public void close(MessageContext messageContext) {
    }

    /*
     * Check the MESSAGE_OUTBOUND_PROPERTY in the context
     * to see if this is an outgoing or incoming message.
     * Write a brief message to the print stream and
     * output the message. The writeTo() method can throw
     * SOAPException or IOException
     */
    private void logToSystemOut(SOAPMessageContext smc) {
        Boolean outboundProperty = (Boolean)
            smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {
            out.println("\nOutbound message:");
        } else {
            out.println("\nInbound message:");
        }

        SOAPMessage message = smc.getMessage();
        try {
            message.writeTo(out);
            out.println("");   // just to add a newline
        } catch (Exception e) {
            out.println("Exception in handler: " + e);
        }
    }
}

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

Setting Windows PowerShell environment variables

To be clear, the 1990's Windows way of click on Start, right click on This PC, and choose Properties, and then select Advanced system settings, and then in the dialog box that pops up, select Environment Variables, and in the list double clicking on PATH and then using the New, Edit, Move Up and Move Down all still work for changing the PATH. Power shell, and the rest of Windows get whatever you set here.

Yes you can use these new methods, but the old one still works. And at the base level all of the permanent change methods are controlled ways of editing your registry files.

FtpWebRequest Download File

This paragraph from the FptWebRequest class reference might be of interest to you:

The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to /path.

how to clear JTable

If we use tMOdel.setRowCount(0); we can get Empty table.

DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);

Font Awesome 5 font-family issue

I had to set searchPseudoElements to to true to get it working in Angular5.

import fontawesome from '@fortawesome/fontawesome';
...
fontawesome.config.searchPseudoElements = true;
...
content: "\f12a";
font-family: 'Font Awesome 5 Solid';

How do I make a dictionary with multiple keys to one value?

It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.

let's go to the code example,

In [6]: a = 10

In [7]: id(a)
Out[7]: 10914656

In [8]: b = 10

In [9]: id(b)
Out[9]: 10914656

In [10]: c = 11

In [11]: id(c)
Out[11]: 10914688

In [12]: d = 21

In [13]: id(d)
Out[13]: 10915008

In [14]: e = 11

In [15]: id(e)
Out[15]: 10914688

In [16]: e = 21

In [17]: id(e)
Out[17]: 10915008

In [18]: e is d
Out[18]: True
In [19]: e = 30

In [20]: id(e)
Out[20]: 10915296

From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.

so any variable which is having same value shares the memory.

Not for list and dictionary objects

let's come to your question.

when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.

you can simply use it like this

In [49]: dictionary = {
    ...:     'k1':1,
    ...:     'k2':1,
    ...:     'k3':2,
    ...:     'k4':2}
    ...:     
    ...:     

In [50]: id(dictionary['k1'])
Out[50]: 10914368

In [51]: id(dictionary['k2'])
Out[51]: 10914368

In [52]: id(dictionary['k3'])
Out[52]: 10914400

In [53]: id(dictionary['k4'])
Out[53]: 10914400

From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P

What is JNDI? What is its basic use? When is it used?

JNDI Overview

JNDI is an API specified in Java technology that provides naming and directory functionality to applications written in the Java programming language. It is designed especially for the Java platform using Java's object model. Using JNDI, applications based on Java technology can store and retrieve named Java objects of any type. In addition, JNDI provides methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes.

JNDI is also defined independent of any specific naming or directory service implementation. It enables applications to access different, possibly multiple, naming and directory services using a common API. Different naming and directory service providers can be plugged in seamlessly behind this common API. This enables Java technology-based applications to take advantage of information in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and NIS(YP), as well as enabling the applications to coexist with legacy software and systems.

Using JNDI as a tool, you can build new powerful and portable applications that not only take advantage of Java's object model but are also well-integrated with the environment in which they are deployed.

Reference

Angular2: Cannot read property 'name' of undefined

You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

Specifically, under the heading Display hero names in a template, it states:

To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

followed by this code block:

<h2>My Heroes</h2>
<ul class="heroes">
  <li>
    <!-- each hero goes here -->
  </li>
</ul>

It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

<h2>{{hero.name}} details!</h2>

outside of our *ngFor.

However, if you scroll further down the page, you will encounter the following:

The template for displaying heroes should look like this:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Note the absence of the detail elements from previous efforts.

An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.

How to get class object's name as a string in Javascript?

Immediately after the object is instantiatd, you can attach a property, say name, to the object and assign the string value you expect to it:

var myObj = new someClass();
myObj.name="myObj";

document.write(myObj.name);

Alternatively, the assignment can be made inside the codes of the class, i.e.

var someClass = function(P)
{ this.name=P;
  // rest of the class definition...
};

var myObj = new someClass("myObj");
document.write(myObj.name);

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Java way to check if a string is palindrome

import java.util.Scanner;

public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;

public void allSubstrings(String s){        
    for(int i=0;i<s.length();i++){
        for(int j=1;j<=s.length()-i;j++){
            String subString=s.substring(i, i+j);  
            palindrome(subString);             
        }
    }
        }   
public void palindrome(String sub){
    System.out.println("String to b checked is "+sub);
    StringBuilder sb=new StringBuilder();
    sb.append(sub);     // append string to string builder 
    sb.reverse();        
    if(sub.equals(sb.toString())){                        // palindrome condition 
        System.out.println("the given String :"+sub+" is a palindrome");
        longestPalindrome(sub);
    }
    else{
        System.out.println("the string "+sub+"iss not a palindrome");
    }
        }
public void longestPalindrome(String s){
            if(s.length()>longest){                 
        longest=s.length();
        longestPalindrome=s;

    }
    else if (s.length()==longest){    
        oldPalindrome=longestPalindrome;
        longestPalindrome=s;

    }




}

public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();

    Scanner sc=new Scanner(System.in);    
    System.out.println("Enter the String ::");
    String s=sc.nextLine(); 
    fp.allSubstrings(s);      
    sc.close();
    if(fp.oldPalindrome.length()>0){
    System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");  
    }
    else{
        System.out.println(longestPalindrome+":is the longest palindrome`````");
    }}
}

How to open the Chrome Developer Tools in a new window?

enter image description here

  1. click on three dots in the top right ->
  2. click on "Undock into separate window" icon