Programs & Examples On #Message passing

Message passing is a data transfer mechanism that is used in various forms in a number of programming languages

Why is setState in reactjs Async instead of Sync?

I know this question is old, but it has been causing a lot of confusion for many reactjs users for a long time, including me. Recently Dan Abramov (from the react team) just wrote up a great explanation as to why the nature of setState is async:

https://github.com/facebook/react/issues/11527#issuecomment-360199710

setState is meant to be asynchronous, and there are a few really good reasons for that in the linked explanation by Dan Abramov. This doesn't mean it will always be asynchronous - it mainly means that you just can't depend on it being synchronous. ReactJS takes into consideration many variables in the scenario that you're changing the state in, to decide when the state should actually be updated and your component rerendered.
A simple example to demonstrate this, is that if you call setState as a reaction to a user action, then the state will probably be updated immediately (although, again, you can't count on it), so the user won't feel any delay, but if you call setState in reaction to an ajax call response or some other event that isn't triggered by the user, then the state might be updated with a slight delay, since the user won't really feel this delay, and it will improve performance by waiting to batch multiple state updates together and rerender the DOM fewer times.

How to create file object from URL object (image)

Since Java 7

File file = Paths.get(url.toURI()).toFile();

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

How to figure out the SMTP server host?

To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

Put this in a batch file named: getmns.bat (get mail name server):

@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.

For example:

getmns google.com

output:

google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com

alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com      internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27

For example to pipe the result again into a file do:

getmns google.com > google.mns.txt

:-D

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

How to compare two dates?

Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)

How can I determine if a date is between two dates in Java?

This might be a bit more readable:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.after(min) && d.before(max);

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Is it possible that you can avoid using wsdl2java? You can straight away use CXF FrontEnd APIs to invoke your SOAP Webservice. The only catch is that you need to create your SEI and VOs on your client end. Here is a sample code.

package com.aranin.weblog4j.client;

import com.aranin.weblog4j.services.BookShelfService;
import com.aranin.weblog4j.vo.BookVO;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

public class DemoClient {
    public static void main(String[] args){
        String serviceUrl = "http://localhost:8080/weblog4jdemo/bookshelfservice";
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(BookShelfService.class);
        factory.setAddress(serviceUrl);
        BookShelfService bookService = (BookShelfService) factory.create();

        //insert book
        BookVO bookVO = new BookVO();
        bookVO.setAuthor("Issac Asimov");
        bookVO.setBookName("Foundation and Earth");

        String result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        bookVO = new BookVO();
        bookVO.setAuthor("Issac Asimov");
        bookVO.setBookName("Foundation and Empire");

        result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        bookVO = new BookVO();
        bookVO.setAuthor("Arthur C Clarke");
        bookVO.setBookName("Rama Revealed");

        result = bookService.insertBook(bookVO);

        System.out.println("result : " + result);

        //retrieve book

        bookVO = bookService.getBook("Foundation and Earth");

        System.out.println("book name : " + bookVO.getBookName());
        System.out.println("book author : " + bookVO.getAuthor());

    }
}

You can see the full tutorial here http://weblog4j.com/2012/05/01/developing-soap-web-service-using-apache-cxf/

How to extract one column of a csv file

Many answers for this questions are great and some have even looked into the corner cases. I would like to add a simple answer that can be of daily use... where you mostly get into those corner cases (like having escaped commas or commas in quotes etc.,).

FS (Field Separator) is the variable whose value is dafaulted to space. So awk by default splits at space for any line.

So using BEGIN (Execute before taking input) we can set this field to anything we want...

awk 'BEGIN {FS = ","}; {print $3}'

The above code will print the 3rd column in a csv file.

How to format an inline code in Confluence?

I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.

Creating Colored Monospace with Wiki Markup

As rendered by Confluence

Xcode 6 Bug: Unknown class in Interface Builder file

I had this problem after I added a new target, then created a new class using the 'New File' dialog but accidentally failed to check the new target as well as the original target in the creation dialog, so the object was only added to my original target. The solution was to delete the source files (remove reference only) then add them back using 'Add Files', this time checking both targets.

Truncate a SQLite table if it exists?

After deleting I'm also using VACUUM command. So for full TRUNCATE equivalent I use this code:

DELETE FROM <table>;
UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE name = '<table>';
VACUUM;

Deleting isn't working for me for reset Auto Increment

DELETE FROM "sqlite_sequence" WHERE "name"='<table>';

To read more about VACUUM you can go here: https://blogs.gnome.org/jnelson/2015/01/06/sqlite-vacuum-and-auto_vacuum/

Typescript input onchange event.target.value

  function handle_change(
    evt: React.ChangeEvent<HTMLInputElement>
  ): string {
    evt.persist(); // This is needed so you can actually get the currentTarget
    const inputValue = evt.currentTarget.value;

    return inputValue
  }

And make sure you have "lib": ["dom"] in your tsconfig.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The PostgreSQL documentation on Character Types is a good reference for this. They are two different names for the same type.

INNER JOIN in UPDATE sql for DB2

You don't say what platform you're targeting. Referring to tables as files, though, leads me to believe that you're NOT running DB2 on Linux, UNIX or Windows (LUW).

However, if you are on DB2 LUW, see the MERGE statement:

For your example statement, this would be written as:

merge into file1 a
   using (select anotherfield, something from file2) b
   on substr(a.firstfield,10,20) = substr(b.anotherfield,1,10)
when matched and a.firstfield like 'BLAH%'
   then update set a.firstfield = 'BIT OF TEXT' || b.something;

Please note: For DB2, the third argument of the SUBSTR function is the number of bytes to return, not the ending position. Therefore, SUBSTR(a.firstfield,10,20) returns CHAR(20). However, SUBSTR(b.anotherfield,1,10) returns CHAR(10). I'm not sure if this was done on purpose, but it may affect your comparison.

Remove duplicated rows using dplyr

Most of the time, the best solution is using distinct() from dplyr, as has already been suggested.

However, here's another approach that uses the slice() function from dplyr.

# Generate fake data for the example
  library(dplyr)
  set.seed(123)
  df <- data.frame(
    x = sample(0:1, 10, replace = T),
    y = sample(0:1, 10, replace = T),
    z = 1:10
  )

# In each group of rows formed by combinations of x and y
# retain only the first row

    df %>%
      group_by(x, y) %>%
      slice(1)

Difference from using the distinct() function

The advantage of this solution is that it makes it explicit which rows are retained from the original dataframe, and it can pair nicely with the arrange() function.

Let's say you had customer sales data and you wanted to retain one record per customer, and you want that record to be the one from their latest purchase. Then you could write:

customer_purchase_data %>%
   arrange(desc(Purchase_Date)) %>%
   group_by(Customer_ID) %>%
   slice(1)

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

Difference between INNER JOIN and LEFT SEMI JOIN

Tried in Hive and got the below output

table1

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

4,yepie,newyork,USA

table2

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

5,chapie,Los angels,USA

Inner Join

SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

Left Join

SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

4 yepie newyork USA NULL NULL NULL NULL

Left Semi Join

SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india

2 stu salem india

3 mia bangalore india

note: Only records in left table are displayed whereas for Left Join both the table records displayed

changing textbox border colour using javascript

document.getElementById("fName").style.border="1px solid black";

SQL Server: Get data for only the past year

Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1

Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

matplotlib: how to draw a rectangle on image

From my understanding matplotlib is a plotting library.

If you want to change the image data (e.g. draw a rectangle on an image), you could use PIL's ImageDraw, OpenCV, or something similar.

Here is PIL's ImageDraw method to draw a rectangle.

Here is one of OpenCV's methods for drawing a rectangle.

Your question asked about Matplotlib, but probably should have just asked about drawing a rectangle on an image.

Here is another question which addresses what I think you wanted to know: Draw a rectangle and a text in it using PIL

C# create simple xml file

You could use XDocument:

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

If the file you want to create is very big and cannot fit into memory you might use XmlWriter.

Run batch file from Java code

import java.lang.Runtime;

Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");

This will work for you and is easy to use.

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

Android Horizontal RecyclerView scroll Direction

//in fragment page: 

 recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity(), HORIZONTAL,true));

//this worked for me but before that please import :

implementation 'com.android.support:recyclerview-v7:28.0.0'

How do I read a large csv file with pandas?

The function read_csv and read_table is almost the same. But you must assign the delimiter “,” when you use the function read_table in your program.

def get_from_action_data(fname, chunk_size=100000):
    reader = pd.read_csv(fname, header=0, iterator=True)
    chunks = []
    loop = True
    while loop:
        try:
            chunk = reader.get_chunk(chunk_size)[["user_id", "type"]]
            chunks.append(chunk)
        except StopIteration:
            loop = False
            print("Iteration is stopped")

    df_ac = pd.concat(chunks, ignore_index=True)

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Detect Close windows event by jQuery

Combine the mousemove and window.onbeforeunload event :- I used for set TimeOut for Audit Table.

 $(document).ready(function () {
 var checkCloseX = 0;
        $(document).mousemove(function (e) {
            if (e.pageY <= 5) {
                checkCloseX = 1;
            }
            else { checkCloseX = 0; }
        });

        window.onbeforeunload = function (event) {
            if (event) {
                if (checkCloseX == 1) {

                    //alert('1111');
                    $.ajax({
                        type: "GET",
                        url: "Account/SetAuditHeaderTimeOut",
                        dataType: "json",
                        success: function (result) {
                            if (result != null) {
                            }
                        }
                    });
                }
            }
        };
  });

Creating java date object from year,month,day

java.time

Using java.time framework built into Java 8

int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter 
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22

If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime

LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00

Error inflating class android.support.v7.widget.Toolbar?

It is unclearly why this error happened with me but I solved. I used same layout, in-line or using include, both of them cause NPE error. So I think it's not layout issue.

I had an abstract class call BaseActivity extends ActionBarActivity which have initActionBar() method. I override and call this method in OnCreate of child class. Something like that:

android.support.v7.app.ActionBar mActionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book_appointment);

    // Inject View using ButterKnife
    ButterKnife.inject(this);

    // Init toolbar & status bar
    initActionBar();
}

@Override
protected void initActionBar() {
    super.initActionBar();

    setSupportActionBar(mToolBar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mActionBar = getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setHomeButtonEnabled(true);
}

I HAD NPE ERROR WITH ABOVE CODE. I DON'T KNOW WHY I'M WRONG. I SOLVE BY BELOW CODE AND IT'S LOOK SAME.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book_appointment);
    ButterKnife.inject(this);

    setSupportActionBar(mToolBar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mActionBar = getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setHomeButtonEnabled(true);

    initActionBar();
}

@Override
protected void initActionBar() {
    super.initActionBar();
}

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

Delete item from array and shrink array

object[] newarray = new object[oldarray.Length-1];

for(int x=0; x < array.Length; x++)
{
  if(!(array[x] == value_of_array_to_delete))
  // if(!(x == array_index_to_delete))
   {
     newarray[x] = oldarray[x];
   }
}

There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.

How do you uninstall a python package that was installed using distutils?

On Mac OSX, manually delete these 2 directories under your pathToPython/site-packages/ will work:

  • {packageName}
  • {packageName}-{version}-info

for example, to remove pyasn1, which is a distutils installed project:

  • rm -rf lib/python2.7/site-packages/pyasn1
  • rm -rf lib/python2.7/site-packages/pyasn1-0.1.9-py2.7.egg-info

To find out where is your site-packages:

python -m site

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

Error Installing Homebrew - Brew Command Not Found

You can use this:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" 

to install homebrew.

POST request with a simple string in body with Alamofire

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
            (convertible, params) in
            var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
            mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
            return (mutableRequest, nil)
        }))

Note: parameters should not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])

What does "dereferencing" a pointer mean?

Reviewing the basic terminology

It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....

  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.
  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know" at the end of this answer.

When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.

Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.

A pointer scenario

Consider in C, given a pointer such as p below...

const char* p = "abc";

...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p. This way C encodes text in memory is known as ASCIIZ.

For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.

Dereferencing the pointer

To refer to the characters p points to, we dereference p using one of these notations (again, for C):

assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
                     // p and 1 times the size of the things to which p points:
                     // In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b');  // Another notation for p[1]

You can also move pointers through the pointed-to data, dereferencing them as you go:

++p;  // Increment p so it's now 0x1001
assert(*p == 'b');  // p == 0x1001 which is where the 'b' is...

If you have some data that can be written to, then you can do things like this:

int x = 2;
int* p_x = &x;  // Put the address of the x variable into the pointer p_x
*p_x = 4;       // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4

Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.

Dereferencing and accessing a structure data member

In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:

typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159;  // Dereference and access data member x.d_
(*p).d_ *= -1;    // Another equivalent notation for accessing x.d_

Multi-byte data types

To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.

So, looking at a slightly more complex example:

double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3);  // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4);  // Actually looks at bytes from address p + 1 * sizeof(double)
                       // (sizeof(double) is almost always eight bytes)
++p;                   // Advance p by sizeof(double)
assert(*p == 13.4);    // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;       // Change sizes[3] from 19.4 to 29.8
                       // Note earlier ++p and + 2 here => sizes[3]

Pointers to dynamically allocated memory

Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...

int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10;            // Dereference the pointer to the memory, then write a value in
fn(*p);             // Call a function, passing it the value at address p
(*p) += 3;          // Change the value, adding 3 to it
free(p);            // Release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete:

int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10];      // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10]();    // Memory for ten ints that are value initialised (to 0)
delete[] p;

See also C++ smart pointers below.

Losing and leaking addresses

Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...

const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
    if (!isprint(*q))
        *q = '_';

printf("%s\n", p); // Only q was modified
free(p);

...or carefully orchestrate reversal of any changes...

const size_t n = ...;
p += n;
...
p -= n;  // Restore earlier value...
free(p);

C++ smart pointers

In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...

{
    std::unique_ptr<T> p{new T(42, "meaning")};
    call_a_function(p);
    // The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete

...and shared_ptr for share ownership (using reference counting)...

{
    auto p = std::make_shared<T>(3.14, "pi");
    number_storage1.may_add(p); // Might copy p into its container
    number_storage2.may_add(p); // Might copy p into its container    } // p's destructor will only delete the T if neither may_add copied it

Null pointers

In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:

const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
    switch (c) {
      case f: p_filename = optarg; break;
    }
if (p_filename)  // Only NULL converts to false
    ...   // Only get here if -f flag specified

In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).

Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...

More about memory addresses, and why you probably don't need to know

More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.

The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.

For example, an int* properly initialised to point to an int variable might - after casting to a float* - access memory in "GPU" memory quite distinct from the memory where the int variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int* effectively a random, invalid pointer within these other memory regions).

3GL programming languages like C and C++ tend to hide this complexity, such that:

  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used

  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"

  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them

  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.

Intellij IDEA Java classes not auto compiling on save

I had the same issue. I was using the "Power save mode", which prevents from compiling incrementally and showing compilation errors.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Oracle's default date format is YYYY-MM-DD, WHY?

To answer to your question that is WHY default date don't display TIME part, the only answer I find is

Oracle teams are composed of LAZY developpers or responsibles :-)

Why ?

Because DATE, TIME and DATETIME datatypes exist in SQL and Oracle has not yet implemented it !!!

It is a shame for Oracle.

But the correct answer to your problem is not to define a FIX default format but a SIGNIFICANT default format that display only significant digits so that DATE, TIME or DATETIME values displayed (by default) contains always all important digits.

Example:

2015-10-14          will be displayed as 2015-10-14 (or default DATE format)
2018-10-25 12:20:00 will be displayed as 2018-10-25 12:20
1994-04-16 16       will be displayed as 1994-04-16 16

The principle is simple.

All digits being part of DATE will always be displayed as INTEGER part of float number. For TIME part, only significant part will be displayed as for DECIMAL part in float number. Naturally, for TIME type (only HH:MM:SS), the DATE part is never displayed.

Can I use CASE statement in a JOIN condition?

Instead, you simply JOIN to both tables, and in your SELECT clause, return data from the one that matches:

I suggest you to go through this link Conditional Joins in SQL Server and T-SQL Case Statement in a JOIN ON Clause

e.g.

    SELECT  *
FROM    sys.indexes i
        JOIN sys.partitions p
            ON i.index_id = p.index_id 
        JOIN sys.allocation_units a
            ON a.container_id =
            CASE
               WHEN a.type IN (1, 3)
                   THEN  p.hobt_id 
               WHEN a.type IN (2)
                   THEN p.partition_id
               END 

Edit: As per comments.

You can not specify the join condition as you are doing.. Check the query above that have no error. I have take out the common column up and the right column value will be evaluated on condition.

Algorithm to generate all possible permutations of a list?

If anyone wonders how to be done in permutation in javascript.

Idea/pseudocode

  1. pick one element at a time
  2. permute rest of the element and then add the picked element to the all of the permutation

for example. 'a'+ permute(bc). permute of bc would be bc & cb. Now add these two will give abc, acb. similarly, pick b + permute (ac) will provice bac, bca...and keep going.

now look at the code

function permutations(arr){

   var len = arr.length, 
       perms = [],
       rest,
       picked,
       restPerms,
       next;

    //for one or less item there is only one permutation 
    if (len <= 1)
        return [arr];

    for (var i=0; i<len; i++)
    {
        //copy original array to avoid changing it while picking elements
        rest = Object.create(arr);

        //splice removed element change array original array(copied array)
        //[1,2,3,4].splice(2,1) will return [3] and remaining array = [1,2,4]
        picked = rest.splice(i, 1);

        //get the permutation of the rest of the elements
        restPerms = permutations(rest);

       // Now concat like a+permute(bc) for each
       for (var j=0; j<restPerms.length; j++)
       {
           next = picked.concat(restPerms[j]);
           perms.push(next);
       }
    }

   return perms;
}

Take your time to understand this. I got this code from (pertumation in JavaScript)

FileNotFoundError: [Errno 2] No such file or directory

When you open a file with the name address.csv, you are telling the open() function that your file is in the current working directory. This is called a relative path.

To give you an idea of what that means, add this to your code:

import os

cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))

That will print the current working directory along with all the files in it.

Another way to tell the open() function where your file is located is by using an absolute path, e.g.:

f = open("/Users/foo/address.csv")

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

Count the number occurrences of a character in a string

Python 3

Ther are two ways to achieve this:

1) With built-in function count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2) Without using a function

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

EC2 instance has no public DNS

Go to VPC console, select your VPC, and click ACTIONS menu, select Edit DNS Hostnames - select Yes. That should fix it.

What is the best IDE for PHP?

There are a few IDEs out there you can use. I personally like UltraEdit. It does syntax highlighting, FTP/SFTP support, super fast, macros, etc. - only $30.

If you're doing anything heavy and would like some enterprise level IDE features (local/remote debugging, framework support, IntelliSense), try Zend IDE. I believe it's a few hundred dollars but be worth it.

There's also a plugin for Eclipse you try (PHPEclipse I think). I hope this helps.

Use Mockito to mock some methods but not others

Partial mocking of a class is also supported via Spy in mockito

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls real methods
spy.add("one");
spy.add("two");

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

Check the 1.10.19 and 2.7.22 docs for detailed explanation.

How do you explicitly set a new property on `window` in TypeScript?

Using

window["MyNamespace"] = window["MyNamespace"] || {};

should be alright as using string property, but if you really want to have a separated window and organised your code, you can extends window object:

interface MyNamespacedWindow extends Window {
    MyNamespace: object;
}

declare var window: MyNamespacedWindow;

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

if you want to upgrade only a single column of a table row then you can use as following:

$this->db->set('column_header', $value); //value that used to update column  
$this->db->where('column_id', $column_id_value); //which row want to upgrade  
$this->db->update('table_name');  //table name

Display more Text in fullcalendar

With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.

In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.

function htmlEscape(s) {
    return s.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#039;')
    .replace(/"/g, '&quot;')
    .replace(/\n/g, '<br />')
    .replace(/&lt;br\s?\/?&gt;/g, '<br />');
}

This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'

Responsive Images with CSS

um responsive is simple

  • first off create a class named cell give it the property of display:table-cell
  • then @ max-width:700px do {display:block; width:100%; clear:both}

and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width - for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.

PS : reset.css style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.

angular2: how to copy object into another object

Loadsh is the universal standard library for coping any object deepcopy. It's a recursive algorithm. It's check everything and does copy for the given object. Writing this kind of algorithm will take longer time. It's better to leverage the same.

How to install python-dateutil on Windows?

I followed several suggestions in this list without success. Finally got it installed on Windows using this method: I extracted the zip file and placed the folders under my python27 folder. In a DOS window, I navigated to the installed root folder from extracting the zip file (python-dateutil-2.6.0), then issued this command:

.\python setup.py install

Whammo-bammo it all worked.

How to read an external properties file in Maven

Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.

  <build>    
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/../project-parent/buildNumber.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
   </plugins>

How do I analyze a .hprof file?

I personally prefer VisualVM. One of the features I like in VisualVM is heap dump comparison. When you are doing a heap dump analysis there are various ways to go about figuring out what caused the crash. One of the ways I have found useful is doing a comparison of healthy vs unhealthy heap dumps.

Following are the steps you can follow for it :

  1. Getting a heap dump of OutOfMemoryError let's call it "oome.hprof". You can get this via JVM parameter HeapDumpOnOutOfMemoryError.
  2. Restart the application let it run for a big (minutes/hours) depending on your application. Get another heap dump while the application is still running. Let's call it "healthy.hprof".
  3. You can open both these dumps in VisualVM and do a heap dump comparison. You can do it on class or package level. This can often point you into the direction of the issue.

link : https://visualvm.github.io

html select only one checkbox in a group

My version: use data attributes and Vanilla JavaScript

<div class="test-checkbox">
    Group One: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Eat" />Eat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Sleep" />Sleep</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupOne" value="Play" />Play</label>
    <br />
    Group Two: <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Fat" />Fat</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Comfort" />Comfort</label>
    <label>
        <input type="checkbox" data-limit="only-one-in-a-group" name="groupTwo" value="Happy" />Happy</label>
</div>
<script>
    let cbxes = document.querySelectorAll('input[type="checkbox"][data-limit="only-one-in-a-group"]');
    [...cbxes].forEach((cbx) => {
        cbx.addEventListener('change', (e) => {
            if (e.target.checked)
                uncheckOthers(e.target);
        });
    });
    function uncheckOthers (clicked) {
        let name = clicked.getAttribute('name');
        // find others in same group, uncheck them
        [...cbxes].forEach((other) => {
            if (other != clicked && other.getAttribute('name') == name)
                other.checked = false;
        });
    }
</script>

How do I create a simple Qt console application in C++?

Had the same problem. found some videos on Youtube. So here is an even simpler suggestion. This is all the code you need:

#include <QDebug>

int main(int argc, char *argv[])  
{
   qDebug() <<"Hello World"<< endl;
   return 0;
}

The above code comes from Qt5 Tutorial: Building a simple Console application by

Dominique Thiebaut

http://www.youtube.com/watch?v=1_aF6o6t-J4

jQuery delete all table rows except first

wrapped in a function:

function remove_rows(tablename) { 
    $(tablename).find("tr:gt(0)").remove();        
}

then call it:

remove_rows('#table1');
remove_rows('#table2');

HTML5 Canvas Rotate Image

@Steve Farthing's answer is absolutely right.

But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
    if(angleInDegrees == 360){  // add this lines
        angleInDegrees = 0
    }
});

Then you will get the desired result. Thanks. Hope this will help someone :)

Create HTTP post request and receive response using C# console application

For this you can simply use the "HttpWebRequest" and "HttpWebResponse" classes in .net.

Below is a sample console app I wrote to demonstrate how easy this is.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "www.somewhere.com";       
            string fileName = @"C:\output.file";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 5000;

            try
            {
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        byte[] bytes = ReadFully(response.GetResponseStream());

                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (WebException)
            {
                Console.WriteLine("Error Occured");
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}

Enjoy!

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

How to get to Model or Viewbag Variables in a Script Tag

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

How to create User/Database in script for Docker Postgres

You can now put .sql files inside the init directory:

From the docs

If you would like to do additional initialization in an image derived from this one, add one or more *.sql or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files and source any *.sh scripts found in that directory to do further initialization before starting the service.

So copying your .sql file in will work.

Int division: Why is the result of 1/3 == 0?

I did this.

double g = 1.0/3.0;
System.out.printf("%gf", g);

Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.

How to establish ssh key pair when "Host key verification failed"

If you're sure the server is correct, sed -i 1d ~/.ssh/known_hosts will delete line 1 of your local ~/.ssh/known_hosts. The new correct key will be added to the file the next time you connect.

How can I get the actual video URL of a YouTube live stream?

Yes this is possible Since the question is update, this solution can only gives you the embed url not the HLS url, check @JAL answer. with the ressource search.list and the parameters:

* part: id
* channelId: UCURGpU4lj3dat246rysrWsw
* eventType: live
* type: video

Request :

GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCURGpU4lj3dat246rysrWsw&eventType=live&type=video&key={YOUR_API_KEY}

Result:

 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/enc3-yCp8APGcoiU_KH-mSKr4Yo\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "WVZpCdHq3Qg"
   }
  },

Then get the videoID value WVZpCdHq3Qg for example and add the value to this url:

https://www.youtube.com/embed/ + videoID
https://www.youtube.com/watch?v= + videoID

Select n random rows from SQL Server table

Try this:

SELECT TOP 10 Field1, ..., FieldN
FROM Table1
ORDER BY NEWID()

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

Method List in Visual Studio Code

UPDATE: The extension features are now built-in and the extension itself is now deprecated

I have found this extention: Code Outline. This is how it looks like:


This is how it looks like


I believe that is what you have been looking for.

How do I get the last character of a string using an Excel function?

Just another way to do this:

=MID(A1, LEN(A1), 1)

How to decode a Base64 string?

Isn't encoding taking the text TO base64 and decoding taking base64 BACK to text? You seem be mixing them up here. When I decode using this online decoder I get:

BASE64: blahblah
UTF8: nVnV

not the other way around. I can't reproduce it completely in PS though. See sample below:

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("blahblah"))
nV?nV?

PS > [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nVnV"))
blZuVg==

EDIT I believe you're using the wrong encoder for your text. The encoded base64 string is encoded from UTF8(or ASCII) string.

PS > [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

PS > [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
????

PS > [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("YmxhaGJsYWg="))
blahblah

SQL Server Case Statement when IS NULL

  case isnull(B.[stat],0)
  when 0 then dateadd(dd,10,(c.[Eventdate]))
  end

you can add in else statement if you want to add 30 days to the same .

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

On my machine mysqld service stopped that's why it was giving me the same problem.

1:- Go to terminal and type

sudo service mysqld restart

This will restart the mysqld service and create a new sock file on the required location.

How to check if array element exists or not in javascript?

Use typeof arrayName[index] === 'undefined'

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

List all the files and folders in a Directory with PHP recursive function

This will print the full path of all files in the given directory, you can also pass other callback functions to recursiveDir.

function printFunc($path){
    echo $path."<br>";
}

function recursiveDir($path, $fileFunc, $dirFunc){
    $openDir = opendir($path);
    while (($file = readdir($openDir)) !== false) {
        $fullFilePath = realpath("$path/$file");
        if ($file[0] != ".") {
            if (is_file($fullFilePath)){
                if (is_callable($fileFunc)){
                    $fileFunc($fullFilePath);
                }
            } else {
                if (is_callable($dirFunc)){
                    $dirFunc($fullFilePath);
                }
                recursiveDir($fullFilePath, $fileFunc, $dirFunc);
            }
        }
    }
}

recursiveDir($dirToScan, 'printFunc', 'printFunc');

How to print strings with line breaks in java

Do this way:-

String newline = System.getProperty("line.separator");

private static final String mText = "SHOP MA" + newline +
        + "----------------------------" + newline +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + newline +
        + "No  Item  Qty  Price  Amount" + newline +
        + "1 Bread 1 50.00  50.00" + newline +
        + "____________________________" + newline;

Using Enum values as String literals

package com.common.test;

public  enum Days {


    monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
    thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");

    private int id;
    private String desc;


    Days(int id,String desc){
        this.id=id;
        this.desc=desc;
    }

    public static String getDay(int id){

        for (Days day : Days.values()) {
            if (day.getId() == id) {
                return day.getDesc();
            }
        }
        return null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }



};

SQL Server - Adding a string to a text column (concat equivalent)

UPDATE test SET a = CONCAT(a, "more text")

What are the best practices for SQLite on Android?

Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's answer is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.

The basic answer.

The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.

So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.

So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).

If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.

So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.

Here's a blog post with far more detail and an example app.

Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.


In the meantime, there is a follow up blog post:

Also checkout the fork by 2point0 of the previously mentioned locking example:

Javascript switch vs. if...else if...else

Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)

React Native Change Default iOS Simulator Device

change line code of /node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js

line 55

  if (
    simulator.availability !== '(available)' &&
    simulator.isAvailable !== true
  ) {
    continue;
  }

replace which:

   if (
                simulator.availability !== '(available)' &&
                simulator.isAvailable !== true
              ) {
                continue;
     }

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

remove url parameters with javascript or jquery

Hmm... Looking for better way... here it is

var onlyUrl = window.location.href.replace(window.location.search,'');

Activating Anaconda Environment in VsCode

Just launch the VS Code from the Anaconda Navigator. It works for me.

python object() takes no parameters error

You must press twice on tap and (_) key each time, it must look like:

__init__

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

Location Services not working in iOS 8

A little helper for all of you that have more than one Info.plist file...

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Add NSLocationWhenInUseUsageDescription string' {} 

It will add the needed tag to all of the Info.plist files in the current directory (and subfolders).

Another is:

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Set NSLocationWhenInUseUsageDescription $YOURDESCRIPTION' {} 

It will add your description to all files.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

or in perl (for completeness...):

perl -npe 'chomp; /null/ and print "$_ - Line number : $.\n" and $i++;$_="";END{print "Total null count : $i\n"}'

How can I get the full/absolute URL (with domain) in Django?

You can also use:

import socket
socket.gethostname()

This is working fine for me,

I'm not entirely sure how it works. I believe this is a bit more low level and will return your server hostname, which might be different than the hostname used by your user to get to your page.

Difference between java.lang.RuntimeException and java.lang.Exception

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.

If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.

ActiveRecord: size vs count

tl;dr

  • If you know you won't be needing the data use count.
  • If you know you will use or have used the data use length.
  • If you don't know what you are doing, use size...

count

Resolves to sending a Select count(*)... query to the DB. The way to go if you don't need the data, but just the count.

Example: count of new messages, total elements when only a page is going to be displayed, etc.

length

Loads the required data, i.e. the query as required, and then just counts it. The way to go if you are using the data.

Example: Summary of a fully loaded table, titles of displayed data, etc.

size

It checks if the data was loaded (i.e. already in rails) if so, then just count it, otherwise it calls count. (plus the pitfalls, already mentioned in other entries).

def size
  loaded? ? @records.length : count(:all)
end

What's the problem?

That you might be hitting the DB twice if you don't do it in the right order (e.g. if you render the number of elements in a table on top of the rendered table, there will be effectively 2 calls sent to the DB).

Warning comparison between pointer and integer

It should be

if (*message == '\0')

In C, simple quotes delimit a single character whereas double quotes are for strings.

How to delete large data of table in SQL without log?

  1. If you are Deleting All the rows in that table the simplest option is to Truncate table, something like

    TRUNCATE TABLE LargeTable
    GO
    

    Truncate table will simply empty the table, you cannot use WHERE clause to limit the rows being deleted and no triggers will be fired.

  2. On the other hand if you are deleting more than 80-90 Percent of the data, say if you have total of 11 Million rows and you want to delete 10 million another way would be to Insert these 1 million rows (records you want to keep) to another staging table. Truncate this Large table and Insert back these 1 Million rows.

  3. Or if permissions/views or other objects which has this large table as their underlying table doesnt get affected by dropping this table you can get these relatively small amount of the rows into another table drop this table and create another table with same schema and import these rows back into this ex-Large table.

  4. One last option I can think of is to change your database's Recovery Mode to SIMPLE and then delete rows in smaller batches using a while loop something like this..

    DECLARE @Deleted_Rows INT;
    SET @Deleted_Rows = 1;
    
    
    WHILE (@Deleted_Rows > 0)
      BEGIN
       -- Delete some small number of rows at a time
         DELETE TOP (10000)  LargeTable 
         WHERE readTime < dateadd(MONTH,-7,GETDATE())
    
      SET @Deleted_Rows = @@ROWCOUNT;
    END
    

and dont forget to change the Recovery mode back to full and I think you have to take a backup to make it fully affective (the change or recovery modes).

Open Excel file for reading with VBA without display

In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.

Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.

How to handle invalid SSL certificates with Apache HttpClient?

want to paste the answer here:

in Apache HttpClient 4.5.5

How to handle invalid SSL certificate with Apache client 4.5.5?

HttpClient httpClient = HttpClients
            .custom()
            .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();

how to make a specific text on TextView BOLD

While you can use Html.fromHtml() you can use a more native approach which is SpannableStringBuilder , this post may be helful.

SpannableStringBuilder str = new SpannableStringBuilder("Your awesome text");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), INT_START, INT_END, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv=new TextView(context);
tv.setText(str);

How to remove CocoaPods from a project?

enter image description here

pictorial representation detailed

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

From a Sybase Database, how I can get table description ( field names and types)?

If Sybase is SQL-92 compliant then this information is stored within the INFORMATION_SCHEMA tables.

So the following will give you a list of tables and views in any SQL-92 compliant database

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES

How to reset sequence in postgres and fill id column with new data?

FYI: If you need to specify a new startvalue between a range of IDs (256 - 10000000 for example):

SELECT setval('"Sequence_Name"', 
       (SELECT coalesce(MAX("ID"),255) 
           FROM "Table_Name" 
           WHERE "ID" < 10000000 and "ID" >= 256)+1
       ); 

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

What causes: "Notice: Uninitialized string offset" to appear?

Check out the contents of your array with

echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';

Difference between AutoPostBack=True and AutoPostBack=False?

There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server side.

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The "adjustment" in adjusted R-squared is related to the number of variables and the number of observations.

If you keep adding variables (predictors) to your model, R-squared will improve - that is, the predictors will appear to explain the variance - but some of that improvement may be due to chance alone. So adjusted R-squared tries to correct for this, by taking into account the ratio (N-1)/(N-k-1) where N = number of observations and k = number of variables (predictors).

It's probably not a concern in your case, since you have a single variate.

Some references:

  1. How high, R-squared?
  2. Goodness of fit statistics
  3. Multiple regression
  4. Re: What is "Adjusted R^2" in Multiple Regression

PHP: How can I determine if a variable has a value that is between two distinct constant values?

returns true if subject is between low and high (inclusive)

$between = function( $low, $high, $subject ) {
    if( $subject < $low ) return false;
    if( $subject > $high ) return false;
    return true;
};

if( $between( 0, 100, $givenNumber )) {
   // do whatever...
}

looks cleaner to me

How to import a module given its name as string?

Similar as @monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:

import os
import imp

def importFromURI(uri, absl):
    mod = None
    if not absl:
        uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
    path, fname = os.path.split(uri)
    mname, ext = os.path.splitext(fname)

    if os.path.exists(os.path.join(path,mname)+'.pyc'):
        try:
            return imp.load_compiled(mname, uri)
        except:
            pass
    if os.path.exists(os.path.join(path,mname)+'.py'):
        try:
            return imp.load_source(mname, uri)
        except:
            pass

    return mod

how to get all child list from Firebase android

You Need to write a custom Deserializer and then loop it and get the values of the hasmap.

Custom Deserializer:-

public class UserDetailsDeserializer implements JsonDeserializer<AllUserDetailsKeyModel> {
  /*
    bebebejunskjd:{
      "email": "[email protected]",
          "mobileNum": "12345678",
          "password": "1234567",
          "username": "akhil"}*/
  @Override public AllUserDetailsKeyModel deserialize(JsonElement json, Type typeOfT,
      JsonDeserializationContext context) throws JsonParseException {

    final JsonObject jsonObject = json.getAsJsonObject();

    Gson gson = new Gson();

    Type AllUserDetailsResponseModel =
        new TypeToken<HashMap<String, AllUserDetailsResponseModel>>(){}.getType();

    HashMap<String, AllUserDetailsResponseModel> user =
        gson.fromJson(jsonObject, AllUserDetailsResponseModel);
    AllUserDetailsKeyModel result = new AllUserDetailsKeyModel();
    result.setResult(user);
    return result;
  }


}

The code in comments is my object model and u should replaceAllUserDetailsKeyModel with your model class and add this to the rest client like below:-

private Converter.Factory createGsonConverter() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AllUserDetailsKeyModel.class, new UserDetailsDeserializer());
    Gson gson = gsonBuilder.create();
    return GsonConverterFactory.create(gson);
  }

This the custom Convertor for Retrofit.

In your onResponse you just loop with hasmaps and get value by key and my model class looks like below:-

public class AllUserDetailsKeyModel {

  private Map<String, AllUserDetailsResponseModel> result;

  public Map<String, AllUserDetailsResponseModel> getResult() {
    return result;
  }

  public void setResult(Map<String, AllUserDetailsResponseModel> result) {
    this.result = result;
  }

}

probably you need to give a Type T where T is your data Type and my model consists only of a hashmap and getters and setters for that.

And finally set Custom Convertor to retrofit like below:- .addConverterFactory(createGsonConverter())

Let me know if you need more clarifications.

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

What is causing the error `string.split is not a function`?

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

Eclipse does not highlight matching variables

Eclipse Toolbar > Windows > Preferences > General (Right side) > Editors (Right side) > Text Editors (Right side) > Annotations (Right side)

For Occurrences and Write Occurrences, make sure you DO have the 'Text as highlighted' option checked for all of them. See screenshot below:

enter image description here

enter image description here

enter image description here

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

How to install Cmake C compiler and CXX compiler

Even though I had gcc already installed, I had to run

sudo apt-get install build-essential

to get rid of that error

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Address validation using Google Maps API

Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.

This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.

This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API's.

As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.

Print a string as hex bytes?

Just for convenience, very simple.

def hexlify_byteString(byteString, delim="%"):
    ''' very simple way to hexlify a bytestring using delimiters '''
    retval = ""
    for intval in byteString:
        retval += ( '0123456789ABCDEF'[int(intval / 16)])
        retval += ( '0123456789ABCDEF'[int(intval % 16)])
        retval += delim
    return( retval[:-1])

hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'

How to convert from []byte to int in Go Programming

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}

Simulate delayed and dropped packets on Linux

One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:

./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2

In order to also introduce 50% of packet losses you have to run:

./ipfw pipe 1 config plr 0.5

Here more details.

Bootstrap 3 - 100% height of custom div inside column

The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?

2 ways:

1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.


DEMO: http://jsbin.com/EtUBujI/2

  .row.table-row > [class*="col-"].custom {
    background-color: lightgrey;
    text-align: center;
  }


@media (min-width: 768px) {
  
  img.img-fluid {width:100%;}

  .row.table-row {display:table;width:100%;margin:0 auto;}

  .row.table-row > [class*="col-"] {
    float:none;
    float:none;
    display:table-cell;
    vertical-align:top;
  }

  .row.table-row > .col-sm-11 {
    width: 91.66666666666666%;
  }
  .row.table-row > .col-sm-10 {
    width: 83.33333333333334%;
  }
  .row.table-row > .col-sm-9 {
    width: 75%;
  }
  .row.table-row > .col-sm-8 {
    width: 66.66666666666666%;
  }
  .row.table-row > .col-sm-7 {
    width: 58.333333333333336%;
  }
  .row.table-row > .col-sm-6 {
    width: 50%;
  }
  .col-sm-5 {
    width: 41.66666666666667%;
  }
  .col-sm-4 {
    width: 33.33333333333333%;
  }
  .row.table-row > .col-sm-3 {
    width: 25%;
  }
  .row.table-row > .col-sm-2 {
    width: 16.666666666666664%;
  }
  .row.table-row > .col-sm-1 {
    width: 8.333333333333332%;
  }


}

HTML

<div class="container">
    <div class="row table-row">
        <div class="col-sm-4 custom">
                100% height to make equal to ->
        </div>
        <div class="col-sm-8 image-col">
            <img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
        </div>
    </div>
</div>

2. Absolute bg div

DEMO: http://jsbin.com/aVEsUmig/2/edit

DEMO with content above and below: http://jsbin.com/aVEsUmig/3


.content {
        text-align: center;
        padding: 10px;
        background: #ccc;

}


@media (min-width:768px) { 
    .my-row {
        position: relative;
        height: 100%;
        border: 1px solid red;
        overflow: hidden;
    }
    .img-fluid {
        width: 100%
    }
    .row.my-row > [class*="col-"] {
        position: relative
    }
    .background {
        position: absolute;
        padding-top: 200%;
        left: 0;
        top: 0;
        width: 100%;
        background: #ccc;
    }
    .content {
        position: relative;
        z-index: 1;
        width: 100%;
        text-align: center;
        padding: 10px;
    }

}

HTML

<div class="container">
  
    <div class="row my-row">
      
        <div class="col-sm-6">
          
        <div class="content">
          This is inside a relative positioned z-index: 1 div
          </div>

         <div class="background"><!--empty bg-div--></div>
        </div>
      
        <div class="col-sm-6 image-col">
            <img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
        </div>
      
    </div>
   
</div>
  

$(window).height() vs $(document).height

jQuery $(window).height(); or $(window).width(); is only work perfectly when your html page doctype is html

<!DOCTYPE html>
<html lang="en">
...

How to trigger a build only if changes happen on particular set of files

I wrote this script to skip or execute tests if there are changes:

#!/bin/bash

set -e -o pipefail -u

paths=()
while [ "$1" != "--" ]; do
    paths+=( "$1" ); shift
done
shift

if git diff --quiet --exit-code "${BASE_BRANCH:-origin/master}"..HEAD ${paths[@]}; then
    echo "No changes in ${paths[@]}, skipping $@..." 1>&2
    exit 0
fi
echo "Changes found in ${paths[@]}, running $@..." 1>&2

exec "$@"

So you can do something like:

./scripts/git-run-if-changed.sh cmd vendor go.mod go.sum fixtures/ tools/ -- go test

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Read input numbers separated by spaces

I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.

#include <string>
#include <vector>
...
  string rawInput;
  vector<String> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }

So say the input looks like this:

Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7

You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.

Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.

while(!numbers.empty())
{
  string temp = numbers.pop_back();//removes the last element from the string
  num = atoi( temp.c_str() ); //re-used your 'num' variable from your code

  ...//do stuff
}

Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:

#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  num = atoi( rawInput.c_str() );
  ...//do your stuff
}

There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)

Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/

Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].

#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  bool isNum = true;
  for(int i = 0; i < rawInput.length() && isNum; ++i)
  {
    isNum = isdigit( rawInput[i]);
  }

  if(isNum)
  {
    num = atoi( rawInput.c_str() );
    ...//do your stuff
  }
  else
    cout << rawInput << " is not a number!" << endl;
}

The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.

How to generate .angular-cli.json file in Angular Cli?

I got this same error in my current project and was confused because I'm running the application / ng serve in one terminal, but got this when I tried to generate a component from another terminal. .angular-cli.json was already there and correct. So what gives?

I realized that I used the shortcut to open VisualStudio Code's internal terminal -- which opened the terminal to the *root of the project * (like most IDEs). The project contains other things in addition to the Angular application folder that has the .angular-cli.json file in question. I just had to cd to the right folder and run ng g c again and things were fine.

In my case it was just a silly error. I thought I'd come back to share in order to save people a real headache for something so simple. I see that Shiva actually has mentioned this above, but I thought I would give a bit more detail so it doesn't get overlooked.

ImportError: numpy.core.multiarray failed to import

The same error came for me. The problem is that you might have created a file called numpy.py. This file might coincide with numpy library. So, delete that numpy.py file and the problem gets solved.

Laravel Escaping All HTML in Blade Template

There is no problem with displaying HTML code in blade templates.

For test, you can add to routes.php only one route:

Route::get('/', function () {

        $data = new stdClass();
        $data->page_desc
            = '<strong>aaa</strong><em>bbb</em>
               <p>New paragaph</p><script>alert("Hello");</script>';

        return View::make('hello')->with('content', $data);
    }
);

and in hello.blade.php file:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>

{{ $content->page_desc }}

</body>
</html>

For the following code you will get output as on image

Output

So probably page_desc in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags

EDIT

I've also tested it with putting the same code into database:

Route::get('/', function () {

        $data = User::where('id','=',1)->first();

        return View::make('hello')->with('content', $data);
    }
);

Output is exactly the same in this case

Edit2

I also don't know if Pages is your model or it's a vendor model. For example it can have accessor inside:

public function getPageDescAttribute($value)
{
    return htmlspecialchars($value);
}

and then when you get page_desc attribute you will get modified page_desc with htmlspecialchars. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages class

get the value of "onclick" with jQuery?

mkoryak is correct.

But, if events are bound to that DOM node using more modern methods (not using onclick), then this method will fail.

If that is what you really want, check out this question, and its accepted answer.

Cheers!


I read your question again.
I'd like to tell you this: don't use onclick, onkeypress and the likes to bind events.

Using better methods like addEventListener() will enable you to:

  1. Add more than one event handler to a particular event
  2. remove some listeners selectively

Instead of actually using addEventListener(), you could use jQuery wrappers like $('selector').click().

Cheers again!

Android: How do I prevent the soft keyboard from pushing my view up?

In my case, the reason the buttons got pushed up was because the view above them was a ScrollView, and it got collapsed with the buttons pushed up above the keyboard no matter what value of android:windowSoftInputMode I was setting.

I was able to avoid my bottom row of buttons getting pushed up by the soft keyboard by setting android:isScrollContainer="false" on the ScrollView that sits above the buttons.

Override body style for content in an iframe

give the body of your iframe page an ID (or class if you wish)

<html>
<head></head>
<body id="myId">
</body>
</html>

then, also within the iframe's page, assign a background to that in CSS

#myId {
    background-color: white;
}

Android Studio rendering problems

In new update android studio 2.2 facing rendering issue then follow this steps.

I fixed it - in styles.xml file I changed

"Theme.AppCompat.Light.DarkActionBar"

to

"Base.Theme.AppCompat.Light.DarkActionBar"

It's some kind of hack I came across a long time ago to solve similar rendering problems in previous Android Studio versions.

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

What is difference between @RequestBody and @RequestParam?

Here is an example with @RequestBody, First look at the controller !!

  public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {

   ...
        productService.registerProductDto(newProductDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
   ....

}

And here is angular controller

function postNewProductDto() {
                var url = "/admin/products/newItem";
                $http.post(url, vm.newProductDto).then(function () {
                            //other things go here...
                            vm.newProductMessage = "Product successful registered";
                        }
                        ,
                        function (errResponse) {
                            //handling errors ....
                        }
                );
            }

And a short look at form

 <label>Name: </label>
 <input ng-model="vm.newProductDto.name" />

<label>Price </label> 
 <input ng-model="vm.newProductDto.price"/>

 <label>Quantity </label>
  <input ng-model="vm.newProductDto.quantity"/>

 <label>Image </label>
 <input ng-model="vm.newProductDto.photo"/>

 <Button ng-click="vm.postNewProductDto()" >Insert Item</Button>

 <label > {{vm.newProductMessage}} </label>

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

It seems that your server fails to establish a connection to Gmail SMTP server. Here are some hints to troubleshoot this: 1) check if SSL correctly configured on your PHP (module that handle it isn't installed by default on PHP. You have to check your configuration in phph.ini). 2) check if your firewall let outgoing calls to the required port (here 465 or 587). Use telnet to do so. If the port isn't opened, you'll then require some support from sysdmin to setup the config. I hope you'll sort this out quickly!

Difference between javacore, thread dump and heap dump in Websphere

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.

JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.

Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.

Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.

How can I get Apache gzip compression to work?

In my case i have used following code for enabling gzip compression in apache web server.

  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

Merging dictionaries in C#

The following works for me. If there are duplicates, it will use dictA's value.

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(this IDictionary<TKey, TValue> dictA, IDictionary<TKey, TValue> dictB)
    where TValue : class
{
    return dictA.Keys.Union(dictB.Keys).ToDictionary(k => k, k => dictA.ContainsKey(k) ? dictA[k] : dictB[k]);
}

Ruby array to string conversion

irb(main):027:0> puts ['12','34','35','231'].inspect.to_s[1..-2].gsub('"', "'")
'12', '34', '35', '231'
=> nil

Is it better to return null or empty collection?

Empty is much more consumer friendly.

There is a clear method of making up an empty enumerable:

Enumerable.Empty<Element>()

How to download PDF automatically using js?

/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function

Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/

How do I protect Python code?

Is your employer aware that he can "steal" back any ideas that other people get from your code? I mean, if they can read your work, so can you theirs. Maybe looking at how you can benefit from the situation would yield a better return of your investment than fearing how much you could lose.

[EDIT] Answer to Nick's comment:

Nothing gained and nothing lost. The customer has what he wants (and paid for it since he did the change himself). Since he doesn't release the change, it's as if it didn't happen for everyone else.

Now if the customer sells the software, they have to change the copyright notice (which is illegal, so you can sue and will win -> simple case).

If they don't change the copyright notice, the 2nd level customers will notice that the software comes from you original and wonder what is going on. Chances are that they will contact you and so you will learn about the reselling of your work.

Again we have two cases: The original customer sold only a few copies. That means they didn't make much money anyway, so why bother. Or they sold in volume. That means better chances for you to learn about what they do and do something about it.

But in the end, most companies try to comply to the law (once their reputation is ruined, it's much harder to do business). So they will not steal your work but work with you to improve it. So if you include the source (with a license that protects you from simple reselling), chances are that they will simply push back changes they made since that will make sure the change is in the next version and they don't have to maintain it. That's win-win: You get changes and they can make the change themselves if they really, desperately need it even if you're unwilling to include it in the official release.

How do I remove the horizontal scrollbar in a div?

With overflow-y: scroll, the vertical scrollbar will always be there even if it is not needed. If you want y-scrollbar to be visible only when it is needed, I found this works:

.mydivclass {overflow-x: hidden; overflow-y: auto;}

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

How to sort findAll Doctrine's method?

You can sort an existing ArrayCollection using an array iterator.

assuming $collection is your ArrayCollection returned by findAll()

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

This can easily be turned into a function you can put into your repository in order to create findAllOrderBy() method.

Pandas create empty DataFrame with only column names

Are you looking for something like this?

    COLUMN_NAMES=['A','B','C','D','E','F','G']
    df = pd.DataFrame(columns=COLUMN_NAMES)
    df.columns

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

How to SELECT the last 10 rows of an SQL table which has no ID field?

All the answers here are better, but just in case... There is a way of getting 10 last added records. (thou this is quite unreliable :) ) still you can do something like

SELECT * FROM table LIMIT 10 OFFSET N-10

N - should be the total amount of rows in the table (SELECT count(*) FROM table). You can put it in a single query using prepared queries but I'll not get into that.

Making a request to a RESTful API using python

Using requests and json makes it simple.

  1. Call the API
  2. Assuming the API returns a JSON, parse the JSON object into a Python dict using json.loads function
  3. Loop through the dict to extract information.

Requests module provides you useful function to loop for success and failure.

if(Response.ok): will help help you determine if your API call is successful (Response code - 200)

Response.raise_for_status() will help you fetch the http code that is returned from the API.

Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()

python: sys is not defined

I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.

try:

import sys
# .. other safe imports
try:
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

How to check Network port access and display useful message?

boiled this down to a one liner sets the variable "$port389Open" to True or false - its fast and easy to replicate for a list of ports

try{$socket = New-Object Net.Sockets.TcpClient($ipAddress,389);if($socket -eq $null){$Port389Open = $false}else{Port389Open = $true;$socket.close()}}catch{Port389Open = $false}

If you want ot go really crazy you can return the an entire array-

Function StdPorts($ip){
    $rst = "" |  select IP,Port547Open,Port135Open,Port3389Open,Port389Open,Port53Open
    $rst.IP = $Ip
    try{$socket = New-Object Net.Sockets.TcpClient($ip,389);if($socket -eq $null){$rst.Port389Open = $false}else{$rst.Port389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,53);if($socket -eq $null){$rst.Port53Open = $false}else{$rst.Port53Open = $true;$socket.close();$ipscore++}}catch{$rst.Port53Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,3389);if($socket -eq $null){$rst.Port3389Open = $false}else{$rst.Port3389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port3389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,547);if($socket -eq $null){$rst.Port547Open = $false}else{$rst.Port547Open = $true;$socket.close();$ipscore++}}catch{$rst.Port547Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,135);if($socket -eq $null){$rst.Port135Open = $false}else{$rst.Port135Open = $true;$socket.close();$SkipWMI = $False;$ipscore++}}catch{$rst.Port135Open = $false}
    Return $rst
}

Updating the value of data attribute using jQuery

I want to change the width and height of a div. data attributes did not change it. Instead I use:

var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);

be careful:

$("#imageupload_img").data("height", size[1]); //did not work

did not set it

$("#imageupload_img").attr("data-height", size[1]); // yes it worked!

this has set it.

Add st, nd, rd and th (ordinal) suffix to a number

Here is another option.

_x000D_
_x000D_
function getOrdinalSuffix(day) {_x000D_
        _x000D_
    if(/^[2-3]?1$/.test(day)){_x000D_
     return 'st';_x000D_
    } else if(/^[2-3]?2$/.test(day)){_x000D_
     return 'nd';_x000D_
    } else if(/^[2-3]?3$/.test(day)){_x000D_
     return 'rd';_x000D_
    } else {_x000D_
     return 'th';_x000D_
    }_x000D_
        _x000D_
}_x000D_
    _x000D_
console.log(getOrdinalSuffix('1'));_x000D_
console.log(getOrdinalSuffix('13'));_x000D_
console.log(getOrdinalSuffix('22'));_x000D_
console.log(getOrdinalSuffix('33'));
_x000D_
_x000D_
_x000D_

Notice the exception for the teens? Teens are so akward!

Edit: Forgot about 11th and 12th

$(document).on("click"... not working?

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

It's probably not working due to one of:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

For example:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

JSFiddle with jQuery 1.9.1

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.

If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.

If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.

Good PHP ORM Library?

PHP ORM Faces For PDO extension. See PHP Faces Framework.

$urun = new Product();
$urun->name='CPU'
$urun->prince='124';
$urun->save();

How to read single Excel cell value

It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.

How to send cookies in a post request with the Python Requests library?

Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:

import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)

How to trigger click event on href element

Just want to let you guys know, the accepted answer doesn't always work.

Here's an example it will fail.

if <href='/list'>

href = $('css_selector').attr('href')
"/list"
href = document.querySelector('css_selector').href
"http://localhost/list"

or you could append the href you got from jQuery to this

href = document.URL +$('css_selector').attr('href');

or jQuery way

href = $('css_selector').prop('href')

Finally, invoke it to change the browser current page's url

window.location.href = href

or pop it out using window.open(url)

Here's an example in JSFiddle.

How can I force clients to refresh JavaScript files?

As far as I know a common solution is to add a ?<version> to the script's src link.

For instance:

<script type="text/javascript" src="myfile.js?1500"></script>

I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?

You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.

It would look something like this:

<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>

Of course, there are always better solutions like this one.

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

how to set radio button checked in edit mode in MVC razor view

Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.

For example

public class MyViewModel
{
        public MyViewModel()
        {
            Gender = "Male";
        }
}

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
  </tr>_x000D_
 </table>
_x000D_
_x000D_
_x000D_

What is stability in sorting algorithms and why is it important?

Sorting stability means that records with the same key retain their relative order before and after the sort.

So stability matters if, and only if, the problem you're solving requires retention of that relative order.

If you don't need stability, you can use a fast, memory-sipping algorithm from a library, like heapsort or quicksort, and forget about it.

If you need stability, it's more complicated. Stable algorithms have higher big-O CPU and/or memory usage than unstable algorithms. So when you have a large data set, you have to pick between beating up the CPU or the memory. If you're constrained on both CPU and memory, you have a problem. A good compromise stable algorithm is a binary tree sort; the Wikipedia article has a pathetically easy C++ implementation based on the STL.

You can make an unstable algorithm into a stable one by adding the original record number as the last-place key for each record.

Windows Task Scheduler doesn't start batch file task

For me it was trigger issue. By default it should On a Schedule in trigger tab. I had selected At log on and then I was waiting to run task. As it's name says at log on, means you have to logout and log on.

Try putting it on a Schedule and fire it every minute.

enter image description here

What are ODEX files in Android?

The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.

Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.

An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.

If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.

To actually deodex, use small and baksmali:

https://github.com/JesusFreke/smali/wiki/DeodexInstructions

Read lines from a text file but skip the first two lines

You can use random access.

Open "C:\docs\TESTFILE.txt" For Random As #1 

    Position = 3    ' Define record number.
    Get #1, Position, ARecord    ' Read record.

Close #1

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to set DOM element as the first child?

Unless I have misunderstood:

$("e").prepend("<yourelem>Text</yourelem>");

Or

$("<yourelem>Text</yourelem>").prependTo("e");

Although it sounds like from your description that there is some condition attached, so

if (SomeCondition){
    $("e").prepend("<yourelem>Text</yourelem>");
}
else{
    $("e").append("<yourelem>Text</yourelem>");
}

JQuery - File attributes

The input.files attribute is an HTML5 feature. That's why some browsers din't return anything. Simply add a fallback to the plain old input.value (string) if files doesn't exist.

reference: http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-apis.html#dom-input-files

How to redirect DNS to different ports

Since I had troubles understanding this post here is a simple explanation for people like me. It is useful if:

  • You DO NOT need Load Balacing.
  • You DO NOT want to use nginx to do port forwarding.
  • You DO want to do PORT FORWARDING according to specific subdomains using SRV record.

Then here is what you need to do:

SRV records:

_minecraft._tcp.1.12          IN SRV    1 100 25567 1.12.<your-domain-name.com>.
_minecraft._tcp.1.13          IN SRV    1 100 25566 1.13.<your-domain-name.com>.

(I did not need a srv record for 1.14 since my 1.14 minecraft server was already on the 25565 port which is the default port of minecraft.)

And the A records:

1.12                          IN A      <your server IP>
1.13                          IN A      <your server IP>
1.14                          IN A      <your server IP>

Incrementing a variable inside a Bash loop

You are using USCOUNTER in a subshell, that's why the variable is not showing in the main shell.

Instead of cat FILE | while ..., do just a while ... done < $FILE. This way, you avoid the common problem of I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?:

while read country _; do
  if [ "US" = "$country" ]; then
        USCOUNTER=$(expr $USCOUNTER + 1)
        echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Note I also replaced the `` expression with a $().

I also replaced while read line; do country=$(echo "$line" | cut -d' ' -f1) with while read country _. This allows you to say while read var1 var2 ... varN where var1 contains the first word in the line, $var2 and so on, until $varN containing the remaining content.

Delete specified file from document directory

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
  let fileManager = FileManager.default
  let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
      return
  }  
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItem(atPath: filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }}

Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:

static func removeImage(itemName:String, fileExtension: String) {
  let fileManager = NSFileManager.defaultManager()
  let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
  let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
    return
  }
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItemAtPath(filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }
}

Pinging an IP address using PHP and echoing the result

this works fine for me..

$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);

echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it

if (strpos($output, 'out') !== false) {
    echo "Dead";
}
    elseif(strpos($output, 'expired') !== false)
{
    echo "Network Error";
}
    elseif(strpos($output, 'data') !== false)
{
    echo "Alive";
}
else
{
    echo "Unknown Error";
}

How to add icons to React Native app

iOS Icons

  • Set AppIcon in Images.xcassets.
  • Add 9 different size icons:
    • 29pt
    • 29pt*2
    • 29pt*3
    • 40pt*2
    • 40pt*3
    • 57pt
    • 57pt*2
    • 60pt*2
    • 60pt*3.

Images.xcassets will look like this:

Android Icons

  • Put ic_launcher.png in folders [ProjectDirectory]/android/app/src/main/res/mipmap-*/.
    • 72*72 ic_launcher.png in mipmap-hdpi.
    • 48*48 ic_launcher.png in mipmap-mdpi.
    • 96*96 ic_launcher.png in mipmap-xhdpi.
    • 144*144 ic_launcher.png in mipmap-xxhdpi.
    • 192*192 ic_launcher.png in mipmap-xxxhdpi.

Update 2019 Android

The latest versions of react native also supports round icon. For this particular case, you have two choices:

A. Add round icons: In each mipmap folder, add additionally to the ic_launcher.png file also a round version called ic_launcher_round.png with the same size.

B. Remove round icons: Inside yourProjectFolder/android/app/src/main/AndroidManifest.xml remove the line android:roundIcon="@mipmap/ic_launcher_round"and save it.

Otherwhise the build throws an error.

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

Is there a way to get version from package.json in nodejs code?

In case you want to get version of the target package.

import { version } from 'TARGET_PACKAGE/package.json';

Example:

import { version } from 'react/package.json';

From ND to 1D arrays

One of the simplest way is to use flatten(), like this example :

 import numpy as np

 batch_y =train_output.iloc[sample, :]
 batch_y = np.array(batch_y).flatten()

My array it was like this :

    0
0   6
1   6
2   5
3   4
4   3
.
.
.

After using flatten():

array([6, 6, 5, ..., 5, 3, 6])

It's also the solution of errors of this type :

Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)' 

Show loading gif after clicking form submit using jQuery

Button inputs don't have a submit event. Try attaching the event handler to the form instead:

<script type="text/javascript">
     $('#login_form').submit(function() {
       $('#gif').show(); 
       return true;
     });
 </script>

ng serve not detecting file changes automatically

I had the same issue and figured out, that some files in my Angular Project were only permitted to the user root and to the corresponding group root. You can check that with ls -hal. I fixed it by setting both to the user I used the system with.

You can do that with: chown -R username:groupname *

If you want to know what exactly this command does, checkout:

https://superuser.com/questions/462141/how-to-chown-chmod-all-files-in-current-directory

Netbeans 8.0.2 The module has not been deployed

the solution to this problem differs because each time you deploy the application will give you the same sentence or the problem is different, so you should see the tomcat server log for the exact problem.

Java URL encoding of query string parameters

  1. Use this: URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); or this:URLEncoder.encode(query, "UTF-8");
  2. You can use the follwing code.

    String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8");//not change 
    String encodedUrl2 = URLEncoder.encode(query, "UTF-8");//changed
    String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());//changed
    
    System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);
    

Multiple radio button groups in MVC 4 Razor

Ok here's how I fixed this

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
{
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
  {
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)
  }    
}

The result is:

<input name="127" type="radio" value="110">

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

Thanks to all of the people who helped me solve this ;)

anaconda - path environment variable in windows

You could also just re-install Anaconda, and tick the option add variable to Path.. This will prevent you from making mistakes when editing environment variables. If you make mistakes here, your operating system could start malfunctioning.

Creating SVG graphics using Javascript?

Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.

A tutorial about how to create SVG objects using Javascript can be found here:

var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r",  20);
shape.setAttributeNS(null, "fill", "green"); 

SQL INSERT INTO from multiple tables

Here is an short extension for 3 or more tables to the answer of D Stanley:

INSERT INTO other_table (name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table_1 p
INNER JOIN table_2 a ON a.id = p.id
INNER JOIN table_3 b ON b.id = p.id
...
INNER JOIN table_n x ON x.id = p.id

Checking whether the pip is installed?

Use command line and not python.
TLDR; On Windows, do:
python -m pip --version
OR
py -m pip --version

Details:

On Windows, ~> (open windows terminal)
Start (or Windows Key) > type "cmd" Press Enter
You should see a screen that looks like this enter image description here
To check to see if pip is installed.

python -m pip --version

if pip is installed, go ahead and use it. for example:

Z:\>python -m pip install selenium

if not installed, install pip, and you may need to
add its path to the environment variables.
(basic - windows)
add path to environment variables (basic+advanced)

if python is NOT installed you will get a result similar to the one below

enter image description here

Install python. add its path to environment variables.

UPDATE: for newer versions of python replace "python" with py - see @gimmegimme's comment and link https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.