Programs & Examples On #On screen keyboard

For programming questions about creating or using an on-screen keyboard (a virtual keyboard displayed on the screen), including osk.exe included with Windows.

How to list all available Kafka brokers in a cluster?

If you are using new version of Kafka e.g. 5.3.3, you can use

kafka-broker-api-versions  --bootstrap-server BROKER | grep 9092

You just need to pass one of the brokers

How to display all methods of an object?

Most modern browser support console.dir(obj), which will return all the properties of an object that it inherited through its constructor. See Mozilla's documentation for more info and current browser support.

console.dir(Math)
=> MathConstructor
E: 2.718281828459045
LN2: 0.6931471805599453
...
tan: function tan() { [native code] }
__proto__: Object

How to get $HOME directory of different user in bash script?

I was also looking for this, but didn't want to impersonate a user to simply acquire a path!

user_path=$(grep $username /etc/passwd|cut -f6 -d":");

Now in your script, you can refer to $user_path in most cases would be /home/username

Assumes: You have previously set $username with the value of the intended users username. Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

AngularJS ngClass conditional

Your first attempt was almost right, It should work without the quotes.

{test: obj.value1 == 'someothervalue'}

Here is a plnkr.

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here. If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

Just to complement: You can also use logical operators to form logical expressions like

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

See line breaks and carriage returns in editor

I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :

cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF

When you're executing vim, the commands into .vimrc are executed, and you can see this example :

My line with CRLF eol here ^M¶

What are the "spec.ts" files generated by Angular CLI for?

The .spec.ts files are for unit tests for individual components. You can run Karma task runner through ng test. In order to see code coverage of unit test cases for particular components run ng test --code-coverage

How do I get my Python program to sleep for 50 milliseconds?

Note that if you rely on sleep taking exactly 50 ms, you won't get that. It will just be about it.

Automatically running a batch file as an administrator

Runas.exe won't work here. You can use VBScript to invoke the "Run as Administrator" shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:

elevatecmd.exe

http://blogs.technet.com/b/elevationpowertoys/

error opening trace file: No such file or directory (2)

I think this is the problem

A little background

Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.

It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application

How do I enable it:

There are two ways to generate trace logs:

  1. Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.

  2. Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

But the following restrictions exist for the above

If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).

If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

So in essence the traceFile access requires two things

1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure

2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.

What do I do with this error:

Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on. But in general this doesn't affect you directly, you should check direct application logs/errors. Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.

Additional information on Traceview:

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:

traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug

More in the docs

Link to download apache http server for 64bit windows.

From: http://wiki.apache.org/httpd/FAQ#Where_can_I_download_.28certified.29_64_bit_Apache_httpd_binaries_for_Windows.3F

Where can I download (certified) 64 bit Apache httpd binaries for Windows?

Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.

Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.

JSON and XML comparison

Before answering when to use which one, a little background:

edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.

In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

myJSON = {"age" : 12,
          "name" : "Danielle"}

The parser doesn't need to be intelligent enough to realise that 12 represents a number, (and Danielle is a string like any other). So in javascript we can do:

anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False

In XML we'd have to do something like the following:

<person>
    <age>12</age>
    <name>Danielle</name>
</person>

(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:

myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True

Actually, a good parser might well type the age for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name. It might be more intuitive to form the XML like this:

<person name="Danielle" age="12" />

But we'd still have to do map lookups to access our data:

myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");

EDIT: Original:

In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).

This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.

If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.

As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.

What is the most "pythonic" way to iterate over a list in chunks?

Why not use list comprehension

l = [1 , 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
n = 4
filler = 0
fills = len(l) % n
chunks = ((l + [filler] * fills)[x * n:x * n + n] for x in range(int((len(l) + n - 1)/n)))
print(chunks)

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 0]]

Python: TypeError: object of type 'NoneType' has no len()

What is the purpose of this

 names = list;

? Also, no ; required in Python.

Do you want

 names = []

or

 names = list()

at the start of your program instead? Though given your particular code, there's no need for this statement to create this names variable since you do so later when you read data into it from your file.

@JBernardo has already pointed out the other (and more major) problem with the code.

How to display default text "--Select Team --" in combo box on pageload in WPF?

I believe a watermark as mentioned in this post would work well in this case

There's a bit of code needed but you can reuse it for any combobox or textbox (and even passwordboxes) so I prefer this way

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

How to convert an NSTimeInterval (seconds) into minutes

All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

How to get element value in jQuery

To get value of li we should use $("#list li").click(function() { var selected = $(this).html();

or

var selected = $(this).text();

alert(selected);

})

How to change Toolbar home icon color

Try this: Set the toolbar's theme in your layout as follows

android:theme = "@android:style/ThemeOverlay.Material.Dark.ActionBar"

If you want further information

The curious case of the Overflow Icon Color by Martin Bonnin

How do I include a pipe | in my linux find -exec command?

the solution is easy: execute via sh

... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

Convert date to UTC using moment.js

moment.utc(date).format(...); 

is the way to go, since

moment().utc(date).format(...);

does behave weird...

Why can't DateTime.Parse parse UTC date

Just replace "UTC" with "GMT" -- simple and doesn't break correctly formatted dates:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC".Replace("UTC", "GMT"))

Can an XSLT insert the current date?

XSLT 2

Date functions are available natively, such as:

<xsl:value-of  select="current-dateTime()"/>

There is also current-date() and current-time().

XSLT 1

Use the EXSLT date and times extension package.

  1. Download the date and times package from GitHub.
  2. Extract date.xsl to the location of your XSL files.
  3. Set the stylesheet header.
  4. Import date.xsl.

For example:

<xsl:stylesheet version="1.0" 
    xmlns:date="http://exslt.org/dates-and-times" 
    extension-element-prefixes="date"
    ...>

    <xsl:import href="date.xsl" />

    <xsl:template match="//root">
       <xsl:value-of select="date:date-time()"/>
    </xsl:template>
</xsl:stylesheet>

jQuery Dialog Box

This is a little more concise and also allows you to have different dialog values etc based on different click events:

$('#click_link').live("click",function() {
    $("#popup").dialog({modal:true, width:500, height:800});

    $("#popup").dialog("open");

    return false;
});

pop/remove items out of a python tuple

The best solution is the tuple applied to a list comprehension, but to extract one item this could work:

def pop_tuple(tuple, n): return tuple[:n]+tuple[n+1:], tuple[n]

Swift: Display HTML data in a label or textView

Display images and text paragraphs is not possible in a UITextView or UILabel, to this, you must use a UIWebView.

Just add the item in the storyboard, link to your code, and call it to load the URL.

OBJ-C

NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];

Swift

let url = NSURL (string: "http://www.sourcefreeze.com");
let requestObj = NSURLRequest(URL: url!);
viewWeb.loadRequest(requestObj);

Step by step tutorial. http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

Spring MVC: Complex object as GET @RequestParam

Accepted answer works like a charm but if the object has a list of objects it won't work as expected so here is my solution after some digging.

Following this thread advice, here is how I've done.

  • Frontend: stringify your object than encode it in base64 for submission.
  • Backend: decode base64 string then convert the string json into desired object.

It isn't the best for debugging your API with postman but it is working as expected for me.

Original object: { page: 1, size: 5, filters: [{ field: "id", value: 1, comparison: "EQ" }

Encoded object: eyJwYWdlIjoxLCJzaXplIjo1LCJmaWx0ZXJzIjpbeyJmaWVsZCI6ImlkUGFyZW50IiwiY29tcGFyaXNvbiI6Ik5VTEwifV19

@GetMapping
fun list(@RequestParam search: String?): ResponseEntity<ListDTO> {
    val filter: SearchFilterDTO = decodeSearchFieldDTO(search)
    ...
}

private fun decodeSearchFieldDTO(search: String?): SearchFilterDTO {
    if (search.isNullOrEmpty()) return SearchFilterDTO()
    return Gson().fromJson(String(Base64.getDecoder().decode(search)), SearchFilterDTO::class.java)
}

And here the SearchFilterDTO and FilterDTO

class SearchFilterDTO(
    var currentPage: Int = 1,
    var pageSize: Int = 10,
    var sort: Sort? = null,
    var column: String? = null,
    var filters: List<FilterDTO> = ArrayList<FilterDTO>(),
    var paged: Boolean = true
)

class FilterDTO(
    var field: String,
    var value: Any,
    var comparison: Comparison
)

Why I get 'list' object has no attribute 'items'?

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

Regular expression for URL validation (in JavaScript)

This REGEX is a patch from @Aamir answer that worked for me

/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi

It matches these URL formats

  1. yourwebsite.com
  2. yourwebsite.com/4564564/546564/546564?=adsfasd
  3. www.yourwebsite.com
  4. http://yourwebsite.com
  5. https://yourwebsite.com
  6. ftp://www.yourwebsite.com
  7. ftp://yourwebsite.com
  8. http://yourwebsite.com/4564564/546564/546564?=adsfasd

disable textbox using jquery?

HTML

<span id="radiobutt">
  <input type="radio" name="rad1" value="1" />
  <input type="radio" name="rad1" value="2" />
  <input type="radio" name="rad1" value="3" />
</span>
<div>
  <input type="text" id="textbox1" />
  <input type="checkbox" id="checkbox1" />
</div>

Javascript

  $("#radiobutt input[type=radio]").each(function(i){
    $(this).click(function () {
        if(i==2) { //3rd radiobutton
            $("#textbox1").attr("disabled", "disabled"); 
            $("#checkbox1").attr("disabled", "disabled"); 
        }
        else {
            $("#textbox1").removeAttr("disabled"); 
            $("#checkbox1").removeAttr("disabled"); 
        }
      });

  });

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Use below date function to get current time in MySQL format/(As requested on question also)

echo date("Y-m-d H:i:s", time());

Hash function for a string

Java's String implements hashCode like this:

public int hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

     s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 

So something like this:

int HashTable::hash (string word) {
    int result = 0;
    for(size_t i = 0; i < word.length(); ++i) {
        result += word[i] * pow(31, i);
    }
    return result;
}

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

How to test a variable is null in python

You can do this in a try and catch block:

try:
    if val is None:
        print("null")
except NameError:
    # throw an exception or do something else

How to echo shell commands as they are executed

Type "bash -x" on the command line before the name of the Bash script. For instance, to execute foo.sh, type:

bash -x foo.sh

How to avoid reverse engineering of an APK file?

100% avoidance of reverse engineering of the Android APK is not possible, but you can use these ways to avoid extracting more data, like source code, assets form your APK, and resources:

  1. Use ProGuard to obfuscate application code

  2. Use NDK using C and C++ to put your application core and secure part of code in .so files

  3. To secure resources, don't include all important resources in the assets folder with APK. Download these resources at the time of application first start up.

How to center an element in the middle of the browser window?

This is completely possible with just CSS-- no JavaScript needed: Here's an example

Here is the source code behind that example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>  
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Dead Centre</title>  
<style type="text/css" media="screen"><!--
body 
    {
    color: white;
    background-color: #003;
    margin: 0px
    }

#horizon        
    {
    color: white;
    background-color: transparent;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 0px;
    width: 100%;
    height: 1px;
    overflow: visible;
    visibility: visible;
    display: block
    }

#content    
    {
    font-family: Verdana, Geneva, Arial, sans-serif;
    background-color: transparent;
    margin-left: -125px;
    position: absolute;
    top: -35px;
    left: 50%;
    width: 250px;
    height: 70px;
    visibility: visible
    }

.bodytext 
    {
    font-size: 14px
    }

.headline 
    {
    font-weight: bold;
    font-size: 24px
    }

#footer 
    {
    font-size: 11px;
    font-family: Verdana, Geneva, Arial, sans-serif;
    text-align: center;
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 20px;
    visibility: visible;
    display: block
    }

a:link, a:visited 
    {
    color: #06f;
    text-decoration: none
    }

a:hover 
    {
    color: red;
    text-decoration: none
    }

--></style>
</head>
<body>
<div id="horizon">
    <div id="content">
        <div class="bodytext">
        This text is<br>
        <span class="headline">DEAD CENTRE</span><br>
        and stays there!</div>
    </div>
</div>
<div id="footer">
    <a href="http://www.wpdfd.com/editorial/thebox/deadcentre4.html">view construction</a></div>
</body>
</html>

How to printf "unsigned long" in C?

  • %lu for unsigned long
  • %llu for unsigned long long

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

How to access full source of old commit in BitBucket?

Great answers from a couple of years ago. Now Bitbucket has made it easier.

Tag the Commit you want to download (as mentioned in answer by Rudy Matela).

Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.

Tag Downloads

How to fix "'System.AggregateException' occurred in mscorlib.dll"

In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

If you're not worried about waking your phone up or bringing your app back from the dead, try:

// Param is optional, to run task on UI thread.     
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Do the task...
        handler.postDelayed(this, milliseconds) // Optional, to repeat the task.
    }
};
handler.postDelayed(runnable, milliseconds);

// Stop a repeating task like this.
handler.removeCallbacks(runnable);

How do I declare an array with a custom class?

you just need to add a default constructor to your class to look like this:

class name {
  public:
    string first;
    string last;

  name() {
  }

  name(string a, string b){
    first = a;
    last = b;
  }
};

How to do jquery code AFTER page loading?

I am looking for the same problem and here is what help me. Here is the jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead, you can use on method and bind the JavaScript load event:

$(window).on('load', function () {
  alert("Window Loaded");
});

Auto-indent in Notepad++

In the latest version (at least), you can find it through:

  • Settings (menu)
  • Preferences...
  • MISC (tab)
  • lower-left checkbox list
  • "Auto-indent" is the 2nd option in this group

[EDIT] Though, I don't think it's had the best implementation of Auto-indent. So, check to make sure you have version 5.1 -- auto-indent got an overhaul recently, so it auto-corrects your indenting.


Do also note that you're missing the block for the 2nd if:

void main(){
  if(){
    if() { }  # here
  }
}

How do I convert strings in a Pandas data frame to a 'date' data type?

I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read:

dfcsv = pd.read_csv('xyz.csv', parse_dates=[0]) where the 0 refers to the column the date is in.
You could also add , index_col=0 in there if you want the date to be your index.

See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Best way to parseDouble with comma as decimal separator?

In Kotlin you can use extensions as below:

fun String.toDoubleEx() : Double {
   val decimalSymbol = DecimalFormatSymbols.getInstance().decimalSeparator
  return if (decimalSymbol == ',') {
      this.replace(decimalSymbol, '.').toDouble()
  } else {
      this.toDouble()
  }
}

and you can use it everywhere in your code like this:

val myNumber1 = "5,2"
val myNumber2 = "6.7"

val myNum1 = myNumber1.toDoubleEx()
val myNum2 = myNumber2.toDoubleEx()

It is easy and universal!

Problems with entering Git commit message with Vim

You can change the comment character to something besides # like this:

git config --global core.commentchar "@"

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Coerce multiple columns to factors at once

If you have another objective of getting in values from the table then using them to be converted, you can try the following way

### pre processing
ind <- bigm.train[,lapply(.SD,is.character)]
ind <- names(ind[,.SD[T]])
### Convert multiple columns to factor
bigm.train[,(ind):=lapply(.SD,factor),.SDcols=ind]

This selects columns which are specifically character based and then converts them to factor.

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Ubuntu apt-get unable to fetch packages

I got this issue when the Virtualbox had the wrong networking. I've updated to NAT and was able to get on internet and download packages from us.archive.ubuntu.com

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

Position buttons next to each other in the center of page

Utilize regular buttons and set the display property to inline in order to center the buttons on a single line. Setting the display property to inline-block will also put them on the same line, but they will not be centered via that display property setting.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Get started with Latex on Linux

To get started with LaTeX on Linux, you're going to need to install a couple of packages:

  1. You're going to need a LaTeX distribution. This is the collection of programs that comprise the (La)TeX computer typesetting system. The standard LaTeX distribution on Unix systems used to be teTeX, but it has been superceded by TeX Live. Most Linux distributions have installation packages for TeX Live--see, for example, the package database entries for Ubuntu and Fedora.

  2. You will probably want to install a LaTeX editor. Standard Linux text editors will work fine; in particular, Emacs has a nice package of (La)TeX editing macros called AUCTeX. Specialized LaTeX editors also exist; of those, Kile (KDE Integrated LaTeX Environment) is particularly nice.

  3. You will probably want a LaTeX tutorial. The classic tutorial is "A (Not So) Short Introduction to LaTeX2e," but nowadays the LaTeX wikibook might be a better choice.

Inserting into Oracle and retrieving the generated sequence ID

Doing it as a stored procedure does have lot of advantages. You can get the sequence that is inserted into the table using syntax insert into table_name values returning.

Like:

declare
some_seq_val  number;
lv_seq        number;
begin
some_seq_val := your_seq.nextval;
insert into your_tab (col1, col2, col3) 
values (some_seq_val, val2, val3) returning some_seq_val into lv_seq;

dbms_output.put_line('The inserted sequence is: '||to_char(lv_seq));
end;
/

Or just return some_seq_val. In case you are not making use of SEQUENCE, and arriving the sequence on some calculation, you can make use of returning into effectively.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Make a swap and run composer command again. I hope it'll work for you.

 $ dd if=/dev/zero of=/swapfile bs=1024 count=512k
 $ mkswap /swapfile
 $ swapon /swapfile
 $ echo "/swapfile       none    swap    sw      0       0 " >> /etc/fstab
 $ echo 0 > /proc/sys/vm/swappiness
 $ chown root:root /swapfile
 $ chmod 0600 /swapfile

Change location of log4j.properties

Refer to this example taken from - http://www.dzone.com/tutorials/java/log4j/sample-log4j-properties-file-configuration-1.html

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class HelloWorld {

    static final Logger logger = Logger.getLogger(HelloWorld.class);
    static final String path = "src/resources/log4j.properties";

    public static void main(String[] args) {

        PropertyConfigurator.configure(path);
        logger.debug("Sample debug message");
        logger.info("Sample info message");
        logger.warn("Sample warn message");
        logger.error("Sample error message");
        logger.fatal("Sample fatal message");
    }
}

To change the logger levels - Logger.getRootLogger().setLevel(Level.INFO);

msvcr110.dll is missing from computer error while installing PHP

I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.

How do you dismiss the keyboard when editing a UITextField

Swift 4.2 and It will work 100%

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.delegate = self

    }

    // hide key board when the user touches outside keyboard

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    // user presses return key

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

}

How can I move all the files from one folder to another using the command line?

You can use the command move

move <source directory> <destination directory>

Reference

React js change child component's state from parent component

The state should be managed in the parent component. You can transfer the open value to the child component by adding a property.

class ParentComponent extends Component {
   constructor(props) {
      super(props);
      this.state = {
        open: false
      };

      this.toggleChildMenu = this.toggleChildMenu.bind(this);
   }

   toggleChildMenu() {
      this.setState(state => ({
        open: !state.open
      }));
   }

   render() {
      return (
         <div>
           <button onClick={this.toggleChildMenu}>
              Toggle Menu from Parent
           </button>
           <ChildComponent open={this.state.open} />
         </div>
       );
    }
}

class ChildComponent extends Component {
    render() {
      return (
         <Drawer open={this.props.open}/>
      );
    }
}

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

What is an NP-complete in computer science?

Basically this world's problems can be categorized as

         1) Unsolvable Problem          2) Intractable Problem          3) NP-Problem          4) P-Problem


         1)The first one is no solution to the problem.          2)The second is the need exponential time (that is O (2 ^ n) above).          3)The third is called the NP.          4)The fourth is easy problem.


P: refers to a solution of the problem of Polynomial Time.

NP: refers Polynomial Time yet to find a solution. We are not sure there is no Polynomial Time solution, but once you provide a solution, this solution can be verified in Polynomial Time.

NP Complete: refers in Polynomial Time we still yet to find a solution, but it can be verified in Polynomial Time . The problem NPC in NP is the more difficult problem, so if we can prove that we have P solution to NPC problem then NP problems that can be found in P solution.

NP Hard: refers Polynomial Time is yet to find a solution, but it sure is not able to be verified in Polynomial Time . NP Hard problem surpasses NPC difficulty.

Wait one second in running program

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

//Note Forms.Timer and Timer() have similar implementations. 

public static void DelayAction(int millisecond, Action action)
{
    var timer = new DispatcherTimer();
    timer.Tick += delegate

    {
        action.Invoke();
        timer.Stop();
    };

    timer.Interval = TimeSpan.FromMilliseconds(millisecond);
    timer.Start();
}

javascript regular expression to not match a word

function test(string) {
    return ! string.match(/abc|def/);
}

Proper usage of .net MVC Html.CheckBoxFor

Place this on your model:

[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }

private string electricFanRate;

public string ElectricFanRate
{
    get { return electricFanRate ?? (electricFanRate = "$15/month"); }
    set { electricFanRate = value; }
}

And this in your cshtml:

<div class="row">
    @Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
    @Html.LabelFor(m => m.ElectricFan, new { @class = "" })
    @Html.DisplayTextFor(m => m.ElectricFanRate)
</div>

Which will output this:

MVC Output If you click on the checkbox or the bold label it will check/uncheck the checkbox

.htaccess - how to force "www." in a generic way?

This won't work with subdomains.

domain.com correctly gets redirected to www.domain.com

but

images.domain.com gets redirected to www.images.domain.com

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
if(TRUE) 
{
  1
} else            # also OK
{
  2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

What is the difference between range and xrange functions in Python 2.X?

I am shocked nobody read doc:

This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with break).

DECODE( ) function in SQL Server

If I understand the question correctly, you want the equivalent of decode but in T-SQL

Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
    WHEN '02' THEN 'DR'
    ELSE 'CR'
END

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

How to check if a user is logged in (how to properly use user.is_authenticated)?

Update for Django 1.10+:

is_authenticated is now an attribute in Django 1.10.

The method was removed in Django 2.0.

For Django 1.9 and older:

is_authenticated is a function. You should call it like

if request.user.is_authenticated():
    # do something if the user is authenticated

As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:

{% if user.is_authenticated %}

However, in Python code, it is indeed a method in the User class.

Disabling browser print options (headers, footers, margins) from page?

Since you mentioned "within their browser" and firefox, if you are using Internet Explorer, you can disable the page header/footer by temporarily setting of the value in the registry, see here for an example. AFAIK I have not heard of a way to do this within other browsers. Both Daniel's and Mickel's answers seems to collide with each other, I guess that there could be a similar setting somewhere in the registry for firefox to remove headers/footers or customize them. Have you checked it out?

How do you subtract Dates in Java?

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());

Upload Progress Bar in PHP

You would need to use Javascript to create a progress bar. A simple Google search led me to this article: WebAppers Simple Javascript Progress Bar with CSS.

Dojo File Upload Progress Bar Widget is another option using the Dojo Javascript framework.

EDIT: Assuming your uploading a large number of images (such as a photo album), and POSTing them to your PHP script, you could use javascript to read the results back from the post and update the progress bar based on the number of images uploaded / total number of images. This has the side effect of only updating after each post has completed. Check out here for some info on how to post with JS.

FirebaseInstanceIdService is deprecated

In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService

override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

Get token at run-time,use

FirebaseInstanceId.getInstance().instanceId
                        .addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
                            val mToken = instanceIdResult.token
                            println("printing  fcm token: $mToken")
                        }

When should I use Lazy<T>?

I have been considering using Lazy<T> properties to help improve the performance of my own code (and to learn a bit more about it). I came here looking for answers about when to use it but it seems that everywhere I go there are phrases like:

Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

from MSDN Lazy<T> Class

I am left a bit confused because I am not sure where to draw the line. For example, I consider linear interpolation as a fairly quick computation but if I don't need to do it then can lazy initialisation help me to avoid doing it and is it worth it?

In the end I decided to try my own test and I thought I would share the results here. Unfortunately I am not really an expert at doing these sort of tests and so I am happy to get comments that suggest improvements.

Description

For my case, I was particularly interested to see if Lazy Properties could help improve a part of my code that does a lot of interpolation (most of it being unused) and so I have created a test that compared 3 approaches.

I created a separate test class with 20 test properties (lets call them t-properties) for each approach.

  • GetInterp Class: Runs linear interpolation every time a t-property is got.
  • InitInterp Class: Initialises the t-properties by running the linear interpolation for each one in the constructor. The get just returns a double.
  • InitLazy Class: Sets up the t-properties as Lazy properties so that linear interpolation is run once when the property is first got. Subsequent gets should just return an already calculated double.

The test results are measured in ms and are the average of 50 instantiations or 20 property gets. Each test was then run 5 times.

Test 1 Results: Instantiation (average of 50 instantiations)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.005668 0.005722 0.006704 0.006652 0.005572 0.0060636 6.72
InitInterp 0.08481  0.084908 0.099328 0.098626 0.083774 0.0902892 100.00
InitLazy   0.058436 0.05891  0.068046 0.068108 0.060648 0.0628296 69.59

Test 2 Results: First Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.263    0.268725 0.31373  0.263745 0.279675 0.277775 54.38
InitInterp 0.16316  0.161845 0.18675  0.163535 0.173625 0.169783 33.24
InitLazy   0.46932  0.55299  0.54726  0.47878  0.505635 0.510797 100.00

Test 3 Results: Second Get (average of 20 property gets)

Class      1        2        3        4        5        Avg       %
------------------------------------------------------------------------
GetInterp  0.08184  0.129325 0.112035 0.097575 0.098695 0.103894 85.30
InitInterp 0.102755 0.128865 0.111335 0.10137  0.106045 0.110074 90.37
InitLazy   0.19603  0.105715 0.107975 0.10034  0.098935 0.121799 100.00

Observations

GetInterp is fastest to instantiate as expected because its not doing anything. InitLazy is faster to instantiate than InitInterp suggesting that the overhead in setting up lazy properties is faster than my linear interpolation calculation. However, I am a bit confused here because InitInterp should be doing 20 linear interpolations (to set up it's t-properties) but it is only taking 0.09 ms to instantiate (test 1), compared to GetInterp which takes 0.28 ms to do just one linear interpolation the first time (test 2), and 0.1 ms to do it the second time (test 3).

It takes InitLazy almost 2 times longer than GetInterp to get a property the first time, while InitInterp is the fastest, because it populated its properties during instantiation. (At least that is what it should have done but why was it's instantiation result so much quicker than a single linear interpolation? When exactly is it doing these interpolations?)

Unfortunately it looks like there is some automatic code optimisation going on in my tests. It should take GetInterp the same time to get a property the first time as it does the second time, but it is showing as more than 2x faster. It looks like this optimisation is also affecting the other classes as well since they are all taking about the same amount of time for test 3. However, such optimisations may also take place in my own production code which may also be an important consideration.

Conclusions

While some results are as expected, there are also some very interesting unexpected results probably due to code optimisations. Even for classes that look like they are doing a lot of work in the constructor, the instantiation results show that they may still be very quick to create, compared to getting a double property. While experts in this field may be able to comment and investigate more thoroughly, my personal feeling is that I need to do this test again but on my production code in order to examine what sort of optimisations may be taking place there too. However, I am expecting that InitInterp may be the way to go.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Another way to do this is described below.

First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.

After doing this, use the following formula.

=If(D55="","",IF(C55="",NOW(),C55))

Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.

This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

add title attribute from css

Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from css. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.

What you can do is style the label:after selector and give it display:none, and set it's content from css. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:

label:after{
    content: "my tooltip";
    padding: 2px;
    display:none;
    position: relative;
    top: -20px;
    right: -30px;
    width: 150px;
    text-align: center;
    background-color: #fef4c5;
    border: 1px solid #d4b943;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    -ms-border-radius: 2px;
    border-radius: 2px;
}
label:hover:after{
    display: block;
}

Setting the default page for ASP.NET (Visual Studio) server configuration

Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.

Creating SVG graphics using Javascript?

To do it cross-browser, I strongly recommend RaphaelJS. It has a hell of a good API and does VML in IE, that can't understand SVG.

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

How to Convert double to int in C?

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0

// Now cast
int b = (int) a;
// Now a is 3668

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

How do I programmatically click a link with javascript?

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>

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.

Exception thrown inside catch block - will it be caught again?

No. It's very easy to check.

public class Catch {
    public static void main(String[] args) {
        try {
            throw new java.io.IOException();
        } catch (java.io.IOException exc) {
            System.err.println("In catch IOException: "+exc.getClass());
            throw new RuntimeException();
        } catch (Exception exc) {
            System.err.println("In catch Exception: "+exc.getClass());
        } finally {
            System.err.println("In finally");
        }
    }
}

Should print:

In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
        at Catch.main(Catch.java:8)

Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).

Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.

Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).

How do you redirect to a page using the POST verb?

For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
   // obviously these values might come from somewhere non-trivial
   return Index(2, "text");
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
   // would probably do something non-trivial here with the param values
   return View();
}

That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.

I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.

Hope that helps.

Unsupported major.minor version 52.0 in my app

Sorry for the late reply.Hope it helps someone else

This problem is related with your SDK, not with your JDK. You can check your version information from

Help > About > Show Details

You will get something like

Xamarin.Android Version: 6.0.2.1 (Starter Edition) Android SDK: X:\Android\android-sdk

Supported Android versions:

4.0.3 (API level 15)

4.4 (API level 19)

6.0 (API level 23)

SDK Tools Version: 24.4.1

SDK Platform Tools Version: 23.0.1

SDK Build Tools Version: 24 rc2

Java SDK: X:\Program Files (x86)\Java\jdk1.7.0_71

java version "1.7.0_71"

Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java HotSpot(TM) Client VM (build 24.71-b01, mixed mode, sharing)

If you are using preview tools for building ,then you will get similar errors all over.

What to do now?

goto

Tools -> SDK manager

  1. Select all items in preview channels including Android SDK build tools with rev 24rc2 or 24rc4(latest)

  2. Click on Delete 'n' packages

How to turn off preview channel

  1. In SDK manager, select

    Tools > options

  2. Uncheck Enable preview tools

And what

Back to your code Clean all and rebuild (In rare cases, you have to select build-tools from project settings page)

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

The following solution I found in this forum worked like a charm:

1- close the project

2- close Android Studio IDE

3- delete the .idea directory in the directory where your app resides

4- delete all .iml files in the directory where your app resides

5- open Android Studio IDE and import the project

Get all directories within directory nodejs

This answer does not use blocking functions like readdirSync or statSync. It does not use external dependencies nor find itself in the depths of callback hell.

Instead we use modern JavaScript conveniences like Promises and and async-await syntaxes. And asynchronous results are processed in parallel; not sequentially -

const { readdir, stat } =
  require ("fs") .promises

const { join } =
  require ("path")

const dirs = async (path = ".") =>
  (await stat (path)) .isDirectory ()
    ? Promise
        .all
          ( (await readdir (path))
              .map (p => dirs (join (path, p)))
          )
        .then
          ( results =>
              [] .concat (path, ...results)
          )
    : []

I'll install an example package, and then test our function -

$ npm install ramda
$ node

Let's see it work -

> dirs (".") .then (console.log, console.error)

[ '.'
, 'node_modules'
, 'node_modules/ramda'
, 'node_modules/ramda/dist'
, 'node_modules/ramda/es'
, 'node_modules/ramda/es/internal'
, 'node_modules/ramda/src'
, 'node_modules/ramda/src/internal'
]

Using a generalised module, Parallel, we can simplify the definition of dirs -

const Parallel =
  require ("./Parallel")

const dirs = async (path = ".") =>
  (await stat (path)) .isDirectory ()
    ? Parallel (readdir (path))
        .flatMap (f => dirs (join (path, f)))
        .then (results => [ path, ...results ])
    : []

The Parallel module used above was a pattern that was extracted from a set of functions designed to solve a similar problem. For more explanation, see this related Q&A.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Joda DateTime to Timestamp conversion

I've solved this problem in this way.

String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);

In this way you ignore the server TimeZone forcing your chosen TimeZone.

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.

Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE

so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.

also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.

Richtextbox wpf binding

This VB.Net version works for my situation. I removed thread collection semaphore, instead using RemoveHandler and AddHandler. Also, since a FlowDocument can only be bound to one RichTextBox at a time, I put in a check that the RichTextBox's IsLoaded=True. Let's begin with how I used the class in a MVVM app which uses ResourceDictionary instead of Window.

    ' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Loading document here because Loaded is the last available event to create a document
Private Sub Rtb_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    ' only good place to initialize RichTextBox.Document with DependencyProperty
    Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
    Try
        rtb.Document = RichTextBoxHelper.GetDocumentXaml(rtb)
    Catch ex As Exception
        Debug.WriteLine("Rtb_Loaded: Message:" & ex.Message)
    End Try
End Sub

' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Free document being held by RichTextBox.Document by assigning New FlowDocument to RichTextBox.Document. Otherwise we'll see an of "Document belongs to another RichTextBox"
Private Sub Rtb_Unloaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
    Dim fd As New FlowDocument
    RichTextBoxHelper.SetDocumentXaml(rtb, fd)
    Try
        rtb.Document = fd
    Catch ex As Exception
        Debug.WriteLine("PoemDocument.PoemDocumentView.PoemRtb_Unloaded: Message:" & ex.Message)
    End Try
End Sub

Public Class RichTextBoxHelper
    Inherits DependencyObject

    Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As FlowDocument
        Return depObj.GetValue(DocumentXamlProperty)
    End Function

    Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As FlowDocument)
        depObj.SetValue(DocumentXamlProperty, value)
    End Sub

    Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(FlowDocument), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)
                                                                                                                                                                                                                                                                                                                                   RegisterIt(depObj, e)
                                                                                                                                                                                                                                                                                                                               End Sub))


    Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)
        If rtb.IsLoaded Then
            RemoveHandler rtb.TextChanged, AddressOf TextChanged
            Try
                rtb.Document = GetDocumentXaml(rtb)
            Catch ex As Exception
                Debug.WriteLine("RichTextBoxHelper.RegisterIt: ex:" & ex.Message)
                rtb.Document = New FlowDocument()
            End Try
            AddHandler rtb.TextChanged, AddressOf TextChanged
        Else
            Debug.WriteLine("RichTextBoxHelper: Unloaded control ignored:" & rtb.Name)
        End If
    End Sub

    ' When a RichTextBox Document changes, update the DependencyProperty so they're in sync.
    Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
        Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
        If rtb IsNot Nothing Then
            SetDocumentXaml(sender, rtb.Document)
        End If
    End Sub

End Class

How to convert byte array to string

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

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

I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:

target.replaceAll("^(.{" + position + "})", "$1" + insert);

For example, to insert a missing : into a time String:

"-0300".replaceAll("^(.{3})", "$1:");

What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.

Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.

Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.

How would I stop a while loop after n amount of time?

I have read this but I just want to ask something, wouldn't something like I have written work at all? I have done the testing for 5,10 and 20 seconds. Its time isn't exactly accurate but they are really close to the actual values.

import time

begin_time=0
while begin_time<5:

    begin_time+=1
    time.sleep(1.0)
print("The Work is Done")

How to make circular background using css?

Check with following css. Demo

.circle { 
   width: 140px;
   height: 140px;
   background: red; 
   -moz-border-radius: 70px; 
   -webkit-border-radius: 70px; 
   border-radius: 70px;
}

For more shapes you can follow following urls:

http://davidwalsh.name/css-triangles

How to open spss data files in excel?

You can do it via ODBC. The steps to do it:

  1. Install IBM SPSS Statistics Data File Driver. Standalone Driver is enough.
  2. Create DNS via ODBC manager.
  3. Use the data importer in Excel via ODBC by selecting created DNS.

Extracting a parameter from a URL in WordPress

You can try this function

/**
 * Gets the request parameter.
 *
 * @param      string  $key      The query parameter
 * @param      string  $default  The default value to return if not found
 *
 * @return     string  The request parameter.
 */

function get_request_parameter( $key, $default = '' ) {
    // If not request set
    if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
        return $default;
    }

    // Set so process it
    return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}

Here is what is happening in the function

Here three things are happening.

  • First we check if the request key is present or not. If not, then just return a default value.
  • If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
  • Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.

All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/

How to capture the "virtual keyboard show/hide" event in Android?

I have solve the problem on single line textview back coding.

package com.helpingdoc;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public class MainSearchLayout extends LinearLayout {
    int hieght = 0;
    public MainSearchLayout(Context context, AttributeSet attributeSet) {

        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d("Search Layout", "Handling Keyboard Window shown");
       if(getHeight()>hieght){
           hieght = getHeight();
       }
        final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
        final int actualHeight = getHeight();
        System.out.println("....hieght = "+ hieght);
        System.out.println("....actualhieght = "+ actualHeight);
        System.out.println("....proposedheight = "+ proposedheight);
        if (actualHeight > proposedheight){
            // Keyboard is shown


        } else if(actualHeight<proposedheight){
            // Keyboard is hidden

        }

        if(proposedheight == hieght){
             // Keyboard is hidden
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

jQuery ajax upload file in asp.net mvc

If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button

How can my iphone app detect its own version number?

func getAppVersion() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let versionValue = dictionary["CFBundleShortVersionString"] ?? "0"
    let buildValue = dictionary["CFBundleVersion"] ?? "0"
    return "\(versionValue) (build \(buildValue))"
}

Based on @rajat chauhan answer without forced cast to String.

Angular - "has no exported member 'Observable'"

What helped me is:

  1. Get rid of all old import paths and replace them with new ones like this:

    import { Observable , BehaviorSubject } from 'rxjs';)

  2. Delete node_modules folder

  3. npm cache verify
  4. npm install

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

Linq order by, group by and order by each group?

The way to do it without projection:

StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);

How to get name of calling function/method in PHP?

My favourite way, in one line!

debug_backtrace()[1]['function'];

You can use it like this:

echo 'The calling function: ' . debug_backtrace()[1]['function'];

Note that this is only compatible with versions of PHP released within the last year. But it's a good idea to keep your PHP up to date anyway for security reasons.

Converting Milliseconds to Minutes and Seconds?

Here is the full program

import java.util.concurrent.TimeUnit;

public class Milliseconds {

public static void main(String[] args) {
    long milliseconds = 1000000;

    // long minutes = (milliseconds / 1000) / 60;
    long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);

    // long seconds = (milliseconds / 1000);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);

    System.out.format("%d Milliseconds = %d minutes\n", milliseconds, minutes );
    System.out.println("Or");
    System.out.format("%d Milliseconds = %d seconds", milliseconds, seconds );

}
}

I found this program here "Link" there it is explained in detail.

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

How to position background image in bottom right corner? (CSS)

Voilà:

body {
   background-color: #000; /*Default bg, similar to the background's base color*/
   background-image: url("bg.png");
   background-position: right bottom; /*Positioning*/
   background-repeat: no-repeat; /*Prevent showing multiple background images*/
}

The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position

Perl read line by line

In bash foo is the name of the variable, and $ is an operator which means 'get the value of'.

In perl $foo is the name of the variable.

Difference between jQuery’s .hide() and setting CSS to display: none

They are the same thing. .hide() calls a jQuery function and allows you to add a callback function to it. So, with .hide() you can add an animation for instance.

.css("display","none") changes the attribute of the element to display:none. It is the same as if you do the following in JavaScript:

document.getElementById('elementId').style.display = 'none';

The .hide() function obviously takes more time to run as it checks for callback functions, speed, etc...

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

What is the difference between for and foreach?

A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.

A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.

how to use Spring Boot profiles

Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory

If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)

Then you can use the following commands to build and run the project.

1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa

Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application

What is the difference between old style and new style classes in Python?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

Old-style classes don't.

class OldStyleClass():
    pass

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

encapsulation vs abstraction real world example

I guess an egg shell can be consider the encapsulation and the contents the abstraction. The shell protects the information. You cant have the contents of an egg without the shell.,,LOL

Send a SMS via intent

This is another solution using SMSManager:

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("PhoneNumber-example:+989147375410", null, "SMS Message Body", null, null);

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

Clear contents of cells in VBA using column reference

You can access entire column as a range using the Worksheet.Columns object

Something like:

Worksheets(sheetname).Columns(1).ClearContents 

should clear contents of A column

There is also the Worksheet.Rows object if you need to do something similar for rows


The error you are receiving is likely due to a missing with block.

You can read about with blocks here: Microsoft Help

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

Is Viewstate turned on?

Edit: Perhaps you should reconsider overriding the rendering function

  protected override void RenderContents(HtmlTextWriter output)
    {
        ddlCountries.RenderControl(output);
        ddlStates.RenderControl(output);
    }

and instead add the dropdownlists to the control and render the control using the default RenderContents.

Edit: See the answer from Dennis which I alluded to in my previous comment:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

How to iterate over associative arrays in Bash

Welcome to input associative array 2.0!

    clear
    echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            echo -n "(pair $(( $i+1 )))"
            read -p ' Enter key: ' k
            read -p '         Enter value: ' v
            echo " "
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array 2.0!"

Output:

Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
         Enter value: Value#1

(pair 2) Enter key: Key Two
         Enter value: Value2

(pair 3) Enter key: Key3
         Enter value: Val3

(pair 4) Enter key: Key4
         Enter value: Value4


The keys are:  Key4 Key3 Key Number 1 Key Two
The values are:  Value4 Val3 Value#1 Value2

Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2

Thanks for using input associative array 2.0!

Input associative array 1.0

(keys and values that contain spaces are not supported)

    clear
    echo "Welcome to input associative array! (written by mO extraordinaire!)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            read -p 'Enter key and value separated by a space: ' k v
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array!"

Output:

Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100

The keys are:  h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are:  80 10 100 70 60 50 40 30 90 20

Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20

Thanks for using input associative array!

Fragment MyFragment not attached to Activity

I faced the same problem i just add the singletone instance to get resource as referred by Erick

MainFragmentActivity.defaultInstance().getResources().getString(R.string.app_name);

you can also use

getActivity().getResources().getString(R.string.app_name);

I hope this will help.

how to check if List<T> element contains an item with a Particular Property Value

bool contains = pricePublicList.Any(p => p.Size == 200);

How to terminate a Python script

In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what's built-in to stop the script and print an error message to my users. Here's my example:

## My example:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    print("Start codon is missing! Check your DNA sequence!")
    exit() ## as most folks said above

Later on, I found it is more succinct to just throw an error:

## My example revised:
if "ATG" in my_DNA: 
    ## <Do something & proceed...>
else: 
    raise ValueError("Start codon is missing! Check your DNA sequence!")

MongoDB what are the default user and password?

In addition with what @Camilo Silva already mentioned, if you want to give free access to create databases, read, write databases, etc, but you don't want to create a root role, you can change the 3rd step with the following:

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, 
             { role: "dbAdminAnyDatabase", db: "admin" }, 
             { role: "readWriteAnyDatabase", db: "admin" } ]
  }
)

Netbeans 8.0.2 The module has not been deployed

I had the same error here but with glassfish server. Maybe it can help. I needed to configure the glassfish-web.xml file with the content inside the <resources> from glassfish-resources.xml. As I got another error I could find this annotation in the server log:

Caused by: java.lang.RuntimeException: Error in parsing WEB-INF/glassfish-web.xml for archive [file:/C:/Users/Win/Documents/NetBeansProjects/svad/build/web/]: The xml element should be [glassfish-web-app] rather than [resources]

All I did then was to change the <resources> tag and apply <glassfish-web-app> in the glassfish-web.xml file.

Sort & uniq in Linux shell

Using sort -u does less I/O than sort | uniq, but the end result is the same. In particular, if the file is big enough that sort has to create intermediate files, there's a decent chance that sort -u will use slightly fewer or slightly smaller intermediate files as it could eliminate duplicates as it is sorting each set. If the data is highly duplicative, this could be beneficial; if there are few duplicates in fact, it won't make much difference (definitely a second order performance effect, compared to the first order effect of the pipe).

Note that there times when the piping is appropriate. For example:

sort FILE | uniq -c | sort -n

This sorts the file into order of the number of occurrences of each line in the file, with the most repeated lines appearing last. (It wouldn't surprise me to find that this combination, which is idiomatic for Unix or POSIX, can be squished into one complex 'sort' command with GNU sort.)

There are times when not using the pipe is important. For example:

sort -u -o FILE FILE

This sorts the file 'in situ'; that is, the output file is specified by -o FILE, and this operation is guaranteed safe (the file is read before being overwritten for output).

How to use nan and inf in C?

A compiler independent way, but not processor independent way to get these:

int inf = 0x7F800000;
return *(float*)&inf;

int nan = 0x7F800001;
return *(float*)&nan;

This should work on any processor which uses the IEEE 754 floating point format (which x86 does).

UPDATE: Tested and updated.

A reference to the dll could not be added

I used dependency walker to check out the internal references the dll was having. Turns out it was in need of the VB runtime msvbvm60.dll and since my dev box doesnt have that installed I was unable to register it using regsvr32

That seems to be the answer to my original question for now.

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

How to customize the background color of a UITableViewCell?

To extend on N.Berendt's answer - If you want to set cell color based on some state in the actual cell data object, at the time you are configuring the rest of the information for the table cell, which is typically when you are in the cellForRowAtIndexPath method, you can do this by overriding the willDisplayCell method to set the cell background color from the content view background color - this gets around the issue of the disclosure button backgrounds etc. not being right but still lets you control color in the cellForRowAtIndexPath method where you are doing all of your other cell customisation.

So: If you add this method to your table view delegate:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = cell.contentView.backgroundColor;
}

Then in your cellForRowAtIndexPath method you can do:

if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
    cell.contentView.backgroundColor = [UIColor blueColor];
}

This saves having to retrieve your data objects again in the willDisplayCell method and also saves having two places where you do tailoring/customisation of your table cell - all customisation can go in the cellForRowAtIndexPath method.

What is the correct way to check for string equality in JavaScript?

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

Webpack "OTS parsing error" loading fonts

I experienced the same problem, but for different reasons.

After Will Madden's solution didn't help, I tried every alternative fix I could find via the Intertubes - also to no avail. Exploring further, I just happened to open up one of the font files at issue. The original content of the file had somehow been overwritten by Webpack to include some kind of configuration info, likely from previous tinkering with the file-loader. I replaced the corrupted files with the originals, and voilà, the errors disappeared (for both Chrome and Firefox).

How to get the android Path string to a file on Assets folder?

You can use this method.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

In Kotlin (;D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }

Concatenating two one-dimensional NumPy arrays

Some more facts from the numpy docs :

With syntax as numpy.concatenate((a1, a2, ...), axis=0, out=None)

axis = 0 for row-wise concatenation axis = 1 for column-wise concatenation

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])

# Appending below last row
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

# Appending after last column
>>> np.concatenate((a, b.T), axis=1)    # Notice the transpose
array([[1, 2, 5],
       [3, 4, 6]])

# Flattening the final array
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])

I hope it helps !

Add the loading screen in starting of the android application

You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res folder and make a class like this :-

public class LoadingScreen {private ImageView loading;

LoadingScreen(ImageView loading) {
    this.loading = loading;
}

public void setLoadScreen(){
    final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
    final Handler loadingHandler = new Handler();
    Runnable runnable = new Runnable() {
        int loadingImgIndex = 0;
        public void run() {
            loading.setImageResource(loadingImages[loadingImgIndex]);
            loadingImgIndex++;
            if (loadingImgIndex >= loadingImages.length)
                loadingImgIndex = 0;
            loadingHandler.postDelayed(this, 500);
        }
    };
    loadingHandler.postDelayed(runnable, 500);
}}

In your MainActivity, you can pass a to the LoadingScreen class like this :-

private ImageView loadingImage;

Don't forget to add an ImageView in activity_main. After that call the LoadingScreen class like this;

LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();

I hope this will help you

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

How to pass variable number of arguments to a PHP function

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

Get querystring from URL using jQuery

An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...

  var queries = {};
  $.each(document.location.search.substr(1).split('&'),function(c,q){
    var i = q.split('=');
    queries[i[0].toString()] = i[1].toString();
  });
  console.log(queries);

Adding two numbers concatenates them instead of calculating the sum

You can do a precheck with regular expression wheather they are numbers as like

function myFunction() {
    var y = document.getElementById("txt1").value;
    var z = document.getElementById("txt2").value;
    if((x.search(/[^0-9]/g) != -1)&&(y.search(/[^0-9]/g) != -1))
      var x = Number(y)+ Number(z);
    else
      alert("invalid values....");
    document.getElementById("demo").innerHTML = x;
  }

Turn off auto formatting in Visual Studio

You might have had Power Tool installed.

In this case you can turn it off from 'Tools > Options > Productivity Power Tools > PowerCommands > General'

enter image description here

'Source code does not match the bytecode' when debugging on a device

This is the steps that worked for me (For both Mac and Windows):

  1. Click on "File"
  2. Click on "Invalidate Caches / Restart ..."
  3. Choose: "Invalidate and Restart"
  4. Wait for 20 minutes

How to center a WPF app on screen?

xaml

<Window ... WindowStartupLocation="CenterScreen">...

How to save to local storage using Flutter?

I was looking for the same, simple local storage but also with a reasonable level of security. The two solutions I've found that make the most sense are flutter_secure_storage (as mentioned by Raouf) for the small stuff, and hive for larger datasets.

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

Uncaught Typeerror: cannot read property 'innerHTML' of null

While you should ideally highlight the code which is causing an error and post that within your question, the error is because you are trying to get the inner HTML of the 'status' element:

var idPost=document.getElementById("status").innerHTML;

However the 'status' element does not exist within your HTML - either add the necessary element or change the ID you are trying to locate to point to a valid element.

Uncaught TypeError: Cannot read property 'appendChild' of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

Insert images to XML file

XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.

Deserialize JSON array(or list) in C#

Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

How to exclude a directory from ant fileset, based on directories contents

works for me:

<target name="build2-jar" depends="compile" >
   <jar destfile="./myJjar.jar">
        <fileset dir="./WebContent/WEB-INF/lib" includes="hibernate*.jar,mysql*.jar" />
        <fileset dir="./WebContent/WEB-INF/classes" excludes="**/controlador/*.class,**/form/*.class,**/orm/*.class,**/reporting/*.class,**/org/w3/xmldsig/*.class"/>
   </jar>

How to hide form code from view code/inspect element browser?

You can use the following tag

<body oncontextmenu="return false"><!-- your page body hear--></body>

OR you can create your own menu when right click:

https://github.com/swisnl/jQuery-contextMenu

GCM with PHP (Google Cloud Messaging)

Here's a library I forked from CodeMonkeysRU.

The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

I've also updated it to support iOS.

https://github.com/stevetauber/php-gcm-queue

Readably print out a python dict() sorted by key

I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:

for item in sorted(mydict):
    print(item)

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to read a local text file?

This might help,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", "sample.txt", true);
    xmlhttp.send();

How do I remove trailing whitespace using a regular expression?

To remove trailing white space while ignoring empty lines I use positive look-behind:

(?<=\S)\s+$

The look-behind is the way go to exclude the non-whitespace (\S) from the match.

Write HTML to string

I wrote these classes which served me well. It's simple yet pragmatic.

public class HtmlAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public HtmlAttribute(string name) : this(name, null) { }

    public HtmlAttribute(
        string name,
        string @value)
    {
        this.Name = name;
        this.Value = @value;
    }

    public override string ToString()
    {
        if (string.IsNullOrEmpty(this.Value))
            return this.Name;

        if (this.Value.Contains('"'))
            return string.Format("{0}='{1}'", this.Name, this.Value);

        return string.Format("{0}=\"{1}\"", this.Name, this.Value);
    }
}

public class HtmlElement
{
    protected List<HtmlAttribute> Attributes { get; set; }
    protected List<object> Childs { get; set; }
    public string Name { get; set; }
    protected HtmlElement Parent { get; set; }

    public HtmlElement() : this(null) { }

    public HtmlElement(string name, params object[] childs)
    {
        this.Name = name;
        this.Attributes = new List<HtmlAttribute>();
        this.Childs = new List<object>();

        if (childs != null && childs.Length > 0)
        {
            foreach (var c in childs)
            {
                Add(c);
            }
        }
    }

    public void Add(object o)
    {
        var a = o as HtmlAttribute;
        if (a != null)
            this.Attributes.Add(a);
        else
        {
            var h = o as HtmlElement;
            if (h != null && !string.IsNullOrEmpty(this.Name))
            {
                h.Parent = this;
                this.Childs.Add(h);
            }
            else
                this.Childs.Add(o);
        }
    }

    public override string ToString()
    {
        var result = new StringBuilder();

        if (!string.IsNullOrEmpty(this.Name))
        {
            result.Append(string.Format("<{0}", this.Name));
            if (this.Attributes.Count > 0)
            {
                result.Append(" ");
                foreach (var attr in this.Attributes)
                {
                    result.Append(attr.ToString());
                    result.Append(" ");
                }

                result = new StringBuilder(result.ToString().TrimEnd(' '));
            }

            if (this.Childs.Count == 0)
            {
                result.Append(" />");
            }
            else
            {
                result.AppendLine(">");

                foreach (var c in this.Childs)
                {
                    var cParts = c.ToString().Split('\n');

                    foreach (var p in cParts)
                    {
                        result.AppendLine(string.Format("{0}", p));
                    }
                }

                result.Append(string.Format("</{0}>", this.Name));
            }
        }
        else
        {
            foreach (var c in this.Childs)
            {
                var cParts = c.ToString().Split('\n');

                foreach (var p in cParts)
                {
                    result.AppendLine(string.Format("{0}", p));
                }
            }
        }

        var head = GetHeading(this);

        var ps = result.ToString().Split('\n');
        return string.Join("\r\n", (from p in ps select head + p.TrimEnd('\r')).ToArray());
    }

    string GetHeading(HtmlElement h)
    {
        if (h.Parent != null)
            return "    ";
        else
            return string.Empty;
    }
}

When to use CouchDB over MongoDB and vice versa

Of C, A & P (Consistency, Availability & Partition tolerance) which 2 are more important to you? Quick reference, the Visual Guide To NoSQL Systems

  • MongodB : Consistency and Partition Tolerance
  • CouchDB : Availability and Partition Tolerance

A blog post, Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison has 'Best used' scenarios for each NoSQL database compared. Quoting the link,

  • MongoDB: If you need dynamic queries. If you prefer to define indexes, not map/reduce functions. If you need good performance on a big DB. If you wanted CouchDB, but your data changes too much, filling up disks.
  • CouchDB : For accumulating, occasionally changing data, on which pre-defined queries are to be run. Places where versioning is important.

A recent (Feb 2012) and more comprehensive comparison by Riyad Kalla,

  • MongoDB : Master-Slave Replication ONLY
  • CouchDB : Master-Master Replication

A blog post (Oct 2011) by someone who tried both, A MongoDB Guy Learns CouchDB commented on the CouchDB's paging being not as useful.

A dated (Jun 2009) benchmark by Kristina Chodorow (part of team behind MongoDB),

I'd go for MongoDB.

Hope it helps.

How can I combine hashes in Perl?

This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

Compile to stand alone exe for C# app in Visual Studio 2010

You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.

If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).

Brew install docker does not include docker engine?

Please try running

brew install docker

This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.

If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:

brew install --cask docker 
open /Applications/Docker.app

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

How can I throw CHECKED exceptions from inside Java 8 streams?

You cannot.

However, you may want to have a look at one of my projects which allows you to more easily manipulate such "throwing lambdas".

In your case, you would be able to do that:

import static com.github.fge.lambdas.functions.Functions.wrap;

final ThrowingFunction<String, Class<?>> f = wrap(Class::forName);

List<Class> classes =
    Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
          .map(f.orThrow(MyException.class))
          .collect(Collectors.toList());

and catch MyException.

That is one example. Another example is that you could .orReturn() some default value.

Note that this is STILL a work in progress, more is to come. Better names, more features etc.

How to rotate portrait/landscape Android emulator?

See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.

On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key

Referring to a Column Alias in a WHERE Clause

Came here looking something similar to that, but with a CASE WHEN, and ended using the where like this: WHERE (CASE WHEN COLUMN1=COLUMN2 THEN '1' ELSE '0' END) = 0 maybe you could use DATEDIFF in the WHERE directly. Something like:

SELECT logcount, logUserID, maxlogtm
FROM statslogsummary
WHERE (DATEDIFF(day, maxlogtm, GETDATE())) > 120

Does Java have an exponential operator?

In case if anyone wants to create there own exponential function using recursion, below is for your reference.

public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

Please initialize the log4j system properly warning

Add the code

BasicConfigurator.configure();

in your static main class as below..

Note: add " \hadoop-2.7.1\share\hadoop\common\lib\commons-logging-1.1.3.jar & \hadoop-2.7.1\share\hadoop\common\lib\log4j-1.2.17.jar " as the external references

import org.apache.log4j.BasicConfigurator;

public class ViewCountDriver extends Configured implements Tool{

    public static void main(String[]args) throws Exception{

        BasicConfigurator.configure(); 

        int exitcode = ToolRunner.run(new ViewCountDriver(), args);
        System.exit(exitcode); 
    }
}

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

ASP.NET file download from server

Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.

See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.

Validate IPv4 address in Java

There is also an undocumented utility class sun.net.util.IPAddressUtil, which you should not actually use, although it might be useful in a quick one-off, throw-away utility:

boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);

Internally, this is the utility class InetAddress uses to parse IP addresses.

Note that this will return true for strings like "123", which, technically are valid IPv4 addresses, just not in dot-decimal notation.

Check if a string is a valid date using DateTime.TryParse

So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.

string dateString = "198101";

if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
     //do stuff
}

The output is stored in Temp and not needed afterwards, datestring is the input string to be tested.

Accessing Object Memory Address

Just in response to Torsten, I wasn't able to call addressof() on a regular python object. Furthermore, id(a) != addressof(a). This is in CPython, don't know about anything else.

>>> from ctypes import c_int, addressof
>>> a = 69
>>> addressof(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid type
>>> b = c_int(69)
>>> addressof(b)
4300673472
>>> id(b)
4300673392

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

How to understand nil vs. empty vs. blank in Ruby

nil? is a standard Ruby method that can be called on all objects and returns true if the object is nil:

b = nil
b.nil? # => true

empty? is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true if these objects contain no element:

a = []
a.empty? # => true

b = ["2","4"]
b.empty? # => false

empty? cannot be called on nil objects.

blank? is a Rails method that can be called on nil objects as well as empty objects.

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

Java Ordered Map

I think the closest collection you'll get from the framework is the SortedMap

JavaFX Panel inside Panel auto resizing

No need to cede.

just select pane ,right click then select Fit to parent.

It will automatically resize pane to anchor pane size.

Android SDK Setup under Windows 7 Pro 64 bit

My problem was installing the Android SDK in Eclipse Helios on Windows 7 Enterprise 64bit, I was getting the following error:

Missing requirement: Android Development Tools 0.9.7.v201005071157-36220 (com.android.ide.eclipse.adt.feature.group 0.9.7.v201005071157-36220) requires 'org.eclipse.jdt.junit 0.0.0' but it could not be found

Having followed the advice above to ensure that the JDK was in my PATH variable (it wasn't), installation went smoothly. I guess the error was somewhat spurious (incidentally if you're looking for the JARs that correspond to that class, they were in my profile rather than the Eclipse installation directory)

So, check that PATH variable!

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

Change icon-bar (?) color in bootstrap

Try over-riding CSS using !important

like this

.icon-bar {
   background-color:#FF0000 !important;
}

Hide Twitter Bootstrap nav collapse on click

I'm on Bootstrap 4, using fullPage.js with a fixed top nav, and tried everything listed here, with mixed results.

  • Tried the best, clean way :

    data-toggle="collapse" data-target=".navbar-collapse.show"
    

    The menu would collapse, but the href links wouldn't lead anywhere.

  • Tried the logical other ways :

    $('myClickableElements').on('click touchstart', function(){
      $(".navbar-collapse.show").collapse('hide');
      // or
      $(".navbar-collapse.show").collapse('toggle');
      // or
      $('.navbar-toggler').click()
    });
    

    There would be some weird behavior because of the touchstart event : the clicked buttons would end up not be the ones I actually clicked, hence breaking the links. Plus it would add the .show class to some other unrelated dropdowns in my nav, causing some more weird stuff.

  • Tried to change div to li
  • Tried to e.preventDefault() and e.stopPropagation()
  • Tried and tried more

Nothing would work.

So, instead, I had the (so far) marvelous idea of doing that :

$(window).on('hashchange',function(){
   $(".navbar-collapse.show").collapse('hide');
});

I already had stuff in that hashchange function, si I just had to add this line.

It actually does exactly what I want : collapsing the menu when the hash changes (i.e. a click leading somewhere else has occurred). Which is good, cause I can now have links in my menu that won't collapse it.

Who knows, maybe this will help someone in my situation!

And thanks to everyone who has participated in that thread, lots of info to be learned here.