Programs & Examples On #Activity stack

How to prevent going back to the previous activity?

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android =>
    public void onBackPressed() {


How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

Run CSS3 animation only once (at page loading)

An easy solution to solve this problem is by just adding more seconds to the animation in a:hover and taking advantage of the transitions in @keyframes

a:hover {
        animation: hover 200s infinite alternate ease-in-out;

Just make the progression of @keyframes go faster by using percentages.

@keyframes hover {
    0% {
        transform: scale(1, 1);
    1% {
        transform: scale(1.1, 1.1);
    100% {
        transform: scale(1.1, 1.1);

200 seconds or 300 seconds in the animation is more than enough to make sure the animation doesn't restart. A normal person won't last more than a few seconds hovering an image.

How to remove multiple deleted files in Git repository

You can use

git commit -m "remove files" -a
git push

After you had delete files manually.

how to disable DIV element and everything inside

pure javascript no jQuery

function sah() {_x000D_
  $("#div2").attr("disabled", "disabled").off('click');_x000D_
  var x1=$("#div2").hasClass("disabledDiv");_x000D_
    function sah1(el) {_x000D_
        try {_x000D_
            el.disabled = el.disabled ? false : true;_x000D_
        } catch (E) {}_x000D_
        if (el.childNodes && el.childNodes.length > 0) {_x000D_
            for (var x = 0; x < el.childNodes.length; x++) {_x000D_
  padding:5px 10px;_x000D_
.disabledDiv {_x000D_
    pointer-events: none;_x000D_
    opacity: 0.4;_x000D_
<script src=""></script>_x000D_
<div id="div1">_x000D_
        <div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
        <input type="text" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="button" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="radio" name="sex" value="Male" />Male_x000D_
        <Br />_x000D_
        <input type="radio" name="sex" value="Female" />Female_x000D_
        <Br />_x000D_
    <Br />_x000D_
    <Br />_x000D_
    <input type="button" value="Click" onclick="sah()" />

Display UIViewController as Popup in iPhone

You can use EzPopup (, it is a Swift pod and very easy to use:

// init YourViewController
let contentVC = ...

// Init popup view controller with content is your content view controller
let popupVC = PopupViewController(contentController: contentVC, popupWidth: 100, popupHeight: 200)

// show it by call present(_ , animated:) method from a current UIViewController
present(popupVC, animated: true)

Rearrange columns using cut

Using join:

join -t $'\t' -o 1.2,1.1 file.txt file.txt


  • -t $'\t' In GNU join the more intuitive -t '\t' without the $ fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $ should be necessary. See: unix join separator char.

  • join needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join into performing the desired action.

  • For systems with low resources join offers a smaller footprint than some of the tools used in other answers:

    wc -c $(realpath `which cut join sed awk perl`) | head -n -1
      43224 /usr/bin/cut
      47320 /usr/bin/join
     109840 /bin/sed
     658072 /usr/bin/gawk
    2093624 /usr/bin/perl

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

How to find which git branch I am on when my disk is mounted on other server

git branch with no arguments displays the current branch marked with an asterisk in front of it:

user@host:~/gittest$ git branch
* master

In order to not have to type this all the time, I can recommend git prompt:

In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?

Git stores the HEAD in the file .git/HEAD. If you're on the master branch, it could look like this:

$ cat .git/HEAD
ref: refs/heads/master

regular expression to validate datetime format (MM/DD/YYYY)

It's long, but great:

new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code

MVC 5 Access Claims Identity User Data

To further touch on Darin's answer, you can get to your specific claims by using the FindFirst method:

var identity = (ClaimsIdentity)User.Identity;
var role = identity.FindFirst(ClaimTypes.Role).Value;

How to split a delimited string in Ruby and convert it to an array?


each_char does basically the same as split(''): It splits a string into an array of its characters.

hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..

When a 'blur' event occurs, how can I find out which element focus went *to*?

I am also trying to make Autocompleter ignore blurring if a specific element clicked and have a working solution, but for only Firefox due to explicitOriginalTarget

Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( 
        function(origfunc, ev) {
            if ($(this.options.ignoreBlurEventElement)) {
                var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);
                if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {
                    return origfunc(ev);

This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.

Checkout one file from Subversion

Use svn cat or svn export.

For that, you don't need to fetch the working directory, but you will not be able to commit any changes you make. If you need to make changes and commit them, you need a working directory, but you don't have to fetch it completely. Checkout the revision where the directory was still/almost empty, and then use 'svn cat' to extract the file from HEAD.

Regex match text between tags

Use match instead, and the g flag.


How to delete object from array inside foreach loop?

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array

What database does Google use?

And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.

Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.

How to stop the Timer in android?

In java.util.timer one can use .cancel() to stop the timer and clear all pending tasks.

Back button and refreshing previous activity

Try This

 public void refreshActivity() {
    Intent i = new Intent(this, MainActivity.class);


or in Fragment

  public void refreshActivity() {
    Intent i = new Intent(getActivity(), MainActivity.class);


And Add this method to your onBackPressed() like

public void onBackPressed() {      

Thats It...

How to style a clicked button in CSS

button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well

  color: red;_x000D_

How do I clone a range of array elements to a new array?

As far as cloning goes, I don't think serialization calls your constructors. This may break class invariants if you're doing interesting things in the ctor's.

It seems the safer bet is virtual clone methods calling copy constructors.

protected MyDerivedClass(MyDerivedClass myClass) 

public override MyBaseClass Clone()
  return new MyDerivedClass(this);

How to get the current loop index when using Iterator?

Use a ListIterator to iterate through the Collection. If the Collection is not a List to start with use Arrays.asList(Collection.toArray()) to turn it into a List first.

Difference between require, include, require_once and include_once?

Basically, if you require a wrong path, PHP throws a fatal error and the shutdown function is called, but when you include a wrong path, PHP will continue execution, but it will just display a warning that the file does not exist.

From the English word require, PHP is told that the execution of the page or file depends on the file required.

From my experience, it's norm to require important files such as configuration files, database classes and other important utilities.

What's the difference between JPA and Hibernate?

JPA is a specification that you implement in your data layer to perform db opertations, OR mappings and other required tasks.

Since it is just a specification, you need a tool to have it implemented. That tool can be either Hibernate, TopLink, iBatis, spring-data etc.

You don't necessarily require JPA if you are using Hibernate in your Data Layer. But if you use JPA specification for Hibernate, then it will make switching to other ORM tools like iBatis, TopLink easy in future, because the specification is common for others as well.

*(if you remember, you do import javax.persistence.*; when you use annotations for OR mapping (like @Id, @Column, @GeneratedValue etc.) in Hibernate, that's where you are using JPA under Hibernate, you can use JPA's @Query & other features as well)

Is there any difference between a GUID and a UUID?

GUID has longstanding usage in areas where it isn't necessarily a 128-bit value in the same way as a UUID. For example, the RSS specification defines GUIDs to be any string of your choosing, as long as it's unique, with an "isPermalink" attribute to specify that the value you're using is just a permalink back to the item being syndicated.

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

How to inject a Map using the @Value Spring Annotation?

I had a simple code for Spring Cloud Config

like this:

In[email protected][email protected]


@Bean(name = "mongoConfig")
@ConfigurationProperties(prefix = "")
public Map<String, Map<String, String>> mongoConfig() {
    return new HashMap();


@Qualifier(value = "mongoConfig")
private Map<String, String> mongoConfig;

@Bean(name = "mongoTemplates")
public HashMap<String, MongoTemplate> mongoTemplateMap() throws UnknownHostException {
    HashMap<String, MongoTemplate> mongoTemplates = new HashMap<>();
    for (Map.Entry<String, String>> entry : mongoConfig.entrySet()) {
        String k = entry.getKey();
        String v = entry.getValue();
        MongoTemplate template = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI(v)));
        mongoTemplates.put(k, template);
    return mongoTemplates;

How can I capitalize the first letter of each word in a string?

Here's a summary of different ways to do it, they will work for all these inputs:

""           => ""       
"a b c"      => "A B C"             
"foO baR"    => "FoO BaR"      
"foo    bar" => "Foo    Bar"   
"foo's bar"  => "Foo's Bar"    
"foo's1bar"  => "Foo's1bar"    
"foo 1bar"   => "Foo 1bar"     

- The simplest solution is to split the sentence into words and capitalize the first letter then join it back together:

# Be careful with multiple spaces, and empty strings
# for empty words w[0] would cause an index error, 
# but with w[:1] we get an empty string as desired
def cap_sentence(s):
  return ' '.join(w[:1].upper() + w[1:] for w in s.split(' ')) 

- If you don't want to split the input string into words first, and using fancy generators:

# Iterate through each of the characters in the string and capitalize 
# the first char and any char after a blank space
from itertools import chain 
def cap_sentence(s):
  return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )

- Or without importing itertools:

def cap_sentence(s):
  return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )

- Or you can use regular expressions, from steveha's answer:

# match the beginning of the string or a space, followed by a non-space
import re
def cap_sentence(s):
  return re.sub("(^|\s)(\S)", lambda m: +, s)

Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:

  return s.title()

# Undesired outputs: 
"foO baR"    => "Foo Bar"       
"foo's bar"  => "Foo'S Bar" 
"foo's1bar"  => "Foo'S1Bar"     
"foo 1bar"   => "Foo 1Bar"      

  return ' '.join(w.capitalize() for w in s.split())    
  # or
  import string
  return string.capwords(s)

# Undesired outputs:
"foO baR"    => "Foo Bar"      
"foo    bar" => "Foo Bar"      

using ' ' for the split will fix the second output, but capwords() still won't work for the first

  return ' '.join(w.capitalize() for w in s.split(' '))    
  # or
  import string
  return string.capwords(s, ' ')

# Undesired outputs:
"foO baR"    => "Foo Bar"      

Be careful with multiple blank spaces

  return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo    bar" => "Foo Bar"                 

How to use PHP to connect to sql server

 $server_name = "your server name";
 $database_name = "your database name";
   $conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");

catch(PDOException $e)



href around input type submit

It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).

To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).

SELECT with a Replace()

To expand on Oded's answer, your conceptual model needs a slight adjustment here. Aliasing of column names (AS clauses in the SELECT list) happens very late in the processing of a SELECT, which is why alias names are not available to WHERE clauses. In fact, the only thing that happens after column aliasing is sorting, which is why (to quote the docs on SELECT):

column_alias can be used in an ORDER BY clause. However, it cannot be used in a WHERE, GROUP BY, or HAVING clause.

If you have a convoluted expression in the SELECT list, you may be worried about it 'being evaluated twice' when it appears in the SELECT list and (say) a WHERE clause - however, the query engine is clever enough to work out what's going on. If you want to avoid having the expression appear twice in your query, you can do something like

SELECT c1, c2, c3, expr1
    ( SELECT c1, c2, c3, some_complicated_expression AS expr1 ) inner
WHERE expr1 = condition

which avoids some_complicated_expression physically appearing twice.

How can I tell if a DOM element is visible in the current viewport?

This is the easy and small solution that has worked for me.

Example: You want to see if the element is visible in the parent element that has overflow scroll.

$(window).on('scroll', function () {

     var container = $('#sidebar');
     var containerHeight = container.height();
     var scrollPosition = $('#row1').offset().top - container.offset().top;

     if (containerHeight < scrollPosition) {
         console.log('not visible');
     } else {

Check if a file exists with wildcard in shell script

The question wasn't specific to Linux/Bash so I thought I would add the Powershell way - which treats wildcards different - you put it in the quotes like so below:

If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
  Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
  Remove-Item -force -v -path ./output/test-pdf-docx/*.docx

I think this is helpful because the concept of the original question covers "shells" in general not just Bash or Linux, and would apply to Powershell users with the same question too.

How can I load the contents of a text file into a batch file variable?

for /f "delims=" %%i in (count.txt) do set c=%%i
echo %c%

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo

in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how

cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

if the directory /var/mysql doesnt exist, we must create it with

sudo mkdir /var/mysql

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

mdf <- melt(mdf, id.vars="Company","value","Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

What's the most concise way to read query parameters in AngularJS?

you could also use $location.$$search.yourparameter

How to change PHP version used by composer

Old question I know, but just to add some additional information:

  • WAMP is used only on Microsoft Windows Operating Systems.
  • Changing the version of PHP used through the left-click -> PHP -> Version menu changes the version used by Apache to server your site.
  • Changing the version of PHP used through the right-click -> Tools -> Change PHP CLI Version menu changes the version used by WAMP's PHP CLI.

Note: It is important to understand that the "PHP CLI Version" is used by WAMP's own internal PHP scripts. This "PHP CLI Version" has nothing to do with the version you wish to use for your scripts, Composer or anything else.

For your scripts to work with the version you require, you need to add it's path to the Users Environmental Path. You could add it to the Systems environmental Path but the Users Path is the recommended option.

From WAMP v3.1.2, it would display an error when it detect reference to a PHP path in the System or User Environmental Path. This was to stop confusion such as you were experiencing. Since v3.1.7 the display of this error can now be optionally displayed through a selection in the WampSettings menu.

As indicated in previous answers, adding an installed PHP path (such as "C:\wamp64\bin\php\php7.2.30") to the Users Environmental Path is the correct approach. PS: As the value of the Users Environmental Path is a string, all paths added must be separated with a semi-colon (;)

After experiencing the exact same problem (IE: Choosing which version of PHP I wanted Composer to use), I created a script which could easily and rapidly switch between PHP CLI Versions depending on what project I was working on.

The Windows batch script "WampServer-PHP-CLI-Version-Changer" can be found at

I hope this helps others.

Good luck.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

Generally, this error comes because we don’t make default constructor.
But in my case:
The issue was coming only due to I have made used object class inside parent class.
This has wasted my whole day.

Resize font-size according to div size

Here's a SCSS version of @Patrick's mixin.

$mqIterations: 19;
@mixin fontResize($iterations)
  $i: 1;
  @while $i <= $iterations
    @media all and (min-width: 100px * $i) {
      body { font-size:0.2em * $i; }
    $i: $i + 1;
@include fontResize($mqIterations);

Can you use if/else conditions in CSS?

Set the server up to parse css files as PHP and then define the variable variable with a simple PHP statement.

Of course this assumes you are using PHP...

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

XSLT 2.0 has upper-case() and lower-case() functions. In case of XSLT 1.0, you can use translate():

<xsl:value-of select="translate("xslt", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")" />

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

I was having the same problem in Linux Ubuntu 18. After the update from Ubuntu 17.10, every git command would show that message.

The way to solve it is to make sure that you have the correct permission on the id_rsa and

Check the current chmod number by using stat --format '%a' <file>. It should be 600 for id_rsa and 644 for

To change the permission on the files use

chmod 600 id_rsa
chmod 644

That solved my issue with the update.

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).


  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

Convert tabs to spaces in Notepad++

If you happen to work in a Unix environment, the expand command is what you need:

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
create trigger Employees_Trigger_Update on Employees
after update
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Combine two tables that have no common fields

    null as path, 
    null as Description 

    path as cid, 
    Description from zmw_t_path;

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

Using union and order by clause in mysql

(select add_date,col2 from table_name) 
(select add_date,col2 from table_name) 
(select add_date,col2 from table_name) 

order by add_date

How to maximize a window using Python

Try using 'Figure.set_size_inches' method, with the extra keyword argument forward=True. According to the documentation, this should resize the figure window.

Whether that actually happens will depend on the operating system you are using.

select from one table, insert into another table oracle sql query

From the oracle documentation, the below query explains it better

INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

You can read this link

Your query would be as follows

//just the concept    
    INSERT INTO quotedb
    (COLUMN_NAMES) //seperated by comma
    SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker

Note: Make sure the columns in insert and select are in right position as per your requirement

Hope this helps!

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

one simple workaround is to catch the exception :

try {
catch (WindowManager.BadTokenException e) {
        //use a log message

It's not elegant but sometimes easy when you have to manage async operations and you are not sure wether activity is up or not when you want to show the dialog.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

if you decide to use, a sass-based css framework, it provides very useful darken() and lighten() sass functions to dynamically generate css. it's very clean:

@import compass/utilities

$link_color: #bb8f8f
  color: $link_color
  color: $link_color
  color: darken($link_color,10)


a {
  color: #bb8f8f;

a:visited {
  color: #bb8f8f;

a:hover {
  color: #a86f6f;

jQuery click not working for dynamically created items

$("#container").delegate("span", "click", function (){

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Failed to connect to, reason: errno:111 Connection refused

There are changes in mongod.conf file in the latest MongoDB v 3.6.5 +

Here is how I fixed this issue on mac os High Sierra v 10.12.3

Note: I assume that you have installed/upgrade MongoDB using homebrew

mongo --version

MongoDB shell version v3.6.5 
git version: a20ecd3e3a174162052ff99913bc2ca9a839d618 
OpenSSL version: OpenSSL 1.0.2o  27 Mar 2018 
allocator: system modules: none build environment:
distarch: x86_64
target_arch: x86_64
  1. find mongod.conf file

     sudo find / -name mongod.conf` 

    /usr/local/etc/mongod.conf > first result .

  2. open mongod.conf file

    sudo vi /usr/local/etc/mongod.conf
  3. edit in the file for remote access under net: section

     port: 27017  
     bindIpAll: true 
     #bindIp: // comment this out
  4. restart mongodb

    if you have installed using brew than

    brew services stop mongodb
    brew services start mongodb

otherwise, kill the process.

   sudo kill -9 <procssID>

html vertical align the text inside input type button

Try adding the property line-height: 22px; to the code.

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

Don't forget any? which is generally !empty?. In Rails I typically check for the presence of something at the end of a statement with if something or unless something then use blank? where needed since it seems to work everywhere.

How to git reset --hard a subdirectory?

A reset will normally change everything, but you can use git stash to pick what you want to keep. As you mentioned, stash doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index flag. In your example, you would stash the b directory, then reset everything else.

# How to make files a/* reappear without changing b and without recreating a/c?
git add b               #add the directory you want to keep
git stash --keep-index  #stash anything that isn't added
git reset               #unstage the b directory
git stash drop          #clean up the stash (optional)

This gets you to a point where the last part of your script will output this:

After checkout:
# On branch master
# Changes not staged for commit:
#   modified:   b/a/ba
no changes added to commit (use "git add" and/or "git commit -a")

I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).

This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.

CSS :not(:last-child):after selector

Every things seems correct. You might want to use the following css selector instead of what you used.

ul > li:not(:last-child):after

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options


Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

Raw SQL Query without DbSet - Entity Framework Core

You can use this (from ) :

public static class SqlQueryExtensions
    public static IList<T> SqlQuery<T>(this DbContext db, string sql, params object[] parameters) where T : class
        using (var db2 = new ContextForQueryType<T>(db.Database.GetDbConnection()))
            return db2.Query<T>().FromSql(sql, parameters).ToList();

    private class ContextForQueryType<T> : DbContext where T : class
        private readonly DbConnection connection;

        public ContextForQueryType(DbConnection connection)
            this.connection = connection;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            // switch on the connection type name to enable support multiple providers
            // var name = con.GetType().Name;
            optionsBuilder.UseSqlServer(connection, options => options.EnableRetryOnFailure());


        protected override void OnModelCreating(ModelBuilder modelBuilder)

And the usage:

    using (var db = new Db())
        var results = db.SqlQuery<ArbitraryType>("select 1 id, 'joe' name");
        //or with an anonymous type like this
        var results2 = db.SqlQuery(() => new { id =1, name=""},"select 1 id, 'joe' name");

How do I remove a file from the FileList

If you want to delete only several of the selected files: you can't. The File API Working Draft you linked to contains a note:

The HTMLInputElement interface [HTML5] has a readonly FileList attribute, […]
[emphasis mine]

Reading a bit of the HTML 5 Working Draft, I came across the Common input element APIs. It appears you can delete the entire file list by setting the value property of the input object to an empty string, like:

document.getElementById('multifile').value = "";

BTW, the article Using files from web applications might also be of interest.

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".

The problem relates to the "shrinkwrap" or package-lock.json which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json.

Adding these options to the npm install command should allow packages to install again.

   --no-optional argument will prevent optional dependencies from being installed.

   --no-shrinkwrap argument, which will ignore an available package lock or
                   shrinkwrap file and use the package.json instead.

   --no-package-lock argument will prevent npm from creating a package-lock.json file.

The complete command looks like this:

    npm install --no-optional --no-shrinkwrap --no-package-lock


What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Changing the color of a clicked table row using jQuery

Here's a possible solution that will color the entire row for your table.


tr.highlighted td {
    background: red;


$('#data tr').click(function(e) {
    $('#data tr').removeClass('highlighted');


Open Jquery modal dialog on click event

If you want to put some page in the dialog then you can use these

function Popup()
 height: 625,
 width: 600,
 close: function(event,ui){




<Div id="pop"  style="display:none;">


Change input text border color without changing its height

Is this what you are looking for.

$("input.address_field").on('click', function(){  
     $(this).css('border', '2px solid red');

Can I write into the console in a unit test? If yes, why doesn't the console window open?

I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:

public static void DumbDebug(string message)
    File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
} up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.

jQuery UI DatePicker to show year only

check this out jquery calendar to show only year and month

or something like this

$("#datepicker").datepicker( "option", "dateFormat", "yy" );?

Showing alert in angularjs when user leaves a page

$scope.rtGo = function(){

$scope.init = function () {

Reload page: using init

Tainted canvases may not be exported

Check out CORS enabled image from MDN. Basically you must have a server hosting images with the appropriate Access-Control-Allow-Origin header.

<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS

You will be able to save those images to DOM Storage as if they were served from your domain otherwise you will run into security issue.

var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = ""; // insert image url here

img.crossOrigin = "Anonymous";

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage( img, 0, 0 );
    localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;

Custom thread pool in Java 8 parallel stream

If you don't need a custom ThreadPool but you rather want to limit the number of concurrent tasks, you can use:

List<Path> paths = List.of("/path/file1.csv", "/path/file2.csv", "/path/file3.csv").stream().map(e -> Paths.get(e)).collect(toList());
List<List<Path>> partitions = Lists.partition(paths, 4); // Guava method

partitions.forEach(group -> group.parallelStream().forEach(csvFilePath -> {
       // do your processing   

(Duplicate question asking for this is locked, so please bear me here)

How to customize the back button on ActionBar

tray this:


inside onCreate();

iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

Bootstrap carousel width and height

If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="..." alt="First slide">
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Second slide">
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Third slide">


The solution is to put "div" around the image, with the class ".container", like this:

<div class="carousel-item active">
  <div class="container">
    <img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">

What is username and password when starting Spring Boot with Tomcat?

I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password

Please look into your pom.xml file for:


If you have that in your pom than you should have a log console message like this:

Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

And in the browser prompt you will import the user user and the password printed in the console.

Or if you want to configure spring security you can take a look at Spring Boot secured example

It is explained in the Spring Boot Reference documentation in the Security section, it indicates:

The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

How to capture the browser window close event?

I used Slaks answer but that wasn't working as is, since the onbeforeunload returnValue is parsed as a string and then displayed in the confirmations box of the browser. So the value true was displayed, like "true".

Just using return worked. Here is my code

var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
//var redirectAfterPrompt = "";
$('a').live('click', function() { preventUnloadPrompt = true; });
$('form').live('submit', function() { preventUnloadPrompt = true; });
$(window).bind("beforeunload", function(e) { 
    var rval;
    if(preventUnloadPrompt) {
    } else {
        return messageBeforeUnload;
    return rval;

How to change TextBox's Background color?


TextBox.Background = System.Drawing.Color.Red;

rails generate model

The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.

The normal way to get there from scratch is:

$ rails new PROJECT_NAME
$ rails generate model ad \
    name:string \ 
    description:text \
    price:decimal \
    seller_id:integer \
    email:string img_url:string

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

What is the best way to dump entire objects to a log in C#?

Following is another version that does the same thing (and handle nested properties), which I think is simpler (no dependencies on external libraries and can be modified easily to do things other than logging):

public class ObjectDumper
    public static string Dump(object obj)
        return new ObjectDumper().DumpObject(obj);

    StringBuilder _dumpBuilder = new StringBuilder();

    string DumpObject(object obj)
        DumpObject(obj, 0);
        return _dumpBuilder.ToString();

    void DumpObject(object obj, int nestingLevel = 0)
        var nestingSpaces = "".PadLeft(nestingLevel * 4);

        if (obj == null)
            _dumpBuilder.AppendFormat("{0}null\n", nestingSpaces);
        else if (obj is string || obj.GetType().IsPrimitive)
            _dumpBuilder.AppendFormat("{0}{1}\n", nestingSpaces, obj);
        else if (ImplementsDictionary(obj.GetType()))
            using (var e = ((dynamic)obj).GetEnumerator())
                var enumerator = (IEnumerator)e;
                while (enumerator.MoveNext())
                    dynamic p = enumerator.Current;

                    var key = p.Key;
                    var value = p.Value;
                    _dumpBuilder.AppendFormat("{0}{1} ({2})\n", nestingSpaces, key, value != null ? value.GetType().ToString() : "<null>");
                    DumpObject(value, nestingLevel + 1);
        else if (obj is IEnumerable)
            foreach (dynamic p in obj as IEnumerable)
                DumpObject(p, nestingLevel);
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
                string name = descriptor.Name;
                object value = descriptor.GetValue(obj);

                _dumpBuilder.AppendFormat("{0}{1} ({2})\n", nestingSpaces, name, value != null ? value.GetType().ToString() : "<null>");
                DumpObject(value, nestingLevel + 1);

    bool ImplementsDictionary(Type t)
        return t.GetInterfaces().Any(i => i.Name.Contains("IDictionary"));

How to update a git clone --mirror?

This is the command that you need to execute on the mirror:

git remote update

jQuery: click function exclude children.

I personally would add a click handler to the child element that did nothing but stop the propagation of the click. So it would look something like:

$('.example > div').click(function (e) {

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.

#include <stdio.h>
int main () 
    printf("Hello ");
    goto Cleanup;
Cleanup: ; //This is an empty statement.
    char *str = "World\n";
    printf("%s\n", str);

jQuery: Check if button is clicked

You can use this:

   $(this).data('clicked', true);

Now check it via an if statement:

   // code here 

For more information you can visit the jQuery website on the .data() function.

How to completely uninstall Android Studio from windows(v10)?


check this folder in


its have an issue and fix it then restart android studio.

How do I compile the asm generated by GCC?

nasm -f bin -o 2_hello 2_hello.asm

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

jQuery Multiple ID selectors

Try this:


Add CSS or JavaScript files to layout head from views or partial views

For those of us using ASP.NET MVC 4 - this may be helpful.

First, I added a BundleConfig class in the App_Start folder.

Here’s my code that I used to create it:

using System.Web.Optimization;

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/SiteMaster.css"));

Second, I registered the BundleConfig class in the Global.asax file:

protected void Application_Start()

Third, I added style helpers to the my CSS file:

/* Styles for validation helpers */
.field-validation-error {
    color: red;
    font-weight: bold;

.field-validation-valid {
    display: none;

input.input-validation-error {
    border: 1px solid #e80c4d;

input[type="checkbox"].input-validation-error {
    border: 0 none;

.validation-summary-errors {
    color: #e80c4d;
    font-weight: bold;
    font-size: 1.1em;

.validation-summary-valid {
    display: none;

Finally I used this syntax in any View:


jQuery Screen Resolution Height Adjustment

Another example for vertically and horizontally centered div or any object(s):

 var obj = $("#divID");
 var halfsc = $(window).height()/2;
 var halfh = $(obj).height() / 2; 

 var halfscrn = screen.width/2;
 var halfobj =$(obj).width() / 2; 

 var goRight =  halfscrn - halfobj ;
 var goBottom = halfsc - halfh;

 $(obj).css({marginLeft: goRight }).css({marginTop: goBottom });

WPF C# button style

   <Button x:Name="mybtnSave" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top"  Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF080505" Offset="1"/>
                <GradientStop Color="White" Offset="0.536"/>
        <StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF3ED82E" Offset="0"/>
                    <GradientStop Color="#FF3BF728" Offset="1"/>
                    <GradientStop Color="#FF212720" Offset="0.52"/>
            <Image HorizontalAlignment="Left"  Source="image/Append Or Save 3.png" Height="36" Width="203" />
            <TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
    </Button>ente[![enter image description here][1]][1]r image description here

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:

function stringToBytes(text) {
  const length = text.length;
  const result = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    const code = text.charCodeAt(i);
    const byte = code > 255 ? 32 : code;
    result[i] = byte;
  return result;

If you want to convert the resulting byte array into a Blob, you would do something like this:

const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });

Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.

How to apply slide animation between two activities in Android?

Hopefully, it will work for you.

startActivityForResult( intent, 1 , ActivityOptions.makeCustomAnimation(getActivity(),R.anim.slide_out_bottom,R.anim.slide_in_bottom).toBundle());

Get request URL in JSP which is forwarded by Servlet

To get the current path from within the JSP file you can simply do one of the following:

<%= request.getContextPath() %>
<%= request.getRequestURI() %>
<%= request.getRequestURL() %>

How do I calculate the date six months from the current date using the datetime Python module?

Using below given function you can get date after/before x months.

from datetime import date

def next_month(given_date, month):
    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

    if mm == 0:
        yyyy -= 1
        mm = 12
    return given_date.replace(year=yyyy, month=mm)

if __name__ == "__main__":
    today =

    for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
        next_date = next_month(today, mm)

Unsigned values in C

In the hexadecimal it can't get a negative value. So it shows it like ffffffff.

The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).

Hide separator line on one UITableViewCell

It work for me when I use extension and call within layoutSubviews() for update layout views immediately.

extension UITableViewCell {

    func removeSeparator() {
        separatorInset = UIEdgeInsetsMake(0, bounds.size.width, 0, 0)

override func layoutSubviews() {


Cannot find name 'require' after upgrading to Angular4

Add the following line at the top of the file that gives the error:

declare var require: any

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

If you start Notepad and then File -> Save As -> Write .htaccess and choose "All Files" as the type - then it will create the .htaccess file for you.

Notepad save as .htaccess

How do I create variable variables?

Use the built-in getattr function to get an attribute on an object by name. Modify the name as needed.

obj.spam = 'eggs'
name = 'spam'
getattr(obj, name)  # returns 'eggs'


We only have one person entering records, so I execute the following query immediately following the insert:

$result = $conn->query("SELECT * FROM corex ORDER BY id DESC LIMIT 1");

while ($row = $result->fetch_assoc()) {

            $id = $row['id'];


This retrieves the last id from the database.

Are PostgreSQL column names case-sensitive?

Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:


Values (string literals / constants) are enclosed in single quotes:


So, yes, PostgreSQL column names are case-sensitive (when double-quoted):

SELECT * FROM persons WHERE "first_Name" = 'xyz';

Read the manual on identifiers here.

My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

PHP checkbox set to check based on database value

Extract the information from the database for the checkbox fields. Next change the above example line to: (this code assumes that you've retrieved the information for the user into an associative array called dbvalue and the DB field names match those on the HTML form)

<input type="checkbox" name="tag_1" id="tag_1" value="yes" <?php echo ($dbvalue['tag_1']==1 ? 'checked' : '');?>>

If you're looking for the code to do everything for you, you've come to the wrong place.

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

If input field is empty, disable submit button

You are disabling only on document.ready and this happens only once when DOM is ready but you need to disable in keyup event too when textbox gets empty. Also change $(this).val.length to $(this).val().length

        if($(this).val().length !=0)
            $('.sendButton').attr('disabled', false);            

Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs

        $('.sendButton').prop('disabled', this.value == "" ? true : false);     

Remove part of string in Java

You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.

str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

How can I call the 'base implementation' of an overridden virtual method?

You can't do it by C#, but you can edit MSIL.

IL code of your Main method:

.method private hidebysig static void Main() cil managed
    .maxstack 1
    .locals init (
        [0] class MsilEditing.A a)
    L_0000: nop 
    L_0001: newobj instance void MsilEditing.B::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance void MsilEditing.A::X()
    L_000d: nop 
    L_000e: ret 

You should change opcode in L_0008 from callvirt to call

L_0008: call instance void MsilEditing.A::X()

react-native :app:installDebug FAILED

I couldn't get it to work with a hardware device. I kept getting the same error, but...

For your emulator you have to choose the IntelX86 Atom System image. Then ADB will connect to your emulator and it will properly install the installDebug.apk.

This is what I had to do.

Also look at this tutorial. It helped me immensely.

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

With ng-bind-html-unsafe removed, how do I inject HTML?

I've had a similar problem. Still couldn't get content from my markdown files hosted on github.

After setting up a whitelist (with added github domain) to the $sceDelegateProvider in app.js it worked like a charm.

Description: Using a whitelist instead of wrapping as trusted if you load content from a different urls.

Docs: $sceDelegateProvider and ngInclude (for fetching, compiling and including external HTML fragment)

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();


    return ds;

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

Groovy built-in REST/HTTP client?


public class HttpclassgetrRoles {
     static void main(String[] args){
         def baseUrl = new URL('')

         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text


DECODE( ) function in SQL Server

Just for completeness (because nobody else posted the most obvious answer):



MSSQL (2012+):


The bad news:

DECODE with more than 4 arguments would result in an ugly IIF cascade

JAVA_HOME directory in Linux

To show the value of an environment variable you use:


so in your case will be:


In case you don't have it setted, you can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

Index of element in NumPy array

If you are interested in the indexes, the best choice is np.argsort(a)

a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)

How do I create a batch file timer to execute / call another batch throughout the day

I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)

Thymeleaf: Concatenation - Could not parse as expression

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

How to add an element to a list?

Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

How to move table from one tablespace to another in oracle 11g

Moving tables:

First run:

SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
WHERE OWNER = '<schema_name>'

-- Or suggested in the comments (did not test it myself)

FROM dba_tables 

Where <schema_name> is the name of the user. And <tablespace_name> is the destination tablespace.

As a result you get lines like:


Paste the results in a script or in a oracle sql developer like application and run it.

Moving indexes:

First run:

SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;' 
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';

The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.

As a result you should get something like:


Paste the results in a script or in a oracle sql developer like application and run it.

Last but not least, moving LOBs:

First run:

WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';

This moves the LOB objects to the other tablespace.

As a result you should get something like:

ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);

Paste the results in a script or in a oracle sql developer like application and run it.

O and there is one more thing:

For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.

how to get last insert id after insert query in codeigniter active record

Using the mysqli PHP driver, you can't get the insert_id after you commit.

The real solution is this:

function add_post($post_data){

  $item_id = $this->db->insert_id();

  if( $this->db->trans_status() === FALSE )
    return( 0 );
    return( $item_id );

Source for code structure:

How can I set a css border on one side only?

Try like this

  border-left:1px solid;


How to update Android Studio automatically?

Through Android Studio:

  1. Help
  2. Check for latest update
  3. Update

How do I check if an HTML element is empty using jQuery?


Yes, I know, this is not jQuery, so you could use this:


Happy now?

vuetify center items into v-flex

wrap button inside <div class="text-xs-center">

<div class="text-xs-center">
  <v-btn primary>

Dev uses it in his examples.

For centering buttons in v-card-actions we can add class="justify-center" (note in v2 class is text-center (so without xs):

<v-card-actions class="justify-center">


For more examples with regards to centering see here

How to convert int to float in C?

This can give you the correct Answer

#include <stdio.h>
int main()
    float total=100, number=50;
    float percentage;
    return 0;

Is it possible to have a multi-line comments in R?

Unfortunately, there is still no multi-line commenting in R.

If your text editor supports column-mode, then use it to add a bunch of #s at once. If you use UltraEdit, Alt+c will put you in column mode.

Save PHP array to MySQL?

check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.

$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";

If the values in the array are text values, you will need to add quotes

$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";


Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.

How to add a line to a multiline TextBox?

Try this

textBox1.Text += "SomeText\r\n" 

you can also try

textBox1.Text += "SomeText" + Environment.NewLine;

Where \r is carriage return and \n is new line

make html text input field grow as I type?

From: Is there a jQuery autogrow plugin for text fields?

See a demo here:

The plugin:


    $.fn.autoGrowInput = function(o) {

        o = $.extend({
            maxWidth: 1000,
            minWidth: 0,
            comfortZone: 70
        }, o);


            var minWidth = o.minWidth || $(this).width(),
                val = '',
                input = $(this),
                testSubject = $('<tester/>').css({
                    position: 'absolute',
                    top: -9999,
                    left: -9999,
                    width: 'auto',
                    fontSize: input.css('fontSize'),
                    fontFamily: input.css('fontFamily'),
                    fontWeight: input.css('fontWeight'),
                    letterSpacing: input.css('letterSpacing'),
                    whiteSpace: 'nowrap'
                check = function() {

                    if (val === (val = input.val())) {return;}

                    // Enter new content into testSubject
                    var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

                    // Calculate new width + whether to change
                    var testerWidth = testSubject.width(),
                        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                        currentWidth = input.width(),
                        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                             || (newWidth > minWidth && newWidth < o.maxWidth);

                    // Animate width
                    if (isValidWidthChange) {



            $(this).bind('keyup keydown blur update', check);


        return this;



How to handle the `onKeyPress` event in ReactJS?

React is not passing you the kind of events you might think. Rather, it is passing synthetic events.

In a brief test, event.keyCode == 0 is always true. What you want is event.charCode

How do I set the proxy to be used by the JVM

You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...).

Select data between a date/time range

You must search date defend on how you insert that game_date data on your database.. for example if you inserted date value on long date or short.

SELECT * FROM hockey_stats WHERE game_date >= "6/11/2018" AND game_date <= "6/17/2018"

You can also use BETWEEN:

SELECT * FROM hockey_stats WHERE game_date BETWEEN "6/11/2018" AND "6/17/2018"

simple as that.

Run AVD Emulator without Android Studio

The way to run the emulator from the console (I assume that you installed it before, using Android Studio) is:


cd ~/Android/Sdk/tools/bin && ./avdmanager list avd


cd ~/Android/Sdk/tools && ./emulator -list-avds

You will get the list od your virtual installed devices. In my case it was:

Available Android Virtual Devices:
  Name: Galaxy_Nexus_API_17
  Device: Galaxy Nexus (Google)
  Path: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd
  Target: Google APIs (Google Inc.)
  Based on: Android 4.2 (Jelly Bean) Tag/ABI: google_apis/x86
  Skin: galaxy_nexus
  Sdcard: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd/sdcard.img

Copy name of the device you want to run and then

cd ~/Android/Sdk/tools && ./emulator -avd NAME_OF_YOUR_DEVICE

in my case:

cd ~/Android/Sdk/tools && ./emulator -avd Nexus_5X_API_23

How to fill in proxy information in cntlm config file?

Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):

cntlm -u myusername -d mydomain -H


cntlm -u myusername@mydomain -H

It will ask you the password of myusername and will give you the following output:

PassLM          1AD35398BE6565DDB5C4EF70C0593492
PassNT          77B9081511704EE852F94227CF48A793
PassNTLMv2      A8FC9092D566461E6BEA971931EF1AEC    # Only for user 'myusername', domain 'mydomain'

Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):

Username    myusername
Domain      mydomain

NoProxy     127.0.0.*, 192.168.*

Gateway     yes

SOCKS5Proxy 5866

Auth        NTLMv2
PassNTLMv2  A8FC9092D566461E6BEA971931EF1AEC

Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.

Running a cron job on Linux every six hours


0 */6 * * * command

. * has to

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

A ListIterator allows you to add or remove items in the list. Suppose you have a list of Car objects:

List<Car> cars = ArrayList<>();
// add cars here...

for (ListIterator<Car> carIterator = cars.listIterator();  carIterator.hasNext(); )
   if (<some-condition>)
   else if (<some-other-condition>)

Where to place JavaScript in an HTML file?

The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.

Scenario 1 - Critical script / Must needed script

In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.

Scenario 2 - Less important / analytics scripts

There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.

Bonus - async / defer

You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.

eg. <script async src="script.js"></script>

How to use Jackson to deserialise an array of objects

you could also create a class which extends ArrayList:

public static class MyList extends ArrayList<Myclass> {}

and then use it like:

List<MyClass> list = objectMapper.readValue(json, MyList.class);

Multi-threading in VBA

I know the question specifies Excel, but since the same question for Access got marked as duplicate, so I will post my answer here. The principle is simple: open a new Access application, then open a form with a timer inside that application, send the function/sub you want to execute to that form, execute the task if the timer hits, and quit the application once execution has finished. This allows the VBA to work with tables and queries from your database. Note: it will throw errors if you've exclusively locked the database.

This is all VBA (as opposed to other answers)

The function that runs a sub/function asynchronously

Public Sub RunFunctionAsync(FunctionName As String)
    Dim A As Access.Application
    Set A = New Access.Application
    A.OpenCurrentDatabase Application.CurrentProject.FullName
    A.DoCmd.OpenForm "MultithreadingEngine"
    With A.Forms("MultiThreadingEngine")
        .TimerInterval = 10
        .AddToTaskCollection (FunctionName)
    End With
End Sub

The module of the form required to achieve this

(form name = MultiThreadingEngine, doesn't have any controls or properties set)

Public TaskCollection As Collection

Public Sub AddToTaskCollection(str As String)
    If TaskCollection Is Nothing Then
        Set TaskCollection = New Collection
    End If
    TaskCollection.Add str
End Sub
Private Sub Form_Timer()
    If Not TaskCollection Is Nothing Then
        If TaskCollection.Count <> 0 Then
            Dim CollectionItem As Variant
            For Each CollectionItem In TaskCollection
                Run CollectionItem
            Next CollectionItem
        End If
    End If
End Sub

Implementing support for parameters should be easy enough, returning values is difficult, however.

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.

Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

Get human readable version of file size?

There's always got to be one of those guys. Well today it's me. Here's a one-liner -- or two lines if you count the function signature.

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    """ Returns a human readable string representation of bytes """
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])

>>> human_size(123)
123 bytes
>>> human_size(123456789)

If you need sizes bigger than an Exabyte, it's a little bit more gnarly:

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) if units[1:] else f'{bytes>>10}ZB'

How can I check if a program exists from a Bash script?

Assuming you are already following safe shell practices:

set -eu -o pipefail
shopt -s failglob

./dummy --version 2>&1 >/dev/null

This assumes the command can be invoked in such a way that it does (almost) nothing, like reporting its version or showing help.

If the dummy command is not found, Bash exits with the following error...

./my-script: line 8: dummy: command not found

This is more useful and less verbose than the other command -v (and similar) answers because the error message is auto generated and also contains a relevant line number.

Calling Scalar-valued Functions in SQL

That syntax works fine for me:

CREATE FUNCTION dbo.test_func
(@in varchar(20))
    RETURN 1

SELECT dbo.test_func('blah')

Are you sure that the function exists as a function and under the dbo schema?

using where and inner join in mysql

Try this :

          ID = school_locations.LOCATION_ID
    ) as `NAME`
          ID = school_locations.LOCATION_ID
     ) = 'coun';

Select <a> which href ends with some string


Selector documentation can be found at

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

How to reload a page after the OK click on the Alert Page

Bojan Milic answer work in a way but it error out with a message below,

enter image description here

This can be avoid with,

function message() 
alert("Successful message");
window.location = 'url_Of_Redirected_Page' // i.e. window.location='default.aspx'

What is the best algorithm for overriding GetHashCode?

This is a good one:

/// <summary>
/// Helper class for generating hash codes suitable 
/// for use in hashing algorithms and data structures like a hash table. 
/// </summary>
public static class HashCodeHelper
    private static int GetHashCodeInternal(int key1, int key2)
           var num = 0x7e53a269;
           num = (-1521134295 * num) + key1;
           num += (num << 10);
           num ^= (num >> 6);

           num = ((-1521134295 * num) + key2);
           num += (num << 10);
           num ^= (num >> 6);

           return num;

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="arr">An array of objects used for generating the 
    /// hash code.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode(params object[] arr)
        int hash = 0;
        foreach (var item in arr)
            hash = GetHashCodeInternal(hash, item.GetHashCode());
        return hash;

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <param name="obj4">The fourth object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and
    /// data structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2, T3, T4>(T1 obj1, T2 obj2, T3 obj3,
        T4 obj4)
        return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3)
        return GetHashCode(obj1, GetHashCode(obj2, obj3));

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2>(T1 obj1, T2 obj2)
        return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());

And here is how to use it:

private struct Key
    private Type _type;
    private string _field;

    public Type Type { get { return _type; } }
    public string Field { get { return _field; } }

    public Key(Type type, string field)
        _type = type;
        _field = field;

    public override int GetHashCode()
        return HashCodeHelper.GetHashCode(_field, _type);

    public override bool Equals(object obj)
        if (!(obj is Key))
            return false;
        var tf = (Key)obj;
        return tf._field.Equals(_field) && tf._type.Equals(_type);

@Value annotation type casting to Integer from String

If you want to convert a property to an integer from properties file there are 2 solutions which I found:

Given scenario: contains = 100 as a field and you want to access it in spring configuration file as integer.The property customerId is declared as type int in the Bean Customer

Solution 1:

<property name="customerId" value="#{T(java.lang.Integer).parseInt('${}')}" />

In the above line, the string value from properties file is converted to int type.

solution 2: Use some other extension inplace of propeties.For Ex.- If your properties file name is then make it customer.details and in the configuration file use the below code

<property name="customerId"   value="${}" />

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

  1. Turn on usb debugging
  2. Turn on Install via USB :-> While turning on it asks for mi account sign in you can get instant otp vis sms service to sign in quickly.
  3. Turn off MIUI optimization.

Read specific columns from a csv file with csv module?

With pandas you can use read_csv with usecols parameter:

df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])


import pandas as pd
import io

s = '''

df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])

   total_bill  day  size
0       16.99  Sun     2
1       10.34  Sun     3
2       21.01  Sun     3

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Have you tried editing the shell entry in account settings.

Go to the Accounts preferences, unlock, and right-click on your user account for the Advanced Settings dialog. Your shell should be /bin/zsh, and you can edit that invocation appropriately (i.e. add the --login argument).

Hashset vs Treeset

Even after 11 years, nobody thought of mentioning a very important difference.

Do you think that if HashSet equals TreeSet then the opposite is true as well? Take a look at this code:

TreeSet<String> treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
HashSet<String> hashSet = new HashSet<>();

Try to guess the output and then hover below snippet for seeing what the real output is. Ready? Here you go:


That's right, they don't hold equivalence relation for a comparator that is inconsistent with equals. The reason for this is that a TreeSet uses a comparator to determine the equivalence while HashSet uses equals. Internally they use HashMap and TreeMap so you should expect this behavior with the mentioned Maps as well.

Originally answered

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.


var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});

getJson() is available as a route in app.js.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

It's described on the Angular tutorial:

You have to import FormsModule and add it to imports in your @NgModule declaraction.

import { FormsModule } from '@angular/forms';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread:

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

Magento Product Attribute Get Value

You could write a method that would do it directly via sql I suppose.

Would look something like this:


$store_id = 1;
$product_id = 1234;
$attribute_code = 'manufacturer';


SELECT value FROM eav_attribute_option_value WHERE option_id IN (
    SELECT option_id FROM eav_attribute_option WHERE FIND_IN_SET(
        (SELECT value FROM catalog_product_entity_varchar WHERE
            entity_id = '$product_id' AND 
            attribute_id = (SELECT attribute_id FROM eav_attribute WHERE
    ) > 0) AND

You would have to get the value from the correct table based on the attribute's backend_type (field in eav_attribute) though so it takes at least 1 additional query.

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      return errno;
    getcwd(currentPath, FILENAME_MAX);

    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  return 0;

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  /*Changing back here is necessary because of how stat is done*/

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    helper(dip, dit, statbuf, currentPath, depth, argv);

    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    helper(dip, dit, statbuf, currentPath, depth, argv);

How to search a list of tuples in Python

[k for k,v in l if v =='delicia']

here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

And instead of converting it to a dict, we are using llist comprehension.

*Key* in Key,Value in list, where value = **delicia**

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table


insert into funds (ID, date, price) 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and =
    funds.ID is null

Docker error: invalid reference format: repository name must be lowercase

A "reference" in docker is a pointer to an image. It may be an image name, an image ID, include a registry server in the name, use a sha256 tag to pin the image, and anything else that can be used to point to the image you want to run.

The invalid reference format error message means docker cannot convert the string you've provided to an image. This may be an invalid name, or it may be from a parsing error earlier in the docker run command line if that's how you run the image. With a compose file, if you expand a variable in the image name, that variable may not be expanding correctly.

With the docker run command line, this is often the result in not quoting parameters with spaces, and mistaking the order of the command line. The command line is ordered as:

docker ${args_to_docker} run ${args_to_run} image_ref ${cmd_to_exec}

The most common error in passing args to the run is a volume mapping expanding a path name that includes a space in it, and not quoting the path or escaping the space. E.g.

docker run -v $(pwd):/data image_ref

And the fix is as easy as:

docker run -v "$(pwd):/data" image_ref

What's "this" in JavaScript onclick?

this referes to the object the onclick method belongs to. So inside func this would be the DOM node of the a element and this.innerText would be here.

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns=""

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

TypeError: not all arguments converted during string formatting python

Most Easy way typecast string number to integer


Owl Carousel Won't Autoplay

If you using v1.3.3 then use following property

autoPlay : 5000

Or using latest version then use following property

autoPlay : true

Cannot add a project to a Tomcat server in Eclipse

After following the steps suggested by previous posters, do the following steps:

  • Right click on the project
  • Click Maven, then Update Project
  • Tick the checkbox "Force Update of Snapshots/Releases", then click OK

You should be good to go now.

How to escape strings in SQL Server using PHP?

An answer from 2009-02-22T121000 by user chaos doesn't fit all queries.

For example, "CREATE LOGIN [0x6f6c6f6c6f] FROM WINDOWS" will give you an exception.

PS: look at the SQL Server driver for PHP, and the sqlsrv_prepare function, which can binds parameters.

PSS: Which also didn't help you with the query above ;)

JavaScript: Get image dimensions

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {

How to apply two CSS classes to a single element

As others have pointed out, you simply delimit them with a space.

However, knowing how the selectors work is also useful.

Consider this piece of HTML...

<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>

Using .a { ... } as a selector will select the first and third. However, if you want to select one which has both a and b, you can use the selector .a.b { ... }. Note that this won't work in IE6, it will simply select .b (the last one).

How to achieve ripple animation using support library?

Basic ripple setup

  • Ripples contained within the view.

  • Ripples that extend beyond the view's bounds:

    Have a look here for resolving ?(attr) xml references in Java code.

Support Library

  • Using ?attr: (or the ? shorthand) instead of ?android:attr references the support library, so is available back to API 7.

Ripples with images/backgrounds

  • To have a image or background and overlaying ripple the easiest solution is to wrap the View in a FrameLayout with the ripple set with setForeground() or setBackground().

Honestly there is no clean way of doing this otherwise.

How to make a Java Generic method static?

public static <E> E[] appendToArray(E[] array, E item) { ...

Note the <E>.

Static generic methods need their own generic declaration (public static <E>) separate from the class's generic declaration (public class ArrayUtils<E>).

If the compiler complains about a type ambiguity in invoking a static generic method (again not likely in your case, but, generally speaking, just in case), here's how to explicitly invoke a static generic method using a specific type (_class_.<_generictypeparams_>_methodname_):

String[] newStrings = ArrayUtils.<String>appendToArray(strings, "another string");

This would only happen if the compiler can't determine the generic type because, e.g. the generic type isn't related to the method arguments.

How to get config parameters in Symfony2 Twig Templates

You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.yml
    ga_tracking: UA-xxxxx-x

# app/config/config.yml
        ga_tracking: "%ga_tracking%"

Now, the variable ga_tracking is available in all Twig templates:

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:


You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.yml
    # ...
        user_management: "@acme_user.user_management"

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.

How to compare arrays in JavaScript?

I came up with another way to do it. Use join('') to change them to string, and then compare 2 strings:

var a1_str = a1.join(''),
    a2_str = a2.join('');

if (a2_str === a1_str) {}

How to avoid 'cannot read property of undefined' errors?

If you are using lodash, you could use their "has" function. It is similar to the native "in", but allows paths.

var testObject = {a: {b: {c: 'walrus'}}};
if(_.has(testObject, 'a.b.c')) {
  //Safely access your walrus here

OR is not supported with CASE Statement in SQL Server

select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
'No gender'
as gender 
from contacts

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])

# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

Get error message if ModelState.IsValid fails?

It is sample extension

public class GetModelErrors
    //Usage return Json to View :
    //return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
    public class KeyMessages
        public string Key { get; set; }
        public string Message { get; set; }
    private readonly ModelStateDictionary _entry;
    public GetModelErrors(ModelStateDictionary entry)
        _entry = entry;

    public int Count()
        return _entry.ErrorCount;
    public string Exceptions(string sp = "\n")
        return string.Join(sp, _entry.Values
            .SelectMany(v => v.Errors)
            .Select(e => e.Exception));
    public string Messages(string sp = "\n")
        string msg = string.Empty;
        foreach (var item in _entry)
            if (item.Value.ValidationState == ModelValidationState.Invalid)
                msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
        return msg;

    public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
        List<KeyMessages> list = new List<KeyMessages>();
        foreach (var item in _entry)
            if (item.Value.ValidationState == ModelValidationState.Invalid)
                list.Add(new KeyMessages
                    Key = item.Key,
                    Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
        return list;

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

Adding three months to a date in PHP

I assume by "didn't work" you mean that it's giving you a timestamp instead of the formatted date, because you were doing it correctly:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version

NSString property: copy or retain?

If the string is very large then copy will affect performance and two copies of the large string will use more memory.

Powershell command to hide user from exchange address lists

For Office 365 users or Hybrid exchange, go to using Internet Explorer or Edge, go to the exchange admin center, choose hybrid, setup, chose the right button for hybrid or exchange online.

To connect:


To see the relevant mailboxes:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientType -eq 'UserMailbox' -and RecipientTypeDetails -ne 'SharedMailbox' }

To block based on the above idea of 0KB size:

Get-mailbox -filter {ExchangeUserAccountControl -eq 'AccountDisabled' -and RecipientTypeDetails -ne 'SharedMailbox' -and RecipientType -eq 'UserMailbox' } | Set-Mailbox -MaxReceiveSize 0KB -HiddenFromAddressListsEnabled $true

What does "|=" mean? (pipe equal operator)

| is the bitwise-or operator, and it is being applied like +=.

How to prevent user from typing in text field without disabling the field?

just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.

    <asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >

Git fails when pushing commit to github

If this command not help

git config http.postBuffer 524288000

Try to change ssh method to https

git remote -v
git remote rm origin 
git remote add origin

Check if the number is integer

[UPDATE] ==============================================================

Respect to the [OLD] answer here below, I have discovered that it worked because I have put all the numbers in a single atomic vector; one of them was a character, so every one become characters.

If we use a list (hence, coercion does not happen) all the test pass correctly but one: 1/(1 - 0.98), which remains a numeric. This because the tol parameter is by default 100 * .Machine$double.eps and that number is far from 50 little less than the double of that. So, basically, for this kind of numbers, we have to decide our tolerance!

So if you want all test became TRUE, you can assertive::is_whole_number(x, tol = 200 * .Machine$double.eps)

Anyway, I confirm that IMO assertive remains the best solution.

Here below a reprex for this [UPDATE].

expect_trues_c <- c(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!

#>  Named chr [1:15] "2" "9" "50" "66" "66" "1" "222000" "10000" "1e+05" ...
#>  - attr(*, "names")= chr [1:15] "cl" "pp" "t" "ar0" ...
#> Warning: Coercing expect_trues_c to class 'numeric'.
#>                      2                      9                     50 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66                      1 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36                      2                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE

expect_trues_l <- list(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!

#> List of 15
#>  $ cl : num 2
#>  $ pp : num 9
#>  $ t  : num 50
#>  $ ar0: int 66
#>  $ ar1: num 66
#>  $ ar2: num 1
#>  $ v  : num 222000
#>  $ w1 : num 10000
#>  $ w2 : num 1e+05
#>  $ v2 : chr "1000000000000000000000000000000000001"
#>  $ an : num 2
#>  $ ju1: num 1e+22
#>  $ ju2: num 1e+24
#>  $ al : num 1
#>  $ v5 : num 1
#> Warning: Coercing expect_trues_l to class 'numeric'.
#> There was 1 failure:
#>   Position              Value      Cause
#> 1        3 49.999999999999957 fractional
assertive::is_whole_number(expect_trues_l, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_trues_l to class 'numeric'.
#>     2.0000000000000004                      9     49.999999999999957 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66     1.0000000000000009 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36     1.9999999999999998                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE

expect_falses <- list(
  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"

#> List of 5
#>  $ bb : num 5
#>  $ pt1: num 1
#>  $ pt2: num 1
#>  $ v3 : num 3243
#>  $ v4 : chr "sdfds"
#> Warning: Coercing expect_falses to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing
assertive::is_whole_number(expect_falses, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_falses to class 'numeric'.

#> Warning: NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing

Created on 2019-07-23 by the reprex package (v0.3.0)

[OLD] =================================================================

IMO the best solution comes from the assertive package (which, for the moment, solve all positive and negative examples in this thread):

are_all_whole_numbers <- function(x) {
  all(assertive::is_whole_number(x), na.rm = TRUE)

  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # difference is under machine precision!
#> Warning: Coercing x to class 'numeric'.
#> [1] TRUE

are_all_not_whole_numbers <- function(x) {
  all(!assertive::is_whole_number(x), na.rm = TRUE)

  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"
#> Warning: Coercing x to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> [1] TRUE

Created on 2019-07-23 by the reprex package (v0.3.0)

Using Excel as front end to Access database (with VBA)

Given the ease of use of Access, I don't see a compelling reason to use Excel at all other than to export data for number crunching. Access is designed to easily build data forms and, in my opinion, will be orders of magnitude easier and less time-consuming than using Excel. A few hours to learn the Access object model will pay for itself many times over in terms of time and effort.

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

Redis: Show database size/size for keys

MEMORY USAGE key command gives you the number of bytes that a key and its value require to be stored in RAM.

The reported usage is the total of memory allocations for data and administrative overheads that a key its value require (source redis documentation)

Does Java support default parameter values?

There are half a dozen or better issues such as this, eventually, you arrive at the static factory pattern ... see the crypto API for that. Sort difficult to explain, but think of it this way: If you have a constructor, default or otherwise, the only way to propagate state beyond the curly braces is either to have a Boolean isValid; ( along with the null as default value v failed constructor ) or throw an exception which is never informative when getting it back from field users.

Code Correct be damned, I write thousand line constructors and do what I need. I find using isValid at object construction - in other words, two-line constructors - but for some reason, I am migrating to the static factory pattern. I just seem you can do a lot if you in a method call, there are still sync() issues but defaults can be 'substituted' better ( safer )

I think what we need to do here is address the issue of null as default value vis-a-vis something String one=new String(""); as a member variable, then doing a check for null before assigning string passed to the constructor.

Very remarkable the amount of raw, stratospheric computer science done in Java.

C++ and so on has vendor libs, yes. Java can outrun them on large scale servers due to it's a massive toolbox. Study static initializer blocks, stay with us.

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.