Programs & Examples On #Oprofile

OProfile is a profiling system for systems running Linux 2.2, 2.4, and 2.6. Profiling runs transparently in the background and profile data can be collected at any time. OProfile makes use of the hardware performance counters provided on Intel, AMD, and other processors, and uses a timer-interrupt based mechanism on CPUs without counters. OProfile can profile the whole system in high detail.

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

Center image horizontally within a div

This also would do it

#imagewrapper {
    text-align:center;
}

#imagewrapper img {
    display:inline-block;
    margin:0 5px;
}

How to pass boolean values to a PowerShell script from a command prompt

In PowerShell, boolean parameters can be declared by mentioning their type before their variable.

    function GetWeb() {
             param([bool] $includeTags)
    ........
    ........
    }

You can assign value by passing $true | $false

    GetWeb -includeTags $true

Listview Scroll to the end of the list after updating the list

You need to use these parameters in your list view:

  • Scroll lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

  • Set the head of the list to it bottom lv.setStackFromBottom(true);

You can also set these parameters in XML, eg. like this:

<ListView
   ...
   android:transcriptMode="alwaysScroll"
   android:stackFromBottom="true" />

How to use OpenFileDialog to select a folder?

Here is a pure C# version that should work with all versions of .NET (including .NET Core, .NET 5, WPF, Winforms, etc.) and uses Windows Vista (and higher) IFileDialog interface with the FOS_PICKFOLDERS options so it has the nice folder picker Windows standard UI. I have also added WPF's Window type support but this is optional.

usage:

var dlg = new FolderPicker();
dlg.InputPath = @"c:\windows\system32";
if (dlg.ShowDialog() == true)
{
    MessageBox.Show(dlg.ResultPath);
}

code:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.ComTypes;
    using System.Windows; // for WPF support
    using System.Windows.Interop;  // for WPF support

    public class FolderPicker
    {
        public virtual string ResultPath { get; protected set; }
        public virtual string ResultName { get; protected set; }
        public virtual string InputPath { get; set; }
        public virtual bool ForceFileSystem { get; set; }
        public virtual string Title { get; set; }
        public virtual string OkButtonLabel { get; set; }
        public virtual string FileNameLabel { get; set; }

        protected virtual int SetOptions(int options)
        {
            if (ForceFileSystem)
            {
                options |= (int)FOS.FOS_FORCEFILESYSTEM;
            }
            return options;
        }

        // for WPF support
        public bool? ShowDialog(Window owner = null, bool throwOnError = false)
        {
            owner ??= Application.Current.MainWindow;
            return ShowDialog(owner != null ? new WindowInteropHelper(owner).Handle : IntPtr.Zero, throwOnError);
        }

        // for all .NET
        public virtual bool? ShowDialog(IntPtr owner, bool throwOnError = false)
        {
            var dialog = (IFileOpenDialog)new FileOpenDialog();
            if (!string.IsNullOrEmpty(InputPath))
            {
                if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
                    return null;

                dialog.SetFolder(item);
            }

            var options = FOS.FOS_PICKFOLDERS;
            options = (FOS)SetOptions((int)options);
            dialog.SetOptions(options);

            if (Title != null)
            {
                dialog.SetTitle(Title);
            }

            if (OkButtonLabel != null)
            {
                dialog.SetOkButtonLabel(OkButtonLabel);
            }

            if (FileNameLabel != null)
            {
                dialog.SetFileName(FileNameLabel);
            }

            if (owner == IntPtr.Zero)
            {
                owner = Process.GetCurrentProcess().MainWindowHandle;
                if (owner == IntPtr.Zero)
                {
                    owner = GetDesktopWindow();
                }
            }

            var hr = dialog.Show(owner);
            if (hr == ERROR_CANCELLED)
                return null;

            if (CheckHr(hr, throwOnError) != 0)
                return null;

            if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
                return null;

            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)
                return null;

            ResultPath = path;

            if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out path), false) == 0)
            {
                ResultName = path;
            }
            return true;
        }

        private static int CheckHr(int hr, bool throwOnError)
        {
            if (hr != 0)
            {
                if (throwOnError)
                    Marshal.ThrowExceptionForHR(hr);
            }
            return hr;
        }

        [DllImport("shell32")]
        private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);

        [DllImport("user32")]
        private static extern IntPtr GetDesktopWindow();

#pragma warning disable IDE1006 // Naming Styles
        private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
#pragma warning restore IDE1006 // Naming Styles

        [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] // CLSID_FileOpenDialog
        private class FileOpenDialog
        {
        }

        [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IFileOpenDialog
        {
            [PreserveSig] int Show(IntPtr parent); // IModalWindow
            [PreserveSig] int SetFileTypes();  // not fully defined
            [PreserveSig] int SetFileTypeIndex(int iFileType);
            [PreserveSig] int GetFileTypeIndex(out int piFileType);
            [PreserveSig] int Advise(); // not fully defined
            [PreserveSig] int Unadvise();
            [PreserveSig] int SetOptions(FOS fos);
            [PreserveSig] int GetOptions(out FOS pfos);
            [PreserveSig] int SetDefaultFolder(IShellItem psi);
            [PreserveSig] int SetFolder(IShellItem psi);
            [PreserveSig] int GetFolder(out IShellItem ppsi);
            [PreserveSig] int GetCurrentSelection(out IShellItem ppsi);
            [PreserveSig] int SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
            [PreserveSig] int GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
            [PreserveSig] int SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
            [PreserveSig] int SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
            [PreserveSig] int SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
            [PreserveSig] int GetResult(out IShellItem ppsi);
            [PreserveSig] int AddPlace(IShellItem psi, int alignment);
            [PreserveSig] int SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
            [PreserveSig] int Close(int hr);
            [PreserveSig] int SetClientGuid();  // not fully defined
            [PreserveSig] int ClearClientData();
            [PreserveSig] int SetFilter([MarshalAs(UnmanagedType.IUnknown)] object pFilter);
            [PreserveSig] int GetResults([MarshalAs(UnmanagedType.IUnknown)] out object ppenum);
            [PreserveSig] int GetSelectedItems([MarshalAs(UnmanagedType.IUnknown)] out object ppsai);
        }

        [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IShellItem
        {
            [PreserveSig] int BindToHandler(); // not fully defined
            [PreserveSig] int GetParent(); // not fully defined
            [PreserveSig] int GetDisplayName(SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
            [PreserveSig] int GetAttributes();  // not fully defined
            [PreserveSig] int Compare();  // not fully defined
        }

        #pragma warning disable CA1712 // Do not prefix enum values with type name
        private enum SIGDN : uint
        {
            SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
            SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
            SIGDN_FILESYSPATH = 0x80058000,
            SIGDN_NORMALDISPLAY = 0,
            SIGDN_PARENTRELATIVE = 0x80080001,
            SIGDN_PARENTRELATIVEEDITING = 0x80031001,
            SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
            SIGDN_PARENTRELATIVEPARSING = 0x80018001,
            SIGDN_URL = 0x80068000
        }

        [Flags]
        private enum FOS
        {
            FOS_OVERWRITEPROMPT = 0x2,
            FOS_STRICTFILETYPES = 0x4,
            FOS_NOCHANGEDIR = 0x8,
            FOS_PICKFOLDERS = 0x20,
            FOS_FORCEFILESYSTEM = 0x40,
            FOS_ALLNONSTORAGEITEMS = 0x80,
            FOS_NOVALIDATE = 0x100,
            FOS_ALLOWMULTISELECT = 0x200,
            FOS_PATHMUSTEXIST = 0x800,
            FOS_FILEMUSTEXIST = 0x1000,
            FOS_CREATEPROMPT = 0x2000,
            FOS_SHAREAWARE = 0x4000,
            FOS_NOREADONLYRETURN = 0x8000,
            FOS_NOTESTFILECREATE = 0x10000,
            FOS_HIDEMRUPLACES = 0x20000,
            FOS_HIDEPINNEDPLACES = 0x40000,
            FOS_NODEREFERENCELINKS = 0x100000,
            FOS_OKBUTTONNEEDSINTERACTION = 0x200000,
            FOS_DONTADDTORECENT = 0x2000000,
            FOS_FORCESHOWHIDDEN = 0x10000000,
            FOS_DEFAULTNOMINIMODE = 0x20000000,
            FOS_FORCEPREVIEWPANEON = 0x40000000,
            FOS_SUPPORTSTREAMABLEITEMS = unchecked((int)0x80000000)
        }
        #pragma warning restore CA1712 // Do not prefix enum values with type name
    }

result:

enter image description here

How to increase heap size of an android application?

Is there a way to increase this size of memory an application can use?

Applications running on API Level 11+ can have android:largeHeap="true" on the <application> element in the manifest to request a larger-than-normal heap size, and getLargeMemoryClass() on ActivityManager will tell you how big that heap is. However:

  1. This only works on API Level 11+ (i.e., Honeycomb and beyond)

  2. There is no guarantee how large the large heap will be

  3. The user will perceive your large-heap request, because it will force their other apps out of RAM terminate other apps' processes to free up system RAM for use by your large heap

  4. Because of #3, and the fact that I expect that android:largeHeap will be abused, support for this may be abandoned in the future, or the user may be warned about this at install time (e.g., you will need to request a special permission for it)

  5. Presently, this feature is lightly documented

How to load GIF image in Swift?

You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to

import JellyGif

let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))

//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))

//Animates Gif with data
imageView.startGif(with: .data(Data))

For more information you can look at its README

What is the correct way to do a CSS Wrapper?

Most basic example (live example here):

CSS:

    #wrapper {
        width: 500px;
        margin: 0 auto;
    }

HTML:

    <body>
        <div id="wrapper">
            Piece of text inside a 500px width div centered on the page
        </div>
    </body>

How the principle works:

Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto; or margin-left: auto; margin-right: auto;. The automatic margins make sure your element is centered.

Generate your own Error code in swift 3

You can create enums to deal with errors :)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

and then create a method inside enum to receive the http response code and return the corresponding error in return :)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

Finally update your failure block to accept single parameter of type RikhError :)

I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)

Hope it helps :)

Hibernate, @SequenceGenerator and allocationSize

allocationSize=1 It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .

Next generation of Sequence Id is based on allocationSize.

By defualt it is kept as 50 which is too much. It will also only help if your going to have near about 50 records in one session which are not persisted and which will be persisted using this particular session and transation.

So you should always use allocationSize=1 while using SequenceGenerator. As for most of underlying databases sequence is always incremented by 1.

Join vs. sub-query

As per my observation like two cases, if a table has less then 100,000 records then the join will work fast.

But in the case that a table has more than 100,000 records then a subquery is best result.

I have one table that has 500,000 records on that I created below query and its result time is like

SELECT * 
FROM crv.workorder_details wd 
inner join  crv.workorder wr on wr.workorder_id = wd.workorder_id;

Result : 13.3 Seconds

select * 
from crv.workorder_details 
where workorder_id in (select workorder_id from crv.workorder)

Result : 1.65 Seconds

Bootstrap: Collapse other sections when one is expanded

This was helpful for me:

    jQuery('button').click( function(e) {
    jQuery('.in').collapse('hide');
});

It's collapsed already open section. Thnks to GrafiCode Studio

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

cannot open shared object file: No such file or directory

Your LD_LIBRARY_PATH doesn't include the path to libsvmlight.so.

$ export LD_LIBRARY_PATH=/home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PATH

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

Trigger standard HTML5 validation (form) without using submit button?

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:

$(document).ready(function()
{
    $('#theIdOfMyForm').submit(function(event){
        if(!this.checkValidity())
        {
            event.preventDefault();
        }
    });
});

Then just call $('#theIdOfMyForm').submit(); in your code.

UPDATE

If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function()
{
    if(!this.validity.valid)
    {
        $(this).focus();
        // break
        return false;
    }
});

It will give focus on the first invalid input.

How to get a json string from url?

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

invalid use of non-static data member

You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.

And what is p->param?

Actually, it isn't clear what do you want to do

WHERE Clause to find all records in a specific month

If you're using SQL Server, look into DATEPART.

http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx

DATEPART(mm, [THE DATE YOU'RE LOOKING AT])

You can then use normal integer logic with it. Same for year, just use yy instead of mm.

How to open an external file from HTML

You're going to have to rely on each individual's machine having the correct file associations. If you try and open the application from JavaScript/VBScript in a web page, the spawned application is either going to itself be sandboxed (meaning decreased permissions) or there are going to be lots of security prompts.

My suggestion is to look to SharePoint server for this one. This is something that we know they do and you can edit in place, but the question becomes how they manage to pull that off. My guess is direct integration with Office. Either way, this isn't something that the Internet is designed to do, because I'm assuming you want them to edit the original document and not simply create their own copy (which is what the default behavior of file:// would be.

So depending on you options, it might be possible to create a client side application that gets installed on all your client machines and then responds to a particular file handler that says go open this application on the file server. Then it wouldn't really matter who was doing it since all browsers would simply hand off the request to you. You would have to create your own handler like fileserver://.

CSS image resize percentage of itself?

This is a very old thread but I found it while searching for a simple solution to display retina (high res) screen capture on standard resolution display.

So there is an HTML only solution for modern browsers :

<img srcset="image.jpg 100w" sizes="50px" src="image.jpg"/>

This is telling the browser that the image is twice the dimension of it intended display size. The value are proportional and do not need to reflect the actual size of the image. One can use 2w 1px as well to achieve the same effect. The src attribute is only used by legacy browsers.

The nice effect of it is that it display the same size on retina or standard display, shrinking on the latter.

jQuery adding 2 numbers from input fields

There are two way that you can add two number in jQuery

First way:

var x = parseInt(a) + parseInt(b);
alert(x);

Second Way:

var x = parseInt(a+2);
alert(x);

Now come your question

var a = parseInt($("#a").val()); 
var b = parseInt($("#b").val());
alert(a+b);

How to read multiple Integer values from a single line of input in Java?

This works fine ....

int a = nextInt(); int b = nextInt(); int c = nextInt();

Or you can read them in a loop

WPF TemplateBinding vs RelativeSource TemplatedParent

One more thing - TemplateBindings don't allow value converting. They don't allow you to pass a Converter and don't automatically convert int to string for example (which is normal for a Binding).

How to parse a string to an int in C++?

The C++ String Toolkit Library (StrTk) has the following solution:

static const std::size_t digit_table_symbol_count = 256;
static const unsigned char digit_table[digit_table_symbol_count] = {
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF - 0x07
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x08 - 0x0F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x10 - 0x17
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x18 - 0x1F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x20 - 0x27
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x28 - 0x2F
   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 0x30 - 0x37
   0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x38 - 0x3F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x40 - 0x47
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x48 - 0x4F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x50 - 0x57
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x58 - 0x5F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x60 - 0x67
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x68 - 0x6F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x70 - 0x77
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x78 - 0x7F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x80 - 0x87
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x88 - 0x8F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x90 - 0x97
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x98 - 0x9F
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA0 - 0xA7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA8 - 0xAF
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB0 - 0xB7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB8 - 0xBF
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC0 - 0xC7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC8 - 0xCF
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD0 - 0xD7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD8 - 0xDF
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE0 - 0xE7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE8 - 0xEF
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xF0 - 0xF7
   0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF  // 0xF8 - 0xFF
 };

template<typename InputIterator, typename T>
inline bool string_to_signed_type_converter_impl_itr(InputIterator begin, InputIterator end, T& v)
{
   if (0 == std::distance(begin,end))
      return false;
   v = 0;
   InputIterator it = begin;
   bool negative = false;
   if ('+' == *it)
      ++it;
   else if ('-' == *it)
   {
      ++it;
      negative = true;
   }
   if (end == it)
      return false;
   while(end != it)
   {
      const T digit = static_cast<T>(digit_table[static_cast<unsigned int>(*it++)]);
      if (0xFF == digit)
         return false;
      v = (10 * v) + digit;
   }
   if (negative)
      v *= -1;
   return true;
}

The InputIterator can be of either unsigned char*, char* or std::string iterators, and T is expected to be a signed int, such as signed int, int, or long

Set value of hidden input with jquery

This worked for me:

$('input[name="sort_order"]').attr('value','XXX');

How do you sign a Certificate Signing Request with your Certification Authority?

1. Using the x509 module
openssl x509 ...
...

2 Using the ca module
openssl ca ...
...

You are missing the prelude to those commands.

This is a two-step process. First you set up your CA, and then you sign an end entity certificate (a.k.a server or user). Both of the two commands elide the two steps into one. And both assume you have a an OpenSSL configuration file already setup for both CAs and Server (end entity) certificates.


First, create a basic configuration file:

$ touch openssl-ca.cnf

Then, add the following to it:

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ ca ]
default_ca    = CA_default      # The default ca section

[ CA_default ]

default_days     = 1000         # How long to certify for
default_crl_days = 30           # How long before next CRL
default_md       = sha256       # Use public key default MD
preserve         = no           # Keep passed DN ordering

x509_extensions = ca_extensions # The extensions to add to the cert

email_in_dn     = no            # Don't concat the email in the DN
copy_extensions = copy          # Required to copy SANs from CSR to cert

####################################################################
[ req ]
default_bits       = 4096
default_keyfile    = cakey.pem
distinguished_name = ca_distinguished_name
x509_extensions    = ca_extensions
string_mask        = utf8only

####################################################################
[ ca_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = Maryland

localityName                = Locality Name (eg, city)
localityName_default        = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test CA, Limited

organizationalUnitName         = Organizational Unit (eg, division)
organizationalUnitName_default = Server Research Department

commonName         = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test CA

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ ca_extensions ]

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints       = critical, CA:true
keyUsage               = keyCertSign, cRLSign

The fields above are taken from a more complex openssl.cnf (you can find it in /usr/lib/openssl.cnf), but I think they are the essentials for creating the CA certificate and private key.

Tweak the fields above to suit your taste. The defaults save you the time from entering the same information while experimenting with configuration file and command options.

I omitted the CRL-relevant stuff, but your CA operations should have them. See openssl.cnf and the related crl_ext section.

Then, execute the following. The -nodes omits the password or passphrase so you can examine the certificate. It's a really bad idea to omit the password or passphrase.

$ openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

After the command executes, cacert.pem will be your certificate for CA operations, and cakey.pem will be the private key. Recall the private key does not have a password or passphrase.

You can dump the certificate with the following.

$ openssl x509 -in cacert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 11485830970703032316 (0x9f65de69ceef2ffc)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 14:24:11 2014 GMT
            Not After : Feb 23 14:24:11 2014 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                Modulus:
                    00:b1:7f:29:be:78:02:b8:56:54:2d:2c:ec:ff:6d:
                    ...
                    39:f9:1e:52:cb:8e:bf:8b:9e:a6:93:e1:22:09:8b:
                    59:05:9f
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
            X509v3 Authority Key Identifier:
                keyid:4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A

            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Key Usage:
                Certificate Sign, CRL Sign
    Signature Algorithm: sha256WithRSAEncryption
         4a:6f:1f:ac:fd:fb:1e:a4:6d:08:eb:f5:af:f6:1e:48:a5:c7:
         ...
         cd:c6:ac:30:f9:15:83:41:c1:d1:20:fa:85:e7:4f:35:8f:b5:
         38:ff:fd:55:68:2c:3e:37

And test its purpose with the following (don't worry about the Any Purpose: Yes; see "critical,CA:FALSE" but "Any Purpose CA : Yes").

$ openssl x509 -purpose -in cacert.pem -inform PEM
Certificate purposes:
SSL client : No
SSL client CA : Yes
SSL server : No
SSL server CA : Yes
Netscape SSL server : No
Netscape SSL server CA : Yes
S/MIME signing : No
S/MIME signing CA : Yes
S/MIME encryption : No
S/MIME encryption CA : Yes
CRL signing : Yes
CRL signing CA : Yes
Any Purpose : Yes
Any Purpose CA : Yes
OCSP helper : Yes
OCSP helper CA : Yes
Time Stamp signing : No
Time Stamp signing CA : Yes
-----BEGIN CERTIFICATE-----
MIIFpTCCA42gAwIBAgIJAJ9l3mnO7y/8MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV
...
aQUtFrV4hpmJUaQZ7ySr/RjCb4KYkQpTkOtKJOU1Ic3GrDD5FYNBwdEg+oXnTzWP
tTj//VVoLD43
-----END CERTIFICATE-----

For part two, I'm going to create another configuration file that's easily digestible. First, touch the openssl-server.cnf (you can make one of these for user certificates also).

$ touch openssl-server.cnf

Then open it, and add the following.

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ req ]
default_bits       = 2048
default_keyfile    = serverkey.pem
distinguished_name = server_distinguished_name
req_extensions     = server_req_extensions
string_mask        = utf8only

####################################################################
[ server_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = MD

localityName         = Locality Name (eg, city)
localityName_default = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test Server, Limited

commonName           = Common Name (e.g. server FQDN or YOUR name)
commonName_default   = Test Server

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ server_req_extensions ]

subjectKeyIdentifier = hash
basicConstraints     = CA:FALSE
keyUsage             = digitalSignature, keyEncipherment
subjectAltName       = @alternate_names
nsComment            = "OpenSSL Generated Certificate"

####################################################################
[ alternate_names ]

DNS.1  = example.com
DNS.2  = www.example.com
DNS.3  = mail.example.com
DNS.4  = ftp.example.com

If you are developing and need to use your workstation as a server, then you may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.

# IPv4 localhost
IP.1     = 127.0.0.1

# IPv6 localhost
IP.2     = ::1

Then, create the server certificate request. Be sure to omit -x509*. Adding -x509 will create a certificate, and not a request.

$ openssl req -config openssl-server.cnf -newkey rsa:2048 -sha256 -nodes -out servercert.csr -outform PEM

After this command executes, you will have a request in servercert.csr and a private key in serverkey.pem.

And you can inspect it again.

$ openssl req -text -noout -verify -in servercert.csr
Certificate:
    verify OK
    Certificate Request:
        Version: 0 (0x0)
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         6d:e8:d3:85:b3:88:d4:1a:80:9e:67:0d:37:46:db:4d:9a:81:
         ...
         76:6a:22:0a:41:45:1f:e2:d6:e4:8f:a1:ca:de:e5:69:98:88:
         a9:63:d0:a7

Next, you have to sign it with your CA.


You are almost ready to sign the server's certificate by your CA. The CA's openssl-ca.cnf needs two more sections before issuing the command.

First, open openssl-ca.cnf and add the following two sections.

####################################################################
[ signing_policy ]
countryName            = optional
stateOrProvinceName    = optional
localityName           = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

####################################################################
[ signing_req ]
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints       = CA:FALSE
keyUsage               = digitalSignature, keyEncipherment

Second, add the following to the [ CA_default ] section of openssl-ca.cnf. I left them out earlier, because they can complicate things (they were unused at the time). Now you'll see how they are used, so hopefully they will make sense.

base_dir      = .
certificate   = $base_dir/cacert.pem   # The CA certifcate
private_key   = $base_dir/cakey.pem    # The CA private key
new_certs_dir = $base_dir              # Location for new certs after signing
database      = $base_dir/index.txt    # Database index file
serial        = $base_dir/serial.txt   # The current serial number

unique_subject = no  # Set to 'no' to allow creation of
                     # several certificates with same subject.

Third, touch index.txt and serial.txt:

$ touch index.txt
$ echo '01' > serial.txt

Then, perform the following:

$ openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out servercert.pem -infiles servercert.csr

You should see similar to the following:

Using configuration from openssl-ca.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :ASN.1 12:'MD'
localityName          :ASN.1 12:'Baltimore'
commonName            :ASN.1 12:'Test CA'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Oct 20 16:12:39 2016 GMT (1000 days)
Sign the certificate? [y/n]:Y

1 out of 1 certificate requests certified, commit? [y/n]Y
Write out database with 1 new entries
Data Base Updated

After the command executes, you will have a freshly minted server certificate in servercert.pem. The private key was created earlier and is available in serverkey.pem.

Finally, you can inspect your freshly minted certificate with the following:

$ openssl x509 -in servercert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9 (0x9)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 19:07:36 2014 GMT
            Not After : Oct 20 19:07:36 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Authority Key Identifier:
                keyid:42:15:F2:CA:9C:B1:BB:F5:4C:2C:66:27:DA:6D:2E:5F:BA:0F:C5:9E

            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         b1:40:f6:34:f4:38:c8:57:d4:b6:08:f7:e2:71:12:6b:0e:4a:
         ...
         45:71:06:a9:86:b6:0f:6d:8d:e1:c5:97:8d:fd:59:43:e9:3c:
         56:a5:eb:c8:7e:9f:6b:7a

Earlier, you added the following to CA_default: copy_extensions = copy. This copies extension provided by the person making the request.

If you omit copy_extensions = copy, then your server certificate will lack the Subject Alternate Names (SANs) like www.example.com and mail.example.com.

If you use copy_extensions = copy, but don't look over the request, then the requester might be able to trick you into signing something like a subordinate root (rather than a server or user certificate). Which means he/she will be able to mint certificates that chain back to your trusted root. Be sure to verify the request with openssl req -verify before signing.


If you omit unique_subject or set it to yes, then you will only be allowed to create one certificate under the subject's distinguished name.

unique_subject = yes            # Set to 'no' to allow creation of
                                # several ctificates with same subject.

Trying to create a second certificate while experimenting will result in the following when signing your server's certificate with the CA's private key:

Sign the certificate? [y/n]:Y
failed to update database
TXT_DB error number 2

So unique_subject = no is perfect for testing.


If you want to ensure the Organizational Name is consistent between self-signed CAs, Subordinate CA and End-Entity certificates, then add the following to your CA configuration files:

[ policy_match ]
organizationName = match

If you want to allow the Organizational Name to change, then use:

[ policy_match ]
organizationName = supplied

There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:

RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFC's 6797 and 7469 do not allow an IP address, either.

How to change UIPickerView height

I use a mask layer to change it's display size

// swift 3.x
let layer = CALayer()
layer.frame = CGRect(x: 0,y:0, width: displayWidth, height: displayHeight)
layer.backgroundColor = UIColor.red.cgColor
pickerView.layer.mask = layer

first-child and last-child with IE8

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

Specify the from user when sending email using the mail command

You can specify any extra header you may need with -a

$mail -s "Some random subject" -a "From: [email protected]" [email protected]

What does DIM stand for in Visual Basic and BASIC?

Dim have had different meanings attributed to it.

I've found references about Dim meaning "Declare In Memory", the more relevant reference is a document on Dim Statement published Oracle as part of the Siebel VB Language Reference. Of course, you may argue that if you do not declare the variables in memory where do you do it? Maybe "Declare in Module" is a good alternative considering how Dim is used.

In my opinion, "Declare In Memory" is actually a mnemonic, created to make easier to learn how to use Dim. I see "Declare in Memory" as a better meaning as it describes what it does in current versions of the language, but it is not the proper meaning.

In fact, at the origins of Basic Dim was only used to declare arrays. For regular variables no keyword was used, instead their type was inferred from their name. For instance, if the name of the variable ends with $ then it is a string (this is something that you could see even in method names up to VB6, for example Mid$). And so, you used Dim only to give dimension to the arrays (notice that ReDim resizes arrays).


Really, Does It Matter? I mean, it is a keyword it has its meaning inside an artificial language. It doesn't have to be a word in English or any other natural language. So it could just mean whatever you want, all that matters is that it works.

Anyhow, that is not completely true. As BASIC is part of our culture, and understanding why it came to be as it is - I hope - will help improve our vision of the world.


I sit in from of my computer with a desire to help preserve this little piece of our culture that seems lost, replaced by our guessing of what it was. And so, I have dug MSDN both current and the old CDs from the 1998 version. I have also searched the documention for the old QBasic [Had to use DOSBox] and managed to get some Darthmouth manual, all to find how they talk about Dim. For my disappointment, they don't say what does Dim stand for, and only say how it is used.

But before my hope was dim, I managed to find this BBC Microcomputer System Used Guide (that claims to be from 1984, and I don't want to doubt it). The BBC Microcomputer used a variant of BASIC called BBC BASIC and it is described in the document. Even though, it doesn't say what does Dim stand for, it says (on page 104):

... you can dimension N$ to have as many entries as you want. For example, DIM N$(1000) would create a string array with space for 1000 different names.

As I said, it doesn't say that Dim stands for dimension, but serves as proof to show that associating Dim with Dimension was a common thing at the time of writing that document.

Now, I got a rewarding surprise later on (at page 208), the title for the section that describes the DIM keyword (note: that is not listed in the contents) says:

DIM dimension of an array

So, I didn't get the quote "Dim stands for..." but I guess it is clear that any decent human being that is able to read those document will consider that Dim means dimension.


With renewed hope, I decided to search about how Dim was chosen. Again, I didn't find an account on the subject, still I was able to find a definitive quote:

Before you can use an array, you must define it in a DIM (dimension) statement.

You can find this as part of the True BASIC Online User's Guides at the web page of True BASIC inc, a company founded by Thomas Eugene Kurtz, co-author of BASIC.


So, In reallity, Dim is a shorthand for DIMENSION, and yes. That existed in FORTRAN before, so it is likely that it was picked by influence of FORTRAN as Patrick McDonald said in his answer.


Dim sum as string = "this is not a chinese meal" REM example usage in VB.NET ;)

VS 2012: Scroll Solution Explorer to current file

There are many ways to do this:

Go to current File once:

  • Visual Studio 2013

    VS 13 has it's own shortcut to do this: Ctrl+\, S (Press Ctrl + \, Release both keys, Press the S key)

    You can edit this default shortcut, if you are searching for SolutionExplorer.SyncWithActiveDocument in your Keyboard Settings (Tools->Options->Enviornment->Keyboard)

    In addition there is also a new icon in the Solution Explorer, more about this here.

    Sync with Active Document Button in VS2013 - Solution Explorer

  • Visual Studio 2012

    If you use VS 2012, there is a great plugin to add this new functionality from VS2013 to VS2012: . The default shortcut is strg + alt + ü. I think this one is the best, as navigating to the solution explorer is mapped to strg + ü.

  • Resharper

    If you use Resharper try Shift+Alt+L

    This is a nice mapping as you can use Strg+Alt+L for navigating to the solution explorer

Track current file all the time:

  • Visual Studio >= 2012:

    If you like to track your current file in the solution explorer all the time, you can use the solution from the accepted answer (Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer), but I think this can get very annoying in large projects.

change image opacity using javascript

You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached

Each GROUP BY expression must contain at least one column that is not an outer reference

Here's a simple query to find company name who has a medicine type of A and makes more than 2.

SELECT CNAME 
FROM COMPANY 
WHERE CNO IN (
    SELECT CNO 
    FROM MEDICINE 
    WHERE type='A' 
    GROUP BY CNO HAVING COUNT(type) > 2
)

Regex in JavaScript for validating decimal numbers

 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

How to set Spinner Default by its Value instead of Position?

If the list you use for the spinner is an object then you can find its position like this

private int selectSpinnerValue( List<Object> ListSpinner,String myString) 
{
    int index = 0;
    for(int i = 0; i < ListSpinner.size(); i++){
      if(ListSpinner.get(i).getValueEquals().equals(myString)){
          index=i;
          break;
      }
    }
    return index;
}

using:

 int index=selectSpinnerValue(ListOfSpinner,StringEquals);
    spinner.setSelection(index,true);

Intellij JAVA_HOME variable

The problem is your "Project SDK" is none! Add a "Project SDK" by clicking "New ..." and choose the path of JDK. And then it should be OK.

'uint32_t' does not name a type

I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h> or <cstdint.h> to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h> which worked well for me!

How to write asynchronous functions for Node.js

If you KNOW that a function returns a promise, i suggest using the new async/await features in JavaScript. It makes the syntax look synchronous but work asynchronously. When you add the async keyword to a function, it allows you to await promises in that scope:

async function ace() {
  var r = await new Promise((resolve, reject) => {
    resolve(true)
  });

  console.log(r); // true
}

if a function does not return a promise, i recommend wrapping it in a new promise that you define, then resolve the data that you want:

function ajax_call(url, method) {
  return new Promise((resolve, reject) => {
    fetch(url, { method })
    .then(resp => resp.json())
    .then(json => { resolve(json); })
  });
}

async function your_function() {
  var json = await ajax_call('www.api-example.com/some_data', 'GET');
  console.log(json); // { status: 200, data: ... }
}

Bottom line: leverage the power of Promises.

How do you properly return multiple values from a Promise?

Whatever you return from a promise will be wrapped into a promise to be unwrapped at the next .then() stage.

It becomes interesting when you need to return one or more promise(s) alongside one or more synchronous value(s) such as;

Promise.resolve([Promise.resolve(1), Promise.resolve(2), 3, 4])
       .then(([p1,p2,n1,n2]) => /* p1 and p2 are still promises */);

In these cases it would be essential to use Promise.all() to get p1 and p2 promises unwrapped at the next .then() stage such as

Promise.resolve(Promise.all([Promise.resolve(1), Promise.resolve(2), 3, 4]))
       .then(([p1,p2,n1,n2]) => /* p1 is 1, p2 is 2, n1 is 3 and n2 is 4 */);

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

Service has zero application (non-infrastructure) endpoints

This error will occur if the configuration file of the hosting application of your WCF service does not have the proper configuration.

Remember this comment from configuration:

When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries.

If you have a WCF Service hosted in IIS, during runtime via VS.NET it will read the app.config of the service library project, but read the host's web.config once deployed. If web.config does not have the identical <system.serviceModel> configuration you will receive this error. Make sure to copy over the configuration from app.config once it has been perfected.

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

Intellij idea subversion checkout error: `Cannot run program "svn"`

For me, on Debian GNU / Linux, installing the subversion package was the solution

# aptitude install subversion subversion-tool

jquery clone div and append it after specific div

This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

How do I get next month date from today's date and insert it in my database?

You can use PHP's strtotime() function:

// One month from today
$date = date('Y-m-d', strtotime('+1 month'));

// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2015-01-01')));

Just note that +1 month is not always calculated intuitively. It appears to always add the number of days that exist in the current month.

Current Date  | +1 month
-----------------------------------------------------
2015-01-01    | 2015-02-01   (+31 days)
2015-01-15    | 2015-02-15   (+31 days)
2015-01-30    | 2015-03-02   (+31 days, skips Feb)
2015-01-31    | 2015-03-03   (+31 days, skips Feb)
2015-02-15    | 2015-03-15   (+28 days)
2015-03-31    | 2015-05-01   (+31 days, skips April)
2015-12-31    | 2016-01-31   (+31 days)

Some other date/time intervals that you can use:

$date = date('Y-m-d'); // Initial date string to use in calculation

$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+2 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 month', strtotime($date)));
$date = date('Y-m-d', strtotime('+30 days', strtotime($date)));

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Pretty Printing a pandas dataframe

You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:

from StringIO import StringIO
import prettytable    

output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt

How to start MySQL with --skip-grant-tables?

if this is a windows box, the simplest thing to do is to stop the servers, add skip-grant-tables to the mysql configuration file, and restart the server.

once you've fixed your permission problems, repeat the above but remove the skip-grant-tables option.

if you don't know where your configuration file is, then log in to mysql send SHOW VARIABLES LIKE '%config%' and one of the rows returned will tell you where your configuration file is.

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

You have to add

<script>jQuery.noConflict();</script>

after

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

gitorious.org/cadenza is a full library of some of the most useful extension methods I've seen.

illegal character in path

try

"C:/Program Files (x86)/test software/myapp/demo.exe"

How can I search sub-folders using glob.glob module?

In Python 3.5 and newer use the new recursive **/ functionality:

configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)

When recursive is set, ** followed by a path separator matches 0 or more subdirectories.

In earlier Python versions, glob.glob() cannot list files in subdirectories recursively.

In that case I'd use os.walk() combined with fnmatch.filter() instead:

import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

This'll walk your directories recursively and return all absolute pathnames to matching .txt files. In this specific case the fnmatch.filter() may be overkill, you could also use a .endswith() test:

import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]

How to tell if UIViewController's view is visible

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

Instead, take this simple approach which seems to work well in most, if not all cases:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

Query-string encoding of a Javascript Object

_x000D_
_x000D_
const buildSortedQuery = (args) => {_x000D_
    return Object.keys(args)_x000D_
        .sort()_x000D_
        .map(key => {_x000D_
            return window.encodeURIComponent(key)_x000D_
                + '='_x000D_
                + window.encodeURIComponent(args[key]);_x000D_
        })_x000D_
        .join('&');_x000D_
};_x000D_
_x000D_
console.log(buildSortedQuery({_x000D_
  foo: "hi there",_x000D_
  bar: "100%"_x000D_
}));_x000D_
_x000D_
//bar=100%25&foo=hi%20there
_x000D_
_x000D_
_x000D_

How to load data to hive from HDFS without removing the source file?

from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

create external table table_name (
  id int,
  myfields string
)
location '/my/location/in/hdfs';

Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

row format delimited fields terminated by ','

Pointer-to-pointer dynamic two-dimensional array

The first method cannot be used to create dynamic 2D arrays because by doing:

int *board[4];

you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:

for (int i = 0; i < 4; ++i) {
  board[i] = new int[10];
}

what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.

Once again, when you do:

int *board[4];

or:

const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];

you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).

On the other hand, when you do:

int **board;
board = new int*[10];

or:

int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];

the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.

As a result, to truly create dynamic 2D array you have to go with the second method:

int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int

for (int i = 0; i < 10; ++i) {
  board[i] = new int[10];
  // each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}

We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:

for (int i = 0; i < 10; ++i) {   // for each row
  for (int j = 0; j < 10; ++j) { // for each column
    board[i][j] = 1;
  }
}

How can I check if a View exists in a Database?

IN SQL Server ,

declare @ViewName nvarchar(20)='ViewNameExample'

if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
begin
    -- Your SQL Code goes here ...

end

Count the frequency that a value occurs in a dataframe column

df.category.value_counts()

This short little line of code will give you the output you want.

If your column name has spaces you can use

df['category'].value_counts()

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

It is working fine for me, but with a different command:

root@ubuntu:/usr/bin# sudo apt-get install sun-java6

Error message:

Couldn't find package sun-java6.

root@ubuntu:/usr/bin# sudo apt-get install sun-java*

Bam, it worked.

What is the difference between a definition and a declaration?

Stages of an executable generation:

(1) pre-processor -> (2) translator/compiler -> (3) linker

In stage 2 (translator/compiler), declaration statements in our code tell to the compiler that these things we are going to use in future and you can find definition later, meaning is :

translator make sure that : what is what ? means declaration

and (3) stage (linker) needs definition to bind the things

Linker make sure that : where is what ? means definition

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

If using the fasterxml then,

these changes might be needed

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;

in main method--

use

SimpleModule module =
  new SimpleModule("PolymorphicAnimalDeserializerModule");

instead of

new SimpleModule("PolymorphicAnimalDeserializerModule",
      new Version(1, 0, 0, null));

and in Animal deserialize() function, make below changes

//Iterator<Entry<String, JsonNode>> elementsIterator =  root.getFields();
Iterator<Entry<String, JsonNode>> elementsIterator = root.fields();

//return mapper.readValue(root, animalClass);
return  mapper.convertValue(root, animalClass); 

This works for fasterxml.jackson. If it still complains of the class fields. Use the same format as in the json for the field names (with "_" -underscore). as this
//mapper.setPropertyNamingStrategy(new CamelCaseNamingStrategy()); might not be supported.

abstract class Animal
{
  public String name;
}

class Dog extends Animal
{
  public String breed;
  public String leash_color;
}

class Cat extends Animal
{
  public String favorite_toy;
}

class Bird extends Animal
{
  public String wing_span;
  public String preferred_food;
}

VB.NET Empty String Array

try this Dim Arraystr() as String ={}

Resize UIImage and change the size of UIImageView

If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

EDIT----

Ok, so seeing your comment I propose this:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

Vue.js toggle class on click

I've got a solution that allows you to check for different values of a prop and thus different <th> elements will become active/inactive. Using vue 2 syntax.

<th 
class="initial " 
@click.stop.prevent="myFilter('M')"
:class="[(activeDay == 'M' ? 'active' : '')]">
<span class="wkday">M</span>
</th>
...
<th 
class="initial " 
@click.stop.prevent="myFilter('T')"
:class="[(activeDay == 'T' ? 'active' : '')]">
<span class="wkday">T</span>
</th>



new Vue({
  el: '#my-container',

  data: {
      activeDay: 'M'
  },

  methods: {
    myFilter: function(day){
        this.activeDay = day;
      // some code to filter users
    }
  }
})

Python Pandas - Find difference between two data frames

Accepted answer Method 1 will not work for data frames with NaNs inside, as pd.np.nan != pd.np.nan. I am not sure if this is the best way, but it can be avoided by

df1[~df1.astype(str).apply(tuple, 1).isin(df2.astype(str).apply(tuple, 1))]

It's slower, because it needs to cast data to string, but thanks to this casting pd.np.nan == pd.np.nan.

Let's go trough the code. First we cast values to string, and apply tuple function to each row.

df1.astype(str).apply(tuple, 1)
df2.astype(str).apply(tuple, 1)

Thanks to that, we get pd.Series object with list of tuples. Each tuple contains whole row from df1/df2. Then we apply isin method on df1 to check if each tuple "is in" df2. The result is pd.Series with bool values. True if tuple from df1 is in df2. In the end, we negate results with ~ sign, and applying filter on df1. Long story short, we get only those rows from df1 that are not in df2.

To make it more readable, we may write it as:

df1_str_tuples = df1.astype(str).apply(tuple, 1)
df2_str_tuples = df2.astype(str).apply(tuple, 1)
df1_values_in_df2_filter = df1_str_tuples.isin(df2_str_tuples)
df1_values_not_in_df2 = df1[~df1_values_in_df2_filter]

NSDictionary to NSArray?

To get all objects in a dictionary, you can also use enumerateKeysAndObjectsUsingBlock: like so:

NSMutableArray *yourArray = [NSMutableArray arrayWithCapacity:6];
[yourDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [yourArray addObject:obj];
}];

How to check if ZooKeeper is running or up from command prompt?

Go to bin directory of Zookeeper and type

./zkServer.sh status

For More info go through below link:

http://www.ibm.com/developerworks/library/bd-zookeeper/

Hope this could help you.

What's the difference between next() and nextLine() methods from Scanner class?

The key point is to find where the method will stop and where the cursor will be after calling the methods.

All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.


For example, consider the following illustration:

|23_24_25_26_27\n

| -> the current cursor position

_ -> whitespace

stream -> Bold (the information got by the calling method)

See what happens when you call these methods:

nextInt()    

read 23|_24_25_26_27\n

nextDouble()

read 23_24|_25_26_27\n

next()

read 23_24_25|_26_27\n

nextLine()

read 23_24_25_26_27\n|


After this, the method should be called depending on your requirement.

How to change indentation mode in Atom?

I just had the same problem, and none of the suggestions above worked. Finally I tried unchecking "Atomic soft tabs" in the Editor Settings menu, which worked.

Difference between git stash pop and git stash apply

git stash pop throws away the (topmost, by default) stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse (or you can then git stash drop it).

This happens unless there are conflicts after git stash pop, in which case it will not remove the stash, leaving it to behave exactly like git stash apply.

Another way to look at it: git stash pop is git stash apply && git stash drop.

Where is my .vimrc file?

These methods work, if you already have a .vimrc file:

:scriptnames list all the .vim files that Vim loaded for you, including your .vimrc file.

:e $MYVIMRC open & edit the current .vimrc that you are using, then use Ctrl + G to view the path in status bar.

unknown type name 'uint8_t', MinGW

To use uint8_t type alias, you have to include stdint.h standard header.

Adding items to a JComboBox

Wrap the values in a class and override the toString() method.

class ComboItem
{
    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));

Whenever you get the selected item.

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

Regex replace uppercase with lowercase letters

In BBEdit works this (ex.: changing the ID values to lowercase):

Search any value: <a id="(?P<x>.*?)"></a> Replace with the same in lowercase: <a id="\L\P<x>\E"></a>

Was: <a id="VALUE"></a> Became: <a id="value"></a>

IIS: Where can I find the IIS logs?

I think the default place for access logs is

%SystemDrive%\inetpub\logs\LogFiles

Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under "Logging" in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)

You could also look into

%SystemDrive%\Windows\System32\LogFiles\HTTPERR

Which will contain similar log files that only represents errors.

How to set default font family for entire Android app

Not talk about performance, for custom font you can have a recursive method loop through all the views and set typeface if it's a TextView:

public class Font {
    public static void setAllTextView(ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setAllTextView((ViewGroup) child);
            } else if (child instanceof TextView) {
                ((TextView) child).setTypeface(getFont());
            }
        }
    }

    public static Typeface getFont() {
        return Typeface.createFromAsset(YourApplicationContext.getInstance().getAssets(), "fonts/whateverfont.ttf");
    }
}

In all your activity, pass current ViewGroup to it after setContentView and it's done:

ViewGroup group = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
Font.setAllTextView(group);

For fragment you can do something similar.

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

add id to dynamically created <div>

You can add the id="MyID123" at the start of the cartHTML text appends.

The first line would therefore be:

var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';

-OR-

If you want the ID to be in a variable, then something like this:

    var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Work on a remote project with Eclipse via SSH

The very simplest way would be to run Eclipse CDT on the Linux Box and use either X11-Forwarding or remote desktop software such as VNC.

This, of course, is only possible when you Eclipse is present on the Linux box and your network connection to the box is sufficiently fast.

The advantage is that, due to everything being local, you won't have synchronization issues, and you don't get any awkward cross-platform issues.

If you have no eclipse on the box, you could thinking of sharing your linux working directory via SMB (or SSHFS) and access it from your windows machine, but that would require quite some setup.

Both would be better than having two copies, especially when it's cross-platform.

How to check if a variable is set in Bash?

If you wish to test that a variable is bound or unbound, this works well, even after you've turned on the nounset option:

set -o noun set

if printenv variableName >/dev/null; then
    # variable is bound to a value
else
    # variable is unbound
fi

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

If none of the above works, try using this in web.config or app.config:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
        </dependentAssembly>
    </assemblyBinding>
</runtime>

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

How to convert string to integer in UNIX

Any of these will work from the shell command line. bc is probably your most straight forward solution though.

Using bc:

$ echo "$d1 - $d2" | bc

Using awk:

$ echo $d1 $d2 | awk '{print $1 - $2}'

Using perl:

$ perl -E "say $d1 - $d2"

Using Python:

$ python -c "print $d1 - $d2"

all return

4

How to calculate the bounding box for a given lat/lng location?

You're looking for an ellipsoid formula.

The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN. It gives you a baseline to create your tests off of and to compare your results with its results. I used it as the basis for a similar library for PHP at my previous employer.

Geo::Ellipsoid

Take a look at the location method. Call it twice and you've got your bbox.

You didn't post what language you were using. There may already be a geocoding library available for you.

Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

What is N-Tier architecture?

If I understand the question, then it seems to me that the questioner is really asking "OK, so 3-tier is well understood, but it seems that there's a mix of hype, confusion, and uncertainty around what 4-tier, or to generalize, N-tier architectures mean. So...what's a definition of N-tier that is widely understood and agreed upon?"

It's actually a fairly deep question, and to explain why, I need to go a little deeper. Bear with me.

The classic 3-tier architecture: database, "business logic" and presentation, is a good way to clarify how to honor the principle of separation of concerns. Which is to say, if I want to change how "the business" wants to service customers, I should not have to look through the entire system to figure out how to do this, and in particular, decisions business issues shouldn't be scattered willy-nilly through the code.

Now, this model served well for decades, and it is the classic 'client-server' model. Fast forward to cloud offerings, where web browsers are the user interface for a broad and physically distributed set of users, and one typically ends up having to add content distribution services, which aren't a part of the classic 3-tier architecture (and which need to be managed in their own right).

The concept generalizes when it comes to services, micro-services, how data and computation are distributed and so on. Whether or not something is a 'tier' largely comes down to whether or not the tier provides an interface and deployment model to services that are behind (or beneath) the tier. So a content distribution network would be a tier, but an authentication service would not be.

Now, go and read other descriptions of examples of N-tier architectures with this concept in mind, and you will begin to understand the issue. Other perspectives include vendor-based approaches (e.g. NGINX), content-aware load balancers, data isolation and security services (e.g. IBM Datapower), all of which may or may not add value to a given architecture, deployment, and use cases.

How to justify navbar-nav in Bootstrap 3

To justify the bootstrap 3 navbar-nav justify menu to 100% width you can use this code:

@media (min-width: 768px){
    .navbar-nav {
        margin: 0 auto;
        display: table;
        table-layout: auto;
        float: none;
        width: 100%;
    }
    .navbar-nav>li {
        display: table-cell;
        float: none;
        text-align: center;
    }
} 

How do I set the icon for my application in visual studio 2008?

The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file

The file is in the res folder and is named (applicationName).rc

/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID )          ICON                    "res\\filename.ico"

Access localhost from the internet

Try with your IP Address , I think you can access it by internet.

How to uninstall Jenkins?

Keep in mind, that in Terminal you need to add backslash before space, so the proper copy/paste will be

/Library/Application\ Support/Jenkins/Uninstall.command

p.s. sorry for the late answer :)

How can I make a JPA OneToOne relation lazy

If the child entity is used readonly, then it's possible to simply lie and set optional=false. Then ensure that every use of that mapped entity is preloaded via queries.

public class App {
  ...
  @OneToOne(mappedBy = "app", fetch = FetchType.LAZY, optional = false)
  private Attributes additional;

and

String sql = " ... FROM App a LEFT JOIN FETCH a.additional aa ...";

... maybe even persisting would work...

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

UML diagram shapes missing on Visio 2013

If you don't see stencils creating new document with a template you may open the template directly. In my case they are located at 'C:\Program Files\Microsoft Office\Office15\Visio Content\1049\' Last foler name varies regarding locale, I guess. UML template is named 'DBUML_M.VSTX'

SQL recursive query on self referencing table (Oracle)

What about using PRIOR,

so

SELECT id, parent_id, PRIOR name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id`

or if you want to get the root name

SELECT id, parent_id, CONNECT_BY_ROOT name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id

link button property to open in new tab?

When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.

try

lbnkVidTtile1.Enabled = true;

I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

Is there a query language for JSON?

Update: XQuery 3.1 can query either XML or JSON - or both together. And XPath 3.1 can too.

The list is growing:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

I was working with Spring REST, and I solved it adding the AllowedMethods into the WebMvcConfigurer.

@Value( "${app.allow.origins}" )
    private String allowOrigins;    
@Bean
public WebMvcConfigurer corsConfigurer() {
            System.out.println("allow origin: "+allowOrigins);
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                    //.allowedOrigins("http://localhost")
                    .allowedOrigins(allowOrigins)
                    .allowedMethods("PUT", "DELETE","GET", "POST");
                }
            };
        }

How to downgrade Node version

For windows 10,

  • Uninstalling the node from the "Add or remove programs"
  • Installing the required version from https://nodejs.org/en/

worked for me.

How can I convert a date into an integer?

You can run it through Number()

var myInt = Number(new Date(dates_as_int[0]));

If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.

Use of Number()

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8 
ErrorDocument 403   /error/HTTP_XAMPP_FORBIDDEN.html.var   

and add Allow from all after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

A failure occurred while executing com.android.build.gradle.internal.tasks

Solution for:

Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.

All feature modules have to apply the library plugin and NOT the application plugin.

build.gradle (:androidApp:feature_A)

apply plugin: 'com.android.library'

It all depends on the stacktrace of each one. Cause 1 WorkExecutionException may be the consequence of other causes. So I suggest reading the full stacktrace from the last cause printed towards the first cause. So if we solve the last cause, it is very likely that we will have fixed the chain of causes from the last to the first.

I attach an example of my stacktrace where the original or concrete problem was in the last cause:

Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction

Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-4.2.0-alpha16-6840111-linux Daemon #0: Unexpected error during link, attempting to stop daemon.

Caused by: java.io.IOException: Unable to make AAPT link command.

Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.

GL

Feature Package ID was not set

How do I get Fiddler to stop ignoring traffic to localhost?

The correct answer is that it's not that Fiddler ignores traffic targeted at Localhost, but rather that most applications are hardcoded to bypass proxies (of which Fiddler is one) for requests targeted to localhost.

Hence, the various workarounds available: http://fiddler2.com/documentation/Configure-Fiddler/Tasks/MonitorLocalTraffic

(Deep) copying an array using jQuery

Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.

How to store file name in database, with other info while uploading image to server using PHP?

Your part:

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

";

Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.

What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".

Try adding do

$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");

and change the if($result) to $realresult

I suspect your query is failing, perhaps you have additional columns or something?

Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.

TensorFlow not found using pip

For windows this worked for me,

Download the wheel from this link. Then from command line navigate to your download folder where the wheel is present and simply type in the following command -

pip install tensorflow-1.0.0-cp36-cp36m-win_amd64.whl

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

try this

HTML:

<div class="container"></div>

CSS:

.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}

Pass parameter from a batch file to a PowerShell script

Let's say you would like to pass the string Dev as a parameter, from your batch file:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev"

put inside your powershell script head:

$w = $args[0]       # $w would be set to "Dev"

This if you want to use the built-in variable $args. Otherwise:

 powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\""

and inside your powershell script head:

param([string]$Environment)

This if you want a named parameter.

You might also be interested in returning the error level:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE"

The error level will be available inside the batch file as %errorlevel%.

How to deal with floating point number precision in JavaScript?

0.6 * 3 it's awesome!)) For me this works fine:

function dec( num )
{
    var p = 100;
    return Math.round( num * p ) / p;
}

Very very simple))

Remove specific characters from a string in Javascript

Another way to do it:

rnum = rnum.split("F0").pop()

It splits the string into two: ["", "123456"], then selects the last element.

How to pass parameters using ui-sref in ui-router to controller

You don't necessarily need to have the parameters inside the URL.

For instance, with:

$stateProvider
.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },
  },
  params: {
    foo: null,
    bar: null
  }
})

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

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

On Windows Vista/7, with UAC, administrator accounts run programs in unprivileged mode by default.

Programs must prompt for administrator access before they run as administrator, with the ever-so-familiar UAC dialog. Since Python scripts aren't directly executable, there's no "Run as Administrator" context menu option.

It's possible to use ctypes.windll.shell32.IsUserAnAdmin() to detect whether the script has admin access, and ShellExecuteEx with the 'runas' verb on python.exe, with sys.argv[0] as a parameter to prompt the UAC dialog if needed.

How to asynchronously call a method in Java

You can use AsyncFunc from Cactoos:

boolean matches = new AsyncFunc(
  x -> x.matches("something")
).apply("The text").get();

It will be executed at the background and the result will be available in get() as a Future.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Try this:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Or this:

yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 

how to convert a string to a bool

I used the below code to convert a string to boolean.

Convert.ToBoolean(Convert.ToInt32(myString));

Class file for com.google.android.gms.internal.zzaja not found

I had such a similar error when i was recently upgrading my play service dependency. It seems to occur when you leave out updating the firebase dependencies that correspond to the version of play services you use. I beleive this is the most recent update of these dependencies

Here is what the two versions of my dependencies were:

Error version of dependencies

compile 'com.google.firebase:firebase-appindexing:10.0.1'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.google.android.gms:play-services-places:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.firebase:firebase-auth:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.firebaseui:firebase-ui-database:1.0.1'
compile 'com.google.firebase:firebase-storage:9.8.0'

Working version of dependencies ``

compile 'com.google.firebase:firebase-appindexing:10.0.1'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.google.android.gms:play-services-places:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.0'
compile 'com.google.firebase:firebase-database:10.0.0'
compile 'com.firebaseui:firebase-ui-database:1.0.1'
compile 'com.google.firebase:firebase-storage:10.0.0'

`` Google seems to move play service updates along with firebase updates these days. Hopes this saves a few souls out there.

ExecuteNonQuery: Connection property has not been initialized.

A couple of things wrong here.

  1. Do you really want to open and close the connection for every single log entry?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

I highly recommend a C# / SQL Server tutorial.

How to fix SSL certificate error when running Npm on Windows?

I am having the same issue, I overcome using

npm config set proxy http://my-proxy.com:1080
npm config set https-proxy http://my-proxy.com:1080

Additionally info at node-doc

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

AttributeError: 'datetime' module has no attribute 'strptime'

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you're facing (in the future), look at your import statements

  • import datetime: that's the module (that's what you have right now).
  • from datetime import datetime: that's the class.

jQuery `.is(":visible")` not working in Chrome

It seems jQuery's :visible selector does not work for some inline elements in Chrome. The solution is to add a display style, like "block" or "inline-block" to make it work.

Also note that jQuery has a somewhat different definition of what is visible than many developers:

Elements are considered visible if they consume space in the document.
Visible elements have a width or height that is greater than zero.

In other words, an element must have a non-zero width and height to consume space and be visible.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

On the other hand, even if its visibility is set to hidden or the opacity is zero, it's still :visible to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.

Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

All option elements are considered hidden, regardless of their selected state.

During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.

I cleaned up your markup a little and added a display style (i.e. setting the elements display to "block" etc), and this works for me:

FIDDLE

Official API reference for :visible


As of jQuery 3, the definition of :visible has changed slightly

jQuery 3 slightly modifies the meaning of :visible (and therefore of :hidden).
Starting with this version, elements will be considered :visible if they have any layout boxes, including those of zero width and/or height. For example, br elements and inline elements with no content will be selected by the :visible selector.

How to customize listview using baseadapter

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

custom.xml:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="255dp"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Video1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#339966"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/detail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="video1"
                    android:textColor="#606060" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

main.java:

package com.example.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity {

    ListView l1;
    String[] t1={"video1","video2"};
    String[] d1={"lesson1","lesson2"};
    int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1=(ListView)findViewById(R.id.list);
        l1.setAdapter(new dataListAdapter(t1,d1,i1));
    }

    class dataListAdapter extends BaseAdapter {
        String[] Title, Detail;
        int[] imge;

        dataListAdapter() {
            Title = null;
            Detail = null;
            imge=null;
        }

        public dataListAdapter(String[] text, String[] text1,int[] text3) {
            Title = text;
            Detail = text1;
            imge = text3;

        }

        public int getCount() {
            // TODO Auto-generated method stub
            return Title.length;
        }

        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = getLayoutInflater();
            View row;
            row = inflater.inflate(R.layout.custom, parent, false);
            TextView title, detail;
            ImageView i1;
            title = (TextView) row.findViewById(R.id.title);
            detail = (TextView) row.findViewById(R.id.detail);
            i1=(ImageView)row.findViewById(R.id.img);
            title.setText(Title[position]);
            detail.setText(Detail[position]);
            i1.setImageResource(imge[position]);

            return (row);
        }
    }
}

Try this.

Where is Xcode's build folder?

In case of Debug Running

~/Library/Developer/Xcode/DerivedData/{your app}/Build/Products/Debug/{Project Name}.app/Contents/MacOS

You can find standalone executable file(Mach-O 64-bit executable x86_64)

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

Validate IPv4 address in Java

If it is IP4, you can use a regular expression as follows:

^(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)\\.){3}(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)$.

How to modify a specified commit?

Use the awesome interactive rebase:

git rebase -i @~9   # Show the last 9 commits in a text editor

Find the commit you want, change pick to e (edit), and save and close the file. Git will rewind to that commit, allowing you to either:

  • use git commit --amend to make changes, or
  • use git reset @~ to discard the last commit, but not the changes to the files (i.e. take you to the point you were at when you'd edited the files, but hadn't committed yet).

The latter is useful for doing more complex stuff like splitting into multiple commits.

Then, run git rebase --continue, and Git will replay the subsequent changes on top of your modified commit. You may be asked to fix some merge conflicts.

Note: @ is shorthand for HEAD, and ~ is the commit before the specified commit.

Read more about rewriting history in the Git docs.


Don't be afraid to rebase

ProTip™:   Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:

$ git reset @~3   # go back 3 commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started

* Watch out for options like --hard and --force though — they can discard data.
* Also, don't rewrite history on any branches you're collaborating on.



On many systems, git rebase -i will open up Vim by default. Vim doesn't work like most modern text editors, so take a look at how to rebase using Vim. If you'd rather use a different editor, change it with git config --global core.editor your-favorite-text-editor.

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

How To Use DateTimePicker In WPF?

There is a DateTimePicker available in the Extended Toolkit.

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Experienced this myself when using requests:

This is extremely insecure; use only as a last resort! (See rdlowrey's comment.)

requests.get('https://github.com', verify=True)

Making that verify=False did the trick for me.

string to string array conversion in java

Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).

import org.apache.commons.lang3.StringUtils;

StringUtils.split(null)       => null
StringUtils.split("")         => []
StringUtils.split("abc def")  => ["abc", "def"]
StringUtils.split("abc  def") => ["abc", "def"]
StringUtils.split(" abc ")    => ["abc"]

Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:

import com.google.common.base.Splitter;

Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

SPLITTER.split("a,b,   c , , ,, ")     =>  [a, b, c]
SPLITTER.split("")                     =>  []
SPLITTER.split("  ")                   =>  []
SPLITTER.split(null)                   =>  NullPointerException

If you want a list rather than an iterator then use Splitter.splitToList().

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

How to read data when some numbers contain commas as thousand separator?

This question is several years old, but I stumbled upon it, which means maybe others will.

The readr library / package has some nice features to it. One of them is a nice way to interpret "messy" columns, like these.

library(readr)
read_csv("numbers\n800\n\"1,800\"\n\"3500\"\n6.5",
          col_types = list(col_numeric())
        )

This yields

Source: local data frame [4 x 1]

  numbers
    (dbl)
1   800.0
2  1800.0
3  3500.0
4     6.5

An important point when reading in files: you either have to pre-process, like the comment above regarding sed, or you have to process while reading. Often, if you try to fix things after the fact, there are some dangerous assumptions made that are hard to find. (Which is why flat files are so evil in the first place.)

For instance, if I had not flagged the col_types, I would have gotten this:

> read_csv("numbers\n800\n\"1,800\"\n\"3500\"\n6.5")
Source: local data frame [4 x 1]

  numbers
    (chr)
1     800
2   1,800
3    3500
4     6.5

(Notice that it is now a chr (character) instead of a numeric.)

Or, more dangerously, if it were long enough and most of the early elements did not contain commas:

> set.seed(1)
> tmp <- as.character(sample(c(1:10), 100, replace=TRUE))
> tmp <- c(tmp, "1,003")
> tmp <- paste(tmp, collapse="\"\n\"")

(such that the last few elements look like:)

\"5\"\n\"9\"\n\"7\"\n\"1,003"

Then you'll find trouble reading that comma at all!

> tail(read_csv(tmp))
Source: local data frame [6 x 1]

     3"
  (dbl)
1 8.000
2 5.000
3 5.000
4 9.000
5 7.000
6 1.003
Warning message:
1 problems parsing literal data. See problems(...) for more details. 

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How can I convert a string to upper- or lower-case with XSLT?

<xsl:variable name="upper">UPPER CASE</xsl:variable>
<xsl:variable name="lower" select="translate($upper,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')"/>
<xsl:value-of select ="$lower"/>

//displays UPPER CASE as upper case

How to check if a Java 8 Stream is empty?

If you can live with limited parallel capablilities, the following solution will work:

private static <T> Stream<T> nonEmptyStream(
    Stream<T> stream, Supplier<RuntimeException> e) {

    Spliterator<T> it=stream.spliterator();
    return StreamSupport.stream(new Spliterator<T>() {
        boolean seen;
        public boolean tryAdvance(Consumer<? super T> action) {
            boolean r=it.tryAdvance(action);
            if(!seen && !r) throw e.get();
            seen=true;
            return r;
        }
        public Spliterator<T> trySplit() { return null; }
        public long estimateSize() { return it.estimateSize(); }
        public int characteristics() { return it.characteristics(); }
    }, false);
}

Here is some example code using it:

List<String> l=Arrays.asList("hello", "world");
nonEmptyStream(l.stream(), ()->new RuntimeException("No strings available"))
  .forEach(System.out::println);
nonEmptyStream(l.stream().filter(s->s.startsWith("x")),
               ()->new RuntimeException("No strings available"))
  .forEach(System.out::println);

The problem with (efficient) parallel execution is that supporting splitting of the Spliterator requires a thread-safe way to notice whether either of the fragments has seen any value in a thread-safe manner. Then the last of the fragments executing tryAdvance has to realize that it is the last one (and it also couldn’t advance) to throw the appropriate exception. So I didn’t add support for splitting here.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

"Parameter not valid" exception loading System.Drawing.Image

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

AngularJS: Service vs provider vs factory

For me the best and the simplest way of understanding the difference is:

var service, factory;
service = factory = function(injection) {}

How AngularJS instantiates particular components (simplified):

// service
var angularService = new service(injection);

// factory
var angularFactory = factory(injection);

So, for the service, what becomes the AngularJS component is the object instance of the class which is represented by service declaration function. For the factory, it is the result returned from the factory declaration function. The factory may behave the same as the service:

var factoryAsService = function(injection) {
  return new function(injection) {
    // Service content
  }
}

The simplest way of thinking is the following one:

  • Service is an singleton object instance. Use services if you want to provide a singleton object for your code.
  • Factory is a class. Use factories if you want to provide custom classes for your code (can't be done with services because they are already instantiated).

The factory 'class' example is provided in the comments around, as well as provider difference.

set option "selected" attribute from dynamic created option

Make option defaultSelected

HTMLOptionElement.defaultSelected = true;     // JS
$('selector').prop({defaultSelected: true});  // jQuery  

HTMLOptionElement MDN

If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:

_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
EL_country.value = 'ID';   // Set SELECT value to 'ID' ("Indonesia")_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country">_x000D_
    <option value="AF">Afghanistan</option>_x000D_
    <option value="AL">Albania</option>_x000D_
    <option value="HR">Croatia</option>_x000D_
    <option value="ID">Indonesia</option>_x000D_
    <option value="ZW">Zimbabwe</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
_x000D_
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)_x000D_
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, ''); _x000D_
_x000D_
EL_country.value = 'ID';_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true;_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Option gets Attribute selected by using defaultSelected

Make option defaultSelected while dynamically creating options

To make an option selected while populating the SELECT Element, use the Option() constructor MDN

var optionElementReference = new Option(text, value, defaultSelected, selected);

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',     // <<< make this one defaultSelected_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
const DF_options = document.createDocumentFragment();_x000D_
_x000D_
Object.keys(countries).forEach(key => {_x000D_
  const isIndonesia = key === 'ID';  // Boolean_x000D_
  DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))_x000D_
});_x000D_
_x000D_
EL_country.appendChild(DF_options);_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.


SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected

Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness

one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.


Comparison test of the different methods

_x000D_
_x000D_
const EL_select = document.querySelector('#country');_x000D_
const TPL_options = `_x000D_
  <option value="AF">Afghanistan</option>_x000D_
  <option value="AL">Albania</option>_x000D_
  <option value="HR">Croatia</option>_x000D_
  <option value="ID">Indonesia</option>_x000D_
  <option value="ZW">Zimbabwe</option>_x000D_
`;_x000D_
_x000D_
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver_x000D_
const mutationCB = (mutationsList, observer) => {_x000D_
  mutationsList.forEach(mu => {_x000D_
    const EL = mu.target;_x000D_
    if (mu.type === 'attributes') {_x000D_
      return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);_x000D_
    }_x000D_
  });_x000D_
};_x000D_
_x000D_
// (PREPARE SOME TEST FUNCTIONS)_x000D_
_x000D_
const testOptionsSelectedByProperty = () => {_x000D_
  const test = 'OPTION with Property selected:';_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.selected);_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testOptionsSelectedByAttribute = () => {_x000D_
  const test = 'OPTION with Attribute selected:'_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testSelect = () => {_x000D_
  console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);_x000D_
}_x000D_
_x000D_
const formReset = () => {_x000D_
  EL_select.value = '';_x000D_
  EL_select.innerHTML = TPL_options;_x000D_
  // Attach MutationObserver to every Option to track if Attribute will change_x000D_
  [...EL_select.options].forEach(EL_option => {_x000D_
    const observer = new MutationObserver(mutationCB);_x000D_
    observer.observe(EL_option, {attributes: true});_x000D_
  });_x000D_
}_x000D_
_x000D_
// -----------_x000D_
// LET'S TEST! _x000D_
_x000D_
console.log('\n1. Set SELECT value');_x000D_
formReset();_x000D_
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n2. Set HTMLElement.setAttribute()');_x000D_
formReset();_x000D_
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n3. Set HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.options[3].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.value = 'ZW'_x000D_
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
/* END */_x000D_
console.log('\n*. Getting MutationObservers out from call-stack...');
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:

EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!

will actually make the option selected

Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?

Instead test 3. (and 4.) using defaultSelected gives the expected results:

  • Attribute selected as a named Selectedness state.
  • Property selected on the Element Object, with a Boolean value.

How to use enums as flags in C++?

As above(Kai) or do the following. Really enums are "Enumerations", what you want to do is have a set, therefore you should really use stl::set

enum AnimalFlags
{
    HasClaws = 1,
    CanFly =2,
    EatsFish = 4,
    Endangered = 8
};

int main(void)
{
    AnimalFlags seahawk;
    //seahawk= CanFly | EatsFish | Endangered;
    seahawk= static_cast<AnimalFlags>(CanFly | EatsFish | Endangered);
}

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

For Swift 3+

Simply use UITableViewStyleGrouped and set the footer's height to zero with the following:

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return .leastNormalMagnitude
}

Set initially selected item in Select list in Angular2

The easiest way to solve this problem in Angular is to do:

In Template:

<select [ngModel]="selectedObjectIndex">
  <option [value]="i" *ngFor="let object of objects; let i = index;">{{object.name}}</option>
</select>

In your class:

this.selectedObjectIndex = 1/0/your number wich item should be selected

Oracle - How to generate script from sql developer

step 1. select * from <tablename>;

step 2. just right click on your output(t.e data) then go to last option export it will give u some extension then click on your required extension then apply u will get new file including data.

Changing MongoDB data store directory

The short answer is that the --dbpath parameter in MongoDB will allow you to control what directory MongoDB reads and writes it's data from.

mongod --dbpath /usr/local/mongodb-data

Would start mongodb and put the files in /usr/local/mongodb-data.

Depending on your distribution and MongoDB installation, you can also configure the mongod.conf file to do this automatically:

# Store data in /usr/local/var/mongodb instead of the default /data/db
dbpath = /usr/local/var/mongodb

The official 10gen Linux packages (Ubuntu/Debian or CentOS/Fedora) ship with a basic configuration file which is placed in /etc/mongodb.conf, and the MongoDB service reads this when it starts up. You could make your change here.

'tuple' object does not support item assignment

A tuple is immutable and thus you get the error you posted.

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

In your specific case, as correctly pointed out in other answers, you should write:

pixel = (pixel[0] + 20, pixel[1], pixel[2])

String to byte array in php

I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.

Take byteStr2byteArray() as an example:

<?php
function byteStr2byteArray($s) {
    return array_slice(unpack("C*", "\0".$s), 1);
}

$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);

for($i=0;$i<count($byte_array);$i++)
{
   printf("0x%02x ", $byte_array[$i]);
}
?>

How to drop SQL default constraint without knowing its name?

Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.

declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command  nvarchar(1000)

set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'

select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
 from sys.tables t
  join sys.default_constraints d on d.parent_object_id = t.object_id
  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
 where t.name = @table_name
  and t.schema_id = schema_id(@schema_name)
  and c.name = @col_name

--print @Command

execute (@Command)

How to make the overflow CSS property work with hidden as value

Ok if anyone else is having this problem this may be your answer:

If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

Solution for yml file:

1.Copy yml to in same directory that jar application

2.Run command, example for xxx.yml:

java -jar app.jar --spring.config.location=xxx.yml

It's works fine, but in startup logger is INFO:

No active profile set .........

ALTER DATABASE failed because a lock could not be placed on database

I will add this here in case someone will be as lucky as me.

When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.

Check if you have any processes in KILL/RollBack state for master database

SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'

If you have the same issue, just the KILL command will probably not help. You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

How can I get the height and width of an uiimage?

UIImageView *imageView = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MyImage.png"]]autorelease];

NSLog(@"Size of my Image => %f, %f ", [[imageView image] size].width, [[imageView image] size].height) ;

How to use ArrayList.addAll()?

Assuming you have an ArrayList that contains characters, you could do this:

List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));

How to find the size of a table in SQL?

You may refer the answer by Marc_s in another thread, Very useful.

Get size of all tables in database

Simulator or Emulator? What is the difference?

A simulation is a system that behaves similar to something else, but is implemented in an entirely different way. It provides the basic behavior of a system but may not necessarily abide by all of the rules of the system being simulated. It is there to give you an idea about how something works.

An emulation is a system that behaves exactly like something else, and abides by all of the rules of the system being emulated. It is effectively a complete replication of another system, right down to being binary compatible with the emulated system's inputs and outputs, but operating in a different environment to the environment of the original emulated system. The rules are fixed, and cannot be changed or the system fails.

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
    string str;
    emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
    ~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first) 
{
    if (!skip_first)
        static emitter a("in if");
    static emitter b("in foo");
}

int main(int argc, char*[])
{
    foo(argc != 2);
    if (argc == 3)
        foo(false);
}

Output:

C:>sample.exe
Created in foo
Destroyed in foo

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

How to check if the URL contains a given string?

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf('franky') > -1) {
     alert("your url contains the name franky");
}

What should main() return in C and C++?

What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why?

Those words "(most efficient)" don't change the question. Unless you're in a freestanding environment, there is one universally correct way to declare main(), and that's as returning int.

What should main() return in C and C++?

It's not what should main() return, it's what does main() return. main() is, of course, a function that someone else calls. You don't have any control over the code that calls main(). Therefore, you must declare main() with a type-correct signature to match its caller. You simply don't have any choice in the matter. You don't have to ask yourself what's more or less efficient, or what's better or worse style, or anything like that, because the answer is already perfectly well defined, for you, by the C and C+ standards. Just follow them.

If int main() then return 1 or return 0?

0 for success, nonzero for failure. Again, not something you need to (or get to) pick: it's defined by the interface you're supposed to be conforming to.

When to use pthread_exit() and when to use pthread_join() in Linux?

When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.

It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Edit 3:

Cordova Android 6.2.2 has been released and it's fully compatible with SDK tools 26.0.x and 25.3.1. Use this version:

cordova platform update [email protected]

or

cordova platform rm android
cordova platform add [email protected]

Edit 2:

There has been another Android SDK tools release (26.0.x) that is not fully compatible with cordova-android 6.2.1.

Edit: Cordova Android 6.2.1 has been released and it's now compatible with latest Android SDK.

You can update your current incompatible android platform with cordova platform update [email protected]

Or you can remove the existing platform and add the new one (will delete any manual change you did inside yourProject/platforms/android/ folder)

cordova platform rm android cordova platform add [email protected]

You have to specify the version because current CLI installs 6.1.x by default.

Old answer:

Sadly Android SDK tools 25.3.1 broke cordova-android 6.1.x

For those who don't want to downgrade the SDK tools, you can install cordova-android from github url as most of the problems are already fixed on master branch.

cordova platform add https://github.com/apache/cordova-android

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

How to force NSLocalizedString to use a specific language

I usually do this in this way, but you MUST have all localization files in your project.

@implementation Language

static NSBundle *bundle = nil;

+(void)initialize 
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString *current = [[languages objectAtIndex:0] retain];
    [self setLanguage:current];
}

/*
  example calls:
    [Language setLanguage:@"it"];
    [Language setLanguage:@"de"];
*/
+(void)setLanguage:(NSString *)l
{
    NSLog(@"preferredLang: %@", l);
    NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
    bundle = [[NSBundle bundleWithPath:path] retain];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate 
{
    return [bundle localizedStringForKey:key value:alternate table:nil];
}

@end

Which version of Python do I have installed?

In short:

Type python in a command prompt

Simply open the command prompt (Win + R) and type cmd and in the command prompt then typing python will give you all necessary information regarding versions:

Python version

"SDK Platform Tools component is missing!"

The latest version of the Android SDK ships with two different applications: an SDK Manager and an AVD Manager rather than one single app that was valid when this question was originally asked.

My particular problem was unrelated to the other suggestions. I'm on a network at the moment where HTTPS traffic is mostly disallowed. In order to install the Android Platform Tools I needed to turn on the option to "Force https://... sources to be fetched using http://..." and then this allowed me to install the other tools.

check android application is in foreground or not?

Below is updated solution for the latest Android SDK.

String PackageName = context.getPackageName();
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ComponentName componentInfo;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            List<ActivityManager.AppTask> tasks = manager.getAppTasks();
            componentInfo = tasks.get(0).getTaskInfo().topActivity;
        }
        else
        {
            List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(1);
            componentInfo = tasks.get(0).topActivity;
        }

        if (componentInfo.getPackageName().equals(PackageName))
            return true;
        return false;

Hope this helps, thanks.

Properly embedding Youtube video into bootstrap 3.0 page

There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed

since Bootstrap 3.2.0!

If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).

Eloquent - where not equal to

While this seems to work

Code::query()
    ->where('to_be_used_by_user_id', '!=' , 2)
    ->orWhereNull('to_be_used_by_user_id')
    ->get();

you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"

enter image description here enter image description here

Instead, try Union

$first = Code::whereNull('to_be_used_by_user_id');

$code = Code::where('to_be_used_by_user_id', '!=' , 2)
        ->union($first)
        ->get();

Git clone without .git directory

Use

git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
  • The depth option will make sure to copy the least bit of history possible to get that repo.
  • The branch option is optional and if not specified would get master.
  • The second line will make your directory dirformynewrepo not a Git repository any more.
  • If you're doing recursive submodule clone, the depth and branch parameter don't apply to the submodules.

How to remove all callbacks from a Handler?

Define a new handler and runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do what ever you want
        }
    };

Call post delayed:

handler.postDelayed(runnable, sleep_time);

Remove your callback from your handler:

handler.removeCallbacks(runnable);

what is reverse() in Django

The function supports the dry principle - ensuring that you don't hard code urls throughout your app. A url should be defined in one place, and only one place - your url conf. After that you're really just referencing that info.

Use reverse() to give you the url of a page, given either the path to the view, or the page_name parameter from your url conf. You would use it in cases where it doesn't make sense to do it in the template with {% url 'my-page' %}.

There are lots of possible places you might use this functionality. One place I've found I use it is when redirecting users in a view (often after the successful processing of a form)-

return HttpResponseRedirect(reverse('thanks-we-got-your-form-page'))

You might also use it when writing template tags.

Another time I used reverse() was with model inheritance. I had a ListView on a parent model, but wanted to get from any one of those parent objects to the DetailView of it's associated child object. I attached a get__child_url() function to the parent which identified the existence of a child and returned the url of it's DetailView using reverse().

Sending emails with Javascript

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.

CMake does not find Visual C++ compiler

Check name folder too long or not.

<script> tag vs <script type = 'text/javascript'> tag

You only need <script></script> Tag that's it. <script type="text/javascript"></script> is not a valid HTML tag, so for best SEO practice use <script></script>

MongoDB Aggregation: How to get total records count?

Use this to find total count in resulting collection.

db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );

How to backup a local Git repository?

Both answers to this questions are correct, but I was still missing a complete, short solution to backup a Github repository into a local file. The gist is available here, feel free to fork or adapt to your needs.

backup.sh:

#!/bin/bash
# Backup the repositories indicated in the command line
# Example:
# bin/backup user1/repo1 user1/repo2
set -e
for i in $@; do
  FILENAME=$(echo $i | sed 's/\//-/g')
  echo "== Backing up $i to $FILENAME.bak"
  git clone [email protected]:$i $FILENAME.git --mirror
  cd "$FILENAME.git"
  git bundle create ../$FILENAME.bak --all
  cd ..
  rm -rf $i.git
  echo "== Repository saved as $FILENAME.bak"
done

restore.sh:

#!/bin/bash
# Restore the repository indicated in the command line
# Example:
# bin/restore filename.bak
set -e

FOLDER_NAME=$(echo $1 | sed 's/.bak//')
git clone --bare $1 $FOLDER_NAME.git

Boxplot in R showing the mean

Check chart.Boxplot from package PerformanceAnalytics. It lets you define the symbol to use for the mean of the distribution.

By default, the chart.Boxplot(data) command adds the mean as a red circle and the median as a black line.

Here is the output with sample data; MWE:

#install.packages(PerformanceAnalytics)    
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)

picture of a boxplot using performance analytics package

How to allow Cross domain request in apache2

In httpd.conf

  1. Make sure these are loaded:
LoadModule headers_module modules/mod_headers.so

LoadModule rewrite_module modules/mod_rewrite.so
  1. In the target directory:
<Directory "**/usr/local/PATH**">
    AllowOverride None
    Require all granted

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
    Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
    Header always set Access-Control-Max-Age "600"

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]

</Directory>

If running outside container, you may need to restart apache service.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

For an array:

var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();

As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.

But as we all know JavaScript is strange, so here are some weird bits:

array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!

This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

So what are Objects?

Objects in JavaScript are just like arrays but the "index" can be any string.

var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK

You can even opt to not use the square brackets when working with objects!

console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";

You can go even further and define objects like so:

var newObject = {
    a: 2,
};
newObject.a === 2; // true

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

How do I create a comma-separated list using a SQL query?

From next version of SQL Server you will be able to do

SELECT r.name,
       STRING_AGG(a.name, ',')
FROM   RESOURCES r
       JOIN APPLICATIONSRESOURCES ar
         ON ar.resource_id = r.id
       JOIN APPLICATIONS a
         ON a.id = ar.app_id
GROUP  BY r.name 

For previous versions of the product there are quite a wide variety of different approaches to this problem. An excellent review of them is in the article: Concatenating Row Values in Transact-SQL.

  • Concatenating values when the number of items are not known

    • Recursive CTE method
    • The blackbox XML methods
    • Using Common Language Runtime
    • Scalar UDF with recursion
    • Table valued UDF with a WHILE loop
    • Dynamic SQL
    • The Cursor approach
      .
  • Non-reliable approaches

    • Scalar UDF with t-SQL update extension
    • Scalar UDF with variable concatenation in SELECT

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

How can I access each element of a pair in a pair list?

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0]. Or if you want the second element of the third element, it's pair[2][1].

How do I get my solution in Visual Studio back online in TFS?

I searched for the solution online and found this solution but wasn't too keen on the registry change.

I found a better way: right-click on the solution name right at the top of the Solution Explorer and select the Go Online option. Clicking this allowed me to select the files that had been changed when I was offline and make the solution online again.

After finding the solution, I found the following msdn forum thread which confirmed the above.

How can I get dict from sqlite query?

A generic alternative, using just three lines

def select_column_and_value(db, sql, parameters=()):
    execute = db.execute(sql, parameters)
    fetch = execute.fetchone()
    return {k[0]: v for k, v in list(zip(execute.description, fetch))}

con = sqlite3.connect('/mydatabase.db')
c = con.cursor()
print(select_column_and_value(c, 'SELECT * FROM things WHERE id=?', (id,)))

But if your query returns nothing, will result in error. In this case...

def select_column_and_value(self, sql, parameters=()):
    execute = self.execute(sql, parameters)
    fetch = execute.fetchone()

    if fetch is None:
        return {k[0]: None for k in execute.description}

    return {k[0]: v for k, v in list(zip(execute.description, fetch))}

or

def select_column_and_value(self, sql, parameters=()):
    execute = self.execute(sql, parameters)
    fetch = execute.fetchone()

    if fetch is None:
        return {}

    return {k[0]: v for k, v in list(zip(execute.description, fetch))}

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

Android: Create spinner programmatically from array

this work for me:-

String[] array = {"A", "B", "C"};
String abc = "";


Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);

I am using a Fragment.

Loaded nib but the 'view' outlet was not set

I just fixed this in mine. Large project, two files. One was "ReallyLargeNameView" and another was "ReallyLargeNameViewController"

Based on the 2nd answer chosen above, I decided I should clean my build. Nada, but I was still suspect of XCode (as I have two identical classes, should abstract them but eh...) So one's working, one's not. File's owner names are so far as copy and pasted, outlets rehooked up, xCode rebooted, still nothing.

So I delete the similar named class (which is a view). Soon, new error "outlet inside not hooked up" literally was "webView not key value" blah... basically saying "Visual Studio's better". Anyway... I erase the smaller named file, and bam, it works.

XCode is confused by similar-named files. And the project is large enough to need rebooting a bit, that may be part of it.

Wish I had a more technical answer than "XCode is confused", but well, xCode gets confused a lot at this point. Unconfused it the same way I'd help a little kid. It works now, :) Should benefit others if the above doesn't fix anything.

Always remember to clean your builds (by deleting off the simulator too)

Use of var keyword in C#

Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.

Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.

Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.

I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.

Check if input is integer type in C

This method works for everything (integers and even doubles) except zero (it calls it invalid):

The while loop is just for the repetitive user input. Basically it checks if the integer x/x = 1. If it does (as it would with a number), its an integer/double. If it doesn't, it obviously it isn't. Zero fails the test though.

#include <stdio.h> 
#include <math.h>

void main () {
    double x;
    int notDouble;
    int true = 1;
    while(true) {
        printf("Input an integer: \n");
        scanf("%lf", &x);
        if (x/x != 1) {
            notDouble = 1;
            fflush(stdin);
        }
        if (notDouble != 1) {
            printf("Input is valid\n");
        }
        else {
            printf("Input is invalid\n");
        }
        notDouble = 0;
    }
}

String formatting: % vs. .format vs. string literal

PEP 3101 proposes the replacement of the % operator with the new, advanced string formatting in Python 3, where it would be the default.