Programs & Examples On #Document database

A document database stores, retrieves, and manages document-oriented information, also known as semi-structured data. Document databases often store data in a denormalized fashion as opposed to normalized data, which would appear in a relational database.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Run gradle -q dependencies (or gradle -q :projectName:dependencies) to generate a dependency report. You should see where r7 is coming from, such as:

compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
|    +--- com.actionbarsherlock:actionbarsherlock:4.4.0
|    |    \--- com.google.android:support-v4:r7
|    +--- com.commonsware.cwac:camera:0.5.4
|    \--- com.android.support:support-v4:18.0.+ -> 18.0.0
\--- com.android.support:support-v4:18.0.+ -> 18.0.0

Then, use the exclude directive to block that dependency. In my case, it is coming from my CWAC-Camera library, and so I use:

dependencies {
    compile('com.commonsware.cwac:camera-v9:0.5.4') {
      exclude module: 'support-v4'
    }

    compile 'com.android.support:support-v4:18.0.+'
}

(where the second compile statement indicates what version you actually want)

That should clear matters up, as you will see if you run the dependency report again:

compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
|    +--- com.actionbarsherlock:actionbarsherlock:4.4.0
|    \--- com.commonsware.cwac:camera:0.5.4
\--- com.android.support:support-v4:18.0.+ -> 18.0.0

Optional Parameters in Go?

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

  1. If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often.
  2. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.

How to dynamically change a web page's title?

One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.

How to use jQuery in chrome extension?

You have to add your jquery script to your chrome-extension project and to the background section of your manifest.json like this :

  "background":
    {
        "scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]
    }

If you need jquery in a content_scripts, you have to add it in the manifest too:

"content_scripts": 
    [
        {
            "matches":["http://website*"],
            "js":["thirdParty/jquery.1.10.2.min.js", "script.js"],
            "css": ["css/style.css"],
            "run_at": "document_end"
        }
    ]

This is what I did.

Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions.

Length of the String without using length() method

This is a complete program you can compile and run it.

import java.util.Scanner;

class Strlen{

    public static void main(String...args){
        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter Your Name =>" +"  ");
        String ab = sc.nextLine();
        System.out.println("\nName Length is:" +len(ab));
    }

    public static int len(String ab){
        char[] ac = ab.toCharArray();
        int i = 0, k = 0;

        try{
            for(i=0,k=0;ac[i]!='\0';i++)
                k++;
        }
        catch(Exception e){
        }
        return k;
    }

}

Credentials for the SQL Server Agent service are invalid

I had a VM that was server 2012 and I had to change the nic to VMXNET 3. It wasn't connecting to the domain fast enough for the services to start I guess.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Dan Abramov wrote an article on this topic:

Why Do We Write super(props)?

And the gist of it is that it's helpful to have a habit of passing it to avoid this scenario, that honestly, I don't see it unlikely to happen:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// Inside your code
class Button extends React.Component {
  constructor(props) {
    super(); //  We forgot to pass props
    console.log(props);      // ? {}
    console.log(this.props); //  undefined 
  }
  // ...
}

HTML/CSS font color vs span style

Actually I would say the 1st preference would be an external style sheet (External CSS), the 2nd preference would be writing CSS in style tags in the header section of the current page (Internal CSS)

<style type="text/css">
<!-- CSS goes here -->
</style>

And as a 3rd option - or last resort rather - I'd use CSS in the tags themselves (Inline CSS).

How to check if command line tools is installed

I think the simplest way which worked for me to find Command line tools is installed or not and its version irrespective of what macOS version is

$brew config

macOS: 10.14.2-x86_64
CLT: 10.1.0.0.1.1539992718
Xcode: 10.1

This when you have Command Line tools properly installed and paths set properly.

Earlier i got output as below
macOS: 10.14.2-x86_64
CLT: N/A
Xcode: 10.1

CLT was shown as N/A in spite of having gcc and make working fine and below outputs

$xcode-select -p              
/Applications/Xcode.app/Contents/Developer
$pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
$brew doctor
Your system is ready to brew.

Finally doing xcode-select --install resolved my issue of brew unable to find CLT for installing packages as below.

Installing sphinx-doc dependency: python
Warning: Building python from source:
  The bottle needs the Apple Command Line Tools to be installed.
  You can install them, if desired, with:
    xcode-select --install

JNI and Gradle in Android Studio

Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.

You need to do something like this:

externalNativeBuild{
   ndkBuild{
        path "Android.mk"
    }
}

defaultConfig {
  externalNativeBuild{
    ndkBuild {
      arguments "NDK_APPLICATION_MK:=Application.mk"
      cFlags "-DTEST_C_FLAG1"  "-DTEST_C_FLAG2"
      cppFlags "-DTEST_CPP_FLAG2"  "-DTEST_CPP_FLAG2"
      abiFilters "armeabi-v7a", "armeabi"
    }
  } 
}

See http://tools.android.com/tech-docs/external-c-builds

NB: The extra nesting of externalNativeBuild inside defaultConfig was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.

How do I do base64 encoding on iOS?

Better solution :

There is a built in function in NSData

[data base64Encoding]; //iOS < 7.0
[data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]; //iOS >= 7.0

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

I had the same issue.

Make sure that In SQL Server configuration --> SQL Server Services --> SQL Server Agent is enable

This solved my problem

How do I call ::CreateProcess in c++ to launch a Windows executable?

Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.

#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>

class process
{
public:

    static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)
    {

        // Prepare handles.
        STARTUPINFO si;
        PROCESS_INFORMATION pi; // The function returns this
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        //Prepare CreateProcess args
        std::wstring app_w(app.length(), L' '); // Make room for characters
        std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.

        std::wstring arg_w(arg.length(), L' '); // Make room for characters
        std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.

        std::wstring input = app_w + L" " + arg_w;
        wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );
        const wchar_t* app_const = app_w.c_str();

        // Start the child process.
        if( !CreateProcessW(
            app_const,      // app path
            arg_concat,     // Command line (needs to include app path as first argument. args seperated by whitepace)
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            NULL,           // Use parent's starting directory
            &si,            // Pointer to STARTUPINFO structure
            &pi )           // Pointer to PROCESS_INFORMATION structure
        )
        {
            printf( "CreateProcess failed (%d).\n", GetLastError() );
            throw std::exception("Could not create child process");
        }
        else
        {
            std::cout << "[          ] Successfully launched child process" << std::endl;
        }

        // Return process handle
        return pi;
    }

    static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)
    {
        // Check if handle is closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle is closed or invalid (%d).\n", GetLastError());
                return FALSE;
            }

        // If handle open, check if process is active
        DWORD lpExitCode = 0;
        if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)
        {
            printf( "Cannot return exit code (%d).\n", GetLastError() );
            throw std::exception("Cannot return exit code");
        }
        else
        {
            if (lpExitCode == STILL_ACTIVE)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

    static bool stopProcess( PROCESS_INFORMATION &pi)
    {
        // Check if handle is invalid or has allready been closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle invalid. Possibly allready been closed (%d).\n");
                return 0;
            }

        // Terminate Process
            if( !TerminateProcess(pi.hProcess,1))
            {
                printf( "ExitProcess failed (%d).\n", GetLastError() );
                return 0;
            }

        // Wait until child process exits.
            if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)
            {
                printf( "Wait for exit process failed(%d).\n", GetLastError() );
                return 0;
            }

        // Close process and thread handles.
            if( !CloseHandle( pi.hProcess ))
            {
                printf( "Cannot close process handle(%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                pi.hProcess = NULL;
            }

            if( !CloseHandle( pi.hThread ))
            {
                printf( "Cannot close thread handle (%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                 pi.hProcess = NULL;
            }
            return 1;
    }
};//class process
#endif //win32

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

Make a nav bar stick

You can do it with CSS only by creating your menu twice. It's not ideal but it gives you the opportunity have a different design for the menu once it's on top and you'll have nothing else than CSS, no jquery. Here is an example with DIV (you can of course change it to NAV if you prefer):

<div id="hiddenmenu">
 THIS IS MY HIDDEN MENU
</div>
<div id="header">
 Here is my header with a lot of text and my main menu
</div>
<div id="body">
 MY BODY
</div>

And then have the following CSS:

#hiddenmenu {
position: fixed;
top: 0;
z-index:1;
 }
#header {
top: 0;
position:absolute;
z-index:2;
 }
#body {
padding-top: 80px;
position:absolute;
z-index: auto;
 }

Here is a fiddle for you to see: https://jsfiddle.net/brghtk4z/1/

I cannot access tomcat admin console?

This is all I did and restarted the server.

<tomcat-users>

  <role rolename="tomcat"/>
  <user username="tomcat" password="tomcat" roles="manager-gui"/>

</tomcat-users>

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

MySQL vs MongoDB 1000 reads

Here is a little research that explored RDBMS vs NoSQL using MySQL vs Mongo, the conclusions were inline with @Sean Reilly's response. In short, the benefit comes from the design, not some raw speed difference. Conclusion on page 35-36:

RDBMS vs NoSQL: Performance and Scaling Comparison

The project tested, analysed and compared the performance and scalability of the two database types. The experiments done included running different numbers and types of queries, some more complex than others, in order to analyse how the databases scaled with increased load. The most important factor in this case was the query type used as MongoDB could handle more complex queries faster due mainly to its simpler schema at the sacrifice of data duplication meaning that a NoSQL database may contain large amounts of data duplicates. Although a schema directly migrated from the RDBMS could be used this would eliminate the advantage of MongoDB’s underlying data representation of subdocuments which allowed the use of less queries towards the database as tables were combined. Despite the performance gain which MongoDB had over MySQL in these complex queries, when the benchmark modelled the MySQL query similarly to the MongoDB complex query by using nested SELECTs MySQL performed best although at higher numbers of connections the two behaved similarly. The last type of query benchmarked which was the complex query containing two JOINS and and a subquery showed the advantage MongoDB has over MySQL due to its use of subdocuments. This advantage comes at the cost of data duplication which causes an increase in the database size. If such queries are typical in an application then it is important to consider NoSQL databases as alternatives while taking in account the cost in storage and memory size resulting from the larger database size.

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

If this seems inconsistent from machine to machine, have you made sure that some 3rd party app like virus scan isn't intercepting something?

Drop shadow for PNG image in CSS

In my case it had to work on modern mobile browsers, with a PNG image in different shapes and transparency. I created drop shadow using a duplicate of the image. That means I have two img elements of the same image, one on top of the other (using position: absolute), and the one behind has the following rules applied to it:

.image-shadow {
  filter: blur(10px) brightness(-100);
  -webkit-filter: blur(10px) brightness(-100);
  opacity: .5;
}

This includes brightness filter in order to darken the bottom image, and a blur filter in order to cast the smudgy effect drop shadow usually has. Opacity at 50% is then applied in order to soften it.

This can be applied cross browser using moz and ms flags.

Example: https://jsfiddle.net/5mLssm7o/

Checking letter case (Upper/Lower) within a string in Java

That's what I got:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter a nickname!");
    while (!scanner.hasNext("[a-zA-Z]{3,8}+")) {
        System.out.println("Nickname should contain only Alphabetic letters! At least 3 and max 8 letters");
        scanner.next();
    }
    String nickname = scanner.next();
    System.out.println("Thank you! Got " + nickname);

Read about regex Pattern here: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

SameSite warning Chrome 77

To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:

AllowSameSiteAttribute.cs

public class AllowSameSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;

        if(response != null)
        {
            response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
            //Add more headers...
        }

        base.OnActionExecuting(filterContext);
    }
}

HomeController.cs

    [AllowSameSite] //For the whole controller
    public class UserController : Controller
    {
    }

or

    public class UserController : Controller
    {
        [AllowSameSite] //For the method
        public ActionResult Index()
        {
            return View();
        }
    }

Show space, tab, CRLF characters in editor of Visual Studio

Display white space characters

Menu: You can toggle the visibility of the white space characters from the menu: Edit > Advanced > View White Space.

Button: If you want to add the button to a toolbar, it is called Toggle Visual Space in the command category "Edit".
The actual command name is: Edit.ViewWhiteSpace.

Keyboard Shortcut: In Visual Studio 2015, 2017 and 2019 the default keyboard shortcut still is CTRL+R, CTRL+W
Type one after the other.
All default shortcuts

End-of-line characters

Extension: There is a minimal extension adding the displaying of end-of-line characters (LF and CR) to the visual white space mode, as you would expect. Additionally it supplies buttons and short-cuts to modify all line-endings in a document, or a selection.
VisualStudio gallery: End of the Line

Note: Since Visual Studio 2017 there is no option in the File-menu called Advanced Save Options. Changing the encoding and line-endings for a file can be done using Save File As ... and clicking the down-arrow on the right side of the save-button. This shows the option Save with Encoding. You'll be asked permission to overwrite the current file.

WCF, Service attribute value in the ServiceHost directive could not be found

I had this problem - my service type was in the GAC. It WOULD work if i added the dll containing the type to the bin folder but as it was in the GAC this was NOT what I wanted. I eventually added this to the web.config for the service

<system.web>
    <customErrors mode="RemoteOnly" />
    <compilation debug="true" targetFramework="4.0">
        <assemblies>
            <add assembly="[name in GAC], Version=[version in GAC], Culture=neutral, PublicKeyToken=[ac token]" />
        </assemblies>
    </compilation>
</system.web>

and it worked without needing any dlls in the bin folder.

How to subtract days from a plain Date?

var my date = new Date().toISOString().substring(0, 10);

it can give you only date like 2014-06-20. hope will help

How to align absolutely positioned element to center?

If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.

position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;

Convert UTC Epoch to local date

I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

Comparing two byte arrays in .NET

Couldn't find a solution I'm completely happy with (reasonable performance, but no unsafe code/pinvoke) so I came up with this, nothing really original, but works:

    /// <summary>
    /// 
    /// </summary>
    /// <param name="array1"></param>
    /// <param name="array2"></param>
    /// <param name="bytesToCompare"> 0 means compare entire arrays</param>
    /// <returns></returns>
    public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)
    {
        if (array1.Length != array2.Length) return false;

        var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;
        var tailIdx = length - length % sizeof(Int64);

        //check in 8 byte chunks
        for (var i = 0; i < tailIdx; i += sizeof(Int64))
        {
            if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;
        }

        //check the remainder of the array, always shorter than 8 bytes
        for (var i = tailIdx; i < length; i++)
        {
            if (array1[i] != array2[i]) return false;
        }

        return true;
    }

Performance compared with some of the other solutions on this page:

Simple Loop: 19837 ticks, 1.00

*BitConverter: 4886 ticks, 4.06

UnsafeCompare: 1636 ticks, 12.12

EqualBytesLongUnrolled: 637 ticks, 31.09

P/Invoke memcmp: 369 ticks, 53.67

Tested in linqpad, 1000000 bytes identical arrays (worst case scenario), 500 iterations each.

Calling JavaScript Function From CodeBehind

I used ScriptManager in Code Behind and it worked fine.

ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);

If you are using UpdatePanel in ASP Frontend. Then, enter UpdatePanel name and 'function name' defined with script tags.

How to load local html file into UIWebView

if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
    do{
        let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
        webView.loadHTMLString(htmlString as String, baseURL: nil)
    }
    catch _ {
    }
}

Using "super" in C++

is this use of typedef super common/rare/never seen in the code you work with?

I have never seen this particular pattern in the C++ code I work with, but that doesn't mean it's not out there.

is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?

It doesn't allow for multiple inheritance (cleanly, anyway).

should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?

For the above cited reason (multiple inheritance), no. The reason why you see "super" in the other languages you listed is that they only support single inheritance, so there is no confusion as to what "super" is referring to. Granted, in those languages it IS useful but it doesn't really have a place in the C++ data model.

Oh, and FYI: C++/CLI supports this concept in the form of the "__super" keyword. Please note, though, that C++/CLI doesn't support multiple inheritance either.

How do I make an input field accept only letters in javaScript?

Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.

Common elements comparison between 2 lists

The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result list and collecting the common elements in that list:

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

An even shorter version using list comprehensions:

def common_elements(list1, list2):
    return [element for element in list1 if element in list2]

However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

I got this error and I think its the same reason of yours

error while loading shared libraries: libnw.so: cannot open shared object file: No such file or directory

Try this. Fix permissions on files:

cd /opt/Popcorn (or wherever it is) 
chmod -R 555 * (755 if not ok) 

Can't resolve module (not found) in React.js

You need to be in project folder, if you are in src or public you have to come out of those folders. Suppose your react-project name is 'hello-react' then cd hello-react

Room persistance library. Delete all

Use clearAllTables() with RXJava like below inorder to avoid java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            getRoomDatabase().clearAllTables();
        }
    }).subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Action() {
                @Override
                public void run() throws Exception {
                    Log.d(TAG, "--- clearAllTables(): run() ---");
                    getInteractor().setUserAsLoggedOut();
                    getMvpView().openLoginActivity();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
                    Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());


                }
            });

How to create a HTML Cancel button that redirects to a URL

There are a few problems here.

First of all, there is no such thing as <button type="cancel">, so it is treated as just a <button>. This means that your form will be submitted, instead of the button taking you elsewhere.

Second, javascript: is only needed in href or action attributes, where a URL is expected, to designate JavaScript code. Inside onclick, where JavaScript is already expected, it merely acts as a label and serves no real purpose.

Finally, it's just generally better design to have a cancel link rather than a cancel button. So you can just do this:

<a href="http://stackoverflow.com/">Cancel</a>

With CSS you can even make it look the same as a button, but with this HTML there is absolutely no confusion as to what it is supposed to do.

jQuery post() with serialize and extra data

Try $.param

$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));

Convert XML String to Object

Another way with an Advanced xsd to c# classes generation Tools : xsd2code.com. This tool is very handy and powerfull. It has a lot more customisation than the xsd.exe tool from Visual Studio. Xsd2Code++ can be customised to use Lists or Arrays and supports large schemas with a lot of Import statements.

Note of some features,

  • Generates business objects from XSD Schema or XML file to flexible C# or Visual Basic code.
  • Support Framework 2.0 to 4.x
  • Support strong typed collection (List, ObservableCollection, MyCustomCollection).
  • Support automatic properties.
  • Generate XML read and write methods (serialization/deserialization).
  • Databinding support (WPF, Xamarin).
  • WCF (DataMember attribute).
  • XML Encoding support (UTF-8/32, ASCII, Unicode, Custom).
  • Camel case / Pascal Case support.
  • restriction support ([StringLengthAttribute=true/false], [RegularExpressionAttribute=true/false], [RangeAttribute=true/false]).
  • Support large and complex XSD file.
  • Support of DotNet Core & standard

Bash scripting, multiple conditions in while loop

The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.

Alternatively:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]

How many files can I put in a directory?

What most of the answers above fail to show is that there is no "One Size Fits All" answer to the original question.

In today's environment we have a large conglomerate of different hardware and software -- some is 32 bit, some is 64 bit, some is cutting edge and some is tried and true - reliable and never changing. Added to that is a variety of older and newer hardware, older and newer OSes, different vendors (Windows, Unixes, Apple, etc.) and a myriad of utilities and servers that go along. As hardware has improved and software is converted to 64 bit compatibility, there has necessarily been considerable delay in getting all the pieces of this very large and complex world to play nicely with the rapid pace of changes.

IMHO there is no one way to fix a problem. The solution is to research the possibilities and then by trial and error find what works best for your particular needs. Each user must determine what works for their system rather than using a cookie cutter approach.

I for example have a media server with a few very large files. The result is only about 400 files filling a 3 TB drive. Only 1% of the inodes are used but 95% of the total space is used. Someone else, with a lot of smaller files may run out of inodes before they come near to filling the space. (On ext4 filesystems as a rule of thumb, 1 inode is used for each file/directory.) While theoretically the total number of files that may be contained within a directory is nearly infinite, practicality determines that the overall usage determine realistic units, not just filesystem capabilities.

I hope that all the different answers above have promoted thought and problem solving rather than presenting an insurmountable barrier to progress.

Assign a synthesizable initial value to a reg in Verilog

When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.

This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.

always @(posedge clk) begin
    if (reset == 1) begin // For an active high reset
        data_reg = 8'b10101011;
    end else begin
        data_reg = next_data_reg;
    end
end

Recursive directory listing in DOS

dir /s /b /a:d>output.txt will port it to a text file

How do you import classes in JSP?

In the page tag:

<%@ page import="java.util.List" %>

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

How to force a line break on a Javascript concatenated string?

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

How to return a resolved promise from an AngularJS Service using $q?

To return a resolved promise, you can use:

return $q.defer().resolve();

If you need to resolve something or return data:

return $q.defer().resolve(function(){

    var data;
    return data;

});

Prevent flex items from overflowing a container

It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width on the offending element/container can put it back in line.

Stop node.js program from command line

My use case: on MacOS, run/rerun multiple node servers on different ports from a script

run: "cd $PATH1 && node server1.js & cd $PATH2 && node server2.js & ..."

stop1: "kill -9 $(lsof -nP -i4TCP:$PORT1 | grep LISTEN | awk '{print $2}')"

stop2, stop3...

rerun: "stop1 & stop2 & ... & stopN ; run

for more info about finding a process by a port: Who is listening on a given TCP port on Mac OS X?

arranging div one below the other

You don't even need the float:left;

It seems the default behavior is to render one below the other, if it doesn't happen it's because they are inheriting some style from above.

CSS:

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
}
</style>

HTML:

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

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

Creating multiline strings in JavaScript

My extension to https://stackoverflow.com/a/15558082/80404. It expects comment in a form /*! any multiline comment */ where symbol ! is used to prevent removing by minification (at least for YUI compressor)

Function.prototype.extractComment = function() {
    var startComment = "/*!";
    var endComment = "*/";
    var str = this.toString();

    var start = str.indexOf(startComment);
    var end = str.lastIndexOf(endComment);

    return str.slice(start + startComment.length, -(str.length - end));
};

Example:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();

Twitter bootstrap scrollable modal

I also added

.modal { position: absolute; }

to the stylesheet to allow the dialog to scroll, but if the user has moved down to the bottom of a long page the modal can end up hidden off the top of the visible area.

I understand this is no longer an issue in bootstrap 3, but looking for a relatively quick fix until we upgrade I ended up with the above plus calling the following before opening the modal

$('.modal').css('top', $(document).scrollTop() + 50);

Seems to be happy in FireFox, Chrome, IE10 8 & 7 (the browsers I had to hand)

jquery $(this).id return Undefined

$(this) and this aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id property exists on the element, but not the jQuery object. As such, you have a few options:

  1. Access the property on the element directly:

    this.id

  2. Access it from the jQuery object:

    $(this).attr("id")

  3. Pull the object out of jQuery:

    $(this).get(0).id; // Or $(this)[0].id

  4. Get the id from the event object:

    When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget and target.

    Using target, you can get the id of the element that raised the event. currentTarget would simply tell you which element the event is currently bubbling through. These are not always the same.

    $("#button").on("click", function(e){ console.log( e.target.id ) });

Of all of these, the best option is to just access it directly from this itself, unless you're engaged in a series of nested events, then it might be best to use the event object of each nested event (give them all unique names) to reference elements in higher or lower scopes.

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Responsive iframe using Bootstrap

Option 3

To update current iframe

$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');

How to show SVG file on React Native?

Note: Svg does not work for android release versions so do not consider for android. It will work for android in debug mode only. But it works fine for ios.

Use https://github.com/vault-development/react-native-svg-uri

Install

npm install react-native-svg-uri --save
react-native link react-native-svg # not react-native-svg-uri

Usage

import SvgUri from 'react-native-svg-uri';


<SvgUri source={require('./path_to_image/image.svg')} />

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

HttpClient 4.0.1 - how to release connection?

This seems to work great :

      if( response.getEntity() != null ) {
         response.getEntity().consumeContent();
      }//if

And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !

reCAPTCHA ERROR: Invalid domain for site key

There is another point must be noted before regenerating keys that resolve 90% issue.

for example your xampp directory is C:\xampp

and htdocs folder is C:\xampp\htdocs

we want to open page called: example-cap.html and page is showing error "invalid domain for site key"

USE YOUR LOCALHOST ADDRESS in browser address like:

localhost/example-cap.html

this will resolve your issue

DONOT USE ADDRESS c:\xampp\htdocs\example-cap.html this will generate error

C#: Limit the length of a string?

string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;

Note that you can't just use foo.Substring(0, 5) by itself because it will throw an error when foo is less than 5 characters.

Save Javascript objects in sessionStorage

This is a dynamic solution which works with all value types including objects :

class Session extends Map {
  set(id, value) {
    if (typeof value === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(id, value);
  }

  get(id) {
    const value = sessionStorage.getItem(id);
    try {
      return JSON.parse(value);
    } catch (e) {
      return value;
    }
  }
}

Then :

const session = new Session();

session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');

How to generate .NET 4.0 classes from xsd?

I show you here the easiest way using Vs2017 and Vs2019 Open your xsd with Visual Studio and generate a sample xml file as in the url suggested.

  1. Once you opened your xsd in design view as below, click on xml schema explorer enter image description here

2. Within “XML Schema Explorer” scroll all the way down to find the root/data node. Right click on root/data node and it will show “Generate Sample XML”. If it does not show, it means you are not on the data element node but you are on any of the data definition node.

enter image description here

  1. Copy your generated Xml into the clipboard
  2. Create a new empty class in your solution and delete the class definition. Only Namespace should remain
  3. While your mouse pointer focused inside your class, choose EDIT-> Paste Special-> Paste Xml as Classes

SQL Server SELECT LAST N Rows

Is "Id" indexed? If not, that's an important thing to do (I suspect it is already indexed).

Also, do you need to return ALL columns? You may be able to get a substantial improvement in speed if you only actually need a smaller subset of columns which can be FULLY catered for by the index on the ID column - e.g. if you have a NONCLUSTERED index on the Id column, with no other fields included in the index, then it would have to do a lookup on the clustered index to actually get the rest of the columns to return and that could be making up a lot of the cost of the query. If it's a CLUSTERED index, or a NONCLUSTERED index that includes all the other fields you want to return in the query, then you should be fine.

ProgressDialog spinning circle

Just change from ProgressDialog to ProgressBar in a layout:

res/layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        //Your content here
     </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"
            android:indeterminateDrawable="@drawable/progress" >
        </ProgressBar>
</RelativeLayout>

src/yourPackage/YourActivity.java

public class YourActivity extends Activity{

private ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    bar = (ProgressBar) this.findViewById(R.id.progressBar);
    new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
    @Override
    protected void onPreExecute(){
        bar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... arg0) {   
           //my stuff is here
    }

    @Override
    protected void onPostExecute(Void result) {
          bar.setVisibility(View.GONE);
    }
}
}

drawable/progress.xml This is a custom ProgressBar that i use to change the default colors.

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

<!-- 
    Duration = 1 means that one rotation will be done in 1 second. leave it.
    If you want to speed up the rotation, increase duration value. 
    in example 1080 shows three times faster revolution. 
    make the value multiply of 360, or the ring animates clunky 
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >
        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
            android:startColor="@color/color_preloader_start"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

index.php not loading by default

While adding 'DirectoryIndex index.php' to a .htaccess file may work,

NOTE:

In general, you should never use .htaccess files

This is quoted from http://httpd.apache.org/docs/1.3/howto/htaccess.html
Although this refers to an older version of apache, I believe the principle still applies.

Adding the following to your httpd.conf (if you have access to it) is considered better form, causes less server overhead and has the exact same effect:

<Directory /myapp>
DirectoryIndex index.php
</Directory>

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

AngularJS 1.2 $injector:modulerr

If you go through the official tutorial of angularjs https://docs.angularjs.org/tutorial/step_07

Note: Starting with AngularJS version 1.2, ngRoute is in its own module and must be loaded by loading the additional angular-route.js file, which we download via Bower above.

Also please note from ngRoute api https://docs.angularjs.org/api/ngRoute

Installation First include angular-route.js in your HTML:

You can download this file from the following places:

Google CDN e.g. //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js Bower e.g. bower install [email protected] code.angularjs.org e.g. "//code.angularjs.org/X.Y.Z/angular-route.js" where X.Y.Z is the AngularJS version you are running.

Then load the module in your application by adding it as a dependent module:

angular.module('app', ['ngRoute']); With that you're ready to get started!

'mat-form-field' is not a known element - Angular 5 & Material2

@NgModule({
  declarations: [
    SearchComponent
  ],
  exports: [
    CommonModule,
    MatInputModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatDialogModule,
  ]
})
export class MaterialModule { }

Also, do not forget to import the MaterialModule in the imports array of AppModule.

Android difference between Two Dates

I arranged a little. This works great.

@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
    Date date = new Date();
    String dateOfDay = simpleDateFormat.format(date);

    String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();

    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
    try {
        Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
        Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);

        printDifference(date1, date2);

    } catch (ParseException e) {
        e.printStackTrace();
    }

@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}

How do you change the colour of each category within a highcharts column chart?

You can also set the color individually for each point/bar if you change the data array to be configuration objects instead of numbers.

data: [
      {y: 34.4, color: 'red'},     // this point is red
      21.8,                        // default blue
      {y: 20.1, color: '#aaff99'}, // this will be greenish
      20]                          // default blue

Example on jsfiddle

enter image description here

CSS no text wrap

Use the css property overflow . For example:

  .item{
    width : 100px;
    overflow:hidden;
  }

The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.

I hope this helps.

Concatenate two JSON objects

okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.

json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';

json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

Reading and writing binary file

Here is a short example, the C++ way using rdbuf. I got this from the web. I can't find my original source on this:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

How do I get the SharedPreferences from a PreferenceActivity in Android?

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

How to validate an e-mail address in swift?

Swift 5

 func isValidEmailAddress(emailAddressString: String) -> Bool {

 var returnValue = true
 let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"

 do {
        let regex = try NSRegularExpression(pattern: emailRegEx)
        let nsString = emailAddressString as NSString
        let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

Then:

let validEmail = isValidEmailAddress(emailAddressString: "[email protected]")
print(validEmail)

How can I get key's value from dictionary in Swift?

For finding value use below

if let a = companies["AAPL"] {
   // a is the value
}

For traversing through the dictionary

for (key, value) in companies {
    print(key,"---", value)
}

Finally for searching key by value you firstly add the extension

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

Then just call

companies.findKey(val : "Apple Inc")

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

You did not need

Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted

the only thing what you need is...

Require all granted

...inside the directory section.

See Apache 2.4 upgrading side:

http://httpd.apache.org/docs/2.4/upgrading.html

Swift: Testing optionals for nil

Although you must still either explicitly compare an optional with nil or use optional binding to additionally extract its value (i.e. optionals are not implicitly converted into Boolean values), it's worth noting that Swift 2 has added the guard statement to help avoid the pyramid of doom when working with multiple optional values.

In other words, your options now include explicitly checking for nil:

if xyz != nil {
    // Do something with xyz
}

Optional binding:

if let xyz = xyz {
    // Do something with xyz
    // (Note that we can reuse the same variable name)
}

And guard statements:

guard let xyz = xyz else {
    // Handle failure and then exit this code block
    // e.g. by calling return, break, continue, or throw
    return
}

// Do something with xyz, which is now guaranteed to be non-nil

Note how ordinary optional binding can lead to greater indentation when there is more than one optional value:

if let abc = abc {
    if let xyz = xyz {
        // Do something with abc and xyz
    }        
}

You can avoid this nesting with guard statements:

guard let abc = abc else {
    // Handle failure and then exit this code block
    return
}

guard let xyz = xyz else {
    // Handle failure and then exit this code block
    return
}

// Do something with abc and xyz

How to prevent a background process from being stopped after closing SSH client in Linux

Accepted answer suggest using nohup. I would rather suggest using pm2. Using pm2 over nohup has many advantages, like keeping the application alive, maintain log files for application and lot more other features. For more detail check this out.

To install pm2 you need to download npm. For Debian based system

sudo apt-get install npm

and for Redhat

sudo yum install npm

Or you can follow these instruction. After installing npm use it to install pm2

npm install pm2@latest -g

Once its done you can start your application by

$ pm2 start app.js              # Start, Daemonize and auto-restart application (Node)
$ pm2 start app.py              # Start, Daemonize and auto-restart application (Python)

For process monitoring use following commands:

$ pm2 list                      # List all processes started with PM2
$ pm2 monit                     # Display memory and cpu usage of each app
$ pm2 show [app-name]           # Show all informations about application

Manage processes using either app name or process id or manage all processes together:

$ pm2 stop     <app_name|id|'all'|json_conf>
$ pm2 restart  <app_name|id|'all'|json_conf>
$ pm2 delete   <app_name|id|'all'|json_conf>

Log files can be found in

$HOME/.pm2/logs #contain all applications logs

Binary executable files can also be run using pm2. You have to made a change into the jason file. Change the "exec_interpreter" : "node", to "exec_interpreter" : "none". (see the attributes section).

#include <stdio.h>
#include <unistd.h>  //No standard C library
int main(void)
{
    printf("Hello World\n");
    sleep (100);
    printf("Hello World\n");

    return 0;
}

Compiling above code

gcc -o hello hello.c  

and run it with np2 in the background

pm2 start ./hello

Spring REST Service: how to configure to remove null objects in json response

As of Jackson 2.0, @JsonSerialize(include = xxx) has been deprecated in favour of @JsonInclude

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

The example URLs for standard gmail, above, return a google error.

The February 2014 post to thread 2583928 recommends replacing view=cm&fs=1&tf=1 with &v=b&cs=wh.

Note: It also no longer seems possible to autopopulate the mail body.

What is the most compatible way to install python modules on a Mac?

Directly install one of the fink packages (Django 1.6 as of 2013-Nov)

fink install django-py27
fink install django-py33

Or create yourself a virtualenv:

fink install virtualenv-py27
virtualenv django-env
source django-env/bin/activate
pip install django
deactivate # when you are done

Or use fink django plus any other pip installed packages in a virtualenv

fink install django-py27
fink install virtualenv-py27
virtualenv django-env --system-site-packages
source django-env/bin/activate
# django already installed
pip install django-analytical # or anything else you might want
deactivate # back to your normally scheduled programming

Illegal string offset Warning PHP

In my case, I solved it when I changed in function that does sql query after: return json_encode($array) then: return $array

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Cannot find "Package Explorer" view in Eclipse

Not all view are listed directly in every perspective ... choose:

Window->Show View->Other...->Java->Package Explorer

How do I split a string into an array of characters?

The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated. But, if you specify the empty string as a separator, the string is split between each character.

Therefore:

s.split('')

will have the effect you seek.

More information here

Making button go full-width?

Bootstrap v3 & v4

Use btn-block class on your button/element

Bootstrap v2

Use input-block-level class on your button/element

How do I rotate a picture in WinForms

This solution assumes that you want to draw the image in a picture box and that the image orientation will follow the mouse movements over this picture box. No image is assigned to the picture box. Instead I'm getting the image from a project resource.

private float _angle;

public Form1()
{
    InitializeComponent();
}

private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
    (float centerX, float centerY) = GetCenter(pictureBox1.ClientRectangle);
    _angle = (float)(Math.Atan2(e.Y - centerY, e.X - centerX) * 180.0 / Math.PI);
    pictureBox1.Invalidate(); // Triggers redrawing
}

private void PictureBox_Paint(object sender, PaintEventArgs e)
{
    Bitmap image = Properties.Resources.ExampleImage;
    float scale = (float)pictureBox1.Width / image.Width;

    (float centerX, float centerY) = GetCenter(e.ClipRectangle);

    e.Graphics.TranslateTransform(centerX, centerY);
    e.Graphics.RotateTransform(_angle);
    e.Graphics.TranslateTransform(-centerX, -centerY);
    e.Graphics.ScaleTransform(scale, scale);
    e.Graphics.DrawImage(image, 0, 0);
}

// Uses C# 7.0 value tuples / .NET Framework 4.7.
// For previous versions, return a PointF instead.
private static (float, float) GetCenter(Rectangle rect)
{
    float centerX = (rect.Left + rect.Right) * 0.5f;
    float centerY = (rect.Top + rect.Bottom) * 0.5f;
    return (centerX, centerY);
}

Make sure to to select the mouse event handlers PictureBox_MouseMove and PictureBox_Paint in properties window of the picture box for these events, after you copy/pasted this code into the form.

Note: You could also use a simple Panel or any other control, like a label; however, the PictureBox has the advantage to use double buffering by default, which eliminates flickering.

Return outside function error in Python

It basically occours when you return from a loop you can only return from function

How would I find the second largest salary from the employee table?

select max(Emp_Sal) 
from Employee a
where 1 = ( select count(*) 
         from Employee b
         where b.Emp_Sal > a.Emp_Sal)

Yes running man.

Git - remote: Repository not found

For Mac

Open KeyChain Access and find your pssword account on password category ( you can search it on top right keychain access page)

when you find it , delete all keys related to your git source control. and try it again

enter image description here

How to redirect to Login page when Session is expired in Java web application?

Until the session timeout we get a normal request, after which we get an Ajax request. We can identify it the following way:

String ajaxRequestHeader = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
    response.sendRedirect("/login.jsp");
}

Java: how to initialize String[]?

String[] errorSoon = { "foo", "bar" };

-- or --

String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";

How do I use WPF bindings with RelativeSource?

In WPF RelativeSource binding exposes three properties to set:

1. Mode: This is an enum that could have four values:

a. PreviousData(value=0): It assigns the previous value of the property to the bound one

b. TemplatedParent(value=1): This is used when defining the templates of any control and want to bind to a value/Property of the control.

For example, define ControlTemplate:

  <ControlTemplate>
        <CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
 </ControlTemplate>

c. Self(value=2): When we want to bind from a self or a property of self.

For example: Send checked state of checkbox as CommandParameter while setting the Command on CheckBox

<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />

d. FindAncestor(value=3): When want to bind from a parent control in Visual Tree.

For example: Bind a checkbox in records if a grid,if header checkbox is checked

<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />

2. AncestorType: when mode is FindAncestor then define what type of ancestor

RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}

3. AncestorLevel: when mode is FindAncestor then what level of ancestor (if there are two same type of parent in visual tree)

RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}

Above are all use-cases for RelativeSource binding.

Here is a reference link.

How to encrypt a large file in openssl using public key

I found the instructions at http://www.czeskis.com/random/openssl-encrypt-file.html useful.

To paraphrase the linked site with filenames from your example:

Generate a symmetric key because you can encrypt large files with it

openssl rand -base64 32 > key.bin

Encrypt the large file using the symmetric key

openssl enc -aes-256-cbc -salt -in myLargeFile.xml \
  -out myLargeFile.xml.enc -pass file:./key.bin

Encrypt the symmetric key so you can safely send it to the other person

openssl rsautl -encrypt -inkey public.pem -pubin -in key.bin -out key.bin.enc

Destroy the un-encrypted symmetric key so nobody finds it

shred -u key.bin

At this point, you send the encrypted symmetric key (key.bin.enc) and the encrypted large file (myLargeFile.xml.enc) to the other person

The other person can then decrypt the symmetric key with their private key using

openssl rsautl -decrypt -inkey private.pem -in key.bin.enc -out key.bin

Now they can use the symmetric key to decrypt the file

openssl enc -d -aes-256-cbc -in myLargeFile.xml.enc \
  -out myLargeFile.xml -pass file:./key.bin

And you're done. The other person has the decrypted file and it was safely sent.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Fwiw, I downloaded the standard Java EE version of the Mars version of Eclipse, and ran into the same deal -- didn't see a Web option if I tried File >>> New >>> Project wizard.

The good news: Probably no extra installation needed.

It looks like what I wanted was to select the Other option rather than the Project item (strangely this is what comes up when you hit Ctrl-N, but that also lets us know we're probably on the right track):

Screenshot of the new project menu hierarchy with "Other" highlighted.

After you select "Other", you'll see the "Select a wizard" screen, where you can select "Dynamic Web Project" and profit.

Dynamic Web Project highlighted in Select a wizard screen.

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

you can use

style="display:none"

Ex:

<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>

HTML form with two submit buttons and two "target" attributes

Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!

<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">

<input type="submit"  name="scheduled" value="Schedule Emails">
<input type="submit"  name="single" value="Email Now">
</form>

twosubmits.php

<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}

if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>

Tool to Unminify / Decompress JavaScript

click on these link for JS deminification. That will install on FF as extension that help you in debugging js at runtime.

https://addons.mozilla.org/en-US/firefox/addon/javascript-deminifier/eula/141018?src=dp-btn-primary

How to handle checkboxes in ASP.NET MVC forms?

From what I can gather, the model doesn't want to guess whether checked = true or false, I got around this by setting a value attribute on the checkbox element with jQuery before submitting the form like this:

 $('input[type="checkbox"]').each(function () {
       $(this).attr('value', $(this).is(':checked'));
 }); 

This way, you don't need a hidden element just to store the value of the checkbox.

using lodash .groupBy. how to add your own keys for grouped output?

Highest voted answer uses Lodash _.chain function which is considered a bad practice now "Why using _.chain is a mistake."

Here is a fewliner that approaches the problem from functional programming perspective:

import tap from "lodash/fp/tap";
import flow from "lodash/fp/flow";
import groupBy from "lodash/fp/groupBy";

const map = require('lodash/fp/map').convert({ 'cap': false });

const result = flow(
      groupBy('color'),
      map((users, color) => ({color, users})),
      tap(console.log)
    )(input)

Where input is an array that you want to convert.

How do I use HTML as the view engine in Express?

The answers at the other link will work, but to serve out HTML, there is no need to use a view engine at all, unless you want to set up funky routing. Instead, just use the static middleware:

app.use(express.static(__dirname + '/public'));

Time complexity of nested for-loop

First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:

 for (i = 0; i < N; i++) {
     for (j = 0; j < M; j++) {
         sequence of statements
      }
  }

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).

How to change the session timeout in PHP?

Put $_SESSION['login_time'] = time(); into the previous authentication page. And the snipped below in every other page where you want to check the session time-out.

if(time() - $_SESSION['login_time'] >= 1800){
    session_destroy(); // destroy session.
    header("Location: logout.php");
    die(); // See https://thedailywtf.com/articles/WellIntentioned-Destruction
    //redirect if the page is inactive for 30 minutes
}
else {        
   $_SESSION['login_time'] = time();
   // update 'login_time' to the last time a page containing this code was accessed.
}

Edit : This only works if you already used the tweaks in other posts, or disabled Garbage Collection, and want to manually check the session duration. Don't forget to add die() after a redirect, because some scripts/robots might ignore it. Also, directly destroying the session with session_destroy() instead of relying on a redirect for that might be a better option, again, in case of a malicious client or a robot.

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

Inserting values into tables Oracle SQL

You can insert into a table from a SELECT.

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  (SELECT id FROM state WHERE name = 'New York'),
  (SELECT id FROM positions WHERE name = 'Sales Executive'),
  (SELECT id FROM manager WHERE name = 'Barry Green')
FROM
  dual

Or, similarly...

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  state.id,
  positions.id,
  manager.id
FROM
  state
CROSS JOIN
  positions
CROSS JOIN
  manager
WHERE
      state.name     = 'New York'
  AND positions.name = 'Sales Executive'
  AND manager.name   = 'Barry Green'

Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

Where is my m2 folder on Mac OS X Mavericks

By default it will be hidden in your home directory. Type ls -a ~ to view that.

AppFabric installation failed because installer MSI returned with error code : 1603

I had a similar problem

9/21/2012 11:28:01 AM EXEPATH=powershell.exe PARAMS=-command "$str = [System.Environment]::GetEnvironmentVariable(\"PSModulePath\", [System.EnvironmentVariableTarget]::Machine); $str = $str+\";c:\Program Files\AppFabric 1.1 for Windows Server\PowershellModules\"; c:\Windows\system32\setx.exe /M PSModulePath \"$str\"" LOGFILE=C:\Users\XXXXXXX\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2012-09-21 11-27-26).log Error: ERROR: Invalid syntax. Default option is not allowed more than '2' time(s). Error: Type "SETX /?" for usage.

My issue was the PSModulePath having an improper " in it

it was:

C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules"

removing the extraneous " corrected the issue

To change this go to Control Panel -> System -> Advanced System Settings -> On the Advanced Tab Select Enviroment Variables -> Under System Variables there is a Variable named PSModulePath, select it -> Click Edit -> Remove trailing "

System Properties

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

How can jQuery deferred be used?

1) Use it to ensure an ordered execution of callbacks:

var step1 = new Deferred();
var step2 = new Deferred().done(function() { return step1 });
var step3 = new Deferred().done(function() { return step2 });

step1.done(function() { alert("Step 1") });
step2.done(function() { alert("Step 2") });
step3.done(function() { alert("All done") });
//now the 3 alerts will also be fired in order of 1,2,3
//no matter which Deferred gets resolved first.

step2.resolve();
step3.resolve();
step1.resolve();

2) Use it to verify the status of the app:

var loggedIn = logUserInNow(); //deferred
var databaseReady = openDatabaseNow(); //deferred

jQuery.when(loggedIn, databaseReady).then(function() {
  //do something
});

Get the closest number out of an array

This solution uses ES5 existential quantifier Array#some, which allows to stop the iteration, if a condition is met.

Opposit of Array#reduce, it does not need to iterate all elements for one result.

Inside the callback, an absolute delta between the searched value and actual item is taken and compared with the last delta. If greater or equal, the iteration stops, because all other values with their deltas are greater than the actual value.

If the delta in the callback is smaller, then the actual item is assigned to the result and the delta is saved in lastDelta.

Finally, smaller values with equal deltas are taken, like in the below example of 22, which results in 2.

If there is a priority of greater values, the delta check has to be changed from:

if (delta >= lastDelta) {

to:

if (delta > lastDelta) {
//       ^^^ without equal sign

This would get with 22, the result 42 (Priority of greater values).

This function needs sorted values in the array.


Code with priority of smaller values:

_x000D_
_x000D_
function closestValue(array, value) {_x000D_
    var result,_x000D_
        lastDelta;_x000D_
_x000D_
    array.some(function (item) {_x000D_
        var delta = Math.abs(value - item);_x000D_
        if (delta >= lastDelta) {_x000D_
            return true;_x000D_
        }_x000D_
        result = item;_x000D_
        lastDelta = delta;_x000D_
    });_x000D_
    return result;_x000D_
}_x000D_
_x000D_
var data = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
_x000D_
console.log(21, closestValue(data, 21)); // 2_x000D_
console.log(22, closestValue(data, 22)); // 2  smaller value_x000D_
console.log(23, closestValue(data, 23)); // 42_x000D_
console.log(80, closestValue(data, 80)); // 82
_x000D_
_x000D_
_x000D_

Code with priority of greater values:

_x000D_
_x000D_
function closestValue(array, value) {_x000D_
    var result,_x000D_
        lastDelta;_x000D_
_x000D_
    array.some(function (item) {_x000D_
        var delta = Math.abs(value - item);_x000D_
        if (delta > lastDelta) {_x000D_
            return true;_x000D_
        }_x000D_
        result = item;_x000D_
        lastDelta = delta;_x000D_
    });_x000D_
    return result;_x000D_
}_x000D_
_x000D_
var data = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
_x000D_
console.log(21, closestValue(data, 21)); //  2_x000D_
console.log(22, closestValue(data, 22)); // 42 greater value_x000D_
console.log(23, closestValue(data, 23)); // 42_x000D_
console.log(80, closestValue(data, 80)); // 82
_x000D_
_x000D_
_x000D_

Git Symlinks in Windows

I was looking for an easy solution to deal with the unix symbolic links on windows. Thank you very much for the above Git aliases. There is one little optimization that can be done to the rm-symlinks so that it doesn't delete the files in the destination folder in case the alias is run a second time accidentally. Please observe the new if condition in the loop to make sure the file is not already a link to a directory before the logic is run.

git config --global alias.rm-symlinks '!__git_rm_symlinks(){
for symlink in $(git ls-files -s | egrep "^120000" | cut -f2); do
    *if [ -d "$symlink" ]; then
      continue
    fi*
    git rm-symlink "$symlink"
    git update-index --assume-unchanged "$symlink"
done
}; __git_rm_symlinksenter 

How can I have a newline in a string in sh?

I'm no bash expert, but this one worked for me:

STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1

$STR2
EOF
)
echo "$NEWSTR"

I found this easier to formatting the texts.

VBA: Convert Text to Number

For large datasets a faster solution is required.

Making use of 'Text to Columns' functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

Image library for Python 3

Qt works very well with graphics. In my opinion it is more versatile than PIL.

You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter.

To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.

Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:

from PySide.QtCore import *
from PySide.QtGui import *

app = QCoreApplication([])

img = QImage('input.jpg')

g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()

img.save('output.png')

But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.

Bootstrap 3 Glyphicons CDN

Although Bootstrap CDN restored glyphicons to bootstrap.min.css, Bootstrap CDN's Bootswatch css files doesn't include glyphicons.

For example Amelia theme: http://bootswatch.com/amelia/

Default Amelia has glyphicons in this file: http://bootswatch.com/amelia/bootstrap.min.css

But Bootstrap CDN's css file doesn't include glyphicons: http://netdna.bootstrapcdn.com/bootswatch/3.0.0/amelia/bootstrap.min.css

So as @edsioufi mentioned, you should include you should include glphicons css, if you use Bootswatch files from the bootstrap CDN. File: http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css

Reset MySQL root password using ALTER USER statement after install on Mac

In mysql 5.7.x(replication) this issue can happen because the on the slave user either the password is unmatched or the root user does not exists on master.

For example(in my case):

I created an instance, altered password for the root and before replicating the slave, I dropped the root user. When I made the slave instance this alert appeared on the query: (because I altered the password on master before dropping the root user, and slave was reading from the first log which was actually an alter root user statement)

show slave status\G

So there are 2 solutions that can be applied here:

  1. you can create root user on master host and slave host with same password
  2. you can run the query on master hostreset master;

and reconnect slave to master.

How can I determine browser window size on server side C#

So here is how you will do it.

Write a javascript function which fires whenever the window is resized.

window.onresize = function(event) {
    var height=$(window).height();
    var width=$(window).width();
    $.ajax({
     url: "/getwindowsize.ashx",
     type: "POST",
     data : { Height: height, 
              Width:width, 
              selectedValue:selectedValue },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (response) { 
           // do stuff
     }

}

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
     string Height = context.Request.QueryString["Height"]; 
     string Width = context.Request.QueryString["Width"]; 
    }

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

How to retrieve the current version of a MySQL database management system (DBMS)?

SHOW VARIABLES LIKE "%version%";
+-------------------------+------------------------------------------+
| Variable_name           | Value                                    |
+-------------------------+------------------------------------------+
| protocol_version        | 10                                       |
| version                 | 5.0.27-standard                          |
| version_comment         | MySQL Community Edition - Standard (GPL) |
| version_compile_machine | i686                                     |
| version_compile_os      | pc-linux-gnu                             |
+-------------------------+------------------------------------------+
5 rows in set (0.04 sec)

MySQL 5.0 Reference Manual (pdf) - Determining Your Current MySQL Version - page 42

Auto-size dynamic text to fill fixed size container

EDIT: This code was used to show notes on top of a HTML5 video. It changes the font-size on the fly when the video is resized (when the browser window is resized.) The notes was connected to the video (just like notes on YouTube), which is why the code uses instances instead of a DOM handle directly.

As per request I'll throw in some code that I used to achieve this. (Text boxes over an HTML5 video.) The code was written a long time ago, and I quite frankly think it's pretty messy. Since the question is already answered and an answer is already accepted a long time ago I don't bother rewriting this. But if anyone wants to simplify this a bit, you're more than welcome!

// Figure out the text size:
var text = val['text'];
var letters = text.length;
var findMultiplier = function(x) { // g(x)
    /* By analysing some functions with regression, the resulting function that
     gives the best font size with respect to the number of letters and the size
     of the note is:
     g(x) = 8.3 - 2.75x^0.15 [1 < x < 255]
     f(x) = g(letters) * (x / 1000)^0.5
     Font size = f(size)
     */
    return 8.3 - 2.75 * Math.pow(x, 0.15);
};

var findFontSize = function(x) { // f(x)
    return findMultiplier(letters) * Math.pow(x / 1000, 0.5);
};

val.setFontSizeListener = function() {
    p.style.fontSize = '1px'; // So the text should not overflow the box when measuring.
    var noteStyle = window.getComputedStyle(table);
    var width = noteStyle.getPropertyValue('width');
    var height = noteStyle.getPropertyValue('height');
    var size = width.substring(0, width.length - 2) * height.substring(0, height.length - 2);
    p.style.fontSize = findFontSize(size) + 'px';
};
window.addEventListener('resize', val.setFontSizeListener);

You'll probably need to tweak these numbers from font-family to font-family. A good way to do this is download a free graph visualizer called GeoGebra. Change the length of the text and the size of the box. Then you manually set the size. Plot the manual results into the coordinate system. Then you enter the two equations I've posted here and you tweak the numbers until "my" graph fits your own manually plotted points.

Visual Studio breakpoints not being hit

In my scenario, I've got an MVC app and WebAPI in one solution, and I'm using local IIS (not express).

I also set up the sites in IIS as real domains, and edited my host file so that I can type in the real domain and everything works. I also noticed 2 things:

  1. The MVC code debugging was working perfectly.

  2. Attaching to process worked perfectly too. Just when I was debugging it didn't hit the breakpoint in my API.

This was the solution for me:

Right click webapi project > properties > Web > Project URL

By default it points to localhost, but since I set up the site in IIS, I forgot to change the URL to the website domain (i.e. instead of locahost, it should say http://{domain-name}/).

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Read and overwrite a file in Python

Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.

How do I convert a Python program to a runnable .exe Windows program?

I use cx_Freeze. Works with Python 2 and 3, and I have tested it to work on Windows, Mac, and Linux.

cx_Freeze: http://cx-freeze.sourceforge.net/

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.

The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.

I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.

Get loop counter/index using for…of syntax in JavaScript

As others have said, you shouldn't be using for..in to iterate over an array.

for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }

If you want cleaner syntax, you could use forEach:

myArray.forEach( function ( val, i ) { ... } );

If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.

Get to UIViewController from UIView?

If your rootViewController is UINavigationViewController, which was set up in AppDelegate class, then

    + (UIViewController *) getNearestViewController:(Class) c {
NSArray *arrVc = [[[[UIApplication sharedApplication] keyWindow] rootViewController] childViewControllers];

for (UIViewController *v in arrVc)
{
    if ([v isKindOfClass:c])
    {
        return v;
    }
}

return nil;}

Where c required view controllers class.

USAGE:

     RequiredViewController* rvc = [Utilities getNearestViewController:[RequiredViewController class]];

Truncate (not round off) decimal numbers in javascript

just to point out a simple solution that worked for me

convert it to string and then regex it...

var number = 123.45678;
var number_s = '' + number;
var number_truncated_s = number_s.match(/\d*\.\d{4}/)[0]
var number_truncated = parseFloat(number_truncated_s)

It can be abbreviated to

var number_truncated = parseFloat(('' + 123.4568908).match(/\d*\.\d{4}/)[0])

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

Java: How to check if object is null?

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Android Recyclerview GridLayoutManager column spacing

RecyclerViews support the concept of ItemDecoration: special offsets and drawing around each element. As seen in this answer, you can use

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
  private int space;

  public SpacesItemDecoration(int space) {
    this.space = space;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, 
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = space;
    outRect.right = space;
    outRect.bottom = space;

    // Add top margin only for the first item to avoid double space between items
    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = space;
    } else {
        outRect.top = 0;
    }
  }
}

Then add it via

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));

How to define an enum with string value?

You can't do this with enums, but you can do it like that:

public static class SeparatorChars
{
    public static string Comma = ",";

    public static string Tab = "\t";

    public static string Space = " ";
}

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

scipy.misc module has no attribute imread?

In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0

$ pip uninstall scipy

$ pip install scipy==1.1.0

How do I count occurrence of duplicate items in array

I came here from google looking for a way to count the occurence of duplicate items in an array. Here is the way to do it simply:

$colors = array("red", "green", "blue", "red", "yellow", "blue");
$unique_colors = array_unique($colors);
// $unique colors : array("red", "green", "blue", "yellow")
$duplicates = count($colors) - count($unique_colors);
// $duplicates = 6 - 4 = 2
if( $duplicates == 0 ){
 echo "There are no duplicates";
}
echo "No. of Duplicates are :" . $duplicates;

// Output: No. of Duplicates are: 2

How array_unique() works?

It elements all the duplicates. ex: Lets say we have an array as follows -

$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");

When you do $cars = array_unique($cars); cars will have only following elements. $cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

To read more: https://www.w3schools.com/php/func_array_unique.asp

Hope it is helpful to those who are coming here from google looking for a way to count duplicate values in array.

Finding modified date of a file/folder

If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:

Get-Item c:\folder | Format-List  

Or you can access the property directly like so:

Get-Item c:\folder | Foreach {$_.LastWriteTime}

To start to filter folders & files based on last write time you can do this:

Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

if (boolean == false) vs. if (!boolean)

Apart from "readability", no. They're functionally equivalent.

("Readability" is in quotes because I hate == false and find ! much more readable. But others don't.)

How to test that a registered variable is not empty?

You can check for empty string (when stderr is empty)

- name: Check script
  shell: . {{ venv_name }}/bin/activate && myscritp.py
  args:
    chdir: "{{ home }}"
  sudo_user: "{{ user }}"
  register: test_myscript

- debug: msg='myscritp is Ok'
  when: test_myscript.stderr == ""

If you want to check for fail:

- debug: msg='myscritp has error: {{test_myscript.stderr}}'
  when: test_myscript.stderr != ""

Also look at this stackoverflow question

GitHub README.md center image

We can use this. Please change the src location of ur img from git folder and add alternate text if img is not loaded

 <p align="center"> 
    <img src="ur img url here" alt="alternate text">
 </p>

How do I change UIView Size?

For a progress bar kind of thing, in Swift 4

I follow these steps:

  1. I create a UIView outlet : @IBOutlet var progressBar: UIView!
  2. Then a property to increase its width value after a user action var progressBarWidth: Int = your value
  3. Then for the increase/decrease of the progress progressBar.frame.size.width = CGFloat(progressBarWidth)
  4. And finally in the IBACtion method I add progressBarWidth += your value for auto increase the width every time user touches a button.

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

Change form size at runtime in C#

Something like this works fine for me:

public partial class Form1 : Form
{
    Form mainFormHandler;
...
}

private void Form1_Load(object sender, EventArgs e){
    mainFormHandler = Application.OpenForms[0];
   //or instead use this one:
   //mainFormHandler = Application.OpenForms["Form1"];
}

Then you can change the size as below:

mainFormHandler.Width = 600;
mainFormHandler.Height= 400;

or

mainFormHandler.Size = new Size(600, 400);

Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Redirect to external URL with return in laravel

You can use Redirect::away($url)

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

col align right

How about this? Bootstrap 4

<div class="row justify-content-end">
    <div class="col-3">
        The content is positioned as if there was
        "col-9" classed div appending this one.
    </div>
</div>

How to implement a queue using two stacks?

I'll answer this question in Go because Go does not have a rich a lot of collections in its standard library.

Since a stack is really easy to implement I thought I'd try and use two stacks to accomplish a double ended queue. To better understand how I arrived at my answer I've split the implementation in two parts, the first part is hopefully easier to understand but it's incomplete.

type IntQueue struct {
    front       []int
    back        []int
}

func (q *IntQueue) PushFront(v int) {
    q.front = append(q.front, v)
}

func (q *IntQueue) Front() int {
    if len(q.front) > 0 {
        return q.front[len(q.front)-1]
    } else {
        return q.back[0]
    }
}

func (q *IntQueue) PopFront() {
    if len(q.front) > 0 {
        q.front = q.front[:len(q.front)-1]
    } else {
        q.back = q.back[1:]
    }
}

func (q *IntQueue) PushBack(v int) {
    q.back = append(q.back, v)
}

func (q *IntQueue) Back() int {
    if len(q.back) > 0 {
        return q.back[len(q.back)-1]
    } else {
        return q.front[0]
    }
}

func (q *IntQueue) PopBack() {
    if len(q.back) > 0 {
        q.back = q.back[:len(q.back)-1]
    } else {
        q.front = q.front[1:]
    }
}

It's basically two stacks where we allow the bottom of the stacks to be manipulated by each other. I've also used the STL naming conventions, where the traditional push, pop, peek operations of a stack have a front/back prefix whether they refer to the front or back of the queue.

The issue with the above code is that it doesn't use memory very efficiently. Actually, it grows endlessly until you run out of space. That's really bad. The fix for this is to simply reuse the bottom of the stack space whenever possible. We have to introduce an offset to track this since a slice in Go cannot grow in the front once shrunk.

type IntQueue struct {
    front       []int
    frontOffset int
    back        []int
    backOffset  int
}

func (q *IntQueue) PushFront(v int) {
    if q.backOffset > 0 {
        i := q.backOffset - 1
        q.back[i] = v
        q.backOffset = i
    } else {
        q.front = append(q.front, v)
    }
}

func (q *IntQueue) Front() int {
    if len(q.front) > 0 {
        return q.front[len(q.front)-1]
    } else {
        return q.back[q.backOffset]
    }
}

func (q *IntQueue) PopFront() {
    if len(q.front) > 0 {
        q.front = q.front[:len(q.front)-1]
    } else {
        if len(q.back) > 0 {
            q.backOffset++
        } else {
            panic("Cannot pop front of empty queue.")
        }
    }
}

func (q *IntQueue) PushBack(v int) {
    if q.frontOffset > 0 {
        i := q.frontOffset - 1
        q.front[i] = v
        q.frontOffset = i
    } else {
        q.back = append(q.back, v)
    }
}

func (q *IntQueue) Back() int {
    if len(q.back) > 0 {
        return q.back[len(q.back)-1]
    } else {
        return q.front[q.frontOffset]
    }
}

func (q *IntQueue) PopBack() {
    if len(q.back) > 0 {
        q.back = q.back[:len(q.back)-1]
    } else {
        if len(q.front) > 0 {
            q.frontOffset++
        } else {
            panic("Cannot pop back of empty queue.")
        }
    }
}

It's a lot of small functions but of the 6 functions 3 of them are just mirrors of the other.

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

Creating an iframe with given HTML dynamically

I know this is an old question but I thought I would provide an example using the srcdoc attribute as this is now widely supported and this is question is viewed often.

Using the srcdoc attribute, you can provide inline HTML to embed. It overrides the src attribute if supported. The browser will fall back to the src attribute if unsupported.

I would also recommend using the sandbox attribute to apply extra restrictions to the content in the frame. This is especially important if the HTML is not your own.

_x000D_
_x000D_
const iframe = document.createElement('iframe');_x000D_
const html = '<body>Foo</body>';_x000D_
iframe.srcdoc = html;_x000D_
iframe.sandbox = '';_x000D_
document.body.appendChild(iframe);
_x000D_
_x000D_
_x000D_

If you need to support older browsers, you can check for srcdoc support and fallback to one of the other methods from other answers.

_x000D_
_x000D_
function setIframeHTML(iframe, html) {_x000D_
  if (typeof iframe.srcdoc !== 'undefined') {_x000D_
    iframe.srcdoc = html;_x000D_
  } else {_x000D_
    iframe.sandbox = 'allow-same-origin';_x000D_
    iframe.contentWindow.document.open();_x000D_
    iframe.contentWindow.document.write(html);_x000D_
    iframe.contentWindow.document.close();_x000D_
  }_x000D_
}_x000D_
_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.sandbox = '';_x000D_
var html = '<body>Foo</body>';_x000D_
_x000D_
document.body.appendChild(iframe);_x000D_
setIframeHTML(iframe, html);
_x000D_
_x000D_
_x000D_

Run PowerShell scripts on remote PC

The accepted answer didn't work for me but the following did:

>PsExec.exe \\<SERVER FQDN> -u <DOMAIN\USER> -p <PASSWORD> /accepteula cmd 
    /c "powershell -noninteractive -command gci c:\"

Example from here

How to import the class within the same directory or sub directory?

I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

from .user import User
from .dir import Dir

Check/Uncheck all the checkboxes in a table

$(document).ready(function () {

            var someObj = {};

            $("#checkAll").click(function () {
                $('.chk').prop('checked', this.checked);
            });

            $(".chk").click(function () {

                $("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
            });

            $("input:checkbox").change(function () {
                debugger;

                someObj.elementChecked = [];

                $("input:checkbox").each(function () {
                    if ($(this).is(":checked")) {
                        someObj.elementChecked.push($(this).attr("id"));

                    }

                });             
            });

            $("#button").click(function () {
                debugger;

                alert(someObj.elementChecked);

            });

        });
    </script>
</head>

<body>

    <ul class="chkAry">
        <li><input type="checkbox" id="checkAll" />Select All</li>

        <li><input class="chk" type="checkbox" id="Delhi">Delhi</li>

        <li><input class="chk" type="checkbox" id="Pune">Pune</li>

        <li><input class="chk" type="checkbox" id="Goa">Goa</li>

        <li><input class="chk" type="checkbox" id="Haryana">Haryana</li>

        <li><input class="chk" type="checkbox" id="Mohali">Mohali</li>

    </ul>
    <input type="button" id="button" value="Get" />

</body>

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Amazon S3 exception: "The specified key does not exist"

The reason for the issue is wrong or typo in the Bucket/Key name. Do check if the bucket or key name you are providing does exists.

Is it possible to select the last n items with nth-child?

:nth-last-child(-n+2) should do the trick

SUM OVER PARTITION BY

In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.

Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.

Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:

SELECT
  OrderLine, 
  OrderDateTime, 
  SalePrice, 
  OrderCategory,
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).

If we remove the other columns from our select statement, and leave our final SUM() column, like this:

SELECT
  SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales 
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate

The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.

The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:

Over Clause

Spring Boot and multiple external configuration files

A modified version of @mxsb solution that allows us to define multiple files and in my case these are yml files.

In my application-dev.yml, I added this config that allows me to inject all the yml that have -dev.yml in them. This can be a list of specific files also. "classpath:/test/test.yml,classpath:/test2/test.yml"

application:
  properties:
    locations: "classpath*:/**/*-dev.yml"

This helps to get a properties map.

@Configuration

public class PropertiesConfig {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

@Value("${application.properties.locations}")
private String[] locations;

@Autowired
private ResourceLoader rl;

@Bean
Map<String, Properties> myProperties() {
    return stream(locations)
            .collect(toMap(filename -> filename, this::loadProperties));
}

private Properties loadProperties(final String filename) {

    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .forEach(propertySource -> {
                    Map source = ((MapPropertySource) propertySource).getSource();
                    properties.putAll(source);
                });

        return properties;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
}

However, if like in my case, I wanted to have to split yml files for each profile and load them and inject that directly into spring configuration before beans initialisation.

config
    - application.yml
    - application-dev.yml
    - application-prod.yml
management
    - management-dev.yml
    - management-prod.yml

... you get the idea

The component is slightly different

@Component
public class PropertiesConfigurer extends     PropertySourcesPlaceholderConfigurer
    implements EnvironmentAware, InitializingBean {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfigurer.class);

private String[] locations;

@Autowired
private ResourceLoader rl;
private Environment environment;

@Override
public void setEnvironment(Environment environment) {
    // save off Environment for later use
    this.environment = environment;
    super.setEnvironment(environment);
}

@Override
public void afterPropertiesSet() throws Exception {
    // Copy property sources to Environment
    MutablePropertySources envPropSources = ((ConfigurableEnvironment) environment).getPropertySources();
    envPropSources.forEach(propertySource -> {
        if (propertySource.containsProperty("application.properties.locations")) {
            locations = ((String) propertySource.getProperty("application.properties.locations")).split(",");
            stream(locations).forEach(filename -> loadProperties(filename).forEach(source ->{
                envPropSources.addFirst(source);
            }));
        }
    });
}


private List<PropertySource> loadProperties(final String filename) {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        return stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .collect(Collectors.toList());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

}

Submitting a form on 'Enter' with jQuery?

This is my code:

  $("#txtMessage").on( "keypress", function(event) {
    if (event.which == 13 && !event.shiftKey) {
        event.preventDefault();
        $("#frSendMessage").submit();
    }
    });

The point of test %eax %eax

test is a non-destructive and, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz conditional jump.

Cycles in an Undirected Graph

I believe that the assumption that the graph is connected can be handful. thus, you can use the proof shown above, that the running time is O(|V|). if not, then |E|>|V|. reminder: the running time of DFS is O(|V|+|E|).

Unique Key constraints for multiple columns in Entity Framework

Completing @chuck answer for using composite indices with foreign keys.

You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.

For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:

class Company
{
    public Guid Id { get; set; }
}

class Employee
{
    public Guid Id { get; set; }
    [Required]
    public String Name { get; set; }
    public Company Company  { get; set; }
    [Required]
    public Guid CompanyId { get; set; }
}

Now the mapping of the Employee class:

class EmployeeMap : EntityTypeConfiguration<Employee>
{
    public EmployeeMap ()
    {
        ToTable("Employee");

        Property(p => p.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(p => p.Name)
            .HasUniqueIndexAnnotation("UK_Employee_Name_Company", 0);
        Property(p => p.CompanyId )
            .HasUniqueIndexAnnotation("UK_Employee_Name_Company", 1);
        HasRequired(p => p.Company)
            .WithMany()
            .HasForeignKey(p => p.CompanyId)
            .WillCascadeOnDelete(false);
    }
}

Note that I also used @niaher extension for unique index annotation.

Android - java.lang.SecurityException: Permission Denial: starting Intent

Select your proper configuration for launching Application.

In my case i found mistake as below image:

enter image description here

I had just changed like:

enter image description here

May it will help to someone, Thanks :)

How to join two sets in one line without using "|"

You can do union or simple list comprehension

[A.add(_) for _ in B]

A would have all the elements of B

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

You have to change from wb to w:

def __init__(self):
    self.myCsv = csv.writer(open('Item.csv', 'wb')) 
    self.myCsv.writerow(['title', 'link'])

to

def __init__(self):
    self.myCsv = csv.writer(open('Item.csv', 'w'))
    self.myCsv.writerow(['title', 'link'])

After changing this, the error disappears, but you can't write to the file (in my case). So after all, I don't have an answer?

Source: How to remove ^M

Changing to 'rb' brings me the other error: io.UnsupportedOperation: write

How to add a right button to a UINavigationController?

Try adding the button to the navigationItem of the view controller that is going to be pushed onto this PropertyViewController class you have created.

That is:

MainViewController *vc = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];

PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];

Now, this infoButton that has been created programatically will show up in the navigation bar. The idea is that the navigation controller picks up its display information (title, buttons, etc) from the UIViewController that it is about to display. You don't actually add buttons and such directly to the UINavigationController.

Remove trailing spaces automatically or with a shortcut

Menu FilePreferenceSettings

Enter image description here

Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".

How to replace an entire line in a text file by line number

in bash, replace N,M by the line numbers and xxx yyy by what you want

i=1
while read line;do
  if((i==N));then
    echo 'xxx'
  elif((i==M));then
    echo 'yyy'
  else
    echo "$line"
  fi
  ((i++))
done  < orig-file > new-file

EDIT

In fact in this solution there are some problems, with characters "\0" "\t" and "\"

"\t", can be solve by putting IFS= before read: "\", at end of line with -r

IFS= read -r line

but for "\0", the variable is truncated, there is no a solution in pure bash : Assign string containing null-character (\0) to a variable in Bash But in normal text file there is no nul character \0

perl would be a better choice

perl -ne 'if($.==N){print"xxx\n"}elsif($.==M){print"yyy\n"}else{print}' < orig-file > new-file

Returning anonymous type in C#

Using C# 7.0 we still can't return anonymous types but we have a support of tuple types and thus we can return a collection of tuple (System.ValueTuple<T1,T2> in this case). Currently Tuple types are not supported in expression trees and you need to load data into memory.

The shortest version of the code you want may look like this:

public IEnumerable<(int SomeVariable, object AnotherVariable)> TheMethod()
{
    ...

    return (from data in TheDC.Data
        select new { data.SomeInt, data.SomeObject }).ToList()
        .Select(data => (SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject))
}

Or using the fluent Linq syntax:

return TheDC.Data
    .Select(data => new {SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject})
    .ToList();
    .Select(data => (SomeVariable: data.SomeInt, AnotherVariable: data.SomeObject))

Using C# 7.1 we can omit properties names of tuple and they will be inferred from tuple initialization like it works with anonymous types:

select (data.SomeInt, data.SomeObject)
// or
Select(data => (data.SomeInt, data.SomeObject))

How to load CSS Asynchronously

If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script nonce):

<script nonce="(your nonce)" async>
$(document).ready(function() {
    $('link[media="none"]').each(function(a, t) {
        var n = $(this).attr("data-async"),
            i = $(this);
        void 0 !== n && !1 !== n && ("true" == n || n) && i.attr("media", "all")
    })
});
</script>

Just add the following to your stylesheet reference: media="none" data-async="true". Here's an example:

<link rel="stylesheet" href="../path/script.js" media="none" data-async="true" />

Example for jQuery:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" media="none" data-async="true" crossorigin="anonymous" /><noscript><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" /></noscript>

Is there a way to perform "if" in python's lambda

Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

Query comparing dates in SQL

If You are comparing only with the date vale, then converting it to date (not datetime) will work

select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= convert(date,'2013-04-12',102)

This conversion is also applicable during using GetDate() function

ORA-00972 identifier is too long alias column name

No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.

However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).

Replace or delete certain characters from filenames of all files in a folder

Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _ underscores.

Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }

EDIT :
Optionally, the Where-Object command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:

  • To skip any document files

    Dir |
    Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    
  • To process only directories (pre-3.0 version)

    Dir |
    Where-Object { $_.Mode -match "^d" } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

    PowerShell v3.0 introduced new Dir flags. You can also use Dir -Directory there.

  • To skip any files already containing an underscore (or some other character)

    Dir |
    Where-Object { -not $_.Name.Contains("_") } |
    Rename-Item -NewName { $_.Name -replace " ","_" }
    

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

Git Stash vs Shelve in IntelliJ IDEA

In addition to previous answers there is one important for me note:

shelve is JetBrains products feature (such as WebStorm, PhpStorm, PyCharm, etc.). It puts shelved files into .idea/shelf directory.

stash is one of git options. It puts stashed files under the .git directory.

Is there a max size for POST parameter content?

Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.

Increase max size of each multipart file to 10MB and total payload size of 100MB max

 spring:
    servlet:
      multipart:max-file-size: 10MB
      multipart:max-request-size: 100MB
 

Setting max size of post requests which might just be the formdata in string format to ~10 MB

 server:
    tomcat:
        max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version

You might need to add this for the latest sprintboot version ->

server: tomcat: max-http-form-post-size: 10MB

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

Getting all types in a namespace via reflection

Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()

How to define dimens.xml for every different screen size in android?

You can put dimens.xml in

1) values

2) values-hdpi

3) values-xhdpi

4) values-xxhdpi

And give different sizes in dimens.xml within corresponding folders according to densities.

npm behind a proxy fails with status 403

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

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add elements in first arraylist

ArrayList<String> firstArrayList = new ArrayList<String>();

firstArrayList.add("A");
firstArrayList.add("B");
firstArrayList.add("C");
firstArrayList.add("D");
firstArrayList.add("E");

Add elements in second arraylist

ArrayList<String> secondArrayList = new ArrayList<String>();

secondArrayList.add("B");
secondArrayList.add("D");
secondArrayList.add("F");
secondArrayList.add("G");

Add first arraylist's elements in second arraylist

secondArrayList.addAll(firstArrayList);

Assign new combine arraylist and add all elements from both arraylists

ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);
comboArrayList.addAll(secondArrayList);

Assign new Set for remove duplicate entries from arraylist

Set<String> setList = new LinkedHashSet<String>(comboArrayList);
comboArrayList.clear();
comboArrayList.addAll(setList);

Sorting arraylist

Collections.sort(comboArrayList);

Output

 A
 B
 C
 D
 E
 F
 G

How to pass argument to Makefile from command line?

Few years later, want to suggest just for this: https://github.com/casey/just

action v1 v2=default:
    @echo 'take action on {{v1}} and {{v2}}...'

Trying to SSH into an Amazon Ec2 instance - permission error

Checklist:

  1. Are you using the right private key .pem file?

  2. Are its permissions set correctly? (My Amazon-brand AMIs work with 644, but Red hat must be at least 600 or 400. Don't know about Ubuntu.)

  3. Are you using the right username in your ssh line? Amazon-branded = "ec2-user", Red Hat = "root", Ubuntu = "ubuntu". User can be specified as "ssh -i pem usename@hostname" OR "ssh -l username -i pem hostname"

Instance member cannot be used on type

You just have syntax error when saying = {return self.someValue}. The = isn't needed.

Use :

var numPages: Int {
    get{
        return categoriesPerPage.count
    }

}

if you want get only you can write

var numPages: Int {
     return categoriesPerPage.count
}

with the first way you can also add observers as set willSet & didSet

var numPages: Int {
    get{
        return categoriesPerPage.count
    }
    set(v){
       self.categoriesPerPage = v
    }
}

allowing to use = operator as a setter

myObject.numPages = 5

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

_x000D_
_x000D_
div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adjust percentages to your liking. Here is a JSFiddle