Programs & Examples On #Structured exception

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

In MVC 3 I had to add:

using System.ComponentModel.DataAnnotations;

among usings when adding properties:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Especially if you are adding these properties in .edmx file like me. I found that by default .edmx files don't have this using so adding only propeties is not enough.

SQL how to increase or decrease one for a int column in one command

UPDATE Orders Order
SET Order.Quantity =  Order.Quantity - 1
WHERE SomeCondition(Order)

As far as I know there is no build-in support for INSERT-OR-UPDATE in SQL. I suggest to create a stored procedure or use a conditional query to achiev this. Here you can find a collection of solutions for different databases.

Remove all unused resources from an android project

Since ADT 16 you can use Android Lint. It is really amazing tool.

Android Lint is a new tool for ADT 16 (and Tools 16) which scans Android project sources for potential bugs.

Here are some examples of the types of errors that it looks for:

  • Missing translations (and unused translations)
  • Layout performance problems (all the issues the old layoutopt tool used to find, and more)
  • Unused resources
  • Inconsistent array sizes (when arrays are defined in multiple configurations)
  • Accessibility and internationalization problems (hardcoded strings, missing contentDescription, etc)
  • Icon problems (like missing densities, duplicate icons, wrong sizes, etc)
  • Usability problems (like not specifying an input type on a text field)
  • Manifest errors and many more.

However, it has some issues (don't know if they're already fixed) and if you want to delete hundreds of supposedly unused resources I'd recommend to manually compile project several times during resource removing to be sure that Lint didn't remove something needed.

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How to get the onclick calling object?

http://docs.jquery.com/Events/jQuery.Event

Try with event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

Adding onClick event dynamically using jQuery

let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");

Hexadecimal to Integer in Java

SHA-1 produces a 160-bit message (20 bytes), too large to be stored in an int or long value. As Ralph suggests, you could use BigInteger.

To get a (less-secure) int hash, you could return the hash code of the returned byte array.

Alternatively, if you don't really need SHA at all, you could just use the UUID's String hash code.

What are the special dollar sign shell variables?

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.

For a comprehensive index, please see the Reference Manual Variable Index.

Can I install Python 3.x and 2.x on the same Windows computer?

As far as I know Python runs off of the commandline using the PATH variable as opposed to a registry setting.

So if you point to the correct version on your PATH you will use that. Remember to restart your command prompt to use the new PATH settings.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

I solved this problem like so:

1.) Set classpath in top-level build file as GUG mentioned:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0-beta2'
    }
    allprojects {
        repositories {
           jcenter()
        }
    }
}

2.) In build file of specific module:

android {
   useLibrary 'org.apache.http.legacy'
   compileSdkVersion 'android-MNC'
   buildToolsVersion '23.0.0 rc3'
}

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Pick any kind of file via an Intent in Android

Not for camera but for other files..

In my device I have ES File Explorer installed and This simply thing works in my case..

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

I think you have added firebase json file "google-services".json with the new file. Make sure to create a new file check the link on how to create json file from firebase and it should match with your package name

Second thing is that if you are changing the package name use the option " replace in path" when you right click under files when you select project from the drop down. You have to search for package name in the whole project and replace it !

Hope this helps !

How do I change the background color with JavaScript?

if you wish to use a button or some other event, just use this in JS:

document.querySelector("button").addEventListener("click", function() {
document.body.style.backgroundColor = "red";
});

import sun.misc.BASE64Encoder results in error compiled in Eclipse

This error is because of you are importing below two classes import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder;. Maybe you are using encode and decode of that library like below.

new BASE64Encoder().encode(encVal);
newBASE64Decoder().decodeBuffer(encryptedData);

Yeah instead of sun.misc.BASE64Encoder you can import java.util.Base64 class.Now change the previous encode method as below:

encryptedData=Base64.getEncoder().encodeToString(encryptedByteArray);

Now change the previous decode method as below

byte[] base64DecodedData = Base64.getDecoder().decode(base64EncodedData);

Now everything is done , you can save your program and run. It will run without showing any error.

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

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

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

How to run Spyder in virtual environment?

The above answers are correct but I calling spyder within my virtualenv would still use my PATH to look up the version of spyder in my default anaconda env. I found this answer which gave the following workaround:

source activate my_env            # activate your target env with spyder installed
conda info -e                     # look up the directory of your conda env
find /path/to/my/env -name spyder # search for the spyder executable in your env
/path/to/my/env/then/to/spyder    # run that executable directly

I chose this over modifying PATH or adding a link to the executable at a higher priority in PATH since I felt this was less likely to break other programs. However, I did add an alias to the executable in ~/.bash_aliases.

What's the difference between a Future and a Promise?

Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future) is just a read-only view of the other (Promise) ... but actually this is not needed.

For example take a look at how promises are defined in javascript:

https://promisesaplus.com/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The focus is on the composability using the then method like:

asyncOp1()
.then(function(op1Result){
  // do something
  return asyncOp2();
})
.then(function(op2Result){
  // do something more
  return asyncOp3();
})
.then(function(op3Result){
  // do something even more
  return syncOp4(op3Result);
})
...
.then(function(result){
  console.log(result);
})
.catch(function(error){
  console.log(error);
})

which makes asynchronous computation to look like synchronous:

try {
  op1Result = syncOp1();
  // do something
  op1Result = syncOp2();
  // do something more
  op3Result = syncOp3();
  // do something even more
  syncOp4(op3Result);
  ...
  console.log(result);
} catch(error) {
  console.log(error);
}

which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).

And actually their abstraction is pretty good as the promise constructor

new Promise( function(resolve, reject) { /* do it */ } );

allows you to provide two callbacks which can be used to either complete the Promise successfully or with an error. So that only the code that constructs the Promise can complete it and the code that receives an already constructed Promise object has the read-only view.

With inheritance the above can be achieved if resolve and reject are protected methods.

select2 - hiding the search box

//readonly on all select2 input
$(".select2-search input").prop("readonly", true);

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

Try this to move your table (tbl1) to tablespace (tblspc2).

alter table tb11 move tablespace tblspc2;

Failed to load resource under Chrome

I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).

As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via chrome://extensions).

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

No problem if all the arrays you are about to use in this scenario are small like in your example.

If you will use this for large blobs (e.g. storing large binary files many Mbs or even Gbs in size into a VARBINARY) then you'd probably be much better off using specific support in SQL Server for reading/writing subsections of such large blobs. Things like READTEXT and UPDATETEXT, or in current versions of SQL Server SUBSTRING.

For more information and examples see either my 2006 article in .NET Magazine ("BLOB + Stream = BlobStream", in Dutch, with complete source code), or an English translation and generalization of this on CodeProject by Peter de Jonghe. Both of these are linked from my weblog.

Android button font size

<resource>
<style name="button">
<item name="android:textSize">15dp</item>
</style>
<resource>

Ternary operator ?: vs if...else

I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.

How do I generate random number for each row in a TSQL Select?

When called multiple times in a single batch, rand() returns the same number.

I'd suggest using convert(varbinary,newid()) as the seed argument:

SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number 
FROM information_schema.tables

newid() is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.

Edited to get a random whole number from 1 to 14.

In MySQL, can I copy one row to insert into the same table?

Just wanted to post my piece of PHP code, because I think the way I collect the columns is a bit cleaner in code than the previous examples. Also this shows how you could easily alter an field, in this case adding a string. But you could also replace a foreign key field with the newly added record, in case you want to copy some child records as well.

  // Read columns, unset the PK (always the first field in my case)
  $stmt = $conn->prepare('SHOW COLUMNS FROM template');
  $stmt->execute();

  $columns = $stmt->fetchAll();
  $columns = array_map(function ($element) { return $element['Field']; }, $columns);

  unset($columns[0]);

  // Insert record in the database. Add string COPY to the name field.
  $sql = "INSERT INTO `template` (".implode(",", $columns).")";
  if ($key = array_search('name', $columns))
      $columns[$key] = "CONCAT(name, ' COPY')";
  $sql .= " SELECT ".implode(",", $columns)." FROM `template` WHERE `id` = ".$id;

  $stmt = $conn->prepare($sql);
  $stmt->execute();

Does Android keep the .apk files? if so where?

You can pull apps with ADB. They are in /data/App/, I believe.

adb pull (location on device) (where to save)

Note that you have to root your phone to pull copy protected apps.

Delete entire row if cell contains the string X

I'd like to add to @MBK's answer. Although I found @MBK's answer to be very helpful in solving a similar problem, it'd be better if @MBK included a screenshot of how to filter a particular column.enter image description here

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Find out time it took for a python script to complete execution

Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works

>>>fun(input)
output

Good, that works, now import timeit and set up a timer

>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>

Now we have our timer set up we can see how long it takes

>>>t.timeit(number=1)
some number here

And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.

I hope this helps.

Detect end of ScrollView

EDIT

With the content of your XML, I can see that you use a ScrollView. If you want to use your custom view, you must write com.your.packagename.ScrollViewExt and you will be able to use it in your code.

<com.your.packagename.ScrollViewExt
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/textterms"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:textColor="@android:color/black" />

</com.your.packagename.ScrollViewExt>

EDIT END

Could you post the xml content ?

I think that you could simply add a scroll listener and check if the last item showed is the lastest one from the listview like :

mListView.setOnScrollListener(new OnScrollListener() {      
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub      
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
        if(view.getLastVisiblePosition()==(totalItemCount-1)){
            //dosomething
        }
    }
});

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

How to check whether a variable is a class or not?

The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

java get file size efficiently

The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:

   file sum___19.0, per Iteration___19.0
    raf sum___16.0, per Iteration___16.0
channel sum__273.0, per Iteration__273.0

For 100 runs and 10000 iterations I get:

   file sum__1767629.0, per Iteration__1.7676290000000001
    raf sum___881284.0, per Iteration__0.8812840000000001
channel sum___414286.0, per Iteration__0.414286

I did run the following modified code giving as an argument the name of a 100MB file.

import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;

public class FileSizeBench {

  private static File file;
  private static FileChannel channel;
  private static RandomAccessFile raf;

  public static void main(String[] args) throws Exception {
    int runs = 1;
    int iterations = 1;

    file = new File(args[0]);
    channel = new FileInputStream(args[0]).getChannel();
    raf = new RandomAccessFile(args[0], "r");

    HashMap<String, Double> times = new HashMap<String, Double>();
    times.put("file", 0.0);
    times.put("channel", 0.0);
    times.put("raf", 0.0);

    long start;
    for (int i = 0; i < runs; ++i) {
      long l = file.length();

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != file.length()) throw new Exception();
      times.put("file", times.get("file") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != channel.size()) throw new Exception();
      times.put("channel", times.get("channel") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != raf.length()) throw new Exception();
      times.put("raf", times.get("raf") + System.nanoTime() - start);
    }
    for (Map.Entry<String, Double> entry : times.entrySet()) {
        System.out.println(
            entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
            ", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
    }
  }
}

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

Counting the number of True Booleans in a Python List

You can use sum():

>>> sum([True, True, False, False, False, True])
3

JavaScript and Threads

See http://caniuse.com/#search=worker for the most up-to-date support info.

The following was the state of support circa 2009.


The words you want to google for are JavaScript Worker Threads

Apart from from Gears there's nothing available right now, but there's plenty of talk about how to implement this so I guess watch this question as the answer will no doubt change in future.

Here's the relevant documentation for Gears: WorkerPool API

WHATWG has a Draft Recommendation for worker threads: Web Workers

And there's also Mozilla’s DOM Worker Threads


Update: June 2009, current state of browser support for JavaScript threads

Firefox 3.5 has web workers. Some demos of web workers, if you want to see them in action:

The Gears plugin can also be installed in Firefox.

Safari 4, and the WebKit nightlies have worker threads:

Chrome has Gears baked in, so it can do threads, although it requires a confirmation prompt from the user (and it uses a different API to web workers, although it will work in any browser with the Gears plugin installed):

  • Google Gears WorkerPool Demo (not a good example as it runs too fast to test in Chrome and Firefox, although IE runs it slow enough to see it blocking interaction)

IE8 and IE9 can only do threads with the Gears plugin installed

Where does PostgreSQL store the database?

As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:

ps aux | grep postgres | grep -- -D

Converting PKCS#12 certificate into PEM using OpenSSL

There is a free and open-source GUI tool KeyStore Explorer to work with crypto key containers. Using it you can export a certificate or private key into separate files or convert the container into another format (jks, pem, p12, pkcs12, etc)

enter image description here

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

recursively use scp but excluding some folders

Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude.

Something like this should do:

sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store

Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.

Converting HTML files to PDF

You can use a headless firefox with an extension. It's pretty annoying to get running but it does produce good results.

Check out this answer for more info.

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

Get my phone number in android

From the documentation:

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.

So you have done everything right, but there is no phone number stored.

If you get null, you could display something to get the user to input the phone number on his/her own.

Formatting a float to 2 decimal places

I believe:

String.Format("{0:0.00}",Sale);

Should do it.

See Link String Format Examples C#

Having links relative to root?

A root-relative URL starts with a / character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>.

The link you posted: <a href="fruits/index.html">Back to Fruits List</a> is linking to an html file located in a directory named fruits, the directory being in the same directory as the html page in which this link appears.

To make it a root-relative URL, change it to:

<a href="/fruits/index.html">Back to Fruits List</a>

Edited in response to question, in comments, from OP:

So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?

Yes, prefacing the URL, in the href or src attributes, with a / will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html, the a of href="/vegetables/carrots.html" will link to the page www.example.com/vegetables/carrots.html.

The base tag element allows you to specify the base-uri for that page (though the base tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:

For example, given the following BASE declaration and A declaration:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
   <TITLE>Our Products</TITLE>
   <BASE href="http://www.aviary.com/products/intro.html">
 </HEAD>

 <BODY>
   <P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
 </BODY>
</HTML>

the relative URI "../cages/birds.gif" would resolve to:

http://www.aviary.com/cages/birds.gif

Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.

Suggested reading:

select rows in sql with latest date for each ID repeated multiple times

One way is:

select table.* 
from table
join 
(
    select ID, max(Date) as max_dt 
    from table
    group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt 

Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result

Meaning of 'const' last in a function declaration of a class?

The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const:

const foobar fb;
fb.foo();

would be legal.

See How many and which are the uses of “const” in C++? for more information.

Open Source Javascript PDF viewer

There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

With Java 8, you could probably use Method Reference to achieve what you want.

Assume this is your onClick event handler for a button.

private void onMyButtonClicked(View v) {
    if (v.getId() == R.id.myButton) {
        // Do something when myButton was clicked
    }
}

Then, you pass onMyButtonClicked instance method reference in a setOnClickListener() call like this.

Button myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(this::onMyButtonClicked);

This will allow you to avoid explicitly defining an anonymous class by yourself. I must however emphasize that Java 8's Method Reference is actually just a syntactic sugar. It actually create an instance of the anonymous class for you (just like lambda expression did) hence similar caution as lambda-expression-style event handler was applied when you come to the unregistering of your event handler. This article explains it really nice.

PS. For those who curious about how can I really use Java 8 language feature in Android, it is a courtesy of retrolambda library.

What port number does SOAP use?

There is no such thing as "SOAP protocol". SOAP is an XML schema.

It usually runs over HTTP (port 80), however.

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

How to find good looking font color if background color is known?

Okay, this is still not the best possible solution, but a nice point to start. I wrote a little Java app that calculates the contrast ratio of two colors and only processes colors with a ratio of 5:1 or better - this ratio and the formula I use has been released by the W3C and will probably replace the current recommendation (which I consider very limited). It creates a file in the current working dir named "chosen-font-colors.html", with the background color of your choice and a line of text in every color that passed this W3C test. It expects a single argument, being the background color.

E.g. you can call it like this

java FontColorChooser 33FFB4

then just open the generated HTML file in a browser of your choice and choose a color from the list. All colors given passed the W3C test for this background color. You can change the cut off by replacing 5 with a number of your choice (lower numbers allow weaker contrasts, e.g. 3 will only make sure contrast is 3:1, 10 will make sure it is at least 10:1) and you can also cut off to avoid too high contrasts (by making sure it is smaller than a certain number), e.g. adding

|| cDiff > 18.0

to the if clause will make sure contrast won't be too extreme, as too extreme contrasts can stress your eyes. Here's the code and have fun playing around with it a bit :-)

import java.io.*;

/* For text being readable, it must have a good contrast difference. Why?
 * Your eye has receptors for brightness and receptors for each of the colors
 * red, green and blue. However, it has much more receptors for brightness
 * than for color. If you only change the color, but both colors have the
 * same contrast, your eye must distinguish fore- and background by the
 * color only and this stresses the brain a lot over the time, because it
 * can only use the very small amount of signals it gets from the color
 * receptors, since the breightness receptors won't note a difference.
 * Actually contrast is so much more important than color that you don't
 * have to change the color at all. E.g. light red on dark red reads nicely
 * even though both are the same color, red.
 */


public class FontColorChooser {
    int bred;
    int bgreen;
    int bblue;

    public FontColorChooser(String hexColor) throws NumberFormatException {
        int i;

        i = Integer.parseInt(hexColor, 16);
        bred = (i >> 16);
        bgreen = (i >> 8) & 0xFF;
        bblue = i & 0xFF;
    }

    public static void main(String[] args) {
        FontColorChooser fcc;

        if (args.length == 0) {
            System.out.println("Missing argument!");
            System.out.println(
                "The first argument must be the background" +
                "color in hex notation."
            );
            System.out.println(
                "E.g. \"FFFFFF\" for white or \"000000\" for black."
            );
            return;
        }
        try {
            fcc = new FontColorChooser(args[0]);
        } catch (Exception e) {
            System.out.println(
                args[0] + " is no valid hex color!"
            );
            return;
        }
        try {
            fcc.start();
        } catch (IOException e) {
            System.out.println("Failed to write output file!");
        }
    }

    public void start() throws IOException {
        int r;
        int b;
        int g;
        OutputStreamWriter out;

        out = new OutputStreamWriter(
            new FileOutputStream("chosen-font-colors.html"),
            "UTF-8"
        );

        // simple, not W3C comform (most browsers won't care), HTML header
        out.write("<html><head><title>\n");
        out.write("</title><style type=\"text/css\">\n");
        out.write("body { background-color:#");
        out.write(rgb2hex(bred, bgreen, bblue));
        out.write("; }\n</style></head>\n<body>\n");

        // try 4096 colors
        for (r = 0; r <= 15; r++) {
            for (g = 0; g <= 15; g++) {
                for (b = 0; b <= 15; b++) {
                    int red;
                    int blue;
                    int green;
                    double cDiff;

                    // brightness increasse like this: 00, 11,22, ..., ff
                    red = (r << 4) | r;
                    blue = (b << 4) | b;
                    green = (g << 4) | g;

                    cDiff = contrastDiff(
                        red, green, blue,
                        bred, bgreen, bblue
                    );
                    if (cDiff < 5.0) continue;
                    writeDiv(red, green, blue, out);
                }
            }
        }

        // finalize HTML document
        out.write("</body></html>");

        out.close();
    }

    private void writeDiv(int r, int g, int b, OutputStreamWriter out)
        throws IOException
    {
        String hex;

        hex = rgb2hex(r, g, b);
        out.write("<div style=\"color:#" + hex + "\">");
        out.write("This is a sample text for color " + hex + "</div>\n");
    }

    private double contrastDiff(
        int r1, int g1, int b1, int r2, int g2, int b2
    ) {
        double l1;
        double l2;

        l1 = ( 
            0.2126 * Math.pow((double)r1/255.0, 2.2) +
            0.7152 * Math.pow((double)g1/255.0, 2.2) +
            0.0722 * Math.pow((double)b1/255.0, 2.2) +
            0.05
        );
        l2 = ( 
            0.2126 * Math.pow((double)r2/255.0, 2.2) +
            0.7152 * Math.pow((double)g2/255.0, 2.2) +
            0.0722 * Math.pow((double)b2/255.0, 2.2) +
            0.05
        );

        return (l1 > l2) ? (l1 / l2) : (l2 / l1);
    }

    private String rgb2hex(int r, int g, int b) {
        String rs = Integer.toHexString(r);
        String gs = Integer.toHexString(g);
        String bs = Integer.toHexString(b);
        if (rs.length() == 1) rs = "0" + rs;
        if (gs.length() == 1) gs = "0" + gs;
        if (bs.length() == 1) bs = "0" + bs;
        return (rs + gs + bs);
    }
}

The simplest way to resize an UIImage?

This improvement to Paul's code will give you a sharp high res image on an iPhone with a retina display. Otherwise when scaling down it's blurry.

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([[UIScreen mainScreen] scale] == 2.0) {
        UIGraphicsBeginImageContextWithOptions(newSize, YES, 2.0);
    } else {
        UIGraphicsBeginImageContext(newSize);
    }
} else {
    UIGraphicsBeginImageContext(newSize);
}
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();
return newImage;
}

"Could not load type [Namespace].Global" causing me grief

Here's another one for the books. It appears that this happens when you launch more than one web application from the same port number.

Basically, I have a couple of branches that I work off, I have a main branch and a staging branch and a release branch. When I switched branch to the staging branch I noticed that it was using the same port address configuration so I opted to change that. I then received another warning that this reservation conflicts with another configured application. The IIS Express server is sensitive about that and for whatever reason it bricks the configuration.

By simply picking a third unaffected port this problem went away because it then maps the port to a new directory mapping (my branches are located differently on disk). I noticed this because I tried to change the type name pointed to by Global.asax but the type name was unchanged even after restarting the server, so clearly, the code I was changing wasn't reflected by the IIS Express deployment.

So, before you lose too much sleep over this, try changing the IIS port number that is currently used to run the web project.

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

How do I load a file from resource folder?

this.getClass().getClassLoader().getResource("filename").getPath()

Express-js wildcard routing to cover everything under and including a path

In array you also can use variables passing to req.params:

app.get(["/:foo", "/:foo/:bar"], /* function */);

How can I create a keystore?

You can create your keystore by exporting a signed APK. When you will try to export/build a signed APK, it will ask for a keystore.

You can choose your existing keystore or you can easily create a new one by clicking create new keystore

Here a link very useful and well-explained of how to create your keystore and generate a signed APK

THis link explained how to do it with Android Studio, but if I remember, it is pretty similar on Eclipse

WATCH OUT

Once you generate your keystore, keep it somewhere safe because you will need it to regenerate a new signed APK.

How do I export a project in the Android studio?

How to link home brew python version and set it as default

The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking

First, open up the document setting up the path of python

 nano ~/.bash_profile

Then something like this shows up:

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH

The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

Change and save the file. Restart the computer, and typing in python3.7, I get the python I installed for brew.

Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

create unique id with javascript

const uid = function(){
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

This Function generates very unique IDs that are sorted by its generated Date. Also useable for IDs in Databases.

Compare two files line by line and generate the difference in another file

Consider this:
file a.txt:

abcd
efgh

file b.txt:

abcd

You can find the difference with:

diff -a --suppress-common-lines -y a.txt b.txt

The output will be:

efgh 

You can redirict the output in an output file (c.txt) using:

diff -a --suppress-common-lines -y a.txt b.txt > c.txt

This will answer your question:

"...which contains the lines in file1 which are not present in file2."

Regex date format validation on Java

For fine control, consider an InputVerifier using the SimpleDateFormat("YYYY-MM-dd") suggested by Steve B.

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

How to add spacing between UITableViewCell

I override this function is subclass of UITableViewCell, and it works OK for me

override func layoutSubviews() {
      super.layoutSubviews()
      //set the values for top,left,bottom,right margins
      let margins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
      contentView.frame = contentView.frame.inset(by: margins)
      contentView.layer.cornerRadius = 8
}

Importing packages in Java

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;

SpringMVC RequestMapping for GET parameters

Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:

@RequestMapping("/userGrid", 
params = {"_search", "nd", "rows", "page", "sidx", "sort"})
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "_search") String search, 
@RequestParam(value = "nd") int nd, 
@RequestParam(value = "rows") int rows, 
@RequestParam(value = "page") int page, 
@RequestParam(value = "sidx") int sidx, 
@RequestParam(value = "sort") Sort sort) {
// Stuff here
}

This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

What is DOM element?

DOM is a logical model that can be implemented in any convenient manner.It is based on an object structure that closely resembles the structure of the documents it models.

For More Information on DOM : Click Here

How to embed a Facebook page's feed into my website

If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.

There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.

1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.

2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.

Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE

Maven plugins can not be found in IntelliJ

In my case, there were two slightly different dependences (version 2.1 vs 2.0) in two maven sub-modules. After I switched to a single version the error has gone in IDEA 14. (Refresh and .m2 swipe didn't help.)

Measuring elapsed time with the Time module

For a longer period.

import time
start_time = time.time()
...
e = int(time.time() - start_time)
print('{:02d}:{:02d}:{:02d}'.format(e // 3600, (e % 3600 // 60), e % 60))

would print

00:03:15

if more than 24 hours

25:33:57

That is inspired by Rutger Hofste's answer. Thank you Rutger!

How can I make my custom objects Parcelable?

IntelliJ IDEA and Android Studio have plugins for this:

These plugins generate Android Parcelable boilerplate code based on fields in the class.

Plugin demo

Can someone explain how to implement the jQuery File Upload plugin?

it's 2021 and here's a fantastically easy plugin to upload anything:

https://pqina.nl/filepond/?ref=pqina

add your element:

<input type="file" 
class="filepond"
name="filepond" 
multiple 
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="3">

Register any additional plugins:

  FilePond.registerPlugin(
FilePondPluginImagePreview,  
FilePondPluginImageExifOrientation,  
FilePondPluginFileValidateSize,  
FilePondPluginImageEdit);

Then wire in the element:

// Select the file input and use 
// create() to turn it into a pond
FilePond.create(
  document.querySelector('input'),

  // Use Doka.js as image editor
  imageEditEditor: Doka.create({
    utils: ['crop', 'filter', 'color']
  })
);

I use this with the additional Doka image editor to upload and transform images at https://www.yoodu.co.uk

crazy simple to setup and the guys who run it are great at support.

As you can tell I'm a fanboy.

Post order traversal of binary tree without recursion

Here is a solution in C++ that does not require any storage for book keeping in the tree.
Instead it uses two stacks. One to help us traverse and another to store the nodes so we can do a post traversal of them.

std::stack<Node*> leftStack;
std::stack<Node*> rightStack;

Node* currentNode = m_root;
while( !leftStack.empty() || currentNode != NULL )
{
    if( currentNode )
    {
        leftStack.push( currentNode );
        currentNode = currentNode->m_left;
    }
    else
    {
        currentNode = leftStack.top();
        leftStack.pop();

        rightStack.push( currentNode );
        currentNode = currentNode->m_right;
    }
}

while( !rightStack.empty() )
{
    currentNode = rightStack.top();
    rightStack.pop();

    std::cout << currentNode->m_value;
    std::cout << "\n";
}

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

How to have Ellipsis effect on Text

use numberOfLines

https://rnplay.org/plays/ImmKkA/edit

or if you know/or can compute the max character count per row, JS substring may be used.

<Text>{ ((mytextvar).length > maxlimit) ? 
    (((mytextvar).substring(0,maxlimit-3)) + '...') : 
    mytextvar }
</Text>

How to get the body's content of an iframe in Javascript?

Using JQuery, try this:

$("#id_description_iframe").contents().find("body").html()

How do I delete files programmatically on Android?

Try this one. It is working for me.

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Set up the projection (we only need the ID)
        String[] projection = { MediaStore.Images.Media._ID };

        // Match on the file path
        String selection = MediaStore.Images.Media.DATA + " = ?";
        String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };

        // Query for the ID of the media matching the file path
        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = getActivity().getContentResolver();
        Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

        if (c != null) {
            if (c.moveToFirst()) {
                // We found the ID. Deleting the item via the content provider will also remove the file
                long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
                contentResolver.delete(deleteUri, null, null);
            } else {
                // File not found in media store DB
            }
            c.close();
        }
    }
}, 5000);

Ruby: How to turn a hash into HTTP parameters?

Update: This functionality was removed from the gem.

Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.

require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
uri.query
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
uri.query
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
uri.query
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
uri.query
# => "a=a&b[c]=c&b[d]"

The gem is 'addressable'

gem install addressable

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

There is another possibility: You may have an error in your .aspx file that does not allow Visual Studio to regenerate the designer.

If you switch to Design View, it will show the control as unable to be rendered. Fixing the control (in my case it was an extra quote in the properties) and recompiling should regenerate the designer.

How do you query for "is not null" in Mongo?

Sharing for future readers.

This query worked for us (query executed from MongoDB compass):

{
  "fieldName": {
    "$nin": [
      "",
      null
    ]
  }
}

Aligning label and textbox on same line (left and right)

You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.

The following would work.

<td  colspan="2" class="cell">
                <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>        
                <asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>       
</td>

In your CSS file:

.cell
{
text-align:left;
}

.righttextbox
{
float:right;
}

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

How do I add images in laravel view?

You should store your images, css and JS files in a public directory. To create a link to any of them, use asset() helper:

{{ asset('img/myimage.png') }}

https://laravel.com/docs/5.1/helpers#method-asset

As alternative, you could use amazing Laravel Collective package for building forms and HTML elements, so your code will look like this:

{{ HTML::image('img/myimage.png', 'a picture') }}

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

add condition only firefox in your custom css file.

/* only Firefox */
@-moz-document url-prefix() {
   .img-responsive, .thumbnail>img, .thumbnail a>img, .carousel-inner>.item>img, .carousel-inner>.item>a>img {
      width: 100%;
   }
}

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

align 3 images in same row with equal spaces?

This should be your answer

<div align="center">
 <img src="@Url.Content("~/images/image3.bmp")" alt="" align="right" style="float:right"/>
 <img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" style="float:left" />
 <div id="content" align="center"> 
     <img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" />
 </div>
 </div>

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Git credential helper - update password

For Windows 10 it is:

Control Panel > User Accounts > Manage your Credentials > Windows Credentials, search for the git credentials and edit

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

Add/remove class with jquery based on vertical scroll?

Its my code

jQuery(document).ready(function(e) {
    var WindowHeight = jQuery(window).height();

    var load_element = 0;

    //position of element
    var scroll_position = jQuery('.product-bottom').offset().top;

    var screen_height = jQuery(window).height();
    var activation_offset = 0;
    var max_scroll_height = jQuery('body').height() + screen_height;

    var scroll_activation_point = scroll_position - (screen_height * activation_offset);

    jQuery(window).on('scroll', function(e) {

        var y_scroll_pos = window.pageYOffset;
        var element_in_view = y_scroll_pos > scroll_activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

        if (element_in_view || has_reached_bottom_of_page) {
            jQuery('.product-bottom').addClass("change");
        } else {
            jQuery('.product-bottom').removeClass("change");
        }

    });

});

Its working Fine

How to change Status Bar text color in iOS

In Info.plist set 'View controller-based status bar appearance' as NO

In AppDelegate add

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

Set Page Title using PHP

create a new page php and add this code:

_x000D_
_x000D_
<?php_x000D_
function ch_title($title){_x000D_
    $output = ob_get_contents();_x000D_
    if ( ob_get_length() > 0) { ob_end_clean(); }_x000D_
    $patterns = array("/<title>(.*?)<\/title>/");_x000D_
    $replacements = array("<title>$title</title>");_x000D_
    $output = preg_replace($patterns, $replacements,$output);_x000D_
    echo $output;_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

in <head> add code: <?php require 'page.php' ?> and on each page you call the function ch_title('my title');

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

Python: "TypeError: __str__ returned non-string" but still prints to output?

Method __str__ should return string, not print.

def __str__(self):
    return 'Memo={0}, Tag={1}'.format(self.memo, self.tags)

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

How to convert a time string to seconds?

import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

result: 3.0

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Stringifying a null value in ActionScript will give the string "NULL". My suspicion is that someone has decided that it is, therefore, a good idea to decode the string "NULL" as null, causing the breakage you see here -- probably because they were passing in null objects and getting strings in the database, when they didn't want that (so be sure to check for that kind of bug, too).

How to center cards in bootstrap 4?

i basically suggest equal gap on right and left, and setting width to auto. Here like:

.bmi {         /*my additional class name -for card*/
    margin-left: 18%;      
    margin-right: 18%;
    width: auto;
}

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

Named colors in matplotlib

I constantly forget the names of the colors I want to use and keep coming back to this question =)

The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.

I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.

enter image description here

I really didn't change much from the matplotlib example, but here is the code for completeness.

import matplotlib.pyplot as plt
from matplotlib import colors as mcolors


colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()

Additional named colors

Updated 2017-10-25. I merged my previous updates into this section.

xkcd

If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:

plt.plot([1,2], lw=4, c='xkcd:baby poop green')

Now you have access to a plethora of named colors!

enter image description here

Tableau

The default Tableau colors are available in matplotlib via the 'tab:' prefix:

plt.plot([1,2], lw=4, c='tab:green')

There are ten distinct colors:

enter image description here

HTML

You can also plot colors by their HTML hex code:

plt.plot([1,2], lw=4, c='#8f9805')

This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...


For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


Associative arrays in Shell scripts

I've found it true, as already mentioned, that the best performing method is to write out key/vals to a file, and then use grep/awk to retrieve them. It sounds like all sorts of unnecessary IO, but disk cache kicks in and makes it extremely efficient -- much faster than trying to store them in memory using one of the above methods (as the benchmarks show).

Here's a quick, clean method I like:

hinit() {
    rm -f /tmp/hashmap.$1
}

hput() {
    echo "$2 $3" >> /tmp/hashmap.$1
}

hget() {
    grep "^$2 " /tmp/hashmap.$1 | awk '{ print $2 };'
}

hinit capitols
hput capitols France Paris
hput capitols Netherlands Amsterdam
hput capitols Spain Madrid

echo `hget capitols France` and `hget capitols Netherlands` and `hget capitols Spain`

If you wanted to enforce single-value per key, you could also do a little grep/sed action in hput().

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

The first problem is that your query string is wrong:

I think this: "INSERT INTO employee(hans,germany) values(?,?)" should be like this: "INSERT INTO employee(name,country) values(?,?)"

The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.

You should add these to your code:

String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();

Converting a date string to a DateTime object using Joda Time library

I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:

DateTime date = DateTime.parse("04/02/2011 20:27:05", 
                  DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

Alter Table Add Column Syntax

This is how Adding new column to Table

ALTER TABLE [tableName]
ADD ColumnName Datatype

E.g

ALTER TABLE [Emp]
ADD Sr_No Int

And If you want to make it auto incremented

ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL

Double array initialization in Java

It is called an array initializer and can be explained in the Java specification 10.6.

This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.

Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.

gpg: no valid OpenPGP data found

I got this error in an Ubuntu Docker container. I believe the cause was that the container was missing CA certs. To fix it, I had to run:

apt-get update
apt-get install ca-certificates

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

How to install APK from PC?

Airdroid , android market install the app on android then go onto the computer type in the address given, type in the password given (or scan the QR code). Go to settings and under security (if your running the new ICS or Jellybean) or go to settings->apps->managment and select unknown sources(for gingerbread) then click on (I think) speed install, or something along those lines. it will be on the top of the page slightly towards the left. drag and drop as many .apks as you want then on you android just tap the install buttons that appear. Airdroid is wonderful and does a lot more than just apks.

Is it possible to write data to file using only JavaScript?

I found good answers here, but also found a simpler way.

The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)

You can style the link as a button using bootstrap, which is still pure javascript, except for styling.

Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.

This example needs only one button click to create the text-blob and download it:

<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" 
   onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
   Write To File
</a>

<script>
    // URL pointing to the Blob with the file contents
    var objUrl = null;
    // create the blob with file content, and attach the URL to the downloadlink; 
    // NB: link must have the download attribute
    // this method can go to your library
    function exportFile(fileContent, downloadLinkId) {
        // revoke the old object URL to avoid memory leaks.
        if (objUrl !== null) {
            window.URL.revokeObjectURL(objUrl);
        }
        // create the object that contains the file data and that can be referred to with a URL
        var data = new Blob([fileContent], { type: 'text/plain' });
        objUrl = window.URL.createObjectURL(data);
        // attach the object to the download link (styled as button)
        var downloadLinkButton = document.getElementById(downloadLinkId);
        downloadLinkButton.href = objUrl;
    };
</script>

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

I am using Windows 10 and korean version of Visual studio. I wanted to change from korean to english. I downloaded the english language pack but the error message appeared as "compatibility mode is on..." the only solution to this issue is to rename the Language pack setup file name with its original name, that is to say vs_langpack.exe . And boom the issue is solved.

Hope it is helpful.

Thanks.

how to release localhost from Error: listen EADDRINUSE

Check the Process ID

sudo lsof -i:8081

Than kill the particular Process

sudo kill -9 2925

enter image description here

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

how to get the base url in javascript

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


Further reading is available on this Stack Overflow thread

JavaScript alert box with timer

I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.

I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.

This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.

This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.

The statements above are valid ones.... (Please allow). How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.

CSS menus/DHTML use mouseover(valid statement).

I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.

The Prakash script above I feel could be the answer if you can adapt it.

Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.

1.

<html>
      <head>
            <title></title>
            <script language="JavaScript">
        // Variables
            leftposition=screen.width-350
            strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
            strfiller1='&nbsp;&nbsp;&nbsp;&nbsp; This alert is a timed one.'+'<br><br><br></td></tr></table>'
            temp=strfiller0+strfiller1
        // Javascript
            // This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am


            function preview(){
                            preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
                            preWindow.document.open();
                            preWindow.document.write(temp);
                            preWindow.document.close();
                    setTimeout(function(){preWindow.close()},4000); 
            }

             </script>
      </head>
<body>
    <input type="button" value=" Open " onclick="preview()">
</body>
</html>

2.

<style>
body {
  font-family: Arial, sans-serif;
  background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: #06D85F;
  margin: 80px 0;
}

.box {
  width: 40%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid #06D85F;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: #06D85F;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: #06D85F;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

@media screen and (max-width: 700px){
  .box{
    width: 70%;
  }
  .popup{
    width: 70%;
  }
}
</style>
<script>
    // written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO 
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
    <a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
    <div class="popup">
        <h2>Here i am</h2>
        <a class="close" href="#">&times;</a>
        <div class="content">
            Thank to pop me out of that button, but now i'm done so you can close this window.
        </div>
    </div>
</div>
</body>

3.

<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers

function displayMenu(currentPosition,nextPosition) {

    // Get the menu object located at the currentPosition on the screen
    var whichMenu = document.getElementById(currentPosition).style;

    if (displayMenu.arguments.length == 1) {
        // Only one argument was sent in, so we need to
        // figure out the value for "nextPosition"

        if (parseInt(whichMenu.top) == -5) {
            // Only two values are possible: one for mouseover
            // (-5) and one for mouseout (-90). So we want
            // to toggle from the existing position to the
            // other position: i.e., if the position is -5,
            // set nextPosition to -90...
            nextPosition = -90;
        }
        else {
            // Otherwise, set nextPosition to -5
            nextPosition = -5;
        }
    }

    // Redisplay the menu using the value of "nextPosition"
    whichMenu.top = nextPosition + "px";
}

// End hiding-->
</SCRIPT>

<STYLE TYPE="text/css">
<!--

.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}

 -->

</STYLE>

</HEAD>

<BODY BGCOLOR="white">

<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
<a href="#"> Alert:</a><br>
<a href="#"> </a><br>
<a href="#"> You pushed that button again... Didn't yeah? </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>

Save range to variable

My use case was to save range to variable and then select it later on

Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset

jQuery: Currency Format Number

You can use this way to format your currency needing.

var xx = new Intl.NumberFormat(‘en-US’, {
  style: ‘currency’,
  currency: ‘USD’,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
xx.format(123456.789); // ‘$123,456.79’

For more info you can access this link.

https://www.justinmccandless.com/post/formatting-currency-in-javascript/

What is the difference between `throw new Error` and `throw someObject`?

throw something works with both object and strings.But it is less supported than the other method.throw new Error("") Will only work with strings and turns objects into useless [Object obj] in the catch block.

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

Android emulator not able to access the internet

After 10 days of trouble, I just deleted everything from C:\Android\.android\ and deleted all created AVDs. Now internet seems to work fine.

Difference between | and || or & and && for comparison

in C (and other languages probably) a single | or & is a bitwise comparison.
The double || or && is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"

In practice, since true is often equivalent to 1 and false is often equivalent to 0, the bitwise comparisons can sometimes be valid and return exactly the same result.

There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:

if ( (altitide > 10000) & (knots > 100) )
...

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

You can run below commands. I believe this is what you want!

Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)

 ./catalina.sh run

How do I get the full url of the page I am on in C#

Here is a list I normally refer to for this type of information:

Request.ApplicationPath :   /virtual_dir
Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx
Request.FilePath :  /virtual_dir/webapp/page.aspx
Request.Path :  /virtual_dir/webapp/page.aspx
Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\
Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx
Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Host :  localhost
Request.Url.Authority : localhost:80
Request.Url.LocalPath : /virtual_dir/webapp/page.aspx
Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue
Request.Url.Port :  80
Request.Url.Query : ?q=qvalue
Request.Url.Scheme :    http
Request.Url.Segments :  /
    virtual_dir/
    webapp/
    page.aspx

Hopefully you will find this useful!

Compiling an application for use in highly radioactive environments

Here are huge amount of replies, but I'll try to sum up my ideas about this.

Something crashes or does not work correctly could be result of your own mistakes - then it should be easily to fix when you locate the problem. But there is also possibility of hardware failures - and that's difficult if not impossible to fix in overall.

I would recommend first to try to catch the problematic situation by logging (stack, registers, function calls) - either by logging them somewhere into file, or transmitting them somehow directly ("oh no - I'm crashing").

Recovery from such error situation is either reboot (if software is still alive and kicking) or hardware reset (e.g. hw watchdogs). Easier to start from first one.

If problem is hardware related - then logging should help you to identify in which function call problem occurs and that can give you inside knowledge of what is not working and where.

Also if code is relatively complex - it makes sense to "divide and conquer" it - meaning you remove / disable some function calls where you suspect problem is - typically disabling half of code and enabling another half - you can get "does work" / "does not work" kind of decision after which you can focus into another half of code. (Where problem is)

If problem occurs after some time - then stack overflow can be suspected - then it's better to monitor stack point registers - if they constantly grows.

And if you manage to fully minimize your code until "hello world" kind of application - and it's still failing randomly - then hardware problems are expected - and there needs to be "hardware upgrade" - meaning invent such cpu / ram / ... -hardware combination which would tolerate radiation better.

Most important thing is probably how you get your logs back if machine fully stopped / resetted / does not work - probably first thing bootstap should do - is a head back home if problematic situation is entcovered.

If it's possible in your environment also to transmit a signal and receive response - you could try out to construct some sort of online remote debugging environment, but then you must have at least of communication media working and some processor/ some ram in working state. And by remote debugging I mean either GDB / gdb stub kind of approach or your own implementation of what you need to get back from your application (e.g. download log files, download call stack, download ram, restart)

Pandas "Can only compare identically-labeled DataFrame objects" error

When you compare two DataFrames, you must ensure that the number of records in the first DataFrame matches with the number of records in the second DataFrame. In our example, each of the two DataFrames had 4 records, with 4 products and 4 prices.

If, for example, one of the DataFrames had 5 products, while the other DataFrame had 4 products, and you tried to run the comparison, you would get the following error:

ValueError: Can only compare identically-labeled Series objects

this should work

import pandas as pd
import numpy as np

firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
                   'Price1': [1200,800,200,350]
                   }
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])


secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
                    'Price2': [900,800,300,350]
                    }
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])


df1['Price2'] = df2['Price2'] #add the Price2 column from df2 to df1

df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False')  #create new column in df1 to check if prices match
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2']) #create new column in df1 for price diff 
print (df1)

example from https://datatofish.com/compare-values-dataframes/

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

You can try this way:

open('u.item', encoding='utf8', errors='ignore')

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

Programmatically change the height and width of a UIImageView Xcode Swift

let screenSize: CGRect = UIScreen.mainScreen().bounds
image.frame = CGRectMake(0,0, screenSize.height * 0.2, 50)

How can I initialize an array without knowing it size?

You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T> here - usually ArrayList<T>, but with plenty of other alternatives available.

You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T> to start with.

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

Scanner vs. BufferedReader

See this link, following is quoted from there:

A BufferedReader is a simple class meant to efficiently read from the underling stream. Generally, each read request made of a Reader like a FileReader causes a corresponding read request to be made to underlying stream. Each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Efficiency is improved appreciably if a Reader is warped in a BufferedReader.

BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads.

A scanner on the other hand has a lot more cheese built into it; it can do all that a BufferedReader can do and at the same level of efficiency as well. However, in addition a Scanner can parse the underlying stream for primitive types and strings using regular expressions. It can also tokenize the underlying stream with the delimiter of your choice. It can also do forward scanning of the underlying stream disregarding the delimiter!

A scanner however is not thread safe, it has to be externally synchronized.

The choice of using a BufferedReader or a Scanner depends on the code you are writing, if you are writing a simple log reader Buffered reader is adequate. However if you are writing an XML parser Scanner is the more natural choice.

Even while reading the input, if want to accept user input line by line and say just add it to a file, a BufferedReader is good enough. On the other hand if you want to accept user input as a command with multiple options, and then intend to perform different operations based on the command and options specified, a Scanner will suit better.

Check if one list contains element from the other

With java 8, we can do like below to check if one list contains any element of other list

boolean var = lis1.stream().filter(element -> list2.contains(element)).findFirst().isPresent();

Prevent Default on Form Submit jQuery

DEPRECATED - this part is outdated so please don't use it.

You can also try this code, if you have for example later added dynamic forms. For example you loaded a window async with ajax and want to submit this form.

$('#cpa-form').live('submit' ,function(e){
    e.preventDefault();      
    // do something
});

UPDATE - you should use the jQuery on() method an try to listen to the document DOM if you want to handle dynamically added content.

Case 1, static version: If you have only a few listeners and your form to handle is hardcoded, then you can listen directly on "document level". I wouldn't use the listeners on document level but I would try to go deeper in the doom tree because it could lead to performance issues (depends on the size of your website and your content)

$('form#formToHandle').on('submit'... 

OR

$('form#formToHandle').submit(function(e) {
    e.preventDefault();      
    // do something
});

Case 2, dynamic version: If you already listen to the document in your code, then this way would be good for you. This will also work for code that was added later via DOM or dynamic with AJAX.

$(document).on('submit','form#formToHandle',function(){
   // do something like e.preventDefault(); 
});

OR

$(document).ready(function() {
    console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

OR

$(function() { // <- this is shorthand version
   console.log( "Ready, Document loaded!" );

    // all your other code listening to the document to load 

    $("#formToHandle").on("submit", function(){
        // do something           
    })
});

What are database constraints?

Constraints are nothing but the rules on the data. What data is valid and what is invalid can be defined using constraints. So, that integrity of data can be maintained. Following are the widely used constraints:

  1. Primary Key : which uniquely identifies the data . If this constraint has been specified for certain column then we can't enter duplicate data in that column
  2. Check : Such as NOT NULL . Here we can specify what data we can enter for that particular column and what is not expected for that column.
  3. Foreign key : Foreign key references to the row of other table. So that data referred in one table from another table is always available for the referencing table.

TypeError: $(...).modal is not a function with bootstrap Modal

I have resolved this issue in react by using it like this.

window.$('#modal-id').modal();

How to scan multiple paths using the @ComponentScan annotation?

You use ComponentScan to scan multiple packages using

@ComponentScan({"com.my.package.first","com.my.package.second"})

Specifying an Index (Non-Unique Key) Using JPA

With JPA 2.1 you should be able to do it.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;

@Entity
@Table(name = "region",
       indexes = {@Index(name = "my_index_name",  columnList="iso_code", unique = true),
                  @Index(name = "my_index_name2", columnList="name",     unique = false)})
public class Region{

    @Column(name = "iso_code", nullable = false)
    private String isoCode;

    @Column(name = "name", nullable = false)
    private String name;

} 

Update: If you ever need to create and index with two or more columns you may use commas. For example:

@Entity
@Table(name    = "company__activity", 
       indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

How to compare two double values in Java?

Basically you shouldn't do exact comparisons, you should do something like this:

double a = 1.000001;
double b = 0.000001;
double c = a-b;
if (Math.abs(c-1.0) <= 0.000001) {...}

insert echo into the specific html element like div which has an id or class

The only things I can think of are

  1. including files
  2. replacing elements within files using preg_match_all
  3. using assigned variables

I have recently been using str_replace and setting text in the HTML portion like so

{{TEXT_TO_REPLACE}}

using file_get_contents() you can grab html data and then organise it how you like.

here is a demo

myReplacementCodeFunction(){
  $text = '<img src="'.$row['name'].'" />'; 
  $text .= "<div>".$row['name']."</div>";
  $text .= "<div>".$row['title']."</div>";
  $text .= "<div>".$row['description']."</div>";
  $text .= "<div>".$row['link']."</div>";
  $text .= "<br />";
  return $text;
}

$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;

and now a demo html file:

<html>
<head>
   <style type="text/css">
      body{background:#666666;}
      div{border:1px solid red;}
   </style>
  </head>
  <body>
    {{TEXT_TO_REPLACE}}
  </body>
</html>

How do I return an int from EditText? (Android)

First of all get a string from an EDITTEXT and then convert this string into integer like

      String no=myTxt.getText().toString();       //this will get a string                               
      int no2=Integer.parseInt(no);              //this will get a no from the string

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

jQuery: How to capture the TAB keypress within a Textbox

Working example in jQuery 1.9:

$('body').on('keydown', '#textbox', function(e) {
    if (e.which == 9) {
        e.preventDefault();
        // do your code
    }
});

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

For what it's worth, I had the issue as well in IE11:

  • I was not in Enterprise mode.
  • The "Display intranet sites in Compatibility View" was checked.
  • I had all the <!DOCTYPE html> and IE=Edge settings mentioned in the question
  • The meta header was indeed the 1st element in the <head> element

After a while, I found out that:

  • the User Agent header sent to the server was IE7 but...
  • the JavaScript value was IE11!

HTTP Header:

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E) but

JavaScript:

window.navigator.userAgent === 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'

So I ended up doing the check on the client side.

And BTW, meanwhile, checking the user agent is no longer recommended. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent (but there might be a good case)

Install Qt on Ubuntu

Install Qt

sudo apt-get install build-essential

sudo apt-get install qtcreator

sudo apt-get install qt5-default

Install documentation and examples If Qt Creator is installed thanks to the Ubuntu Sofware Center or thanks to the synaptic package manager, documentation for Qt Creator is not installed. Hitting the F1 key will show you the following message : "No documentation available". This can easily be solved by installing the Qt documentation:

sudo apt-get install qt5-doc

sudo apt-get install qt5-doc-html qtbase5-doc-html

sudo apt-get install qtbase5-examples

Restart Qt Creator to make the documentation available.

Error while loading shared libraries

Problem:

radiusd: error while loading shared libraries: libfreeradius-radius-2.1.10.so: cannot open shared object file: No such file or directory

Reason:

Actually, the libraries have been installed in a place where dynamic linker cannot find it.

Solution:

While this is not a guarantee but using the following command may help you solve the “cannot open shared object file” error:

sudo /sbin/ldconfig -v

http://www.lucidarme.me/how-install-documentation-for-qt-creator/

https://ubuntuforums.org/showthread.php?t=2199929

https://itsfoss.com/error-while-loading-shared-libraries/

ModelSim-Altera error

Can't create handler inside thread which has not called Looper.prepare()

Try running you asyntask from the UI thread. I faced this issue when I wasn't doing the same!

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

MySQL - UPDATE query with LIMIT

If you want to update multiple rows using limit in MySQL you can use this construct:

UPDATE table_name SET name='test'
WHERE id IN (
    SELECT id FROM (
        SELECT id FROM table_name 
        ORDER BY id ASC  
        LIMIT 0, 10
    ) tmp
)

C/C++ check if one bit is set in, i.e. int variable

Why all these bit shifting operations and need for library functions? If you have the value the OP posted: 1011110 and you want to know if the bit in the 3rd position from the right is set, just do:

int temp = 0b1011110;
if( temp & 4 )   /* or (temp & 0b0100) if that's how you roll */
  DoSomething();

Or, something that may be more easily interpreted by future readers of the code with no #include needed:

int temp = 0b1011110;
_Bool bThirdBitIsSet = (temp & 4) ? 1 : 0;
if( bThirdBitIsSet )
  DoSomething();

Or if you like it to look a bit prettier:

#include <stdbool.h>
int temp = 0b1011110;
bool bThirdBitIsSet = (temp & 4) ? true : false;
if( bThirdBitIsSet )
  DoSomething();

Git: How to update/checkout a single file from remote origin master?

With Git 2.23 (August 2019) and the new (still experimental) command git restore, seen in "How to reset all files from working directory but not from staging area?", that would be:

git fetch
git restore -s origin/master -- path/to/file

The idea is: git restore only deals with files, not files and branches as git checkout does.
See "Confused by git checkout": that is where git switch comes in)


codersam adds in the comments:

in my case I wanted to get the data from my upstream (from which I forked).
So just changed to:

git restore -s upstream/master -- path/to/file

How to read from standard input in the console?

Another way to read multiple inputs within a loop which can handle an input with spaces:

package main
import (
    "fmt"
    "bufio"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    var text string
    for text != "q" {  // break the loop if text == "q"
        fmt.Print("Enter your text: ")
        scanner.Scan()
        text = scanner.Text()
        if text != "q" {
            fmt.Println("Your text was: ", text)
        }
    }
}

Output:

Enter your text: Hello world!
Your text was:  Hello world!
Enter your text: Go is awesome!
Your text was:  Go is awesome!
Enter your text: q

How do I output text without a newline in PowerShell?

I cheated, but I believe this is the only answer that addresses every requirement. Namely, this avoids the trailing CRLF, provides a place for the other operation to complete in the meantime, and properly redirects to stdout as necessary.

$c_sharp_source = @"
using System;
namespace StackOverflow
{
   public class ConsoleOut
   {
      public static void Main(string[] args)
      {
         Console.Write(args[0]);
      }
   }
}
"@
$compiler_parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler_parameters.GenerateExecutable = $true
$compiler_parameters.OutputAssembly = "consoleout.exe"
Add-Type -TypeDefinition $c_sharp_source -Language CSharp -CompilerParameters $compiler_parameters

.\consoleout.exe "Enabling feature XYZ......."
Write-Output 'Done.'

Can someone give an example of cosine similarity, in a very simple, graphical way?

Using @Bill Bell example, two ways to do this in [R]

a = c(2,1,0,2,0,1,1,1)

b = c(2,1,1,1,1,0,1,1)

d = (a %*% b) / (sqrt(sum(a^2)) * sqrt(sum(b^2)))

or taking advantage of crossprod() method's performance...

e = crossprod(a, b) / (sqrt(crossprod(a, a)) * sqrt(crossprod(b, b)))

Install .ipa to iPad with or without iTunes

If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.

Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios

Stop an input field in a form from being submitted

All of the above answers already said everything about (not) naming the form controls or programmatically removing them before actually submitting your form.

Although, across my research I found one other solution that I haven't seen mentioned in this post:
If you encapsulate the form controls you want to be unprocessed/not sent, inside another <form> tag with no method attribute nor path (and obviously no submit type control like a button or submit input nested in it), then submitting the parent form won't include those encapsulated form controls.

<form method="POST" path="/path">
  <input type="text" name="sent" value="..." />
  <form>
    <input type="text" name="notSent" value="..." />
  </form>
  <input type="submit" name="submit" value="Submit" />
</form>

The [name="notSent"] control value won't be processed nor sent to the server POST endpoint, but the one from [name="sent"] will.

This solution might be anecdotic but I'm still leaving it for posterity...

How to set HTTP headers (for cache-control)?

As I wrote is best to use the file .htaccess. However beware of the time you leave the contents in the cache.

Use:

<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>

Where: 604800 = 7 days

PS: This can be used to reset any header

How do I remove the space between inline/inline-block elements?

Just for fun: an easy JavaScript solution.

_x000D_
_x000D_
document.querySelectorAll('.container').forEach(clear);_x000D_
_x000D_
function clear(element) {_x000D_
  element.childNodes.forEach(check, element);_x000D_
}_x000D_
_x000D_
function check(item) {_x000D_
  if (item.nodeType === 3) this.removeChild(item);_x000D_
}
_x000D_
span {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  background-color: palevioletred;_x000D_
}
_x000D_
<p class="container">_x000D_
  <span> Foo </span>_x000D_
  <span> Bar </span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Using the "With Clause" SQL Server 2008

Just a poke, but here's another way to write FizzBuzz :) 100 rows is enough to show the WITH statement, I reckon.

;WITH t100 AS (
 SELECT n=number
 FROM master..spt_values
 WHERE type='P' and number between 1 and 100
)                
 SELECT
    ISNULL(NULLIF(
    CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
    CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
 FROM t100

But the real power behind WITH (known as Common Table Expression http://msdn.microsoft.com/en-us/library/ms190766.aspx "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.

;WITH t100 AS (
 SELECT n=1
 union all
 SELECT n+1
 FROM t100
 WHERE n < 100
)                
 SELECT
    ISNULL(NULLIF(
    CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
    CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
 FROM t100

To run a similar query in all database, you can use the undocumented sp_msforeachdb. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.

Be careful when using it though, as some things are not what you expect. Consider this example

exec sp_msforeachdb 'select count(*) from sys.objects'

Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB. To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.

exec sp_msforeachdb 'use [?]; select count(*) from sys.objects'

For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.

create table #tbl (dbname sysname, img_count int);

exec sp_msforeachdb '
use [?];
if object_id(''tbldoc'') is not null
insert #tbl
select ''?'', count(*) from tbldoc'

select * from #tbl

Get current URL/URI without some of $_GET variables

$validar= Yii::app()->request->getParam('id');

How to store NULL values in datetime fields in MySQL?

MySQL does allow NULL values for datetime fields. I just tested it:

mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL       | 
+------------+
1 row in set (0.00 sec)

I'm using this version:

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45    | 
+-----------+
1 row in set (0.03 sec)

EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''), not null. An empty string is different than null and is not a valid datetime value which is why you are getting that error message. You must pass the special sql keyword null if that's what you mean. Also, don't put any quotes around the word null. See my insert statement above for an example of how to insert null.

EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1] type when binding a null. See the answer to this stackoverflow question on how to properly insert null using PDO.

What is the difference between PUT, POST and PATCH?

Difference between PUT, POST, GET, DELETE and PATCH IN HTTP Verbs:

The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.

  1. create - POST
  2. read - GET
  3. update - PUT
  4. delete - DELETE

PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.

Note:
Since POST, PUT, DELETE modifies the content, the tests with Fiddler for the below url just mimicks the updations. It doesn't delete or modify actually. We can just see the status codes to check whether insertions, updations, deletions occur.

URL: http://jsonplaceholder.typicode.com/posts/

1) GET:

GET is the simplest type of HTTP request method; the one that browsers use each time you click a link or type a URL into the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: GET

url: http://jsonplaceholder.typicode.com/posts/

Response: You will get the response as:

"userId": 1, "id": 1, "title": "sunt aut...", "body": "quia et suscipit..."

In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

2) POST:

The POST verb is mostly utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.

On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: POST

url: http://jsonplaceholder.typicode.com/posts/

Request Body:

data: { title: 'foo', body: 'bar', userId: 1000, Id : 1000 }

Response: You would receive the response code as 201.

If we want to check the inserted record with Id = 1000 change the verb to Get and use the same url and click Execute.

As said earlier, the above url only allows reads (GET), we cannot read the updated data in real.

3) PUT:

PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: PUT

url: http://jsonplaceholder.typicode.com/posts/1

Request Body:

data: { title: 'foo', body: 'bar', userId: 1, Id : 1 }

Response: On successful update it returns 200 (or 204 if not returning any content in the body) from a PUT.

4) DELETE:

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: DELETE

url: http://jsonplaceholder.typicode.com/posts/1

Response: On successful deletion it returns HTTP status 200 (OK) along with a response body.

Example between PUT and PATCH

PUT

If I had to change my firstname then send PUT request for Update:

{ "first": "Nazmul", "last": "hasan" } So, here in order to update the first name we need to send all the parameters of the data again.

PATCH:

Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.

Please refer the below links for more information:

https://jsonplaceholder.typicode.com/

https://github.com/typicode/jsonplaceholder#how-to

What is the main difference between PATCH and PUT request?

http://www.restapitutorial.com/lessons/httpmethods.html

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

How to comment and uncomment blocks of code in the Office VBA Editor

After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).

How to overwrite the previous print to stdout in python?

@Mike DeSimone answer will probably work most of the time. But...

for x in ['abc', 1]:
    print '{}\r'.format(x),

-> 1bc

This is because the '\r' only goes back to the beginning of the line but doesn't clear the output.

EDIT: Better solution (than my old proposal below)

If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:

print '\x1b[2K\r',

It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.

Old answer

The (not so good) solution I've found looks like this:

last_x = ''
for x in ['abc', 1]:
    print ' ' * len(str(last_x)) + '\r',
    print '{}\r'.format(x),
    last_x = x

-> 1

One advantage is that it will work on windows too.

How can you find out which process is listening on a TCP or UDP port on Windows?

It is very simple to get the port number from a PID in Windows.

The following are the steps:

  1. Go to run → type cmd → press Enter.

  2. Write the following command...

    netstat -aon | findstr [port number]
    

    (Note: Don't include square brackets.)

  3. Press Enter...

  4. Then cmd will give you the detail of the service running on that port along with the PID.

  5. Open Task Manager and hit the service tab and match the PID with that of the cmd, and that's it.

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

JavaScript: Passing parameters to a callback function

When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

Docker: How to delete all local Docker images

To simple clear everything do:

$ docker system prune --all

Everything means:

  • all stopped containers
  • all networks not used by at least one container
  • all images without at least one container associated to them
  • all build cache

ie8 var w= window.open() - "Message: Invalid argument."

I discovered the same problem and after reading the first answer that supposed the problem is caused by the window name, changed it : first to '_blank', which worked fine (both compatibility and regular view), then to the previous value, only minus the space in the value :) - also worked. IMO, the problem (or part of it) is caused by IE being unable to use a normal string value as the wname. Hope this helps if anybody runs into the same problem.

When is a language considered a scripting language?

I think Mr Roberto Ierusalimschy has a very good answer or the question in 'Programming in Lua':

However, the distinguishing feature of interpreted languages is not that they are not compiled, but that any compiler is part of the language runtime and that, therefore, it is possible (and easy) to execute code generated on the fly