Programs & Examples On #Relational model

What is the difference between an interface and abstract class?

The only difference is that one can participate in multiple inheritance and other cannot.

The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8?

Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do.

Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables.

See Why does Java allow static final variables in interfaces when they are only intended to be contracts?.

Evaluate empty or null JSTL c tags

How can I validate if a String is null or empty using the c tags of JSTL?

You can use the empty keyword in a <c:if> for this:

<c:if test="${empty var1}">
    var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
    var1 is NOT empty or null.
</c:if>

Or the <c:choose>:

<c:choose>
    <c:when test="${empty var1}">
        var1 is empty or null.
    </c:when>
    <c:otherwise>
        var1 is NOT empty or null.
    </c:otherwise>
</c:choose>

Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator ${condition? valueIfTrue : valueIfFalse}:

<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />

To learn more about those ${} things (the Expression Language, which is a separate subject from JSTL), check here.

See also:

What is the C# Using block and why should I use it?

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

Using an HTML button to call a JavaScript function

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

How do I use the nohup command without getting nohup.out?

You can run the below command.

nohup <your command> & >  <outputfile> 2>&1 &

e.g. I have a nohup command inside script

./Runjob.sh > sparkConcuurent.out 2>&1

Get div's offsetTop positions in React

A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.

...
constructor(props){
   ...
   //create a ref
   this.someRefName = React.createRef();

}

onScroll(){
let offsetTop = this.someRefName.current.offsetTop;

}

render(){
...
<Component ref={this.someRefName} />

}

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

OnChange event using React JS for drop down

The change event is triggered on the <select> element, not the <option> element. However, that's not the only problem. The way you defined the change function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.

You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.

var MySelect = React.createClass({
     getInitialState: function() {
         return {
             value: 'select'
         }
     },
     change: function(event){
         this.setState({value: event.target.value});
     },
     render: function(){
        return(
           <div>
               <select id="lang" onChange={this.change} value={this.state.value}>
                  <option value="select">Select</option>
                  <option value="Java">Java</option>
                  <option value="C++">C++</option>
               </select>
               <p></p>
               <p>{this.state.value}</p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

Also note that <p> elements don't have a value attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key and ref). If you want the selected value to be the content of the <p> element then simply put inside of it, like you would do with any static content.

Learn more about event handling, state and form controls:

Android - Pulling SQlite database android device

If you are trying to do it on android 6 request the permission and use the code of the answer of this question

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC); 
    return; 
} 

Once it is granted

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == STORAGE_PERMISSION_RC) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //permission granted  start reading or writing database
        } else { 
            Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
        } 
    } 
} 

Converting from Integer, to BigInteger

You can do in this way:

    Integer i = 1;
    new BigInteger("" + i);

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

Using the "start" command with parameters passed to the started program

You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.

    start  /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

or:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

will start IE with default web page.

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com

starts with Bing, but does not reset your home page.

/D stands for "directory" and using quotes is OK!

WRONG EXAMPLE:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE"

gives:

ERROR "The current directory is invalid."

/D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run

Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.

-Mrbios

How to apply filters to *ngFor?

This is what I implemented without using pipe.

component.html

<div *ngFor="let item of filter(itemsList)">

component.ts

@Component({
....
})
export class YourComponent {
  filter(itemList: yourItemType[]): yourItemType[] {
    let result: yourItemType[] = [];
    //your filter logic here
    ...
    ...
    return result;
  }
}

How do you use the "WITH" clause in MySQL?

'Common Table Expression' feature is not available in MySQL, so you have to go to make a view or temporary table to solve, here I have used a temporary table.

The stored procedure mentioned here will solve your need. If I want to get all my team members and their associated members, this stored procedure will help:

----------------------------------
user_id   |   team_id
----------------------------------
admin     |   NULL
ramu      |   admin
suresh    |   admin
kumar     |   ramu
mahesh    |   ramu
randiv    |   suresh
-----------------------------------

Code:

DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end

This can be called using:

mysql>call user_hier ('admin')//

AngularJS - value attribute for select

you can use

state.name for state in states track by state.code

Where states in the JSON array, state is the variable name for each object in the array.

Hope this helps

Handling Dialogs in WPF with MVVM

I know it's an old question, but when I did this search, I find a lot of related question, but I did not find a really clear response. So I make my own implementation of a dialogbox/messagebox/popin, and I share it!
I think it is "MVVM proof", and I try to make it simple and proper, but I am new to WPF, so feel free to comment, or even make pull request.

https://github.com/Plasma-Paris/Plasma.WpfUtils

You can use it like this:

public RelayCommand YesNoMessageBoxCommand { get; private set; }
async void YesNoMessageBox()
{
    var result = await _Service.ShowMessage("This is the content of the message box", "This is the title", System.Windows.MessageBoxButton.YesNo);
    if (result == System.Windows.MessageBoxResult.Yes)
        // [...]
}

Or like this if you want more sophisticated popin :

var result = await _Service.ShowCustomMessageBox(new MyMessageBoxViewModel { /* What you want */ });

And it is showing things like this :

2

Javascript Drag and drop for touch devices

Thanks for the above codes! - I tried several options and this was the ticket. I had problems in that preventDefault was preventing scrolling on the ipad - I am now testing for draggable items and it works great so far.

if (event.target.id == 'draggable_item' ) {
    event.preventDefault();
}

Using ls to list directories and their total sizes

It is important to note here that du gives you disk usage. Different machines can use different block sizes, so on one machine a block could be 4096 bytes and another machine could contain block sizes of 2048. If I put 10 1 byte files in a machine using 4096 bytes blocks and 10 1 byte file in a machine using 2048 bytes blocks, du -h would report ~40k and ~20k respectively.

If you want to know the size of all the files in a directory, for each directory you can do something like:

for x in ./*;
do
    if [[ -f "$x" ]]; then
        ls -al "$x"
    fi
done | awk '{print $6}' | awk '{s+=$1}END{print s}'

This would give you the total size of all the files in a directory.

Delete with Join in MySQL

You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!

DELETE t FROM posts t
INNER JOIN projects p ON t.project_id = p.project_id
AND t.client_id = p.client_id

Characters allowed in a URL

The full list of the 66 unreserved characters is in RFC3986, here: http://tools.ietf.org/html/rfc3986#section-2.3

This is any character in the following regex set:

[A-Za-z0-9_.\-~]

Flexbox and Internet Explorer 11 (display:flex in <html>?)

You just need flex:1; It will fix issue for the IE11. I second Odisseas. Additionally assign 100% height to html,body elements.

CSS changes:

html, body{
    height:100%;
}
body {
    border: red 1px solid;
    min-height: 100vh;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-direction: column;
    -webkit-flex-direction: column;
    flex-direction: column;
}
header {
    background: #23bcfc;
}
main {
    background: #87ccfc;
    -ms-flex: 1;
    -webkit-flex: 1;
    flex: 1;
}
footer {
    background: #dd55dd;
}

working url: http://jsfiddle.net/3tpuryso/13/

How to add a margin to a table row <tr>

Here's a neat way I did it:

table tr {
    border-bottom: 4px solid;
}

That will add 4px of vertical spacing between each row. And if you wanted to not get that border on the last child:

table tr:last-child {
    border-bottom: 0;
}

Reminder that CSS3 pseudo-selectors will only work in IE 8 and below with selectivizr.

How to run 'sudo' command in windows

I am glad to help you.

To make a sudo command follow the steps :-

  1. Make a folder env in C:\ Drive.
  2. Make a folder inside the env folder named as bin.
  3. Now add C:\env\bin to your PATH.
  4. Create a file sudo.bat in C:\env\bin.
  5. Edit it with notepad and write this code :-
    https://gist.github.com/coder-examples/5ca6c141d6d356ddba4e356d63fb2c13

Hope this will help you

Java : How to determine the correct charset encoding of a stream

An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.

Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

How to Lazy Load div background images

I know it's not related to the image load but here what I did in one of the job interview test.

HTML

<div id="news-feed">Scroll to see News (Newest First)</div>

CSS

article {
   margin-top: 500px;
   opacity: 0;
   border: 2px solid #864488;
   padding: 5px 10px 10px 5px;
   background-image: -webkit-gradient(
   linear,
   left top,
   left bottom,
   color-stop(0, #DCD3E8),
   color-stop(1, #BCA3CC)
   );
   background-image: -o-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -moz-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -webkit-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -ms-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: linear-gradient(to bottom, #DCD3E8 0%, #BCA3CC 100%);
   color: gray;
   font-family: arial;    
}

article h4 {
   font-family: "Times New Roman";
   margin: 5px 1px;
}

.main-news {
   border: 5px double gray;
   padding: 15px;
}

JavaScript

var newsData,
    SortData = '',
    i = 1;

$.getJSON("http://www.stellarbiotechnologies.com/media/press-releases/json", function(data) {

   newsData = data.news;

   function SortByDate(x,y) {
     return ((x.published == y.published) ? 0 : ((x.published < y.published) ? 1 : -1 ));
   }

   var sortedNewsData = newsData.sort(SortByDate);

   $.each( sortedNewsData, function( key, val ) {
     SortData += '<article id="article' + i + '"><h4>Published on: ' + val.published + '</h4><div  class="main-news">' + val.title + '</div></article>';
     i++;    
   });

   $('#news-feed').append(SortData);
});

$(window).scroll(function() {

   var $window = $(window),
       wH = $window.height(),
       wS = $window.scrollTop() + 1

   for (var j=0; j<$('article').length;j++) {
      var eT = $('#article' + j ).offset().top,
          eH = $('#article' + j ).outerHeight();

          if (wS > ((eT + eH) - (wH))) {
             $('#article' + j ).animate({'opacity': '1'}, 500);
          }
    }

});

I am sorting the data by Date and then doing lazy load on window scroll function.

I hope it helps :)

Demo

Python webbrowser.open() to open Chrome browser

Worked for me in windows

Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.

import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")

>>> link to: [a page from my blog where I explain this]<<<

How can I override Bootstrap CSS styles?

If you are planning to make any rather big changes, it might be a good idea to make them directly in bootstrap itself and rebuild it. Then, you could reduce the amount of data loaded.

Please refer to Bootstrap on GitHub for the build guide.

Java SSLHandshakeException "no cipher suites in common"

This problem can be caused by undue manipulation of the enabled cipher suites at the client or the server, but I suspect the most common cause is the server not having a private key and certificate at all.

NB:

ssl.setEnabledCipherSuites(sc.getServerSocketFactory().getSupportedCipherSuites());

Get rid of this line. Your server is insecure enough already with that insecure TrustManager. Then run your server with -Djavax.net.debug=SSL,handshake, try one connect, and post the resulting output here.

How to install PyQt4 on Windows using pip?

You can't use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.

How do I convert dmesg timestamp to custom date format?

Understanding dmesg timestamp is pretty simple: it is time in seconds since the kernel started. So, having time of startup (uptime), you can add up the seconds and show them in whatever format you like.

Or better, you could use the -T command line option of dmesg and parse the human readable format.

From the man page:

-T, --ctime
    Print human readable timestamps. The timestamp could be inaccurate!

    The time source used for the logs is not updated after system SUSPEND/RESUME.

Directory-tree listing in Python

Here's a helper function I use quite often:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

How to wait for a process to terminate to execute another process in batch file

Try something like this...

@ECHO OFF

PSKILL NOTEPAD

START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"

:LOOP
PSLIST wordpad >nul 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO Wordpad is still running
  TIMEOUT /T 5
  GOTO LOOP
)

:CONTINUE
NOTEPAD

I used PSLIST and PSEXEC, but you could also use TASKKILL and TASKLIST. The >nul 2>&1 is just there to hide all the output from PSLIST. The SLEEP 5 line is not required, but is just there to restrict how often you check if WordPad is still running.

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.

    private void textBox_Enter(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
    }

    private void textBox_Leave(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = null; // remove "return" button behavior
    }

Is there any option to limit mongodb memory usage?

There is no reason to limit MongoDB cache as by default the mongod process will take 1/2 of the memory on the machine and no more. The default storage engine is WiredTiger. "With WiredTiger, MongoDB utilizes both the WiredTiger internal cache and the filesystem cache."

You are probably looking at top and assuming that Mongo is using all the memory on your machine. That is virtual memory. Use free -m:

              total        used        free      shared  buff/cache   available
Mem:           7982        1487        5601           8         893        6204
Swap:             0           0           0

Only when the available metric goes to zero is your computer swapping memory out to disk. In that case your database is too large for your machine. Add another mongodb instance to your cluster.

Use these two commands in the mongod console to get information about how much virtual and physical memory Mongodb is using:

var mem = db.serverStatus().tcmalloc;

mem.tcmalloc.formattedString

------------------------------------------------
MALLOC:      360509952 (  343.8 MiB) Bytes in use by application
MALLOC: +    477704192 (  455.6 MiB) Bytes in page heap freelist
MALLOC: +     33152680 (   31.6 MiB) Bytes in central cache freelist
MALLOC: +      2684032 (    2.6 MiB) Bytes in transfer cache freelist
MALLOC: +      3508952 (    3.3 MiB) Bytes in thread cache freelists
MALLOC: +      6349056 (    6.1 MiB) Bytes in malloc metadata
MALLOC:   ------------
MALLOC: =    883908864 (  843.0 MiB) Actual memory used (physical + swap)
MALLOC: +     33611776 (   32.1 MiB) Bytes released to OS (aka unmapped)
MALLOC:   ------------
MALLOC: =    917520640 (  875.0 MiB) Virtual address space used
MALLOC:
MALLOC:          26695              Spans in use
MALLOC:             22              Thread heaps in use
MALLOC:           4096              Tcmalloc page size

window.open with headers

You can't directly add custom headers with window.open() in popup window but to work that we have two possible solutions


  1. Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in<i>window.open()</i> here is abc.html
        $.ajax({
        url: "ORIGIONAL_URL",
        type: 'GET',
        dataType: 'json',
        headers: {
            Authorization : 'Bearer ' + data.id_token,
            AuthorizationCheck : 'AccessCode ' +data.checkSum , 
            ContentType :'application/json'
        },

        success: function (result) {
              console.log(result);
        },
        error: function (error) {

        } });

call html

window.open('*\abc.html')

here CORS policy can block the request if CORS is not enabled in requested URL.


  1. You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.

Suppose in Java Servlet(/requestURL) we'll make this request

`

        String[] responseHeader= new String[2];
        responseHeader[0] = "Bearer " + id_token;
        responseHeader[1] = "AccessCode " + checkSum;

        String url = "ORIGIONAL_URL";

        URL obj = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Authorization", responseHeader[0]);
        urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new 
                         InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response1 = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response1.append(inputLine);
            }
            in.close();
            response.sendRedirect(response1.toString());
            // print result
            System.out.println(response1.toString());
        } else {
            System.out.println("GET request not worked");
        }

`

call servlet in window.open('/requestURL')

Can someone explain Microsoft Unity?

Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.

Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.

Without IoC:

public class MyClass
{
   IMyService _myService; 

   public MyClass()
   {
      _myService = new SomeConcreteService();    
   }
}

With IoC container:

public class MyClass
{
   IMyService _myService; 

   public MyClass(IMyService myService)
   {
      _myService = myService;    
   }
}

Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)

With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.

Using StructureMap, configuring the container looks like this:

StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();

So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.

That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).

Final step: when you create your MyClass, you would do this:

var myClass = ObjectFactory.GetInstance<MyClass>();

Hope that helps. Feel free to e-mail me.

Best Practices for Custom Helpers in Laravel 5

Another Way that I used was: 1) created a file in app\FolderName\fileName.php and had this code inside it i.e

<?php
namespace App\library
{
 class hrapplication{
  public static function libData(){
   return "Data";
  }
 }
}
?>

2) After that in our blade

 $FmyFunctions = new \App\FolderName\classsName;
  echo $is_ok = ($FmyFunctions->libData());

that's it. and it works

WebDriver: check if an element exists?

This works for me every time:

    if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
        //THEN CLICK ON THE SUBMIT BUTTON
    }else{
        //DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
    }

COPYing a file in a Dockerfile, no such file or directory?

Some great answers here already. What worked for me, was to move the comments to the next line.

BAD:

WORKDIR /tmp/app/src # set the working directory (WORKDIR), so we can reference program directly instead of providing the full path.
COPY src/ /tmp/app/src/ # copy the project source code

GOOD:

WORKDIR /tmp/app/src
  # set the working directory (WORKDIR), so we can reference program directly instead of providing the full path.
COPY src/ /tmp/app/src/
  # copy the project source code

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

Onclick event to remove default value in a text input field

This is the right, cross-browser way to do it :

<input type="text" value="Enter Your Name" onfocus="if(this.value  == 'Enter Your Name') { this.value = ''; } " onblur="if(this.value == '') { this.value = 'Enter Your Name'; } " />

How to remove all elements in String array in java?

Reassign again. Like example = new String[(size)]

How to programmatically close a JFrame

You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program. When this is done you may handle the resulting event sequence exactly as you would if the user has clicked on the [x] button for an OS suppled decorated JFrame.

public void closeWindow()
{
    if(awtWindow_ != null) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
            }
        });
    }
}

Force index use in Oracle

You can use:

WITH index = ...

more info

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

Android basics: running code in the UI thread

The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.

TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
    private String txt;
    @Override
    public void run() {
        searchResultTextView.setText(txt);
    }
    public void setText(String txt){
        this.txt = txt;
    }

}

It can be used from anywhere like this:

textViewUpdater.setText("Hello");
        textViewUpdaterHandler.post(textViewUpdater);

How to cherry pick a range of commits and merge into another branch?

Are you sure you don't want to actually merge the branches? If the working branch has some recent commits you don't want, you can just create a new branch with a HEAD at the point you want.

Now, if you really do want to cherry-pick a range of commits, for whatever reason, an elegant way to do this is to just pull of a patchset and apply it to your new integration branch:

git format-patch A..B
git checkout integration
git am *.patch

This is essentially what git-rebase is doing anyway, but without the need to play games. You can add --3way to git-am if you need to merge. Make sure there are no other *.patch files already in the directory where you do this, if you follow the instructions verbatim...

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

How to disable Google Chrome auto update?

On a Mac, you can change the update frequency to a very large value. See:

For myself, I ran the following command in Terminal:

defaults write com.google.Keystone.Agent checkInterval 18000000

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

When should use Readonly and Get only properties

Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count), but generally it's a useful way to decide.

How to set IE11 Document mode to edge as default?

The rendering mode in Internet Explorer 11 can appear stuck if the site is added to your local Compatibility View list. When this happens, the rendering mode inside the developer tools and out will default to the specified compatibility settings.

While this may not be the only way a site can get on this list, Microsoft does document the steps for how to manually add a site to this list.

From Fix site display problems with Compatibility View:

To add a site to the Compatibility View list

  1. Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.

  2. Tap or click the Tools button, and then tap or click Compatibility View settings.

  3. Under Add this website, enter the URL of the site you want to add to the list, and then tap or click Add.

Site Compatibility View Removal Instructions:

To remove a site from this list, follow these instructions.

  1. Go to Tools > Compatibility View settings.
  2. In the resulting dialog, click on the site you want to remove from the list.
  3. Click the Remove button.

Screenshots:

Tools - Compatibility View settings

Compatibility View settings dialog

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

How to convert a String to JsonObject using gson library

JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

How do I select the parent form based on which submit button is clicked?

I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

Swift Bridging Header import issue

I actually created an empty OSX Source Objective C file under the project (where all my swift files are).

I added the imports and then deleted the .m file.

How to configure Git post commit hook

As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:

With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>

This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)

This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.

As mentioned here, make sure to use the right address for your Jenkins server:

since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the /jenkins, like this:

http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git

To reinforce that last point, ptha adds in the comments:

It may be obvious, but I had issues with:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>. 

The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our case ssh://, and it didn't work.


You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"

#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \

http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx

Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (1qaz2wsx in this example).

However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.


I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.

Basically, your build script can:

  • put a 'build' notes (see git notes) on the first call
  • on the subsequent calls, grab the list of commits between HEAD of your branch candidate for build and the commit referenced by the git notes 'build' (git show refs/notes/build): git diff --name-only SHA_build HEAD.
  • your script can parse that list and decide if it needs to go on with the build.
  • in any case, create/move your git notes 'build' to HEAD.

May 2016: cwhsu points out in the comments the following possible url:

you could just use curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN if you set trigger config in your item

http://i.imgur.com/IolrOOj.png


June 2016, polaretto points out in the comments:

I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo name

repository=${PWD%/hooks}; 
repository=${repository##*/} 

and then use it like:

curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository

SQL "select where not in subquery" returns no results

I had an example where I was looking up and because one table held the value as a double, the other as a string, they would not match (or not match without a cast). But only NOT IN. As SELECT ... IN ... worked. Weird, but thought I would share in case anyone else encounters this simple fix.

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Maven: The packaging for this project did not assign a file to the build artifact

I don't know if this is the answer or not but it might lead you in the right direction...

The command install:install is actually a goal on the maven-install-plugin. This is different than the install maven lifecycle phase.

Maven lifecycle phases are steps in a build which certain plugins can bind themselves to. Many different goals from different plugins may execute when you invoke a single lifecycle phase.

What this boils down to is the command...

mvn clean install

is different from...

mvn clean install:install

The former will run all goals in every cycle leading up to and including the install (like compile, package, test, etc.). The latter will not even compile or package your code, it will just run that one goal. This kinda makes sense, looking at the exception; it talks about:

StarTeamCollisionUtil: The packaging for this project did not assign a file to the build artifact

Try the former and your error might just go away!

Turning off eslint rule for a specific file

Accepted answer didn't work for me (maybe a different version of eslint...? I'm using eslint v3.19.0), but did find a solution with the following...

Place the following on the top of your file

/* eslint-disable no-use-before-define */

This will disable the rule for the entire file

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

The main differenece is that bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.

Note that navigational access is not always good, especially for "one-to-very-many" and "many-to-very-many" relationships. Imagine a Group that contains thousands of Users:

  • How would you access them? With so many Users, you usually need to apply some filtering and/or pagination, so that you need to execute a query anyway (unless you use collection filtering, which looks like a hack for me). Some developers may tend to apply filtering in memory in such cases, which is obviously not good for performance. Note that having such a relationship can encourage this kind of developers to use it without considering performance implications.

  • How would you add new Users to the Group? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only set User.group. However, if you want to keep objects in memory consistent, you also need to add User to Group.users. But it would make Hibernate to fetch all elements of Group.users from the database!

So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.

See also:

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

How do you use MySQL's source command to import large files in windows

use mysql source command to avoid redirection failures, especially on windows.

mysql [-u <username>] [-p<password>] <databasename> -e "source /path/to/dump.sql"

where e for "Execute command"

On Windows, please remember to use double quote for sql command.

However, either backslash \ or slash / will work on Windows.

Is there a REAL performance difference between INT and VARCHAR primary keys?

For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).

For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.

How to Convert Boolean to String

Simplest solution:

$converted_res = $res ? 'true' : 'false';

Return multiple values from a function, sub or type?

you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:

Sub CP()
Dim ToolFile As String

Cells(3, 2).Select

For i = 0 To 5
    r = ActiveCell.Row
    ToolFile = Cells(r, 7).Value
    On Error Resume Next
    ActiveCell.Value = CP_getdatta(ToolFile)

    'seperate data by "-"
    Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True

Cells(r + 1, 2).Select
Next


End Sub

Function CP_getdatta(ToolFile As String) As String
    Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True

    Range("A56000").Select
    Selection.End(xlUp).Select
    x = CStr(ActiveCell.Value)
    ActiveCell.Offset(0, 20).Select
    Selection.End(xlToLeft).Select
    While IsNumeric(ActiveCell.Value) = False
        ActiveCell.Offset(0, -1).Select
    Wend
    ' combine data to 1 string
    CP_getdatta = CStr(x & "-" & ActiveCell.Value)
    ActiveWindow.Close False

End Function

How do I return a char array from a function?

A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {
    char* arr = malloc(100);
    strcpy(arr,"xxxx");
    return arr;
}

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Updating a date in Oracle SQL table

If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.

In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..

What is the difference between compileSdkVersion and targetSdkVersion?

compileSdkVersion

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.

targetSdkVersion

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.

For example, as the documentation states:

For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...

The Android OS, at runtime, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.

For all practical purposes, most apps are going to want to set targetSdkVersion to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion, it defaults to the minSdkVersion.

How do you get a directory listing in C?

You can find the sample code on the wikibooks link

/**************************************************************
 * A simpler and shorter implementation of ls(1)
 * ls(1) is very similar to the DIR command on DOS and Windows.
 **************************************************************/
#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) 
{
  struct dirent *entry;
  DIR *dp;

  dp = opendir(path);
  if (dp == NULL) 
  {
    perror("opendir");
    return -1;
  }

  while((entry = readdir(dp)))
    puts(entry->d_name);

  closedir(dp);
  return 0;
}

int main(int argc, char **argv) {
  int counter = 1;

  if (argc == 1)
    listdir(".");

  while (++counter <= argc) {
    printf("\nListing %s...\n", argv[counter-1]);
    listdir(argv[counter-1]);
  }

  return 0;
}

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

How to validate IP address in Python?

Consider IPv4 address as "ip".

if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip):  
    print "Valid IP"  
else:
    print "Invalid IP"

FPDF utf-8 encoding (HOW-TO)

There's an extention to FPDF called UFDPF http://acko.net/blog/ufpdf-unicode-utf-8-extension-for-fpdf/

But, imho, it's better to use mpdf if you're it's possible for you to change class.

How to replace part of string by position?

I believe the simplest way would be this:(without stringbuilder)

string myString = "ABCDEFGHIJ";
char[] replacementChars = {'Z', 'X'};
byte j = 0;

for (byte i = 3; i <= 4; i++, j++)  
{                   
myString = myString.Replace(myString[i], replacementChars[j]);  
}

This works because a variable of type string can be treated as an array of char variables. You can, for example refer to the second character of a string variable with name "myString" as myString[1]

How to create a Multidimensional ArrayList in Java?

What would you think of this for 3D ArrayList - can be used similarly to arrays - see the comments in the code:

    import java.util.ArrayList;
    import java.util.List;

    /**
     * ArrayList3D simulates a 3 dimensional array,<br>
     * e.g: myValue = arrayList3D.get(x, y, z) is the same as: <br>
     *      myValue = array[x][y][z] <br>
     * and<br>
     *      arrayList3D.set(x, y, z, myValue) is the same as:<br> 
     *      array[x][y][z] = myValue; <br>
     * but keeps its full ArrayList functionality, thus its
     * benefits of ArrayLists over arrays.<br>
     * <br>
     * @param <T> data type
     */
    public class ArrayList3D <T> {

        private final List<List<List<T>>> arrayList3D;

        public ArrayList3D() {
            arrayList3D = newArrayDim1();
        }


                                            /**
                                             * Get value of the given array element.<br>
                                             * E.g: get(2, 5, 3);<br>
                                             * For 3 dim array this would equal to:<br>
                                             *      nyValue = array[2][5][3];<br>
                                             * <br>
                                             * Throws: IndexOutOfBoundsException
                                             * - if any index is out of range 
                                             *   (index < 0 || index >= size())<br>
                                             * <br>
                                             * @param dim1 index of the first dimension of the array list
                                             * @param dim2 index of the second dimension of the array list
                                             * @param dim3 index of the third dimension of the array list
                                             * @return value of the given array element (of type T)
                                             */
        public T get(int dim1, int dim2, int dim3) {
            List<List<T>>       ar2 = arrayList3D.get(dim1);
            List<T>             ar3 = ar2.get(dim2);
            return ar3.get(dim3);
        }


                                            /**
                                             * Set value of the given array.<br>
                                             * E.g: set(2, 5, 3, "my value");<br>
                                             * For 3 dim array this would equal to:<br>
                                             *      array[2][5][3]="my value";<br>
                                             * <br>
                                             * Throws: IndexOutOfBoundsException
                                             * - if any index is out of range 
                                             *   (index < 0 || index >= size())<br>
                                             * <br>
                                             * @param dim1 index of the first dimension of the array list
                                             * @param dim2 index of the second dimension of the array list
                                             * @param dim3 index of the third dimension of the array list
                                             * @param value value to assign to the given array
                                             * <br>
                                             */
        public void set(int dim1, int dim2, int dim3, T value) {
            arrayList3D.get(dim1).get(dim2).set(dim3, value);
        }

                                            /**
                                             * Set value of the given array element.<br>
                                             * E.g: set(2, 5, 3, "my value");<br>
                                             * For 3 dim array this would equal to:<br>
                                             *      array[2][5][3]="my value";<br>
                                             * <br>
                                             * Throws: IndexOutOfBoundsException
                                             * - if any index is less then 0
                                             *   (index < 0)<br>
                                             * <br>
                                             * @param indexDim1 index of the first dimension of the array list
                                             * @param indexDim2 index of the second dimension of the array list
                                             *        If you set indexDim1 or indexDim2 to value higher
                                             *        then the current max index,
                                             *        the method will add entries for the
                                             *        difference. The added lists will be empty.
                                             * @param indexDim3 index of the third dimension of the array list
                                             *        If you set indexDim3 to value higher
                                             *        then the current max index,
                                             *        the method will add entries for the
                                             *        difference and fill in the values
                                             *        of param. 'value'.
                                             * @param value value to assign to the given array index
                                             */

        public void setOrAddValue(int indexDim1, 
                                  int indexDim2,
                                  int indexDim3, 
                                  T value) {

            List<T> ar3 = setOrAddDim3(indexDim1, indexDim2);

            int max = ar3.size();

            if (indexDim3 < 0)
                indexDim3 = 0;
            if (indexDim3 < max)
                ar3.set(indexDim3, value);

            for (int ix = max-1; ix < indexDim3; ix++ ) {
                ar3.add(value);
            }
        }



        private List<List<List<T>>> newArrayDim1() {
            List<T> ar3 = new ArrayList<>();
            List<List<T>> ar2 = new ArrayList<>();
            List<List<List<T>>> ar1 = new ArrayList<>();
            ar2.add(ar3);
            ar1.add(ar2);
            return ar1;
        }

        private List<List<T>> newArrayDim2() {
            List<T> ar3 = new ArrayList<>();
            List<List<T>> ar2 = new ArrayList<>();
            ar2.add(ar3);
            return ar2;
        }

        private List<T> newArrayDim3() {
            List<T> ar3 = new ArrayList<>();
            return ar3;
        }


        private List<List<T>> setOrAddDim2(int indexDim1) {

            List<List<T>> ar2 = null;

            int max = arrayList3D.size();
            if (indexDim1 < 0)
                indexDim1 = 0;
            if (indexDim1 < max)
                return arrayList3D.get(indexDim1);

            for (int ix = max-1; ix < indexDim1; ix++ ) {
                ar2 = newArrayDim2();
                arrayList3D.add(ar2);
            }
            return ar2;

        }

        private List<T> setOrAddDim3(int indexDim1, int indexDim2) {

            List<List<T>> ar2 = setOrAddDim2(indexDim1);
            List<T>       ar3 = null;

            int max = ar2.size();
            if (indexDim2 < 0)
                indexDim2 = 0;
            if (indexDim2 < max)
                return ar2.get(indexDim2);

            for (int ix = max-1; ix < indexDim2; ix++ ) {
                ar3 = newArrayDim3();
                ar2.add(ar3);
            }
            return ar3;
        }


        public List<List<List<T>>> getArrayList3D() {
            return arrayList3D;
        }

    }

And here is a test code:

        ArrayList3D<Integer> ar = new ArrayList3D<>();

        int max = 3;
        for (int i1 = 0; i1 < max; i1++) {
            for (int i2 = 0; i2 < max; i2++) {
                for (int i3 = 0; i3 < max; i3++) {
                    ar.setOrAddValue(i1, i2, i3, (i3 + 1) + (i2*max) + (i1*max*max));
                    int x = ar.get(i1, i2, i3);
                    System.out.println(" - " + i1 + ", " + i2 + ", " + i3 + " = " + x);
                }
            }
        }

Result output:

  • 0, 0, 0 = 1
  • 0, 0, 1 = 2
  • 0, 0, 2 = 3
  • 0, 1, 0 = 4
  • 0, 1, 1 = 5
  • 0, 1, 2 = 6
  • 0, 2, 0 = 7
  • 0, 2, 1 = 8
  • 0, 2, 2 = 9
  • 1, 0, 0 = 10
  • 1, 0, 1 = 11
  • 1, 0, 2 = 12
  • 1, 1, 0 = 13
  • 1, 1, 1 = 14
  • 1, 1, 2 = 15
  • 1, 2, 0 = 16
  • 1, 2, 1 = 17
  • 1, 2, 2 = 18
  • 2, 0, 0 = 19
  • 2, 0, 1 = 20
  • 2, 0, 2 = 21
  • 2, 1, 0 = 22
  • 2, 1, 1 = 23
  • 2, 1, 2 = 24
  • 2, 2, 0 = 25
  • 2, 2, 1 = 26
  • 2, 2, 2 = 27

Difference between File.separator and slash in paths

Using File.separator made Ubuntu generate files with "\" on it's name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use "/" every time to avoid files with "\" on it's name

How do you decrease navbar height in Bootstrap 3?

Simply change the default 50px navbar-height by including this to your variable overrides.

You can find this default navbar-height on line 365 and 360 on bootstrap's SASS and LESS variables files respectively.

File location, SASS: bootstrap/assets/stylesheets/bootstrap/_variables.scss

File location, LESS: bootstrap/less/variable.less

Cannot set property 'innerHTML' of null

maybe this will work: document.getElementsByTagName("body")[0].innerHTML

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.

Getting a "This application is modifying the autolayout engine from a background thread" error?

I had this issue when I was using TouchID if that helps anyone else, wrap your success logic which likely does something with the UI in the main queue.

How to get current url in view in asp.net core 1.0

You can consider to use this extension method (from Microsoft.AspNetCore.Http.Extensions namespace:

@Context.Request.GetDisplayUrl()

For some my projects i prefer more flexible solution. There are two extensions methods.

1) First method creates Uri object from incoming request data (with some variants through optional parameters). 2) Second method receives Uri object and returns string in following format (with no trailing slash): Scheme_Host_Port

public static Uri GetUri(this HttpRequest request, bool addPath = true, bool addQuery = true)
    {
        var uriBuilder = new UriBuilder
        {
            Scheme = request.Scheme,
            Host = request.Host.Host,
            Port = request.Host.Port.GetValueOrDefault(80),
            Path = addPath ? request.Path.ToString() : default(string),
            Query = addQuery ? request.QueryString.ToString() : default(string)
        };
        return uriBuilder.Uri;
    }

    public static string HostWithNoSlash(this Uri uri)
    {
        return uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
    }

Usage:

//before >> https://localhost:44304/information/about?param1=a&param2=b
        Request.GetUri(addQuery: false);
        //after >> https://localhost:44304/information/about

        //before >> https://localhost:44304/information/about?param1=a&param2=b
        new Uri("https://localhost:44304/information/about?param1=a&param2=b").GetHostWithNoSlash();
        //after >> https://localhost:44304

An Iframe I need to refresh every 30 seconds (but not the whole page)

You can put a meta refresh Tag in the irc_online.php

<meta http-equiv="refresh" content="30">

OR you can use Javascript with setInterval to refresh the src of the Source...

<script>
window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {
 document.frames["frameNameHere"].location.reload();
}
</script>

CSS media queries: max-width OR max-height

CSS Media Queries & Logical Operators: A Brief Overview ;)

The quick answer.

Separate rules with commas: @media handheld, (min-width: 650px), (orientation: landscape) { ... }

The long answer.

There's a lot here, but I've tried to make it information dense, not just fluffy writing. It's been a good chance to learn myself! Take the time to systematically read though and I hope it will be helpful.


Media Queries

Media queries essentially are used in web design to create device- or situation-specific browsing experiences; this is done using the @media declaration within a page's CSS. This can be used to display a webpage differently under a large number of circumstances: whether you are on a tablet or TV with different aspect ratios, whether your device has a color or black-and-white screen, or, perhaps most frequently, when a user changes the size of their browser or switches between browsing devices with varying screen sizes (very generally speaking, designing like this is referred to as Responsive Web Design)

Logical Operators

In designing for these situations, there appear to be four Logical Operators that can be used to require more complex combinations of requirements when targeting a variety of devices or viewport sizes.

(Note: If you don't understand the the differences between media rules, media queries, and feature queries, browse the bottom section of this answer first to get a bit better acquainted with the terminology associated with media query syntax

1. AND (and keyword)

Requires that all conditions specified must be met before the styling rules will take effect.

@media screen and (min-width: 700px) and (orientation: landscape) { ... }

The specified styling rules won't go into place unless all of the following evaluate as true:

  • The media type is 'screen' and
  • The viewport is at least 700px wide and
  • Screen orientation is currently landscape.

Note: I believe that used together, these three feature queries make up a single media query.

2. OR (Comma-separated lists)

Rather than an or keyword, comma-separated lists are used in chaining multiple media queries together to form a more complex media rule

@media handheld, (min-width: 650px), (orientation: landscape) { ... }

The specified styling rules will go into effect once any one media query evaluates as true:

  1. The media type is 'handheld' or
  2. The viewport is at least 650px wide or
  3. Screen orientation is currently landscape.

3. NOT (not keyword)

The not keyword can be used to negate a single media query (and NOT a full media rule--meaning that it only negates entries between a set of commas and not the full media rule following the @media declaration).

Similarly, note that the not keyword negates media queries, it cannot be used to negate an individual feature query within a media query.*

@media not screen and (min-resolution: 300dpi), (min-width: 800px) { ... }

The styling specified here will go into effect if

  1. The media type AND min-resolution don't both meet their requirements ('screen' and '300dpi' respectively) or
  2. The viewport is at least 800 pixels wide.

In other words, if the media type is 'screen' and the min-resolution is 300 dpi, the rule will not go into effect unless the min-width of the viewport is at least 800 pixels.

(The not keyword can be a little funky to state. Let me know if I can do better. ;)

4. ONLY (only keyword)

As I understand it, the only keyword is used to prevent older browsers from misinterpreting newer media queries as the earlier-used, narrower media type. When used correctly, older/non-compliant browsers should just ignore the styling altogether.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

An older / non-compliant browser would just ignore this line of code altogether, I believe as it would read the only keyword and consider it an incorrect media type. (See here and here for more info from smarter people)

FOR MORE INFO

For more info (including more features that can be queried), see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#Logical_operators


Understanding Media Query Terminology

Note: I needed to learn the following terminology for everything here to make sense, particularly concerning the not keyword. Here it is as I understand it:

A media rule (MDN also seems to call these media statements) includes the term @media with all of its ensuing media queries

@media all and (min-width: 800px)

@media only screen and (max-resolution:800dpi), not print

@media screen and (min-width: 700px), (orientation: landscape)

@media handheld, (min-width: 650px), (min-aspect-ratio: 1/1)

A media query is a set of feature queries. They can be as simple as one feature query or they can use the and keyword to form a more complex query. Media queries can be comma-separated to form more complex media rules (see the or keyword above).

screen (Note: Only one feature query in use here.)

only screen

only screen and (max-resolution:800dpi)

only tv and (device-aspect-ratio: 16/9) and (color)

NOT handheld, (min-width: 650px). (Note the comma: there are two media queries here.)

A feature query is the most basic portion of a media rule and simply concerns a given feature and its status in a given browsing situation.

screen

(min-width: 650px)

(orientation: landscape)

(device-aspect-ratio: 16/9)


Code snippets and information derived from:

CSS media queries by Mozilla Contributors (licensed under CC-BY-SA 2.5). Some code samples were used with minor alterations to (hopefully) increase clarity of explanation.

Perform Segue programmatically and pass parameters to the destination view

In case if you use new swift version.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}

How to open the default webbrowser using java

Its very simple just write below code:

String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

or if you don't want to load URL then just write your browser name into string values like,

String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));

it will open browser automatically with empty URL after executing a program

HTML image bottom alignment inside DIV container

This is your code: http://jsfiddle.net/WSFnX/

Using display: table-cell is fine, provided that you're aware that it won't work in IE6/7. Other than that, it's safe: Is there a disadvantage of using `display:table-cell`on divs?

To fix the space at the bottom, add vertical-align: bottom to the actual imgs:

http://jsfiddle.net/WSFnX/1/

Removing the space between the images boils down to this: bikeshedding CSS3 property alternative?

So, here's a demo with the whitespace removed in your HTML: http://jsfiddle.net/WSFnX/4/

Unit testing with Spring Security

Just do it the usual way and then insert it using SecurityContextHolder.setContext() in your test class, for example:

Controller:

Authentication a = SecurityContextHolder.getContext().getAuthentication();

Test:

Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);

How to insert a line break <br> in markdown

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

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

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

How can I import a database with MySQL from terminal?

Below command is working on ubuntu 16.04, I am not sure it is working or not other Linux platforms.

Export SQL file:

$ mysqldump -u [user_name] -p [database_name] > [database_name.sql]  

Example : mysqldump -u root -p max_development > max_development.sql

Import SQL file:

$ mysqldump -u [user_name] -p [database_name] < [file_name.sql]

Example: mysqldump -u root -p max_production < max_development.sql

Note SQL file should exist same directory

Display Parameter(Multi-value) in Report

Hopefully someone else finds this useful:

Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.

To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):

= "Select * from tProducts Where 1 = 1 " 
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")

In your Parameter do the following:

    SELECT -1 As ProductID, 'All' as ProductName Union All
    Select  
    tProducts.ProductID,tProducts.ProductName
    FROM
    tProducts

By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.

Unit Testing: DateTime.Now

Here is my anwer of this question. I combine the 'Ambient Context' pattern with IDisposable. So you can use the DateTimeProvider.Current in your normal program code and in the test you override the scope with a using statement.

using System;
using System.Collections.Immutable;


namespace ambientcontext {

public abstract class DateTimeProvider : IDisposable
{
    private static ImmutableStack<DateTimeProvider> stack = ImmutableStack<DateTimeProvider>.Empty.Push(new DefaultDateTimeProvider());

    protected DateTimeProvider()
    {
        if (this.GetType() != typeof(DefaultDateTimeProvider))
            stack = stack.Push(this);
    }

    public static DateTimeProvider Current => stack.Peek();
    public abstract DateTime Today { get; }
    public abstract DateTime Now {get; }

    public void Dispose()
    {
        if (this.GetType() != typeof(DefaultDateTimeProvider))
            stack = stack.Pop();
    }

    // Not visible Default Implementation 
    private class DefaultDateTimeProvider : DateTimeProvider {
        public override DateTime Today => DateTime.Today; 
        public override DateTime Now => DateTime.Now; 
    }
}
}

Here is how to use the above DateTimeProvider inside a Unit-Test

using System;
using Xunit;

namespace ambientcontext
{
    public class TestDateTimeProvider
    {
        [Fact]
        public void TestDateTime()
        {
            var actual = DateTimeProvider.Current.Today;
            var expected = DateTime.Today;

            Assert.Equal<DateTime>(expected, actual);

            using (new MyDateTimeProvider(new DateTime(2012,12,21)))
            {
                Assert.Equal(2012, DateTimeProvider.Current.Today.Year);

                using (new MyDateTimeProvider(new DateTime(1984,4,4)))
                {
                    Assert.Equal(1984, DateTimeProvider.Current.Today.Year);    
                }

                Assert.Equal(2012, DateTimeProvider.Current.Today.Year);
            }

            // Fall-Back to Default DateTimeProvider 
            Assert.Equal<int>(expected.Year,  DateTimeProvider.Current.Today.Year);
        }

        private class MyDateTimeProvider : DateTimeProvider 
        {
            private readonly DateTime dateTime; 

            public MyDateTimeProvider(DateTime dateTime):base()
            {
                this.dateTime = dateTime; 
            }

            public override DateTime Today => this.dateTime.Date;

            public override DateTime Now => this.dateTime;
        }
    }
}

How do I remove a property from a JavaScript object?

Dan's assertion that 'delete' is very slow and the benchmark he posted were doubted. So I carried out the test myself in Chrome 59. It does seem that 'delete' is about 30 times slower:

var iterationsTotal = 10000000;  // 10 million
var o;
var t1 = Date.now(),t2;
for (let i=0; i<iterationsTotal; i++) {
   o = {a:1,b:2,c:3,d:4,e:5};
   delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;
}
console.log ((t2=Date.now())-t1);  // 6135
for (let i=0; i<iterationsTotal; i++) {
   o = {a:1,b:2,c:3,d:4,e:5};
   o.a = o.b = o.c = o.d = o.e = undefined;
}
console.log (Date.now()-t2);  // 205

Note that I purposedly carried out more than one 'delete' operations in one loop cycle to minimize the effect caused by the other operations.

How to download a file from a URL in C#?

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Reading numbers from a text file into an array in C

for (i = 0; i < 16; i++)
{
    fscanf(myFile, "%d", &numberArray[i]);
}

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...

Detect all changes to a <input type="text"> (immediately) using JQuery

Here is a slightly different solution if you didn't fancy any of the other answers:

var field_selectors = ["#a", "#b"];
setInterval(function() { 
  $.each(field_selectors, function() { 
    var input = $(this);
    var old = input.attr("data-old-value");
    var current = input.val();
    if (old !== current) { 
      if (typeof old != 'undefined') { 
        ... your code ...
      }
      input.attr("data-old-value", current);
    }   
  }   
}, 500);

Consider that you cannot rely on click and keyup to capture context menu paste.

Count how many rows have the same value

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

It is very likely that the pickled file is empty.

It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.

For example the following writes a pickle file:

pickle.dump(df,open('df.p','wb'))

And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:

df=pickle.load(open('df.p','wb'))

The correct syntax is

df=pickle.load(open('df.p','rb'))

CSS centred header image

I think this is what you need if I'm understanding you correctly:

<div id="wrapperHeader">
 <div id="header">
  <img src="images/logo.png" alt="logo" />
 </div> 
</div>



div#wrapperHeader {
 width:100%;
 height;200px; /* height of the background image? */
 background:url(images/header.png) repeat-x 0 0;
 text-align:center;
}

div#wrapperHeader div#header {
 width:1000px;
 height:200px;
 margin:0 auto;
}

div#wrapperHeader div#header img {
 width:; /* the width of the logo image */
 height:; /* the height of the logo image */
 margin:0 auto;
}

Convert Mat to Array/Vector in OpenCV

Can be done in two lines :)

Mat to array

uchar * arr = image.isContinuous()? image.data: image.clone().data;
uint length = image.total()*image.channels();

Mat to vector

cv::Mat flat = image.reshape(1, image.total()*image.channels());
std::vector<uchar> vec = image.isContinuous()? flat : flat.clone();

Both work for any general cv::Mat.

Explanation with a working example

    cv::Mat image;
    image = cv::imread(argv[1], cv::IMREAD_UNCHANGED);   // Read the file
    cv::namedWindow("cvmat", cv::WINDOW_AUTOSIZE );// Create a window for display.
    cv::imshow("cvmat", image );                   // Show our image inside it.

    // flatten the mat.
    uint totalElements = image.total()*image.channels(); // Note: image.total() == rows*cols.
    cv::Mat flat = image.reshape(1, totalElements); // 1xN mat of 1 channel, O(1) operation
    if(!image.isContinuous()) {
        flat = flat.clone(); // O(N),
    }
    // flat.data is your array pointer
    auto * ptr = flat.data; // usually, its uchar*
    // You have your array, its length is flat.total() [rows=1, cols=totalElements]
    // Converting to vector
    std::vector<uchar> vec(flat.data, flat.data + flat.total());
    // Testing by reconstruction of cvMat
    cv::Mat restored = cv::Mat(image.rows, image.cols, image.type(), ptr); // OR vec.data() instead of ptr
    cv::namedWindow("reconstructed", cv::WINDOW_AUTOSIZE);
    cv::imshow("reconstructed", restored);

    cv::waitKey(0);     

Extended explanation:

Mat is stored as a contiguous block of memory, if created using one of its constructors or when copied to another Mat using clone() or similar methods. To convert to an array or vector we need the address of its first block and array/vector length.

Pointer to internal memory block

Mat::data is a public uchar pointer to its memory.
But this memory may not be contiguous. As explained in other answers, we can check if mat.data is pointing to contiguous memory or not using mat.isContinous(). Unless you need extreme efficiency, you can obtain a continuous version of the mat using mat.clone() in O(N) time. (N = number of elements from all channels). However, when dealing images read by cv::imread() we will rarely ever encounter a non-continous mat.

Length of array/vector

Q: Should be row*cols*channels right?
A: Not always. It can be rows*cols*x*y*channels.
Q: Should be equal to mat.total()?
A: True for single channel mat. But not for multi-channel mat
Length of the array/vector is slightly tricky because of poor documentation of OpenCV. We have Mat::size public member which stores only the dimensions of single Mat without channels. For RGB image, Mat.size = [rows, cols] and not [rows, cols, channels]. Mat.total() returns total elements in a single channel of the mat which is equal to product of values in mat.size. For RGB image, total() = rows*cols. Thus, for any general Mat, length of continuous memory block would be mat.total()*mat.channels().

Reconstructing Mat from array/vector

Apart from array/vector we also need the original Mat's mat.size [array like] and mat.type() [int]. Then using one of the constructors that take data's pointer, we can obtain original Mat. The optional step argument is not required because our data pointer points to continuous memory. I used this method to pass Mat as Uint8Array between nodejs and C++. This avoided writing C++ bindings for cv::Mat with node-addon-api.

References:

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

Bootstrap select dropdown list placeholder

Try @title = "stuff". It worked for me.

ORA-01008: not all variables bound. They are bound

Came here looking for help as got same error running a statement listed below while going through a Udemy course:

INSERT INTO departments (department_id, department_name)
                  values( &dpet_id, '&dname');  

I'd been able to run statements with substitution variables before. Comment by Charles Burns about possibility of server reaching some threshold while recreating the variables prompted me to log out and restart the SQL Developer. The statement ran fine after logging back in.

Thought I'd share for anyone else venturing here with a limited scope issue as mine.

REST URI convention - Singular or plural name of resource while creating it

See Google's API Design Guide: Resource Names for another take on naming resources.

The guide requires collections to be named with plurals.

|--------------------------+---------------+-------------------+---------------+--------------|
| API Service Name         | Collection ID | Resource ID       | Collection ID | Resource ID  |
|--------------------------+---------------+-------------------+---------------+--------------|
| //mail.googleapis.com    | /users        | /[email protected] | /settings     | /customFrom  |
| //storage.googleapis.com | /buckets      | /bucket-id        | /objects      | /object-id   |
|--------------------------+---------------+-------------------+---------------+--------------|

It's worthwhile reading if you're thinking about this subject.

How to update UI from another thread running in another class

If this is a long calculation then I would go background worker. It has progress support. It also has support for cancel.

http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

Here I have a TextBox bound to contents.

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Debug.Write("backgroundWorker_RunWorkerCompleted");
        if (e.Cancelled)
        {
            contents = "Cancelled get contents.";
            NotifyPropertyChanged("Contents");
        }
        else if (e.Error != null)
        {
            contents = "An Error Occured in get contents";
            NotifyPropertyChanged("Contents");
        }
        else
        {
            contents = (string)e.Result;
            if (contentTabSelectd) NotifyPropertyChanged("Contents");
        }
    }

Wrap a text within only two lines inside div

CSS only

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

if you have neccessary .net framework installed. Ex ; .Net 4.0 or .Net 3.5, then you can just copy Gacutil.exe from any of the machine and to the new machine.

1) Open CMD as adminstrator in new server.
2) Traverse to the folder where you copied the Gacutil.exe. For eg - C:\program files.(in my case).
3) Type the below in the cmd prompt and install.

C:\Program Files\gacutil.exe /I dllname

socket connect() vs bind()

To make understanding better , lets find out where exactly bind and connect comes into picture,

Further to positioning of two calls , as clarified by Sourav,

bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.] connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

We cannot use them interchangeably (even when we have client/server on same machine) because of specific roles and corresponding implementation.

I will further recommend to correlate these calls TCP/IP handshake .

enter image description here

So , who will send SYN here , it will be connect() . While bind() is used for defining the communication end point.

Hope this helps!!

What does the 'static' keyword do in a class?

A question was asked here about the choice of the word 'static' for this concept. It was dup'd to this question, but I don't think the etymology has been clearly addressed. So...


It's due to keyword reuse, starting with C.

Consider data declarations in C (inside a function body):

    void f() {
        int foo = 1;
        static int bar = 2;
         :
    }

The variable foo is created on the stack when the function is entered (and destroyed when the function terminates). By contrast, bar is always there, so it's 'static' in the sense of common English - it's not going anywhere.

Java, and similar languages, have the same concept for data. Data can either be allocated per instance of the class (per object) or once for the entire class. Since Java aims to have familiar syntax for C/C++ programmers, the 'static' keyword is appropriate here.

    class C {
        int foo = 1;
        static int bar = 2;
         :
    }

Lastly, we come to methods.

    class C {
        int foo() { ... }
        static int bar() { ... }
         :
    }

There is, conceptually speaking, an instance of foo() for every instance of class C. There is only one instance of bar() for the entire class C. This is parallel to the case we discussed for data, and therefore using 'static' is again a sensible choice, especially if you don't want to add more reserved keywords to your language.

How to establish a connection pool in JDBC?

Pool

  • Pooling Mechanism is the way of creating the Objects in advance. When a class is loaded.
  • It improves the application performance [By re using same object's to perform any action on Object-Data] & memory [allocating and de-allocating many objects creates a significant memory management overhead].
  • Object clean-up is not required as we are using same Object, reducing the Garbage collection load.

« Pooling [ Object pool, String Constant Pool, Thread Pool, Connection pool]

String Constant pool

  • String literal pool maintains only one copy of each distinct string value. which must be immutable.
  • When the intern method is invoked, it check object availability with same content in pool using equals method. « If String-copy is available in the Pool then returns the reference. « Otherwise, String object is added to the pool and returns the reference.

Example: String to verify Unique Object from pool.

public class StringPoolTest {
    public static void main(String[] args) { // Integer.valueOf(), String.equals()
        String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();

        String s1 = "Yash".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
        String s2 = "Yas"+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
        String s3 = "Yas".intern()+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
        String s4 = "Yas"+"h";
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
    }
}

Connection pool using Type-4 Driver using 3rd party libraries[ DBCP2, c3p0, Tomcat JDBC]

Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora]. wiki

In Connection pool mechanism, when the class is loaded it get's the physical JDBC connection objects and provides a wrapped physical connection object to user. PoolableConnection is a wrapper around the actual connection.

  • getConnection() pick one of the free wrapped-connection form the connection objectpool and returns it.
  • close() instead of closing it returns the wrapped-connection back to pool.

Example: Using ~ DBCP2 Connection Pool with Java 7[try-with-resources]

public class ConnectionPool {
    static final BasicDataSource ds_dbcp2 = new BasicDataSource();
    static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
    static final DataSource ds_JDBC = new DataSource();

    static Properties prop = new Properties();
    static {
        try {
            prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));

            ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
            ds_dbcp2.setUrl( prop.getProperty("URL") );
            ds_dbcp2.setUsername( prop.getProperty("UserName") );
            ds_dbcp2.setPassword( prop.getProperty("Password") );
            ds_dbcp2.setInitialSize( 5 );

            ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
            ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
            ds_c3p0.setUser( prop.getProperty("UserName") );
            ds_c3p0.setPassword( prop.getProperty("Password") );
            ds_c3p0.setMinPoolSize(5);
            ds_c3p0.setAcquireIncrement(5);
            ds_c3p0.setMaxPoolSize(20);

            PoolProperties pool = new PoolProperties();
            pool.setUrl( prop.getProperty("URL") );
            pool.setDriverClassName( prop.getProperty("DriverClass") );
            pool.setUsername( prop.getProperty("UserName") );
            pool.setPassword( prop.getProperty("Password") );
            pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)

            pool.setInitialSize(5);
            pool.setMaxActive(3);
            ds_JDBC.setPoolProperties( pool );
        } catch (IOException e) {   e.printStackTrace();
        } catch (PropertyVetoException e) { e.printStackTrace(); }
    }

    public static Connection getDBCP2Connection() throws SQLException {
        return ds_dbcp2.getConnection();
    }

    public static Connection getc3p0Connection() throws SQLException {
        return ds_c3p0.getConnection();
    }

    public static Connection getJDBCConnection() throws SQLException {
        return ds_JDBC.getConnection();
    }
}
public static boolean exists(String UserName, String Password ) throws SQLException {
    boolean exist = false;
    String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
    try ( Connection connection = ConnectionPool.getDBCP2Connection();
          PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
        pstmt.setString(1, UserName );
        pstmt.setString(2, Password );

        try (ResultSet resultSet = pstmt.executeQuery()) {
            exist = resultSet.next(); // Note that you should not return a ResultSet here.
        }
    }
    System.out.println("User : "+exist);
    return exist;
}

jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName> jdbc:oracle:thin:@localhost:1521:myDBName jdbc:mysql://localhost:3306/myDBName

connectionpool.properties

URL         : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName    : root
Password    :

Web Application: To avoid connection problem when all the connection's are closed[MySQL "wait_timeout" default 8 hours] in-order to reopen the connection with underlying DB.

You can do this to Test Every Connection by setting testOnBorrow = true and validationQuery= "SELECT 1" and donot use autoReconnect for MySQL server as it is deprecated. issue

===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
    <Resource name="jdbc/MyAppDB" auth="Container" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        type="javax.sql.DataSource" 

        initialSize="5" minIdle="5" maxActive="15" maxIdle="10"

        testWhileIdle="true"
            timeBetweenEvictionRunsMillis="30000"

        testOnBorrow="true"
            validationQuery="SELECT 1"
            validationInterval="30000"


        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/myDBName" 
        username="yash" password="777"
    />
</Context>

===== ===== web.xml ===== =====
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/MyAppDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet «   init() {}
Normal call used by sevlet  « static {}

static DataSource ds;
static {
    try {
        Context ctx=new InitialContext();
        Context envContext = (Context)ctx.lookup("java:comp/env");
        ds  =   (DataSource) envContext.lookup("jdbc/MyAppDB");
    } catch (NamingException e) {   e.printStackTrace();    }
}

See these also:

How do I access properties of a javascript object if I don't know the names?

You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
            if(this.hasOwnProperty(p)){
                A[A.length]= p+'='+this[p];
            }
        }

    return A.join(', ');
}

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

design a stack such that getMinimum( ) should be O(1)

Add a field to hold the minimum value and update it during Pop() and Push(). That way getMinimum() will be O(1), but Pop() and Push() will have to do a little more work.

If minimum value is popped, Pop() will be O(n), otherwise they will still both be O(1). When resizing Push() becomes O(n) as per the Stack implementation.

Here's a quick implementation

public sealed class MinStack {
    private int MinimumValue;
    private readonly Stack<int> Stack = new Stack<int>();

    public int GetMinimum() {
        if (IsEmpty) {
            throw new InvalidOperationException("Stack is empty");
        }
        return MinimumValue;
    }

    public int Pop() {
        var value = Stack.Pop();
        if (value == MinimumValue) {
            MinimumValue = Stack.Min();
        }
        return value;
    }

    public void Push(int value) {
        if (IsEmpty || value < MinimumValue) {
            MinimumValue = value;
        }
        Stack.Push(value);
    }

    private bool IsEmpty { get { return Stack.Count() == 0; } }
}

Apache - MySQL Service detected with wrong path. / Ports already in use

hello i have had same problem an i did the steps with tommer and the problem solved thank you

note :

you don't have to go to that like just do this ;

1)-- Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

2)--edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

3)--Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

4)--Open Windows Services and set Startup Type: Automatic, Start the service

Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

Graphical DIFF programs for linux

xxdiff is lightweight if that's what you're after.

Passing variable number of arguments around

I'm unsure if this works for all compilers, but it has worked so far for me.

void inner_func(int &i)
{
  va_list vars;
  va_start(vars, i);
  int j = va_arg(vars);
  va_end(vars); // Generally useless, but should be included.
}

void func(int i, ...)
{
  inner_func(i);
}

You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.

The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.

Specifying colClasses in the read.csv

If we combine what @Hendy and @Oddysseus Ithaca contributed, we get cleaner and a more general (i.e., adaptable?) chunk of code.

    data <- read.csv("test.csv", head = F, colClasses = c(V36 = "character", V38 = "character"))                        

VBA Excel 2-Dimensional Arrays

In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:

dim arOne()
arOne = range("A2:F1000")

or even

arOne = range("A2").CurrentRegion

and that's it, your array is filled much faster then with a loop, no redim.

python ignore certificate validation urllib2

According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)

if you need opener, just added this context like:

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))

NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.

Find text in string with C#

This is the simplest way:

if(str.Contains("hello"))

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

What does %5B and %5D in POST requests stand for?

To take a quick look, you can percent-en/decode using this online tool.

Change the mouse cursor on mouse over to anchor-like style

If you want to do this in jQuery instead of CSS, you basically follow the same process.

Assuming you have some <div id="target"></div>, you can use the following code:

$("#target").hover(function() {
    $(this).css('cursor','pointer');
}, function() {
    $(this).css('cursor','auto');
});

and that should do it.

How to pass parameters or arguments into a gradle task

If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true".

Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.

1. If few values, task creation function

If the possible values are few and are known in advance, you can programmatically create a task for each of them:

void createTask(String platform) {
   String taskName = "myTask_" + platform;
   task (taskName) {
      ... do what you want
   }
}

String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
    createTask(platform);
}

You would then call your tasks the following way:

./gradlew myTask_macosx

2. Standard input hack

A convenient hack is to pass the arguments through standard input, and have your task read from it:

./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"

with code below:

String[] splitIntoTokens(String commandLine) {
    String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
    Matcher matcher = Pattern.compile(regex).matcher(commandLine);
    ArrayList<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group());
    }
    return result.toArray();   
}

task taskName, {
        doFirst {
            String typed = new Scanner(System.in).nextLine();
            String[] parsed = splitIntoTokens(typed);
            println ("Arguments received: " + parsed.join(" "))
            ... do what you want
        } 
 }

You will also need to add the following lines at the top of your build script:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

3. -P parameters

The last option is to pass a -P parameter to Gradle:

./gradlew myTask -PmyArg=hello

You can then access it as myArg in your build script:

task myTask {
    doFirst {
       println myArg
       ... do what you want
    }
}

Credit to @789 for his answer on splitting arguments into tokens

Declaring and initializing arrays in C

Is there a way to declare first and then initialize an array in C?

There is! but not using the method you described.

You can't initialize with a comma separated list, this is only allowed in the declaration. You can however initialize with...

myArray[0] = 1;
myArray[1] = 2;
...

or

for(int i = 1; i <= SIZE; i++)
{
  myArray[i-1] = i;
}

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Android: How to turn screen on and off programmatically?

I have tried all above solution but none worked for me. so I googled and found below solutions. I tried and it worked.

https://www.tutorialspoint.com/how-to-turn-android-device-screen-on-and-off-programmatically

if there is any suggestion then please give

How do you configure an OpenFileDialog to select folders?

I assume you're on Vista using VS2008? In that case I think that the FOS_PICKFOLDERS option is being used when calling the Vista file dialog IFileDialog. I'm afraid that in .NET code this would involve plenty of gnarly P/Invoke interop code to get working.

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

Using a global variable with a thread

A lock should be considered to use, such as threading.Lock. See lock-objects for more info.

The accepted answer CAN print 10 by thread1, which is not what you want. You can run the following code to understand the bug more easily.

def thread1(threadname):
    while True:
      if a % 2 and not a % 2:
          print "unreachable."

def thread2(threadname):
    global a
    while True:
        a += 1

Using a lock can forbid changing of a while reading more than one time:

def thread1(threadname):
    while True:
      lock_a.acquire()
      if a % 2 and not a % 2:
          print "unreachable."
      lock_a.release()

def thread2(threadname):
    global a
    while True:
        lock_a.acquire()
        a += 1
        lock_a.release()

If thread using the variable for long time, coping it to a local variable first is a good choice.

Cannot hide status bar in iOS7

Just add these 2 lines in info.plist file. It will make the fix for iOS7 and older version both.

  • Status bar is initially hidden = YES
  • View controller-based status bar appearance = NO

Navigate to the project and select Targets -> General and see the "Status Bar style ...Hide during application launch" check box will be checked. This will work.

How to print SQL statement in codeigniter model

Add this line right after the query you want to print.

Example:

$query = $this->db->query('SELECT * FROM table WHERE condition');

//Add this line.

var_dump($this->db->last_query());

exit();

or

echo $this->db->last_query();

How do you test to see if a double is equal to NaN?

If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

(value==null || Double.isNaN(value))

Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

How can I limit possible inputs in a HTML5 "number" element?

Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

_x000D_
_x000D_
// Reusable Function to Enforce MaxLength_x000D_
function enforce_maxlength(event) {_x000D_
  var t = event.target;_x000D_
  if (t.hasAttribute('maxlength')) {_x000D_
    t.value = t.value.slice(0, t.getAttribute('maxlength'));_x000D_
  }_x000D_
}_x000D_
_x000D_
// Global Listener for anything with an maxlength attribute._x000D_
// I put the listener on the body, put it on whatever._x000D_
document.body.addEventListener('input', enforce_maxlength);
_x000D_
label { margin: 10px; font-size: 16px; display: block }_x000D_
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }_x000D_
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }
_x000D_
<label for="test_input">Text Input</label>_x000D_
<input id="test_input" type="text" maxlength="5"/>_x000D_
<span>set to 5 maxlength</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<label for="test_input">Number Input</label>_x000D_
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>_x000D_
<span>set to 2 maxlength, min 0 and max 99</span>
_x000D_
_x000D_
_x000D_

Save a list to a .txt file

Try this, if it helps you

values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

How to center an element horizontally and vertically

  • Approach 1 - transform translateX/translateY:

    Example Here / Full Screen Example

    In supported browsers (most of them), you can use top: 50%/left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.

_x000D_
_x000D_
.container {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    -moz-transform: translateX(-50%) translateY(-50%);_x000D_
    -webkit-transform: translateX(-50%) translateY(-50%);_x000D_
    transform: translateX(-50%) translateY(-50%);_x000D_
}
_x000D_
<div class="container">_x000D_
    <span>I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 2 - Flexbox method:

    Example Here / Full Screen Example

    In supported browsers, set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering. Just don't forget to add vendor prefixes for additional browser support (see example).

_x000D_
_x000D_
html, body, .container {_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    display: -webkit-flexbox;_x000D_
    display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -webkit-flex-align: center;_x000D_
    -ms-flex-align: center;_x000D_
    -webkit-align-items: center;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <span>I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 3 - table-cell/vertical-align: middle:

    Example Here / Full Screen Example

    In some cases, you will need to ensure that the html/body element's height is set to 100%.

    For vertical alignment, set the parent element's width/height to 100% and add display: table. Then for the child element, change the display to table-cell and add vertical-align: middle.

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements. Alternatively, you could use margin: 0 auto, assuming the element is block level.

_x000D_
_x000D_
html, body {_x000D_
    height: 100%;_x000D_
}_x000D_
.parent {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    display: table;_x000D_
    text-align: center;_x000D_
}_x000D_
.parent > .child {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<section class="parent">_x000D_
    <div class="child">I'm vertically/horizontally centered!</div>_x000D_
</section>
_x000D_
_x000D_
_x000D_


  • Approach 4 - Absolutely positioned 50% from the top with displacement:

    Example Here / Full Screen Example

    This approach assumes that the text has a known height - in this instance, 18px. Just absolutely position the element 50% from the top, relative to the parent element. Use a negative margin-top value that is half of the element's known height, in this case - -9px.

_x000D_
_x000D_
html, body, .container {_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.container > p {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    margin-top: -9px;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>I'm vertically/horizontally centered!</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


  • Approach 5 - The line-height method (Least flexible - not suggested):

    Example Here

    In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this.

_x000D_
_x000D_
.parent {_x000D_
    height: 200px;_x000D_
    width: 400px;_x000D_
    background: lightgray;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.parent > .child {_x000D_
    line-height: 200px;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <span class="child">I'm vertically/horizontally centered!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert datetime format to date format in crystal report using C#?

Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop(); 
  var containerBottom = containerTop + $(container).height(); 
  var elemTop = element.offsetTop;
  var elemBottom = elemTop + $(element).height(); 
  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }
}

Fastest way to write huge data in text file Java

Your transfer speed is likely not to be limited by Java. Instead I would suspect (in no particular order)

  1. the speed of transfer from the database
  2. the speed of transfer to the disk

If you read the complete dataset and then write it out to disk, then that will take longer, since the JVM will have to allocate memory, and the db rea/disk write will happen sequentially. Instead I would write out to the buffered writer for every read that you make from the db, and so the operation will be closer to a concurrent one (I don't know if you're doing that or not)

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

Just solve the problem which come from java compiler instead of Build-Run task

What is ToString("N0") format?

It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.

What N does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2 by rounding right-most digit if necessary.

N0 does not represent any decimal place but rounding is applied to it.

Let's exemplify.

using System;
using System.Globalization;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = 567892.98789;
            CultureInfo someCulture = new CultureInfo("da-DK", false);

            // 10 means left-padded = right-alignment
            Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
            Console.WriteLine("{0,10:N} us", x); 

            // watch out rounding 567,893
            Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x)); 
            Console.WriteLine("{0,10:N0}", x);

            Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
            Console.WriteLine("{0,10:N5}", x);


            Console.ReadKey();

        }
    }
}

It yields,

567.892,99 denmark
567,892.99 us
   567.893
   567,893
567.892,98789
567,892.98789

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

How to pass a callback as a parameter into another function

Yes of course, function are objects and can be passed, but of course you must declare it:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

How to put the legend out of the plot

In addition to all the excellent answers here, newer versions of matplotlib and pylab can automatically determine where to put the legend without interfering with the plots, if possible.

pylab.legend(loc='best')

This will automatically place the legend away from the data if possible! Compare the use of loc='best'

However, if there is no place to put the legend without overlapping the data, then you'll want to try one of the other answers; using loc="best" will never put the legend outside of the plot.

How to reference a method in javadoc?

You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the

{@link package.class#member label}

tag (that you are looking for). The corresponding example from the documentation is as follows

For example, here is a comment that refers to the getComponentAt(int, int) method:

Use the {@link #getComponentAt(int, int) getComponentAt} method.

The package.class part can be ommited if the referred method is in the current class.


Other useful links about JavaDoc are:

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

Repeat a string in JavaScript a number of times

Here is what I use:

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Not really solve your question but it's an important alternative.

If you want to add custom html to the beginning of the page (inside <body> element), you may use Page.ClientScript.RegisterClientScriptBlock().

Although the method is called "script", but you can add arbitary string, including html.

Conveniently map between enum and int / String

Use an interface to show it who's boss.

public interface SleskeEnum {
    int id();

    SleskeEnum[] getValues();

}

public enum BonusType implements SleskeEnum {


  MONTHLY(1), YEARLY(2), ONE_OFF(3);

  public final int id;

  BonusType(int id) {
    this.id = id;
  }

  public SleskeEnum[] getValues() {
    return values();
  }

  public int id() { return id; }


}

public class Utils {

  public static SleskeEnum getById(SleskeEnum type, int id) {
      for(SleskeEnum t : type.getValues())
          if(t.id() == id) return t;
      throw new IllegalArgumentException("BonusType does not accept id " + id);
  }

  public static void main(String[] args) {

      BonusType shouldBeMonthly = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly == BonusType.MONTHLY);

      BonusType shouldBeMonthly2 = (BonusType)getById(BonusType.MONTHLY,1);
      System.out.println(shouldBeMonthly2 == BonusType.YEARLY);

      BonusType shouldBeYearly = (BonusType)getById(BonusType.MONTHLY,2);
      System.out.println(shouldBeYearly  == BonusType.YEARLY);

      BonusType shouldBeOneOff = (BonusType)getById(BonusType.MONTHLY,3);
      System.out.println(shouldBeOneOff == BonusType.ONE_OFF);

      BonusType shouldException = (BonusType)getById(BonusType.MONTHLY,4);
  }
}

And the result:

C:\Documents and Settings\user\My Documents>java Utils
true
false
true
true
Exception in thread "main" java.lang.IllegalArgumentException: BonusType does not accept id 4
        at Utils.getById(Utils.java:6)
        at Utils.main(Utils.java:23)

C:\Documents and Settings\user\My Documents>

check if a string matches an IP address pattern in python?

Other regex answers in this page will accept an IP with a number over 255.

This regex will avoid this problem:

import re

def validate_ip(ip_str):
    reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
    if re.match(reg, ip_str):
        return True
    else:
        return False

How to set a default Value of a UIPickerView

You have to send - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.

How do I convert from int to String?

use Integer.toString(tmpInt).trim();

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

How to thoroughly purge and reinstall postgresql on ubuntu?

Steps that worked for me on Ubuntu 8.04.2 to remove postgres 8.3

  1. List All Postgres related packages

    dpkg -l | grep postgres
    
    ii  postgresql                            8.3.17-0ubuntu0.8.04.1           object-relational SQL database (latest versi
    ii  postgresql-8.3                        8.3.9-0ubuntu8.04                object-relational SQL database, version 8.3
    ii  postgresql-client                     8.3.9-0ubuntu8.04                front-end programs for PostgreSQL (latest ve
    ii  postgresql-client-8.3                 8.3.9-0ubuntu8.04                front-end programs for PostgreSQL 8.3
    ii  postgresql-client-common              87ubuntu2                        manager for multiple PostgreSQL client versi
    ii  postgresql-common                     87ubuntu2                        PostgreSQL database-cluster manager
    ii  postgresql-contrib                    8.3.9-0ubuntu8.04                additional facilities for PostgreSQL (latest
    ii  postgresql-contrib-8.3                8.3.9-0ubuntu8.04                additional facilities for PostgreSQL
    
  2. Remove all above listed

    sudo apt-get --purge remove postgresql postgresql-8.3  postgresql-client  postgresql-client-8.3 postgresql-client-common postgresql-common  postgresql-contrib postgresql-contrib-8.3
    
  3. Remove the following folders

    sudo rm -rf /var/lib/postgresql/
    sudo rm -rf /var/log/postgresql/
    sudo rm -rf /etc/postgresql/
    

Python socket receive - incoming packets always have a different size

The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module.

So, to clarify, since this may be confusing to others looking to this for help:

  1. The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param).
  2. The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available.

See the documentation for details.

Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.

As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.

I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.

How do I convert seconds to hours, minutes and seconds?

If you need to get datetime.time value, you can use this trick:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

You cannot add timedelta to time, but can add it to datetime.

UPD: Yet another variation of the same technique:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

The following are tried, tested and proven methods to check if a row exists.

(Some of which I use myself, or have used in the past).

Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).

I.e.:

if (!mysqli_query($con,$query)) which should have simply read as if (!$query).

  • I apologize for overlooking that mistake.

Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.

Here are the two edited queries:

$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($con));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

and in your case:

$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($dbl));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

You can also use mysqli_ with a prepared statement method:

$query = "SELECT `email` FROM `tblUser` WHERE email=?";

if ($stmt = $dbl->prepare($query)){

        $stmt->bind_param("s", $email);

        if($stmt->execute()){
            $stmt->store_result();

            $email_check= "";         
            $stmt->bind_result($email_check);
            $stmt->fetch();

            if ($stmt->num_rows == 1){

            echo "That Email already exists.";
            exit;

            }
        }
    }

Or a PDO method with a prepared statement:

<?php
$email = $_POST['email'];

$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';

try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     exit( $e->getMessage() );
}

// assuming a named submit button
if(isset($_POST['submit']))
    {

        try {
            $stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
            $stmt->bindParam(1, $_POST['email']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    if($stmt->rowCount() > 0){
        echo "The record exists!";
    } else {
        echo "The record is non-existant.";
    }


    }
?>
  • Prepared statements are best to be used to help protect against an SQL injection.

N.B.:

When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.

  • FYI: Forms default to a GET method if not explicity instructed.

Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.

  • POST arrays are case-sensitive.

Consult:

Error checking references:

Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).

  • You must use the same one from connecting to querying.

Consult the following about this:

If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:

The mysql_* functions are deprecated and will be removed from future PHP releases.

  • It's time to step into the 21st century.

You can also add a UNIQUE constraint to (a) row(s).

References:

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

What's the most efficient way to check if a record exists in Oracle?

Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.

    DECLARE
    rec_count NUMBER := 0;

    BEGIN

    select count(*) 
    into rec_count  
    from EMPLOYEETABLE  
    WHERE employee_id = inEMPLOYEE_ID  
    AND department_nbr = inDEPARTMENT_NBR;  


    if rec_count > 0 then  
       {UPDATE EMPLOYEETABLE}
    else  
       {INSERT INTO EMPLOYEETABLE}  
    end if;  

    END;

Cannot load properties file from resources directory

If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.

The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:

String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
    props.load(resourceStream);
}
// use props here ...

How to make a <div> always full screen?

Unfortunately, the height property in CSS is not as reliable as it should be. Therefore, Javascript will have to be used to set the height style of the element in question to the height of the users viewport. And yes, this can be done without absolute positioning...

<!DOCTYPE html>

<html>
  <head>
    <title>Test by Josh</title>
    <style type="text/css">
      * { padding:0; margin:0; }
      #test { background:#aaa; height:100%; width:100%; }
    </style>
    <script type="text/javascript">
      window.onload = function() {
        var height = getViewportHeight();

        alert("This is what it looks like before the Javascript. Click OK to set the height.");

        if(height > 0)
          document.getElementById("test").style.height = height + "px";
      }

      function getViewportHeight() {
        var h = 0;

        if(self.innerHeight)
          h = window.innerHeight;
        else if(document.documentElement && document.documentElement.clientHeight)
          h = document.documentElement.clientHeight;
        else if(document.body) 
          h = document.body.clientHeight;

        return h;
      }
    </script>
  </head>
  <body>
    <div id="test">
      <h1>Test</h1>
    </div>
  </body>
</html>

Adding a parameter to the URL with JavaScript

With the new achievements in JS here is how one can add query param to the URL:

var protocol = window.location.protocol,
    host = '//' + window.location.host,
    path = window.location.pathname,
    query = window.location.search;

var newUrl = protocol + host + path + query + (query ? '&' : '?') + 'param=1';

window.history.pushState({path:newUrl}, '' , newUrl);

Also see this possibility Moziila URLSearchParams.append()

How do I remove objects from an array in Java?

An alternative in Java 8:

String[] filteredArray = Arrays.stream(array)
    .filter(e -> !e.equals(foo)).toArray(String[]::new);

How do I change the default location for Git Bash on Windows?

I read it somewhere and it worked for me.

First check in git bash what is the HOME location. Open git bash and run

echo $HOME

Now change the HOME path by opening cmd and run

setx HOME "path/to/.ssh/loc" (I gave C:\Users\aXXXX)

Now cross check by running the echo command in git bash.

What is C# equivalent of <map> in C++?

.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Jackson - How to process (deserialize) nested JSON?

Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor object is designed to handle id, name, company_id, but each of those multiple objects are also wrapped in an object with a single property vendor.

I'm assuming that you're using the Jackson Data Binding model.

If so then there are two things to consider:

The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.

So, play around with:

objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor objects being wrapped in a single-property object. Use a wrapper to get around this:

class VendorWrapper
{
    Vendor vendor;

    // gettors, settors for vendor if you need them
}

Similarly, instead of using UNWRAP_ROOT_VALUES, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor, VendorWrapper object, you can define:

class VendorsWrapper
{
    List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();

    // gettors, settors for vendors if you need them
}

// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class); 

The object tree for VendorsWrapper is analogous to your JSON:

VendorsWrapper:
    vendors:
    [
        VendorWrapper
            vendor: Vendor,
        VendorWrapper:
            vendor: Vendor,
        ...
    ]

Finally, you might use the Jackson Tree Model to parse this into JsonNodes, discarding the outer node, and for each JsonNode in the ArrayNode, calling:

mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);

That might result in less code, but it seems no less clumsy than using two wrappers.

DLL load failed error when importing cv2

After spending too much time on this issue and trying out all different answers, here is what found:

  • The accepted answer by @thewaywewere is no longer applicable. I think this was applicable when opencv-python module still wasn't available.

  • This is indeed a bug in Anaconda 4.2 because they forgot to ship python3.dll. They have fixed this in next releases but unfortunately 4.2 is the last release with Python 3.5 as default. If you are stuck with Python 3.5 (for example VS2015 is only aware of versions up to 3.5) then you must manually download python3.dll as described in answer by @Ramesh-X.

  • If you can move on to Python 3.6 (which at present bit difficult if you are using OpenCV and VS2015) then just install latest Anaconda version and you don't have to deal with any of these.

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

How do I remove my IntelliJ license in 2019.3?

Not sure about older versions, but in 2016.2 removing the .key file(s) didn't work for me.

I'm using my JetBrains account and used the 'Remove License' button found at the bottom of the registration dialog. You can find this under the Help menu or from the startup dialog via Configure -> Manage License....

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

Mythical man month 10 lines per developer day - how close on large projects?

It's easy to get a couple of hundred lines of code per day. But try to get a couple of hundred quality lines of code per day and it's not so easy. Top that with debugging and going through days with little or no new lines per day and the average will come down rather quickly. I've spent weeks debugging difficult issues and the answer being 1 or 2 lines of code.

How to add an onchange event to a select box via javascript?

If you are using prototype.js then you can do this:

transport_select.observe('change', function(){
  toggleSelect(transport_select_id)
})

This eliminate (as hope) the problem in cross-browsers