Programs & Examples On #Aquamacs

Aquamacs is an Aqua-native build of the powerful Emacs text editor

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

Ruby on Rails - Import Data from a CSV file

You might try Upsert:

require 'upsert' # add this to your Gemfile
require 'csv'    

u = Upsert.new Moulding.connection, Moulding.table_name
CSV.foreach(file, headers: true) do |row|
  selector = { name: row['name'] } # this treats "name" as the primary key and prevents the creation of duplicates by name
  setter = row.to_hash
  u.row selector, setter
end

If this is what you want, you might also consider getting rid of the auto-increment primary key from the table and setting the primary key to name. Alternatively, if there is some combination of attributes that form a primary key, use that as the selector. No index is necessary, it will just make it faster.

How to add System.Windows.Interactivity to project?

The official package for behaviors is Microsoft.Xaml.Behaviors.Wpf.

It used to be in the Blend SDK (deprecated).
See Jan's answer for more details if you need to migrate.

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

jquery change div text

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

How can I convert an Integer to localized month name in Java?

Kotlin Extension

fun Int.toMonthName(): String {
    return DateFormatSymbols().months[this]
}

Usage

calendar.get(Calendar.MONTH).toMonthName()

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

What HTTP status response code should I use if the request is missing a required parameter?

For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.

I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.

I would copy Google.

How would you count occurrences of a string (actually a char) within a string?

LINQ works on all collections, and since strings are just a collection of characters, how about this nice little one-liner:

var count = source.Count(c => c == '/');

Make sure you have using System.Linq; at the top of your code file, as .Count is an extension method from that namespace.

How do I configure Notepad++ to use spaces instead of tabs?

In my Notepad++ 7.2.2, the Preferences section it's a bit different.

The option is located at: Settings / Preferences / Language / Replace by space as in the Screenshot.

Screenshot of the windows with preferences

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

Split large string in n-size chunks in JavaScript

var str = "123456789";
var chunks = [];
var chunkSize = 2;

while (str) {
    if (str.length < chunkSize) {
        chunks.push(str);
        break;
    }
    else {
        chunks.push(str.substr(0, chunkSize));
        str = str.substr(chunkSize);
    }
}

alert(chunks); // chunks == 12,34,56,78,9

Split string with PowerShell and do something with each token

"Once upon a time there were three little pigs".Split(" ") | ForEach {
    "$_ is a token"
 }

The key is $_, which stands for the current variable in the pipeline.

About the code you found online:

% is an alias for ForEach-Object. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.

$_.Split(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach.

Do HttpClient and HttpClientHandler have to be disposed between requests?

The general consensus is that you do not (should not) need to dispose of HttpClient.

Many people who are intimately involved in the way it works have stated this.

See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.

I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:

Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request. The HttpClient object is intended to live for as long as your application needs to make HTTP requests. Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.

Or even open up DotPeek.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You could cast it to <any> or extend the jquery typing to add your own method.

 (<any>$("div.printArea")).printArea();

//Or add your own custom methods (Assuming this is added by yourself as a part of custom plugin)

interface JQuery {
    printArea():void;
}

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

How to get a value inside an ArrayList java

main class

public class Test {
    public static void main (String [] args){
        Car thisCar= new Car ("Toyota", "$10000", "2003");  
        ArrayList<Car> car= new ArrayList<Car> ();
        car.add(thisCar); 
        processCar(car);
    } 

    public static void processCar(ArrayList<Car> car){
        for(Car c : car){
            System.out.println (c.getPrice());
        }
    }
}

car class

public class Car {
    private String vehicle;
    private String price;
    private String model;

    public Car(String vehicle, String price, String model){
        this.vehicle = vehicle;
        this.model = model;
        this.price = price;
    }

    public String getVehicle() {
        return vehicle;
    }

    public String getPrice() {
        return price;
    }

    public String getModel() {
        return model;
    }  
}

Setting the correct PATH for Eclipse

Eclipse folder has an initialization file which is used by eclipse on launch/Double click it is named as eclipse.ini. Add the following lines in eclipse.ini file. Where the vm defines the path of JVM with which we want eclipse to use.

-vm
C:\Program Files\Java\jdk1.8\bin\javaw.exe

Make sure you have add the above lines separately and above the following line

--launcher.appendVmargs
-vmargs

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

How to select date from datetime column?

Here are all formats

Say this is the column that contains the datetime value, table data.

+--------------------+
| date_created       |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+

mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02         |
+--------------------+

mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
|               2018 |
+--------------------+

mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
|                   6 |
+---------------------+

mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
|                 2 |
+-------------------+

mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
|                 15 |
+--------------------+

mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
|                   50 |
+----------------------+

mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
|                   31 |
+----------------------+

Split column at delimiter in data frame

The newly popular tidyr package does this with separate. It uses regular expressions so you'll have to escape the |

df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
separate(data = df, col = FOO, into = c("left", "right"), sep = "\\|")

  ID left right
1 11    a     b
2 12    b     c
3 13    x     y

though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).

separate(data = df, col = FOO, into = c("left", "right"))

What is App.config in C#.NET? How to use it?

Simply, App.config is an XML based file format that holds the Application Level Configurations.

Example:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="key" value="test" />
  </appSettings>
</configuration>

You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:

var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"

Note: ConfigurationSettings is obsolete method to retrieve configuration information.

var value = System.Configuration.ConfigurationSettings.AppSettings["key"];

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

Is there a way to get a collection of all the Models in your Rails app?

In just one line:

 ActiveRecord::Base.subclasses.map(&:name)

Deleting multiple elements from a list

As a function:

def multi_delete(list_, *args):
    indexes = sorted(list(args), reverse=True)
    for index in indexes:
        del list_[index]
    return list_

Runs in n log(n) time, which should make it the fastest correct solution yet.

How to change the text color of first select option

Here is a way so that when you select an option, it turns black. When you change it back to the placeholder, it turns back into the placeholder color (in this case red).

http://jsfiddle.net/wFP44/166/

It requires the options to have values.

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  if ($(this).val()) {_x000D_
return $(this).css('color', 'black');_x000D_
  } else {_x000D_
return $(this).css('color', 'red');_x000D_
  }_x000D_
});
_x000D_
select{_x000D_
  color: red;_x000D_
}_x000D_
select option { color: black; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value="">Pick one...</option>_x000D_
<option value="test1">Test 1</option>_x000D_
<option value="test2">Test 2</option>_x000D_
<option value="test3">Test 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Align Bootstrap Navigation to Center

Add 'justified' class to 'ul'.

<ul class="nav navbar-nav justified">

CSS:

.justified {
    position:absolute;
    left:50%;
}

Now, calculate its 'margin-left' in order to align it to center.

// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');

JSFiddle Code

JSFiddle Embedded Link

Laravel Update Query

You could use the Laravel query builder, but this is not the best way to do it.

Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.

DB::table('users')
        ->where('email', $userEmail)  // find your user by their email
        ->limit(1)  // optional - to ensure only one record is updated.
        ->update(array('member_type' => $plan));  // update the record in the DB. 

If you have multiple fields to update you can simply add more values to that array at the end.

Multiple REPLACE function in Oracle

Bear in mind the consequences

SELECT REPLACE(REPLACE('TEST123','123','456'),'45','89') FROM DUAL;

will replace the 123 with 456, then find that it can replace the 45 with 89. For a function that had an equivalent result, it would have to duplicate the precedence (ie replacing the strings in the same order).

Similarly, taking a string 'ABCDEF', and instructing it to replace 'ABC' with '123' and 'CDE' with 'xyz' would still have to account for a precedence to determine whether it went to '123EF' or ABxyzF'.

In short, it would be difficult to come up with anything generic that would be simpler than a nested REPLACE (though something that was more of a sprintf style function would be a useful addition).

HTML5 Canvas 100% Width Height of Viewport?

I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.

The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.

Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.

Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.

I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)

1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is

$(ctx.canvas).css("width", "100%");

where ctx is your canvas context. fiddle: resizeByWidth

2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do

$(ctx.canvas).css("height", window.innerHeight);

fiddle: messWithAspectratio

3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.

fiddle: redraw

4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.

fiddle: fixed

All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

Regular expression to match any character being repeated more than 10 times

You can also use PowerShell to quickly replace words or character reptitions. PowerShell is for Windows. Current version is 3.0.

$oldfile = "$env:windir\WindowsUpdate.log"

$newfile = "$env:temp\newfile.txt"
$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"

$text -replace '/(.)\1{9,}/', ' ' | Set-Content -Path $newfile

Get a list of all threads currently running in Java

Yes, take a look at getting a list of threads. Lots of examples on that page.

That's to do it programmatically. If you just want a list on Linux at least you can just use this command:

kill -3 processid

and the VM will do a thread dump to stdout.

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

How to disable phone number linking in Mobile Safari?

Another solution would be to use an image of the IP number

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Which concurrent Queue implementation should I use in Java?

Basically the difference between them are performance characteristics and blocking behavior.

Taking the easiest first, ArrayBlockingQueue is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.

The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.

Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.

How to select last two characters of a string

You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

var member = "my name is Mate";

var last2 = member.slice(-2);

alert(last2); // "te"

Where can I download IntelliJ IDEA Color Schemes?

If you're just looking for a dark color scheme for IntelliJ IDEA, this is the first link I get in a Google search:

Dark Pastels theme for IntelliJ IDEA Dark Pastels theme for IntelliJ IDEA

Of course, you can tweak either of these two schemes to your satisfaction. Don't feel like you have to stick to the fonts and the colors that the original authors have chosen. We programmers don't get nearly enough change to try our hand at interior decorating to pass up this opportunity.

Is there any reason these won't work in the version you have? As best I can tell, you can simply import any theme that you want.

What's a .sh file?

What is a file with extension .sh?

It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form

#!/path/to/interpreter

they will use that particular interpreter. Your file has the first line:

#!/bin/bash

and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.

Depending upon the interpreter you will have different language in which the file is written.

Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).

If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.

How to execute a shell script

Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.

You will need to make the file executable. Let's assume that you have downloaded your file as file.sh, you can then run in your terminal:

chmod +x file.sh

chmod is a command for changing file's permissions, +x sets execute permissions (in this case for everybody) and finally you have your file name.

You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:

File permissions in XUbuntu

If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:

bash file.sh

The shell should be the same as in the first line of your script.

How safe is it?

You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.

Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).

Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".

Setting ANDROID_HOME enviromental variable on Mac OS X

1) Open base profile :

open  ~/.bash_profile

2) Add below line in base profile :

export PATH=${PATH}:/Users/<username>/Library/Android/sdk/build-tools/27.0.3

Save and close base profile.

For me 27.0.3 working great.

Python Brute Force algorithm

If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time:

your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a

On a smaller example, where list = 'ab' and we only go up to 5, this prints the following:

['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']

How to make a phone call using intent in Android?

Just the simple oneliner without any additional permissions needed:

private void dialContactPhone(final String phoneNumber) {
    startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNumber, null)));
}

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

Programmatically add custom event in the iPhone Calendar

Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....

installation app blocked by play protect

the only solution worked for me was using java keytool and generating a .keystore file the command line and then use that .keystore file to sign my app

you can find the java keytool at this directory C:\Program Files\Java\jre7\bin

open a command window and switch to that directory and enter a command like this

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Keytool prompts you to provide passwords for the keystore, your name , company etc . note that at the last prompt you need to enter yes.

It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

you need to check and configure your android gradle plugin (in project level build.gradle) and set suitable gradle versino in gradle-wrapper.properties Cross dependency between two can be find out at https://developer.android.com/studio/releases/gradle-plugin

pip not working in Python Installation in Windows 10

I had the same problem on Visual Studio Code. For various reasons several python versions are installed on my computer. I was thus able to easily solve the problem by switching python interpreter.

If like me you have several versions of python on you machine, in Visual Studio Code, you can easily change the interpreter by clicking on the bottom left corner where it says Python...

enter image description here

Centering a button vertically in table cell, using Twitter Bootstrap

A little update for Bootstrap 3.

Bootstrap now has the following style for table cells:

.table tbody>tr>td
{
    vertical-align: top;
}

The way to go is to add a your own class, with the same selector:

.table tbody>tr>td.vert-align
{
    vertical-align: middle;
}

And then add it to your tds

<td class="vert-align"></td>

How do I escape only single quotes?

You can use the addcslashes function to get this done like so:

echo addcslashes($text, "'\\");

How to check if my string is equal to null?

Apache commons StringUtils.isNotEmpty is the best way to go.

Android Studio installation on Windows 7 fails, no JDK found

In my experience, I was unable (even after adding JDK_HOME) to launch Studio via either the shortcut or studio.exe itself. I had to first run bin/studio.bat (mentioned in the original question). After the first successful launch, I'm able to start it by the shortcut.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Please try this:

Sub deleteConn(xlBook)
    For Each Cn In xlBook.Connections
        Cn.Delete
    Next Cn

    For Each xlsheet In xlBook.Worksheets
        For Each Qt In xlsheet.QueryTables
            Qt.Delete
        Next Qt
    Next xlsheet

End Sub

How to delete projects in Intellij IDEA 14?

1. Choose project, right click, in context menu, choose Show in Explorer (on Mac, select Reveal in Finder).

enter image description here

2. Choose menu File \ Close Project

enter image description here

3. In Windows Explorer, press Del or Shift+Del for permanent delete.

4. At IntelliJ IDEA startup windows, hover cursor on old project name (what has been deleted) press Del for delelte.

enter image description here

How to execute shell command in Javascript

With nashorn you can write a script like this:

$EXEC('find -type f');
var files = $OUT.split('\n');
files.forEach(...
...

and run it:

jjs -scripting each_file.js

How to get distinct values from an array of objects in JavaScript?

If you have Array.prototype.includes or are willing to polyfill it, this works:

var ages = []; array.forEach(function(x) { if (!ages.includes(x.age)) ages.push(x.age); });

How to set a radio button in Android

Many times if your radio buttons belong to the same radioGroup then

radioButton.setChecked(true)

will not select the radio button properly. So to solve this problem try using your radioGroup.

radioGroup.check(R.id.radioButtonId)

Is it possible to set a number to NaN or infinity?

When using Python 2.4, try

inf = float("9e999")
nan = inf - inf

I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999") fixed it. Don't use inf = 9e999, you need convert it from string. -inf gives the -Infinity.

Resize image in the wiki of GitHub using Markdown

This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?


In December 2015, it seems that only links to files on github.com or cloud.githubusercontent.com or the like work. Steps that worked for me in a gist:

  1. Make a gist, say Mygist.md (and optionally more files)
  2. Go to the "Write Comment" box at the end
  3. Click "Attach files ... by selecting them"; select your local image file
  4. GitHub echos a long long string where it put the image, e.g. ![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
  5. Cut-paste that by hand into your Mygist.md.

But: GitHub people may change this behavior tomorrow, without documenting it.

Integer value in TextView

tv.setText(Integer.toString(intValue))

How to add/update child entities when updating a parent entity in EF

var parent = context.Parent.FirstOrDefault(x => x.Id == modelParent.Id);
if (parent != null)
{
  parent.Childs = modelParent.Childs;
}

source

How to generate UML diagrams (especially sequence diagrams) from Java code?

ObjectAid UML Explorer

Is what I used. It is easily installed from the repository:

Name:     ObjectAid UML Explorer
Location: http://www.objectaid.com/update/current

And produces quite nice UML diagrams:

Screenshot

Description from the website:

The ObjectAid UML Explorer is different from other UML tools. It uses the UML notation to show a graphical representation of existing code that is as accurate and up-to-date as your text editor, while being very easy to use. Several unique features make this possible:

  • Your source code and libraries are the model that is displayed, they are not reverse engineered into a different format.
  • If you update your code in Eclipse, your diagram is updated as well; there is no need to reverse engineer source code.
  • Refactoring updates your diagram as well as your source code. When you rename a field or move a class, your diagram simply reflects the changes without going out of sync.
  • All diagrams in your Eclipse workspace are updated with refactoring changes as appropriate. If necessary, they are checked out of your version control system.
  • Diagrams are fully integrated into the Eclipse IDE. You can drag Java classes from any other view onto the diagram, and diagram-related information is shown in other views wherever applicable.

Nested Git repositories?

Summary.

Can I nest git repositories?

Yes. However, by default git does not track the .git folder of the nested repository. Git has features designed to manage nested repositories (read on).

Does it make sense to git init/add the /project_root to ease management of everything locally or do I have to manage my_project and the 3rd party one separately?

It probably doesn't make sense as git has features to manage nested repositories. Git's built in features to manage nested repositories are submodule and subtree.

Here is a blog on the topic and here is a SO question that covers the pros and cons of using each.

npm not working - "read ECONNRESET"

I've tried almost all methods posted here and in other pages but didn't work. Here are the commands I've executed in order, which I encourage you to try because it worked for many people (but not me):

  • npm config rm proxy
  • npm config rm https-proxy
  • npm config set https-proxy https://username:[email protected]:6050
  • npm config set proxy http://username:[email protected]:6050
  • npm config set registry http://registry.npmjs.org/

And then trying to install the package npm install -g express, but it failed.

However, when I tried to run npm install npm@latest -g it miraculously executed and installed fine!
Then running npm install -g express again worked perfectly fine too.

TL;DR: updating npm to the latest version solved the issue (currently 6.0.1)

Convert Decimal to Varchar

Hope this will help .

DECLARE  @emp_cond nvarchar(Max) =' ',@LOCATION_ID  NUMERIC(18,0)   
SET@LOCATION_ID=10110000000
IF CAST(@LOCATION_ID AS VARCHAR(18))<>' ' 
            BEGIN
                SELECT @emp_cond= @emp_cond + N' AND 
CM.STATIC_EMP_INFO.EMP_ID = ' ' '+  CAST(@LOCATION_ID AS VARCHAR(18))  +' ' ' '
           END
print  @emp_cond  
EXEC( @emp_cond) 

Convert binary to ASCII and vice versa

This is my way to solve your task:

str = "0b110100001100101011011000110110001101111"
str = "0" + str[2:]
message = ""
while str != "":
    i = chr(int(str[:8], 2))
    message = message + i
    str = str[8:]
print message

Set database timeout in Entity Framework

I just ran in to this problem and resolved it by updating my application configuration file. For the connection in question, specify "Connection Timeout=60" (I am using entity framework version 5.0.0.0)

ConnectionTimeout Setting

Java, reading a file from current directory?

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));

Notepad++ Regular expression find and delete a line

If it supports standard regex...

find:
^.*#RedirectMatch Permanent.*$

replace:

Replace with nothing.

How do I avoid the "#DIV/0!" error in Google docs spreadsheet?

You can use an IF statement to check the referenced cell(s) and return one result for zero or blank, and otherwise return your formula result.

A simple example:

=IF(B1=0;"";A1/B1)

This would return an empty string if the divisor B1 is blank or zero; otherwise it returns the result of dividing A1 by B1.

In your case of running an average, you could check to see whether or not your data set has a value:

=IF(SUM(K23:M23)=0;"";AVERAGE(K23:M23))

If there is nothing entered, or only zeros, it returns an empty string; if one or more values are present, you get the average.

onchange event on input type=range is not triggering in firefox while dragging

You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:

  1. Browser support.

  2. Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.

In jQuery:

$('#sample').on('drag',function(e){

});

Reference: http://www.w3schools.com/TAgs/ev_ondrag.asp

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.

How do you Sort a DataTable given column and direction?

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;
    dt.DefaultView.Sort = colName + " " + direction;
    dtOut = dt.DefaultView.ToTable();
    return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
    dt.DefaultView.Sort = colName + " " + direction;
    dt = dt.DefaultView.ToTable();
    return dt;
}

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How do you turn a Mongoose document into a plain object?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.

const leanDoc = await MyModel.findOne().lean();

not necessary to use JSON.parse() method

How to maintain a Unique List in Java?

You may want to use one of the implementing class of java.util.Set<E> Interface e.g. java.util.HashSet<String> collection class.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Best way to integrate Python and JavaScript?

There's a bridge based on JavaScriptCore (from WebKit), but it's pretty incomplete: http://code.google.com/p/pyjscore/

How to jump back to NERDTree from file in tab?

Ctrl+ww cycle though all windows

Ctrl+wh takes you left a window

Ctrl+wj takes you down a window

Ctrl+wk takes you up a window

Ctrl+wl takes you right a window

ImageView - have height match width?

Here I what I did to have an ImageButton which always have a width equals to its height (and avoid stupid empty margins in one direction...which I consider a as a bug of the SDK...):

I defined a SquareImageButton class which extends from ImageButton:

package com.myproject;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;

    public class SquareImageButton extends ImageButton {

        public SquareImageButton(Context context) {
        super(context);


        // TODO Auto-generated constructor stub
    }

    public SquareImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

    }

    public SquareImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub

    }

    int squareDim = 1000000000;

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);


        int h = this.getMeasuredHeight();
        int w = this.getMeasuredWidth();
        int curSquareDim = Math.min(w, h);
        // Inside a viewholder or other grid element,
        // with dynamically added content that is not in the XML,
        // height may be 0.
        // In that case, use the other dimension.
        if (curSquareDim == 0)
            curSquareDim = Math.max(w, h);

        if(curSquareDim < squareDim)
        {
            squareDim = curSquareDim;
        }

        Log.d("MyApp", "h "+h+"w "+w+"squareDim "+squareDim);


        setMeasuredDimension(squareDim, squareDim);

    }

}

Here is my xml:

<com.myproject.SquareImageButton
            android:id="@+id/speakButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="centerInside"
            android:src="@drawable/icon_rounded_no_shadow_144px"
            android:background="#00ff00"
            android:layout_alignTop="@+id/searchEditText"
            android:layout_alignBottom="@+id/searchEditText"
            android:layout_alignParentLeft="true"
           />

Works like a charm !

Use FontAwesome or Glyphicons with css :before

In the case of your list items there is a little CSS you can use to achieve the desired effect.

ul.icons li {
  position: relative;
  padding-left: -20px; // for example
}
ul.icons li i {
  position: absolute;
  left: 0;
}

I have tested this in Safari on OS X.

How to convert date format to milliseconds?

You could use

Calendar cal = Calendar.getInstance();
cal.setTime(beginupd);
long millis = cal.getTimeInMillis();

How to run shell script on host from docker container?

docker run --detach-keys="ctrl-p" -it -v /:/mnt/rootdir --name testing busybox
# chroot /mnt/rootdir
# 

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

dynamically add and remove view to viewpager

Here's an alternative solution to this question. My adapter:

    private class PagerAdapter extends FragmentPagerAdapter implements 
                    ViewPager.OnPageChangeListener, TabListener {

    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private ViewPager mPager;
    private ActionBar mActionBar;

    private Fragment mPrimaryItem;

    public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
        super(fm);
        mPager = vp;
        mPager.setAdapter(this);
        mPager.setOnPageChangeListener(this);
        mActionBar = ab;
    }

    public void addTab(PartListFragment frag) {
        mFragments.add(frag);
        mActionBar.addTab(mActionBar.newTab().setTabListener(this).
                            setText(frag.getPartCategory()));
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    /** (non-Javadoc)
     * @see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
     */
    @Override
    public void setPrimaryItem(ViewGroup container, int position,
            Object object) {
        super.setPrimaryItem(container, position, object);
        mPrimaryItem = (Fragment) object;
    }

    /** (non-Javadoc)
     * @see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
     */
    @Override
    public int getItemPosition(Object object) {
        if (object == mPrimaryItem) {
            return POSITION_UNCHANGED;
        }
        return POSITION_NONE;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) { }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) { }

    @Override
    public void onPageScrollStateChanged(int arg0) { }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) { }

    @Override
    public void onPageSelected(int position) {
        mActionBar.setSelectedNavigationItem(position);
    }

    /**
     * This method removes the pages from ViewPager
     */
    public void removePages() {
        mActionBar.removeAllTabs();

                    //call to ViewPage to remove the pages
        vp.removeAllViews();
        mFragments.clear();

        //make this to update the pager
        vp.setAdapter(null);
        vp.setAdapter(pagerAdapter);
    }
}

Code to remove and add dynamically

//remove the pages. basically call to method removeAllViews from `ViewPager`
pagerAdapter.removePages();

pagerAdapter.addPage(pass your fragment);

After the advice of Peri Hartman, it started to work after I set null do ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesnt showed its list contents.

Thanks.

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

How to make a simple rounded button in Storyboard?

I found the easiest way to do this, is by setting the cornerRadius to half of the height of the view.

button.layer.cornerRadius = button.bounds.size.height/2

How do I create HTML table using jQuery dynamically?

I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html to achieve what you want .

Look at the code below :

HTML:

<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>

JS :

createFormElement("Nickname","nickname")

function createFormElement(labelText, id) {

$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}

This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .

WORKING DEMO:

Moreover, when you use the process you mentioned in your post you get only [object Object]. That is because when you call createProviderFormFields , it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object, then construct the html from it.

It's much easier to construct just the html and change the id s of the label and input according to your needs.

What do the makefile symbols $@ and $< mean?

in exemple if you want to compile sources but have objects in an different directory :

You need to do :

gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...

but with most of macros the result will be all objects followed by all sources, like :

gcc -c -o <all OBJ path> <all SRC path>

so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(

the solution is to use these special macros

$@ $<

this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)

$(OBJ):$(SRC)
   gcc -c -o $@ $< $(HEADERS) $(FLAGS)

it means :

    $@ = $(OBJ)
    $< = $(SRC)

but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC

Two way sync with rsync

You could try csync, it is the sync engine under the hood of owncloud.

jQuery datepicker, onSelect won't work

I have downloaded the datepicker from jqueryui.com/download and I got 1.7.2 version but still onSelect function didn't work. Here is what i had -

$("#datepicker").datepicker();

$("#datepicker").datepicker({ 
      onSelect: function(value, date) { 
         alert('The chosen date is ' + value); 
      } 
});

I found the solution in this page -- problem with jquery datepicker onselect . Removed the $("#datepicker").datepicker(); once and it worked.

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

What is the difference between a function expression vs declaration in JavaScript?

Function Declaration

function foo() { ... }

Because of function hoisting, the function declared this way can be called both after and before the definition.

Function Expression

  1. Named Function Expression

    var foo = function bar() { ... }
    
  2. Anonymous Function Expression

    var foo = function() { ... }
    

foo() can be called only after creation.

Immediately-Invoked Function Expression (IIFE)

(function() { ... }());

Conclusion

Crockford recommends to use function expression because it makes it clear that foo is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.

How to get first and last day of previous month (with timestamp) in SQL Server

SELECT DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0) AS PreviousMonthStart

SELECT DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) AS PreviousMonthEnd

Eclipse plugin for generating a class diagram

Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:

  • ObjectAid. My current preference.
  • EclipseUML from Omondo. Only commercial versions appear to be available right now. The class diagram in your question, is most likely generated by this plugin.

Obligatory links

The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.

  • UMLet. I used this several years back. Appears to be in use, going by the comments in the Eclipse marketplace.
  • Violet. This supports creation of other types of UML diagrams in addition to class diagrams.

Related questions on StackOverflow

  1. Is there a free Eclipse plugin that creates a UML diagram out of Java classes / packages?

Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.

How to place object files in separate subdirectory

This is the makefile that I use for most of my projects,

It permits putting source files, headers and inline files in subfolders, and subfolders of subfolders and so-forth, and will automatically generate a dependency file for each object This means that modification of headers and inline files will trigger recompilation of files which are dependent.

Source files are detected via shell find command, so there is no need to explicitly specify, just keep coding to your hearts content.

It will also copy all files from a 'resources' folder, into the bin folder when the project is compiled, which I find handy most of the time.

To provide credit where it is due, the auto-dependencies feature was based largely off Scott McPeak's page that can be found HERE, with some additional modifications / tweaks for my needs.

Example Makefile

#Compiler and Linker
CC          := g++-mp-4.7

#The Target Binary Program
TARGET      := program

#The Directories, Source, Includes, Objects, Binary and Resources
SRCDIR      := src
INCDIR      := inc
BUILDDIR    := obj
TARGETDIR   := bin
RESDIR      := res
SRCEXT      := cpp
DEPEXT      := d
OBJEXT      := o

#Flags, Libraries and Includes
CFLAGS      := -fopenmp -Wall -O3 -g
LIB         := -fopenmp -lm -larmadillo
INC         := -I$(INCDIR) -I/usr/local/include
INCDEP      := -I$(INCDIR)

#---------------------------------------------------------------------------------
#DO NOT EDIT BELOW THIS LINE
#---------------------------------------------------------------------------------
SOURCES     := $(shell find $(SRCDIR) -type f -name *.$(SRCEXT))
OBJECTS     := $(patsubst $(SRCDIR)/%,$(BUILDDIR)/%,$(SOURCES:.$(SRCEXT)=.$(OBJEXT)))

#Defauilt Make
all: resources $(TARGET)

#Remake
remake: cleaner all

#Copy Resources from Resources Directory to Target Directory
resources: directories
    @cp $(RESDIR)/* $(TARGETDIR)/

#Make the Directories
directories:
    @mkdir -p $(TARGETDIR)
    @mkdir -p $(BUILDDIR)

#Clean only Objecst
clean:
    @$(RM) -rf $(BUILDDIR)

#Full Clean, Objects and Binaries
cleaner: clean
    @$(RM) -rf $(TARGETDIR)

#Pull in dependency info for *existing* .o files
-include $(OBJECTS:.$(OBJEXT)=.$(DEPEXT))

#Link
$(TARGET): $(OBJECTS)
    $(CC) -o $(TARGETDIR)/$(TARGET) $^ $(LIB)

#Compile
$(BUILDDIR)/%.$(OBJEXT): $(SRCDIR)/%.$(SRCEXT)
    @mkdir -p $(dir $@)
    $(CC) $(CFLAGS) $(INC) -c -o $@ $<
    @$(CC) $(CFLAGS) $(INCDEP) -MM $(SRCDIR)/$*.$(SRCEXT) > $(BUILDDIR)/$*.$(DEPEXT)
    @cp -f $(BUILDDIR)/$*.$(DEPEXT) $(BUILDDIR)/$*.$(DEPEXT).tmp
    @sed -e 's|.*:|$(BUILDDIR)/$*.$(OBJEXT):|' < $(BUILDDIR)/$*.$(DEPEXT).tmp > $(BUILDDIR)/$*.$(DEPEXT)
    @sed -e 's/.*://' -e 's/\\$$//' < $(BUILDDIR)/$*.$(DEPEXT).tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $(BUILDDIR)/$*.$(DEPEXT)
    @rm -f $(BUILDDIR)/$*.$(DEPEXT).tmp

#Non-File Targets
.PHONY: all remake clean cleaner resources

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Getting full JS autocompletion under Sublime Text

Ternjs is a new alternative for getting JS autocompletion. http://ternjs.net/

Sublime Plugin

The most well-maintained Tern plugin for Sublime Text is called 'tern_for_sublime'

There is also an older plugin called 'TernJS'. It is unmaintained and contains several performance related bugs, that cause Sublime Text to crash, so avoid that.

Getting value of HTML text input

Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.

I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/

It has an alert which goes off on load and when you click the textbox itself.

What causes this error? "Runtime error 380: Invalid property value"

If you write software, or use software written, which stores program window coordinates or sizes to be resused when starting a program, check there for any occurrence(s) of such sizes and positions which would be causing this. I've seen it time and time again from various vendors lazily producing code which resizes and repositions controls on a "form" (a program window) based on the size of said form. Look in HKLM\Software\Vendor\Program and HKCU\Software\Vendor\Program. Look for specific keys which might be offending. I once had a program store -48000 for the program window position in keys called WindowsPosX and WindowPosY. You could see the program start and running on the taskbar but since the program window itself was smaller than 48000 (the absolute value of -48000), it was positioned completely off the screen. If you're not comfortable with editing regstry information - most people aren't - then uninstall the software, use a registry cleaner to remove any leftover entries then reinstall the software and see if that doesn't fix the problem.

Pull request vs Merge request

There is a subtle difference in terms of conflict management. In case of conflicts, a pull request in Github will result in a merge commit on the destination branch. In Gitlab, when a conflict is found, the modifications made will be on a merge commit on the source branch.

See https://docs.gitlab.com/ee/user/project/merge_requests/resolve_conflicts.html

"GitLab resolves conflicts by creating a merge commit in the source branch that is not automatically merged into the target branch. This allows the merge commit to be reviewed and tested before the changes are merged, preventing unintended changes entering the target branch without review or breaking the build."

Correct way to create rounded corners in Twitter Bootstrap

If you're using Bootstrap Sass, here's another way that avoids having to add extra classes to your element markup:

@import "bootstrap/mixins/_border-radius";
@import "bootstrap/_variables";

.your-class {
  $r: $border-radius-base; // or $border-radius-large, $border-radius-small, ...
  @include border-top-radius($r);
  @include border-bottom-radius($r);
}

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

How to trigger HTML button when you press Enter in textbox?

I am using a kendo button. This worked for me.

<div class="form-group" id="indexform">
    <div class="col-md-8">
            <div class="row">
                <b>Search By Customer Name/ Customer Number:</b>
                @Html.TextBox("txtSearchString", null, new { style = "width:400px" , autofocus = "autofocus" })
                @(Html.Kendo().Button()
                    .Name("btnSearch")
                    .HtmlAttributes(new { type = "button", @class = "k-primary" })
                    .Content("Search")
                    .Events(ev => ev.Click("onClick")))
            </div>
    </div>
</div>
<script>
var validator = $("#indexform").kendoValidator().data("kendoValidator"),
          status = $(".status");
$("#indexform").keyup(function (event) {
    if (event.keyCode == 13) {
        $("#btnSearch").click();
    }
});
</script>

Is there a way to create interfaces in ES6 / Node 4?

This is my solution for the problem. You can 'implement' multiple interfaces by overriding one Interface with another.

class MyInterface {
    // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance
    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }


    // delcare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}

class MultipleInterfaces extends MyInterface {
    // this is used for "implement" multiple Interfaces at once
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

class MyCorrectUsedClass extends MyInterface {
    // You can easy use the JS doc declared in the interface
    /** @inheritdoc */
    sum(a, b) {
        return a+b;
    }
}
class MyIncorrectUsedClass extends MyInterface {
    // not overriding the method sum(a, b)
}

class MyMultipleInterfacesClass extends MultipleInterfaces {
    // nothing overriden to show, that it still works
}


let working = new MyCorrectUsedClass();

let notWorking = new MyIncorrectUsedClass();

let multipleInterfacesInstance = new MyMultipleInterfacesClass();

// TEST IT

console.log('working.sum(1, 2) =', working.sum(1, 2));
// output: 'working.sum(1, 2) = 3'

console.log('notWorking.sum(1, 2) =', notWorking.sum(1, 2));
// output: 'notWorking.sum(1, 2) = undefined'
// but also sends a warn to the console with 'WARNING! Function "sum(a, b)" is not overridden in MyIncorrectUsedClass'

console.log('multipleInterfacesInstance.sum(1, 2) =', multipleInterfacesInstance.sum(1, 2));
// output: 'multipleInterfacesInstance.sum(1, 2) = undefined'
// console warn: 'WARNING! Function "sum(a, b)" is not overridden in MyMultipleInterfacesClass'

console.log('multipleInterfacesInstance.square(2) =', multipleInterfacesInstance.square(2));
// output: 'multipleInterfacesInstance.square(2) = undefined'
// console warn: 'WARNING! Function "square(a)" is not overridden in MyMultipleInterfacesClass'

EDIT:

I improved the code so you now can simply use implement(baseClass, interface1, interface2, ...) in the extend.

/**
* Implements any number of interfaces to a given class.
* @param cls The class you want to use
* @param interfaces Any amount of interfaces separated by comma
* @return The class cls exteded with all methods of all implemented interfaces
*/
function implement(cls, ...interfaces) {
    let clsPrototype = Object.getPrototypeOf(cls).prototype;
    for (let i = 0; i < interfaces.length; i++) {
        let proto = interfaces[i].prototype;
        for (let methodName of Object.getOwnPropertyNames(proto)) {
            if (methodName!== 'constructor')
                if (typeof proto[methodName] === 'function')
                    if (!clsPrototype[methodName]) {
                        console.warn('WARNING! "'+methodName+'" of Interface "'+interfaces[i].name+'" is not declared in class "'+cls.name+'"');
                        clsPrototype[methodName] = proto[methodName];
                    }
        }
    }
    return cls;
}

// Basic Interface to warn, whenever an not overridden method is used
class MyBaseInterface {
    // declare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}


// create a custom class
/* This is the simplest example but you could also use
*
*   class MyCustomClass1 extends implement(MyBaseInterface) {
*       foo() {return 66;}
*   }
*
*/
class MyCustomClass1 extends MyBaseInterface {
    foo() {return 66;}
}

// create a custom interface
class MyCustomInterface1 {
     // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance

    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }
}

// and another custom interface
class MyCustomInterface2 {
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

// Extend your custom class even more and implement the custom interfaces
class AllInterfacesImplemented extends implement(MyCustomClass1, MyCustomInterface1, MyCustomInterface2) {
    /**
    * @inheritdoc
    */
    sum(a, b) { return a+b; }

    /**
    * Multiplies two Numbers
    * @param {Number} a The first Number
    * @param {Number} b The second Number
    * @return {Number}
    */
    multiply(a, b) {return a*b;}
}


// TEST IT

let x = new AllInterfacesImplemented();

console.log("x.foo() =", x.foo());
//output: 'x.foo() = 66'

console.log("x.square(2) =", x.square(2));
// output: 'x.square(2) = undefined
// console warn: 'WARNING! Function "square(a)" is not overridden in AllInterfacesImplemented'

console.log("x.sum(1, 2) =", x.sum(1, 2));
// output: 'x.sum(1, 2) = 3'

console.log("x.multiply(4, 5) =", x.multiply(4, 5));
// output: 'x.multiply(4, 5) = 20'

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How do I capture response of form.submit

Future internet searchers:

For new browsers (as of 2018: Chrome, Firefox, Safari, Opera, Edge, and most mobile browsers, but not IE), fetch is a standard API that simplifies asynchronous network calls (for which we used to need XMLHttpRequest or jQuery's $.ajax).

Here is a traditional form:

<form id="myFormId" action="/api/process/form" method="post">
    <!-- form fields here -->
    <button type="submit">SubmitAction</button>
</form>

If a form like the above is handed to you (or you created it because it is semantic html), then you can wrap the fetch code in an event listener as below:

document.forms['myFormId'].addEventListener('submit', (event) => {
    event.preventDefault();
    // TODO do something here to show user that form is being submitted
    fetch(event.target.action, {
        method: 'POST',
        body: new URLSearchParams(new FormData(event.target)) // event.target is the form
    }).then((resp) => {
        return resp.json(); // or resp.text() or whatever the server sends
    }).then((body) => {
        // TODO handle body
    }).catch((error) => {
        // TODO handle error
    });
});

(Or, if like the original poster you want to call it manually without a submit event, just put the fetch code there and pass a reference to the form element instead of using event.target.)

Docs:

Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Other: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript That page in 2018 does not mention fetch (yet). But it mentions that the target="myIFrame" trick is deprecated. And it also has an example of form.addEventListener for the 'submit' event.

CSS Circular Cropping of Rectangle Image

If you can live without the <img> tag, I suggest you use the photo as a background image.

_x000D_
_x000D_
.cropcircle{_x000D_
    width: 250px;_x000D_
    height: 250px;_x000D_
    border-radius: 100%;_x000D_
    background: #eee no-repeat center;_x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
#image1{_x000D_
    background-image: url(http://www.voont.com/files/images/edit/7-ridiculous-ways-boost-self-esteem/happy.jpg);_x000D_
}
_x000D_
<div id="image1" class="cropcircle"></div>
_x000D_
_x000D_
_x000D_

Choose folders to be ignored during search in VS Code

If I understand correctly you want to exclude files from the vscode fuzzy finder. If that is the case, I am guessing the above answers are for older versions of vscode. What worked for me is adding:

"files.exclude": {
    "**/directory-you-want-to-exclude": true,
    "**/.git": true,
    "**/.svn": true,
    "**/.hg": true,
    "**/CVS": true,
    "**/.DS_Store": true
}

to my settings.json. This file can be opened through File>Preferences>Settings

Android: converting String to int

Use regular expression:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

output:

i=123;
j=123;
k=123;

What is the difference between Python's list methods append and extend?

append(): It is basically used in Python to add one element.

Example 1:

>> a = [1, 2, 3, 4]
>> a.append(5)
>> print(a)
>> a = [1, 2, 3, 4, 5]

Example 2:

>> a = [1, 2, 3, 4]
>> a.append([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, [5, 6]]

extend(): Where extend(), is used to merge two lists or insert multiple elements in one list.

Example 1:

>> a = [1, 2, 3, 4]
>> b = [5, 6, 7, 8]
>> a.extend(b)
>> print(a)
>> a = [1, 2, 3, 4, 5, 6, 7, 8]

Example 2:

>> a = [1, 2, 3, 4]
>> a.extend([5, 6])
>> print(a)
>> a = [1, 2, 3, 4, 5, 6]

Set cellpadding and cellspacing in CSS?

I suggest this and all the cells for the particular table are effected.

table.tbl_classname td, th {
    padding: 5px 5px 5px 4px;
 }

jQuery or JavaScript auto click

In jQuery you can trigger a click like this:

$('#foo').trigger('click');

More here:

http://api.jquery.com/trigger/

If you want to do the same using prototype, it looks like this:

$('foo').simulate('click');

How to check Oracle patches are installed?

Maybe you need "sys." before:

select * from sys.registry$history;

How to convert Integer to int?

Another simple way would be:

Integer i = new Integer("10");

if (i != null)
    int ip = Integer.parseInt(i.toString());

How to get the entire document HTML as a string?

PROBABLY ONLY IE:

>     webBrowser1.DocumentText

for FF up from 1.0:

//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));

may work in FF. (Shows up the VERY FIRST 300 characters from the VERY beginning of source-text, mostly doctype-defs.)

BUT be aware, that the normal "Save As"-Dialog of FF MIGHT NOT save the current state of the page, rather the originallly loaded X/h/tml-source-text !! (a POST-up of ss to some temp-file and redirect to that might deliver a saveable source-text WITH the changes/edits prior made to it.)

Although FF surprises by good recovery on "back" and a NICE inclusion of states/values on "Save (as) ..." for input-like FIELDS, textarea etc. , not on elements in contenteditable/ designMode...

If NOT a xhtml- resp. xml-file (mime-type, NOT just filename-extension!), one may use document.open/write/close to SET the appr. content to the source-layer, that will be saved on user's save-dialog from the File/Save menue of FF. see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp.

https://developer.mozilla.org/en-US/docs/Web/API/document.write

Neutral to questions of X(ht)ML, try a "view-source:http://..." as the value of the src-attrib of an (script-made!?) iframe, - to access an iframes-document in FF:

<iframe-elementnode>.contentDocument, see google "mdn contentDocument" for appr. members, like 'textContent' for instance. 'Got that years ago and no like to crawl for it. If still of urgent need, mention this, that I got to dive in ...

position fixed is not working

you need to give width explicitly to header and footer

width: 100%;

Working fiddle

If you want the middle section not to be hidden then give position: absolute;width: 100%; and set top and bottom properties (related to header and footer heights) to it and give parent element position: relative. (ofcourse, remove height: 700px;.) and to make it scrollable, give overflow: auto.

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

How do I turn off PHP Notices?

You are looking for:

php -d error_reporting="E_ERROR | E_WARNING | E_PARSE"

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

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

how to convert string to numerical values in mongodb

Try:

"TimeStamp":{$toDecimal: { $toDate:"$Datum"}}

jQuery find file extension (from string)

var fileName = 'file.txt';

// Getting Extension

var ext = fileName.split('.')[1];

// OR

var ext = fileName.split('.').pop();

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Getting DOM node from React child element

If you want to access any DOM element simply add ref attribute and you can directly access that element.

<input type="text" ref="myinput">

And then you can directly:

componentDidMount: function() 
{
    this.refs.myinput.select();

},

Their is no need of using ReactDOM.findDOMNode(), if you have added a ref to any element.

webpack command not working

I had to reinstall webpack to get it working with my local version of webpack, e.g:

$ npm uninstall webpack
$ npm i -D webpack

IDEA: javac: source release 1.7 requires target release 1.7

I resolved bellow method

File >> Project Structure >> Project >> Project Language Level --> do set proper version (ex: 1.5)

How to quickly edit values in table in SQL Server Management Studio?

Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200".

Parcelable encountered IOException writing serializable object getactivity()

If you can't make DNode serializable a good solution would be to add "transient" to the variable.

Example:

public static transient DNode dNode = null;

This will ignore the variable when using Intent.putExtra(...).

Passing variables in remote ssh command

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell

npm ERR! Error: EPERM: operation not permitted, rename

run the CLI as administrator always solve the problem for me

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

What is the first character in the sort order used by Windows Explorer?

From my testing, there are three criteria for sorting characters as described below. Aside from this, shorter strings are sorted above longer strings that start with the same characters.

Note: This testing only looked at the first character sorting and did not look into edge cases described by this answer, which found that, for all characters after the first character, numbers take precedence over symbols (i.e. the order is 1. Symbols 2. Numbers 3. Letters for first character, 1. Numbers 2. Symbols 3. Letters after). This answer also indicated that the Unicode/ASCII layer of sorting might not be entirely consistent. I'll update this answer if I get time to look into these edge cases.

Note: It's important to note that sorting order might be subject to change as described by this answer. It is not clear to me though the extent to which this actually ever changes. I've done this testing and found it to be valid on both Windows 7 and Windows 10.


Symbols
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Numbers
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

Letters
Latin (ordered by Unicode value (U+xxxx))
Greek (ordered by Unicode value (U+xxxx))
Cyrillic (ordered by Unicode value (U+xxxx))
Hebrew (ordered by Unicode value (U+xxxx))
Arabic (ordered by Unicode value (U+xxxx))

enter image description here


Sorting Rule Sequence vs Observed Order

It's worth noting that there are really two ways of looking at this. Ultimately, what you have are sorting rules that are applied in a certain order, in turn, this produces an observed order. The ordering of older rules becomes nested under the ordering of newer rules. This means that the first rule applied is the last rule observed, while the last rule applied is the first or topmost rule observed.

Sorting Rule Sequence

1.) Sort on Unicode Value (U+xxxx)
2.) Sort on culture/language
3.) Sort on Type (Symbol, Number, Letter)

Observed Order

  • The highest level of grouping is by type in the following order...

    1.) Symbols
    2.) Numbers
    3.) Letters

    Therefore, any symbol from any language comes before any number from any language, while any letter from any language appears after all symbols and numbers.

  • The second level of grouping is by culture/language. The following order seems to apply for this:

    Latin
    Greek
    Cyrillic
    Hebrew
    Arabic

  • The lowest rule observed is Unicode order, so items within a type-language group are ordered by Unicode value (U+xxxx).


Adapted from here: https://superuser.com/a/971721/496260

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

Convert pandas Series to DataFrame

One line answer would be

myseries.to_frame(name='my_column_name')

Or

myseries.reset_index(drop=True, inplace=True)  # As needed

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

jQuery set radio button

You can simply use:

$("input[name='cols']").click();

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

How to trigger click on page load?

$(function(){

    $(selector).click();

});

Basic HTTP authentication with Node and Express 4

I changed in express 4.0 the basic authentication with http-auth, the code is:

var auth = require('http-auth');

var basic = auth.basic({
        realm: "Web."
    }, function (username, password, callback) { // Custom authentication method.
        callback(username === "userName" && password === "password");
    }
);

app.get('/the_url', auth.connect(basic), routes.theRoute);

Changing precision of numeric column in Oracle

If the table is compressed this will work:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES move nocompress;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

alter table EVAPP_FEES compress;

Why is Git better than Subversion?

Eric Sink from SourceGear wrote series of articles on differences between distributed and nondistributed version controls systems. He compares pros and cons of most popular version control systems. Very interesting reading.
Articles can be found on his blog, www.ericsink.com:

How to rename a pane in tmux?

Also when scripting, you can specify a name when creating the window with -n <window name>. For example:

# variable to store the session name
SESSION="my_session"

# set up session
tmux -2 new-session -d -s $SESSION

# create window; split into panes
tmux new-window -t $SESSION:0 -n 'My Window with a Name'

How to enable authentication on MongoDB through Docker?

you can use env variables to setup username and password for mongo

MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD

using simple docker command

docker run -e MONGO_INITDB_ROOT_USERNAME=my-user MONGO_INITDB_ROOT_PASSWORD=my-password mongo

using docker-compose

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: my-user
      MONGO_INITDB_ROOT_PASSWORD: my-password

and the last option is to manually access the container and set the user and password inside the mongo docker container

docker exec -it mongo-container bash

now you can use mongo shell command to configure everything that you want

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

How do I float a div to the center?

if you are using width and height, you should try margin-right: 45%;... it is 100% working for me.. so i can take it to anywhere with percentage!

get the selected index value of <select> tag in php

Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value

<select name="gender">
<option value="default">Select </option>    
<option value="male">   Male   </option>
<option value="female"> Female </option>
</select>

OR

<select name="gender">
<option value="male" selected="selected">   Male   </option>
<option value="female"> Female </option>
</select>

When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.

Most important thing, AVOID SQL INJECTIONS:

//....
$fname   = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname   = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email   = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
  $email = mysql_real_escape_string($_POST['email']);
}
else
{
  //die ('invalid email address');
  // or whatever, a default value? $email = '';
}
$paswod  = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender  = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';

$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
  echo 'userid is already there';
}
else
{
 $sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
         VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';

Multi-dimensional associative arrays in JavaScript

You don't need to necessarily use Objects, you can do it with normal multi-dimensional Arrays.

This is my solution without Objects:

// Javascript
const matrix = [];

matrix.key1 = [
  'value1',
  'value2',
];

matrix.key2 = [
  'value3',
];

which in PHP is equivalent to:

// PHP
$matrix = [
    "key1" => [
        'value1',
        'value2',
    ],
    "key2" => [
        'value3',
    ]
];

Detect if a NumPy array contains at least one non-numeric value?

(np.where(np.isnan(A)))[0].shape[0] will be greater than 0 if A contains at least one element of nan, A could be an n x m matrix.

Example:

import numpy as np

A = np.array([1,2,4,np.nan])

if (np.where(np.isnan(A)))[0].shape[0]: 
    print "A contains nan"
else:
    print "A does not contain nan"

How to convert md5 string to normal text?

I you send passwords to users in an email, you might as well have no passwords at all.

You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).

Android ImageView Animation

Don't hard code image bounds. Just use:

RotateAnimation anim = new RotateAnimation( fromAngle, toAngle, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);

How to remove all characters after a specific character in python?

From a file:

import re
sep = '...'

with open("requirements.txt") as file_in:
    lines = []
    for line in file_in:
        res = line.split(sep, 1)[0]
        print(res)

Console.WriteLine and generic List

public static void WriteLine(this List<int> theList)
{
  foreach (int i in list)
  {
    Console.Write("{0}\t", t.ToString());
  }
  Console.WriteLine();
}

Then, later...

list.WriteLine();

How to encrypt a large file in openssl using public key

Maybe you should check out the accepted answer to this (How to encrypt data in php using Public/Private keys?) question.

Instead of manually working around the message size limitation (or perhaps a trait) of RSA, it shows how to use the S/mime feature of OpenSSL to do the same thing and not needing to juggle with the symmetric key manually.

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

Where do I put image files, css, js, etc. in Codeigniter?

This is how I handle the public assets. Here I use Phalcon PHP's Bootstrap method.

Folder Structure

|-.htaccess*
|-application/
|-public/
  |-.htaccess**
  |-index.php***
  |-css/
  |-js/
  |-img/
  |-font/
  |-upload/
|-system

Files to edit

  1. .htaccess*

    All requests to the project will be rewritten to the public/ directory making it the document root. This step ensures that the internal project folders remain hidden from public viewing and thus eliminates security threats of this kind. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  (.*) public/$1 [L]
    </IfModule>
    
  2. .htaccess**

    Rules will check if the requested file exists and, if it does, it doesn’t have to be rewritten by the web server module. - Phalconphp Doc

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ index.php/$1 [QSA,L]
    </IfModule>
    
  3. index.php***

    Modify the application path and the system path as,

    $system_path = '../system';
    $application_folder = '../application';
    

Now you use the public folder as base_url()."public/[YOUR ASSET FOLDER]"

Hope this helps :)

How do malloc() and free() work?

OK some answers about malloc were already posted.

The more interesting part is how free works (and in this direction, malloc too can be understood better).

In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).

So returning 40 Bytes to the OS will just not work. So what does free do?

Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.

The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.

There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.

Why does your code crash:

The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.

This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!

Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.

Can I pass a JavaScript variable to another browser window?

In your parent window:

var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);

Then in childwindow.html:

var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
    var keyValuePairs = keyValue.split(/=/);
    var key = keyValuePairs[0];
    var value = keyValuePairs[1];
    parameters[key] = value;
}

alert(parameters['yourKey']);

There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.

How to find topmost view controller on iOS

Simple extension for UIApplication in Swift:

NOTE:

It cares about moreNavigationController within UITabBarController

extension UIApplication {

    class func topViewController(baseViewController: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let navigationController = baseViewController as? UINavigationController {
            return topViewController(navigationController.visibleViewController)
        }

        if let tabBarViewController = baseViewController as? UITabBarController {

            let moreNavigationController = tabBarViewController.moreNavigationController

            if let topViewController = moreNavigationController.topViewController where topViewController.view.window != nil {
                return topViewController(topViewController)
            } else if let selectedViewController = tabBarViewController.selectedViewController {
                return topViewController(selectedViewController)
            }
        }

        if let splitViewController = baseViewController as? UISplitViewController where splitViewController.viewControllers.count == 1 {
            return topViewController(splitViewController.viewControllers[0])
        }

        if let presentedViewController = baseViewController?.presentedViewController {
            return topViewController(presentedViewController)
        }

        return baseViewController
    }
}

Simple usage:

if let topViewController = UIApplication.topViewController() {
    //do sth with top view controller
}

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Just wanted to drop a note. I was having trouble formatting a text 4000 field that had a mind of its own and the text would seeming wrap (or not wrap) randomly on the report. When I updated the column using the replace chr(10) noted above. My report finally formatted as I wanted. Many Thanx!

Get all dates between two dates in SQL Server

DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate) 

SELECT * FROM @tbl

How do I rename the android package name?

In Android Studio 1.1, the simplest way is to open your project manifest file, then point to each part of the package name that you want to change it and press SHIFT + F6 , then choose rename package and write the new name in the dialog box. That's all.

How to import a SQL Server .bak file into MySQL?

The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm

The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.

You will need to use SQL server to extract these. SQL Server Express is free and will do the job.

So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator)

then issue the following command.

restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO

This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.

RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH 
   MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', 
   MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO

At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database.

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

How to avoid annoying error "declared and not used"

You can use a simple "null function" for this, for example:

func Use(vals ...interface{}) {
    for _, val := range vals {
        _ = val
    }
}

Which you can use like so:

package main

func main() {
    a := "declared and not used"
    b := "another declared and not used"
    c := 123

    Use(a, b, c)
}

There's also a package for this so you don't have to define the Use function every time:

import (
  "github.com/lunux2008/xulu"
)

func main() {
  // [..]

  xulu.Use(a, b, c)
}

T-SQL: Opposite to string concatenation - how to split string into multiple records

I up-voted "Nathan Wheeler" answer as I found "Cade Roux" answer did not work above a certain string size.

Couple of points

-I found adding the DISTINCT keyword improved performance for me.

-Nathan's answer only works if your identifiers are 5 characters or less, of course you can adjust that...If the items you are splitting are INT identifiers as I am you can us same as me below:

CREATE FUNCTION [dbo].Split
(
    @sep VARCHAR(32), 
    @s VARCHAR(MAX)
)
RETURNS 
    @result TABLE (
        Id INT NULL
    )   
AS
BEGIN
    DECLARE @xml XML
    SET @XML = N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>'

    INSERT INTO @result(Id)
    SELECT DISTINCT r.value('.','int') as Item
    FROM @xml.nodes('//root//r') AS RECORDS(r)

    RETURN
END

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Constructor in an Interface?

A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn't as solid as an abstract class, but it allows more flexibility as being an interface.

However this workaround does require you to use the getInstance() to instantiate all objects of this interface.

E.g.

public interface Module {
    Module getInstance(Receiver receiver);
}

How to check if another instance of my shell script is running

I didn't want to hardcode abc.sh in the check, so I used the following:

MY_SCRIPT_NAME=`basename "$0"`
if pidof -o %PPID -x $MY_SCRIPT_NAME > /dev/null; then
    echo "$MY_SCRIPT_NAME already running; exiting"
    exit 1
fi

Using AJAX to pass variable to PHP and retrieve those using AJAX again

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

Read Docs http://api.jquery.com/jQuery.ajax/

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>

Is there a better jQuery solution to this.form.submit();?

Your question in somewhat confusing in that that you don't explain what you mean by "current element".

If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.

But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.

Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:

<form action="...">
    <input type="hidden" name="rowId" value="...">
    <button type="submit" name="myaction" value="edit">Edit</button>
    <button type="submit" name="myaction" value="delete">Delete</button>
</form>

When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).

Then on the server you just read the value of the variable "myaction" and decide what to do.

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow

Summaring the example, this is what you need to do a slideshow:

HTML:

<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />
</div>

Position absolute is used to put an each image over the other.

CSS

<style type="text/css">
    .active{
        z-index:99;
    }
</style>

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

<script>
    function slideSwitch() {
        var $active = $('div#slideshow IMG.active');
        var $next = $active.next();    

        $next.addClass('active');

        $active.removeClass('active');
    }

    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
</script>

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

How can I set multiple CSS styles in JavaScript?

You can write a function that will set declarations individually in order not to overwrite any existing declarations that you don't supply. Let's say you have this object parameter list of declarations:

const myStyles = {
  'background-color': 'magenta',
  'border': '10px dotted cyan',
  'border-radius': '5px',
  'box-sizing': 'border-box',
  'color': 'yellow',
  'display': 'inline-block',
  'font-family': 'monospace',
  'font-size': '20px',
  'margin': '1em',
  'padding': '1em'
};

You might write a function that looks like this:

function applyStyles (el, styles) {
  for (const prop in styles) {
    el.style.setProperty(prop, styles[prop]);
  }
};

which takes an element and an object property list of style declarations to apply to that object. Here's a usage example:

const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});

_x000D_
_x000D_
// styles to apply_x000D_
const myStyles = {_x000D_
  'background-color': 'magenta',_x000D_
  'border': '10px dotted cyan',_x000D_
  'border-radius': '5px',_x000D_
  'box-sizing': 'border-box',_x000D_
  'color': 'yellow',_x000D_
  'display': 'inline-block',_x000D_
  'font-family': 'monospace',_x000D_
  'font-size': '20px',_x000D_
  'margin': '1em',_x000D_
  'padding': '1em'_x000D_
};_x000D_
_x000D_
function applyStyles (el, styles) {_x000D_
  for (const prop in styles) {_x000D_
    el.style.setProperty(prop, styles[prop]);_x000D_
  }_x000D_
};_x000D_
_x000D_
// create example paragraph and append it to the page body_x000D_
const p = document.createElement('p');_x000D_
p.textContent = 'This is a paragraph.';_x000D_
document.body.appendChild(p);_x000D_
_x000D_
// when the paragraph is clicked, call the function, providing the_x000D_
// paragraph and myStyles object as arguments_x000D_
p.onclick = (ev) => {_x000D_
  applyStyles(p, myStyles);_x000D_
}_x000D_
_x000D_
// this time, target the page body and supply an object literal_x000D_
applyStyles(document.body, {'background-color': 'grey'});
_x000D_
_x000D_
_x000D_

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Simulating a click in jQuery/JavaScript on a link

Easy! Just use jQuery's click function:

$("#theElement").click();

New lines (\r\n) are not working in email body

If you use content-type: text/html you need to put a <br> because your message will be threated like an html file.

But if you change your content-type to text/plain instead of text/html you will be able to use \r\n characters.

How to: "Separate table rows with a line"

Style the row-element with css:

border-bottom: 1px solid black;

How to convert a byte array to a hex string in Java?

We don't need to use any external library or to write code based on loops and constants.
Is enough just this:

byte[] theValue = .....
String hexaString = new BigInteger(1, theValue).toString(16);

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How to display an alert box from C# in ASP.NET?

Hey Try This Code.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "Data has been saved", true);

Cheers

Android new Bottom Navigation bar or BottomNavigationView

You can create the layouts according to the above-mentioned answers If anyone wants to use this in kotlin:-

 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.images -> {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
       R.id.videos ->
         {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

then in oncreate you can set the above listener to your view

   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

What is MVC and what are the advantages of it?

Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).

How to use SQL Select statement with IF EXISTS sub query?

SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;