Programs & Examples On #Onreadystatechange

using setTimeout on promise chain

In node.js you can also do the following:

const { promisify } = require('util')
const delay = promisify(setTimeout)

delay(1000).then(() => console.log('hello'))

How to configure CORS in a Spring Boot + Spring Security application?

You can finish this with only a Single Class, Just add this on your class path.

This one is enough for Spring Boot, Spring Security, nothing else. :

        @Component
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public class MyCorsFilterConfig implements Filter {

            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                final HttpServletResponse response = (HttpServletResponse) res;
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
                response.setHeader("Access-Control-Max-Age", "3600");
                if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
                    response.setStatus(HttpServletResponse.SC_OK);
                } else {
                    chain.doFilter(req, res);
                }
            }

            @Override
            public void destroy() {
            }

            @Override
            public void init(FilterConfig config) throws ServletException {
            }


        }

Uncaught TypeError: Cannot read property 'appendChild' of null

Use querySelector insted of getElementById();

var c = document.querySelector('#mainContent');
    c.appendChild(document.createElement('div'));

How to call a php script/function on a html button click

Of course AJAX is the solution,

To perform an AJAX request (for easiness we can use jQuery library).

Step1.

Include jQuery library in your web page

a. you can download jQuery library from jquery.com and keep it locally.

b. or simply paste the following code,

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Step 2.

Call a javascript function on button click

<button type="button" onclick="foo()">Click Me</button>

Step 3.

and finally the function

 function foo () {
      $.ajax({
        url:"test.php", //the page containing php script
        type: "POST", //request type
        success:function(result){
         alert(result);
       }
     });
 }

it will make an AJAX request to test.php when ever you clicks the button and alert the response.

For example your code in test.php is,

<?php echo 'hello'; ?>

then it will alert "hello" when ever you clicks the button.

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

Uncaught TypeError: Cannot read property 'value' of null

HTML : Pass the whole body inside on click

div class="calculate" id="calculate">
            <div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
        </div>

Then write the JavaScript code inside the function "myCode()"

function myCode()
{
    var bill = document.getElementById("currency").value ;

    var people_count = document.getElementById("number1").value;
    var select_value = document.getElementById("select").value;

    var calculate = document.getElementById("calculate");

    calculate.addEventListener("click" ,function()
    {
        console.log(bill);
        console.log(people_count);
        console.log(select_value);
    });
}

you will get your values I am using visual studio code editor

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

How to add header data in XMLHttpRequest when using formdata?

Check to see if the key-value pair is actually showing up in the request:

In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers

Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like: F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.

But as other answers have said:

xhttp.setRequestHeader(key, value);

should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

What is the cleanest way to get the progress of JQuery ajax request?

I tried about three different ways of intercepting the construction of the Ajax object:

  1. My first attempt used xhrFields, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste.
  2. My second attempt attached a progress function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise).
  3. My third attempt gave me direct access to the XHR for attaching handlers, but again required to much copy-and-paste code.
  4. I wrapped up my third attempt and replaced jQuery's ajax with my own. The only potential shortcoming is you can no longer use your own xhr() setting. You can allow for that by checking to see whether options.xhr is a function.

I actually call my promise.progress function xhrProgress so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.

(function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
{
var $originalAjax = jQuery.ajax;
jQuery.ajax = function( url, options )
{
    if( typeof( url ) === 'object' )
    {options = url;url = undefined;}
    options = options || {};

    // Instantiate our own.
    var xmlHttpReq = $.ajaxSettings.xhr();
    // Make it use our own.
    options.xhr = function()
    {return( xmlHttpReq );};

    var $newDeferred = $.Deferred();
    var $oldPromise = $originalAjax( url, options )
    .done( function done_wrapper( response, text_status, jqXHR )
    {return( $newDeferred.resolveWith( this, arguments ));})
    .fail( function fail_wrapper( jqXHR, text_status, error )
    {return( $newDeferred.rejectWith( this, arguments ));})
    .progress( function progress_wrapper()
    {
        window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
        return( $newDeferred.notifyWith( this, arguments ));
    });

    var $newPromise = $newDeferred.promise();
    // Extend our own.
    $newPromise.progress = function( handler )
    {
        xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
        {
            //window.console.debug( "download_progress", evt );
            handler.apply( this, [evt]);
        }, false );
        xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
        {
            //window.console.debug( "upload_progress", evt );
            handler.apply( this, [evt]);
        }, false );
        return( this );
    };
    return( $newPromise );
};
})( window, jQuery );

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

How to read a local text file?

Try creating two functions:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}

How to save an HTML5 Canvas as an image on a server?

I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:

1) I set up a form so I can use a POST method.

2) When the user is done drawing, he can click the "Save" button.

3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.

document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
document.forms["form1"].submit();

4) When the form is submited I have this small php script:

<?php 
$upload_dir = somehow_get_upload_dir();  //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);
?>

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

How to fix Error: listen EADDRINUSE while using nodejs?

I got:

Error: listen EADDRINUSE: address already in use :::8000

I was trying to look for the process listening to port 8000
and had no luck - there were none
(sudo netstat -nlp | grep 8000 ).

It turned out I had app.listen(8000) written twice in my script.

My assumption is that the interference was happening only in a short time when trying to run the script, so looking for processes listening to the port before and after error didn't show any.

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

load scripts asynchronously

You can use LABJS or RequreJS

Script loaders like LABJS, RequireJS will improve the speed and quality of your code.

How to read data From *.CSV file using javascript?

function CSVParse(csvFile)
{
    this.rows = [];

    var fieldRegEx = new RegExp('(?:\s*"((?:""|[^"])*)"\s*|\s*((?:""|[^",\r\n])*(?:""|[^"\s,\r\n]))?\s*)(,|[\r\n]+|$)', "g");   
    var row = [];
    var currMatch = null;

    while (currMatch = fieldRegEx.exec(this.csvFile))
    {
        row.push([currMatch[1], currMatch[2]].join('')); // concatenate with potential nulls

        if (currMatch[3] != ',')
        {
            this.rows.push(row);
            row = [];
        }

        if (currMatch[3].length == 0)
            break;
    }
}

I like to have the regex do as much as possible. This regex treats all items as either quoted or unquoted, followed by either a column delimiter, or a row delimiter. Or the end of text.

Which is why that last condition -- without it it would be an infinite loop since the pattern can match a zero length field (totally valid in csv). But since $ is a zero length assertion, it won't progress to a non match and end the loop.

And FYI, I had to make the second alternative exclude quotes surrounding the value; seems like it was executing before the first alternative on my javascript engine and considering the quotes as part of the unquoted value. I won't ask -- just got it to work.

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

How to send FormData objects with Ajax-requests in jQuery?

You can send the FormData object in ajax request using the following code,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
});

This is very similar to the accepted answer but an actual answer to the question topic. This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable.

The ajax method looks like this,

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
    //append some non-form data also
    formData.append('other_data',$("#someInputData").val());
    $.ajax({
        type: "POST",
        url: postDataUrl,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
           //process data
        },
        error: function(data, textStatus, jqXHR) {
           //process error msg
        },
});

You can also manually pass the form element inside the FormData object as a parameter like this

var formElem = $("#formId");
var formdata = new FormData(formElem[0]);

Hope it helps. ;)

Download file through an ajax call php

You can't download the file directly via ajax.

You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe and set the URL of the source of that iframe dynamically. This way you can download the file without refreshing the page.

Here is the code

$.ajax({
    url : "yourURL.php",
    type : "GET",
    success : function(data) {
        $("#iframeID").attr('src', 'downloadFileURL');
    }
});

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

A CORS POST request works from plain JavaScript, but why not with jQuery?

Another possibility is that setting dataType: json causes JQuery to send the Content-Type: application/json header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:

1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods and Access-Control-Allow-Headers.

2) Drop the dataType: json setting. JQuery should request Content-Type: application/x-www-form-urlencoded by default, but just to be sure, you can replace dataType: json with contentType: 'application/x-www-form-urlencoded'

XMLHttpRequest status 0 (responseText is empty)

The cause of your problems is that you are trying to do a cross-domain call and it fails.

If you're doing localhost development you can make cross-domain calls - I do it all the time.

For Firefox, you have to enable it in your config settings

signed.applets.codebase_principal_support = true

Then add something like this to your XHR open code:

  if (isLocalHost()){
    if (typeof(netscape) != 'undefined' && typeof(netscape.security) != 'undefined'){
      netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
  }

For IE, if I remember right, all you have to do is enable the browser's Security setting under "Miscellaneous → Access data sources across domains" to get it to work with ActiveX XHRs.

IE8 and above also added cross-domain capabilities to the native XmlHttpRequest objects, but I haven't played with those yet.

Ajax - 500 Internal Server Error

Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".

So log on the server and debug from there.

Empty responseText from XMLHttpRequest

Had a similar problem to yours. What we had to do is use the document.domain solution found here:

Ways to circumvent the same-origin policy

We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:

https://developer.mozilla.org/En/HTTP_access_control

Set a request header in JavaScript

For people looking this up now:

It seems that now setting the User-Agent header is allowed since Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of forbidden headers.

How to call a JavaScript function from PHP?

I always just use echo "<script> function(); </script>"; or something similar. you're not technically calling the function in PHP, but this as close as your going to get.

ssh: The authenticity of host 'hostname' can't be established

Run this in host server it's premonition issue

chmod -R 700 ~/.ssh

Capturing count from an SQL query

Use SqlCommand.ExecuteScalar() and cast it to an int:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

How to validate an OAuth 2.0 access token for a resource server?

Google way

Google Oauth2 Token Validation

Request:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg

Respond:

{
  "audience":"8819981768.apps.googleusercontent.com",
  "user_id":"123456789",
  "scope":"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
  "expires_in":436
} 

Microsoft way

Microsoft - Oauth2 check an authorization

Github way

Github - Oauth2 check an authorization

Request:

GET /applications/:client_id/tokens/:access_token

Respond:

{
  "id": 1,
  "url": "https://api.github.com/authorizations/1",
  "scopes": [
    "public_repo"
  ],
  "token": "abc123",
  "app": {
    "url": "http://my-github-app.com",
    "name": "my github app",
    "client_id": "abcde12345fghij67890"
  },
  "note": "optional note",
  "note_url": "http://optional/note/url",
  "updated_at": "2011-09-06T20:39:23Z",
  "created_at": "2011-09-06T17:26:27Z",
  "user": {
    "login": "octocat",
    "id": 1,
    "avatar_url": "https://github.com/images/error/octocat_happy.gif",
    "gravatar_id": "somehexcode",
    "url": "https://api.github.com/users/octocat"
  }
}

Amazon way

Login With Amazon - Developer Guide (Dec. 2015, page 21)

Request :

https://api.amazon.com/auth/O2/tokeninfo?access_token=Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...

Response :

HTTP/l.l 200 OK
Date: Fri, 3l May 20l3 23:22:l0 GMT 
x-amzn-RequestId: eb5be423-ca48-lle2-84ad-5775f45l4b09 
Content-Type: application/json 
Content-Length: 247 

{ 
  "iss":"https://www.amazon.com", 
  "user_id": "amznl.account.K2LI23KL2LK2", 
  "aud": "amznl.oa2-client.ASFWDFBRN", 
  "app_id": "amznl.application.436457DFHDH", 
  "exp": 3597, 
  "iat": l3ll280970
}

HTML favicon won't show on google chrome

Your html is completely wrong for starters, there should not be a div within your head section, nor after your body section. I suggest you look into correct html first before starting to work with favicons etc.

Creating a JSON dynamically with each input value using jquery

May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];
var elems = $("input[class=email]");

for (i = 0; i < elems.length; i += 1) {
    var id = this.getAttribute('title');
    var email = this.value;
    tmp = {
        'title': id,
        'email': email
    };

    obj.push(tmp);
}

Download a file with Android, and showing the progress in a ProgressDialog

Use Android Query library, very cool indeed.You can change it to use ProgressDialog as you see in other examples, this one will show progress view from your layout and hide it after completion.

File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
    public void callback(String url, File file, AjaxStatus status) {
        if (file != null) {
            // do something with file  
        } 
    }
});

How to do SVN Update on my project using the command line

svn update /path/to/working/copy

If subversion is not in your PATH, then of course

/path/to/subversion/svn update /path/to/working/copy

or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as

svn update

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Scroll to the top of the page after render in react.js

Looks like all the useEffect examples dont factor in you might want to trigger this with a state change.

const [aStateVariable, setAStateVariable] = useState(false);

const handleClick = () => {
   setAStateVariable(true);
}

useEffect(() => {
  if(aStateVariable === true) {
    window.scrollTo(0, 0)
  }
}, [aStateVariable])

How can I calculate the number of years between two dates?

let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)

com.sun.jdi.InvocationException occurred invoking method

I had the same issue once. In my case toString() method was badly created. TO be precise a static final variable was included in the toString method when a developer form my team was assigned code cleaning task and to add toString(), hashCode() code and equals() methods to domain objects where ever possible. but in of the classes because of over looking at it, he included final static variable that caused the "com.sun.jdi.InvocationException" this exception was visible on debugging only when I hovered over the object which has the exception.

How to recognize vehicle license / number plate (ANPR) from an image?

It maybe work looking at Character recoqnition software as there are many libraries out there that perform the same thing. I reading an image and storing it. Micrsoft office is able to read tiff files and return alphanumerics

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

How to check if two arrays are equal with JavaScript?

This method sucks, but I've left it here for reference so others avoid this path:


Using Option 1 from @ninjagecko worked best for me:

Array.prototype.equals = function(array) {
    return array instanceof Array && JSON.stringify(this) === JSON.stringify(array) ;
}

a = [1, [2, 3]]
a.equals([[1, 2], 3]) // false
a.equals([1, [2, 3]]) // true

It will also handle the null and undefined case, since we're adding this to the prototype of array and checking that the other argument is also an array.

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

What are the differences between delegates and events?

In addition to the syntactic and operational properties, there's also a semantical difference.

Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.

Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

ant warning: "'includeantruntime' was not set"

Chet Hosey wrote a nice explanation here:

Historically, Ant always included its own runtime in the classpath made available to the javac task. So any libraries included with Ant, and any libraries available to ant, are automatically in your build's classpath whether you like it or not.

It was decided that this probably wasn't what most people wanted. So now there's an option for it.

If you choose "true" (for includeantruntime), then at least you know that your build classpath will include the Ant runtime. If you choose "false" then you are accepting the fact that the build behavior will change between older versions and 1.8+.

As annoyed as you are to see this warning, you'd be even less happy if your builds broke entirely. Keeping this default behavior allows unmodified build files to work consistently between versions of Ant.

Adding Table rows Dynamically in Android

You can use an inflater with TableRow:

for (int i = 0; i < months; i++) {
    
    View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
        
    TextView textView = view.findViewById (R.id.title);
    
    textView.setText ("Text");
        
    tableLayout.addView (view);
    
}

Layout:

<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:paddingTop="15dp"
    android:paddingRight="15dp"
    android:paddingLeft="15dp"
    android:paddingBottom="10dp"
    >
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        />
    
</TableRow>

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

Updating and committing only a file's permissions using git version control

Not working for me.

The mode is true, the file perms have been changed, but git says there's no work to do.

git init
git add dir/file
chmod 440 dir/file
git commit -a

The problem seems to be that git recognizes only certain permission changes.

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.

http://localhost:8080/env-vars.html/

Just replace localhost with your Jenkins hostname, if its different

Angular2 - Radio Button Binding

On Radio button change get the value of the respective buttons with these lines

<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="dog" name="cat"  checked (change)="onItemChange($event)" value="Dog" />Dog</label>
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="cat" name="cat"   (change)="onItemChange($event)" value="Cat"  />Cat</label>

https://stackblitz.com/edit/angular-jpo2dm?embed=1&file=src/app/app.component.html

Where is jarsigner?

It's in the bin folder of your java JDK install (Java SE). If you only have the JRE installed you probably don't have it.

pip install mysql-python fails with EnvironmentError: mysql_config not found

OSX Mavericks

Due to changes within osx mavericks & xcode development tools you may get the error on installation

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

therefore use :

sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install mysql-python

What should I set JAVA_HOME environment variable on macOS X 10.6?

I am having MAC OS X(Sierra) 10.12.2.

I set JAVA_HOME to work on React Native(for Android apps) by following the following steps.

  • Open Terminal (Command+R, type Terminal, Hit ENTER).

  • Add the following lines to ~/.bash_profile. export JAVA_HOME=$(/usr/libexec/java_home)

  • Now run the following command. source ~/.bash_profile

  • You can check the exact value of JAVA_HOME by typing the following command. echo $JAVA_HOME

The value(output) returned will be something like below. /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

That's it.

Round button with text and icon in flutter

You can achieve that by using a FlatButton that contains a Column (for showing a text below the icon) or a Row (for text next to the icon), and then having an Icon Widget and a Text widget as children.

Here's an example:

class MyPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) =>
      Scaffold(
        appBar: AppBar(
          title: Text("Hello world"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                onPressed: () => {},
                color: Colors.orange,
                padding: EdgeInsets.all(10.0),
                child: Column( // Replace with a Row for horizontal icon + text
                  children: <Widget>[
                    Icon(Icons.add),
                    Text("Add")
                  ],
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => {},
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
}

This will produce the following:

Result

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Select all occurrences of selected word in VSCode

Select All Occurrences of Find Match editor.action.selectHighlights.

Ctrl+Shift+L

Cmd+Shift+L or Cmd+Ctrl+G on Mac

On localhost, how do I pick a free port number?

You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer.

However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.

Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.

I presume you will be using UDP for this?

Rank function in MySQL

The most straight forward solution to determine the rank of a given value is to count the number of values before it. Suppose we have the following values:

10 20 30 30 30 40
  • All 30 values are considered 3rd
  • All 40 values are considered 6th (rank) or 4th (dense rank)

Now back to the original question. Here is some sample data which is sorted as described in OP (expected ranks are added on the right):

+------+-----------+------+--------+    +------+------------+
| id   | firstname | age  | gender |    | rank | dense_rank |
+------+-----------+------+--------+    +------+------------+
|   11 | Emily     |   20 | F      |    |    1 |          1 |
|    3 | Grace     |   25 | F      |    |    2 |          2 |
|   20 | Jill      |   25 | F      |    |    2 |          2 |
|   10 | Megan     |   26 | F      |    |    4 |          3 |
|    8 | Lucy      |   27 | F      |    |    5 |          4 |
|    6 | Sarah     |   30 | F      |    |    6 |          5 |
|    9 | Zoe       |   30 | F      |    |    6 |          5 |
|   14 | Kate      |   35 | F      |    |    8 |          6 |
|    4 | Harry     |   20 | M      |    |    1 |          1 |
|   12 | Peter     |   20 | M      |    |    1 |          1 |
|   13 | John      |   21 | M      |    |    3 |          2 |
|   16 | Cole      |   25 | M      |    |    4 |          3 |
|   17 | Dennis    |   27 | M      |    |    5 |          4 |
|    5 | Scott     |   30 | M      |    |    6 |          5 |
|    7 | Tony      |   30 | M      |    |    6 |          5 |
|    2 | Matt      |   31 | M      |    |    8 |          6 |
|   15 | James     |   32 | M      |    |    9 |          7 |
|    1 | Adams     |   33 | M      |    |   10 |          8 |
|   18 | Smith     |   35 | M      |    |   11 |          9 |
|   19 | Zack      |   35 | M      |    |   11 |          9 |
+------+-----------+------+--------+    +------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for Sarah, you can use this query:

SELECT COUNT(id) + 1 AS rank, COUNT(DISTINCT age) + 1 AS dense_rank
FROM testdata
WHERE gender = (SELECT gender FROM testdata WHERE id = 6)
AND age < (SELECT age FROM testdata WHERE id = 6)

+------+------------+
| rank | dense_rank |
+------+------------+
|    6 |          5 |
+------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for All rows you can use this query:

SELECT testdata.id, COUNT(lesser.id) + 1 AS rank, COUNT(DISTINCT lesser.age) + 1 AS dense_rank
FROM testdata
LEFT JOIN testdata AS lesser ON lesser.age < testdata.age AND lesser.gender = testdata.gender
GROUP BY testdata.id

And here is the result (joined values are added on right):

+------+------+------------+    +-----------+-----+--------+
| id   | rank | dense_rank |    | firstname | age | gender |
+------+------+------------+    +-----------+-----+--------+
|   11 |    1 |          1 |    | Emily     |  20 | F      |
|    3 |    2 |          2 |    | Grace     |  25 | F      |
|   20 |    2 |          2 |    | Jill      |  25 | F      |
|   10 |    4 |          3 |    | Megan     |  26 | F      |
|    8 |    5 |          4 |    | Lucy      |  27 | F      |
|    6 |    6 |          5 |    | Sarah     |  30 | F      |
|    9 |    6 |          5 |    | Zoe       |  30 | F      |
|   14 |    8 |          6 |    | Kate      |  35 | F      |
|    4 |    1 |          1 |    | Harry     |  20 | M      |
|   12 |    1 |          1 |    | Peter     |  20 | M      |
|   13 |    3 |          2 |    | John      |  21 | M      |
|   16 |    4 |          3 |    | Cole      |  25 | M      |
|   17 |    5 |          4 |    | Dennis    |  27 | M      |
|    5 |    6 |          5 |    | Scott     |  30 | M      |
|    7 |    6 |          5 |    | Tony      |  30 | M      |
|    2 |    8 |          6 |    | Matt      |  31 | M      |
|   15 |    9 |          7 |    | James     |  32 | M      |
|    1 |   10 |          8 |    | Adams     |  33 | M      |
|   18 |   11 |          9 |    | Smith     |  35 | M      |
|   19 |   11 |          9 |    | Zack      |  35 | M      |
+------+------+------------+    +-----------+-----+--------+

Reactjs - setting inline styles correctly

Correct and more clear way is :

<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>

It is made more simple by following approach :

// JS
const styleObject = {
      "font-size" : "10px",
      "height" : "100px",
      "width" : "100%"
}

// HTML    
<div style={styleObject}> My inline Style </div>

Inline style attribute expects object. Hence its written in {}, and it becomes double {{}} as one is for default react standards.

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

How do I add a custom script to my package.json file that runs a javascript file?

I have created the following, and it's working on my system. Please try this:

package.json:

{
  "name": "test app",
  "version": "1.0.0",
  "scripts": {
    "start": "node script1.js"   
  }
}

script1.js:

console.log('testing')

From your command line run the following command:

npm start

Additional use case

My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.

 "scripts": {
    "start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w", 
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

PHP Date Format to Month Name and Year

I think your date data should look like 2013-08-14.

<?php
 $yrdata= strtotime('2013-08-14');
    echo date('M-Y', $yrdata);
 ?>
// Output is Aug-2013

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

Read file As String

this is working for me

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;

}

Simplest way to read json from a URL in java

It's very easy, using jersey-client, just include this maven dependency:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.25.1</version>
</dependency>

Then invoke it using this example:

String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);

Then use Google's Gson to parse the JSON:

Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);

How can I check if a file exists in Perl?

Use the below code. Here -f checks, it's a file or not:

print "File $base_path is exists!\n" if -f $base_path;

and enjoy

Atom menu is missing. How do I re-enable

Open Atom and press ALT key you are done.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Execution time of C program

Most of the simple programs have computation time in milli-seconds. So, i suppose, you will find this useful.

#include <time.h>
#include <stdio.h>

int main(){
    clock_t start = clock();
    // Execuatable code
    clock_t stop = clock();
    double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
    printf("Time elapsed in ms: %f", elapsed);
}

If you want to compute the runtime of the entire program and you are on a Unix system, run your program using the time command like this time ./a.out

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

C#: How to add subitems in ListView

Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different. we should add this

listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true; 
listView1.FullRowSelect = true;

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

If you are using the portable XAMPP installation and Windows 7, and, like me have the version after they removed the XAMPP shell from the control panel none of the suggested answers here will do you much good as the packages will not install.

The problem is with the config file. I found the correct settings after a lot of trial and error.

Simply pull up a command window in the \xampp\php directory and run

pear config-set doc_dir :\xampp\php\docs\PEAR
pear config-set cfg_dir :\xampp\php\cfg
pear config-set data_dir :\xampp\php\data\PEAR
pear config-set test_dir :\xampp\php\tests
pear config-set www_dir :\xampp\php\www

you will want to replace the ':' with the actual drive letter that your portable drive is running on at the moment. Unfortunately, this needs to be done any time this drive letter changes, but it did get the module I needed installed.

Failed to instantiate module error in Angular js

Such error happens when,

1. You misspell module name which you injected.
2. If you missed to include js file of that module.

Sometimes people write js file name instead of the module name which we are injecting.

In these cases what happens is angular tries to look for the module provided in the square bracket []. If it doesn't find the module, it throws error.

How can I count occurrences with groupBy?

If you're open to using a third-party library, you can use the Collectors2 class in Eclipse Collections to convert the List to a Bag using a Stream. A Bag is a data structure that is built for counting.

Bag<String> counted =
        list.stream().collect(Collectors2.countBy(each -> each));

Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));

System.out.println(counted.toStringOfItemToCount());

Output:

{World=1, Hello=2}

In this particular case, you can simply collect the List directly into a Bag.

Bag<String> counted = 
        list.stream().collect(Collectors2.toBag());

You can also create the Bag without using a Stream by adapting the List with the Eclipse Collections protocols.

Bag<String> counted = Lists.adapt(list).countBy(each -> each);

or in this particular case:

Bag<String> counted = Lists.adapt(list).toBag();

You could also just create the Bag directly.

Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");

A Bag<String> is like a Map<String, Integer> in that it internally keeps track of keys and their counts. But, if you ask a Map for a key it doesn't contain, it will return null. If you ask a Bag for a key it doesn't contain using occurrencesOf, it will return 0.

Note: I am a committer for Eclipse Collections.

How to execute an .SQL script file using c#

There are two points to considerate.

1) This source code worked for me:

private static string Execute(string credentials, string scriptDir, string scriptFilename)
{ 
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.WorkingDirectory = scriptDir;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.FileName = "sqlplus";
  process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
  process.StartInfo.CreateNoWindow = true;

  process.Start();
  string output = process.StandardOutput.ReadToEnd();
  process.WaitForExit();

  return output;
}

I set the working directory to the script directory, so that sub scripts within the script also work.

Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

2) You have to finalize your SQL script with the statement EXIT;

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

Round double value to 2 decimal places

For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

Finding height in Binary Search Tree

public int getHeight(Node node)
{
    if(node == null)
        return 0;

    int left_val = getHeight(node.left);
    int right_val = getHeight(node.right);
    if(left_val > right_val)
        return left_val+1;
    else
        return right_val+1;
}

BEGIN - END block atomic transactions in PL/SQL

Firstly, BEGIN..END are merely syntactic elements, and have nothing to do with transactions.

Secondly, in Oracle all individual DML statements are atomic (i.e. they either succeed in full, or rollback any intermediate changes on the first failure) (unless you use the EXCEPTIONS INTO option, which I won't go into here).

If you wish a group of statements to be treated as a single atomic transaction, you'd do something like this:

BEGIN
  SAVEPOINT start_tran;
  INSERT INTO .... ; -- first DML
  UPDATE .... ; -- second DML
  BEGIN ... END; -- some other work
  UPDATE .... ; -- final DML
EXCEPTION
  WHEN OTHERS THEN
    ROLLBACK TO start_tran;
    RAISE;
END;

That way, any exception will cause the statements in this block to be rolled back, but any statements that were run prior to this block will not be rolled back.

Note that I don't include a COMMIT - usually I prefer the calling process to issue the commit.


It is true that a BEGIN..END block with no exception handler will automatically handle this for you:

BEGIN
  INSERT INTO .... ; -- first DML
  UPDATE .... ; -- second DML
  BEGIN ... END; -- some other work
  UPDATE .... ; -- final DML
END;

If an exception is raised, all the inserts and updates will be rolled back; but as soon as you want to add an exception handler, it won't rollback. So I prefer the explicit method using savepoints.

pip3: command not found but python3-pip is already installed

Probably pip3 is installed in /usr/local/bin/ which is not in the PATH of the sudo (root) user. Use this instead

sudo /usr/local/bin/pip3 install virtualenv

PostgreSQL: How to make "case-insensitive" query

Use LOWER function to convert the strings to lower case before comparing.

Try this:

SELECT id 
  FROM groups
 WHERE LOWER(name)=LOWER('Administrator')

How can I position my jQuery dialog to center?

Could not get IE9 to center the dialog.

Fixed it by adding this to the css:

.ui-dialog {
    left:1%;
    right:1%;
}

Percent doesn't matter. Any small number worked.

Code for a simple JavaScript countdown timer?

Based on the solution presented by @Layton Everson I developed a counter including hours, minutes and seconds:

var initialSecs = 86400;
var currentSecs = initialSecs;

setTimeout(decrement,1000); 

function decrement() {
   var displayedSecs = currentSecs % 60;
   var displayedMin = Math.floor(currentSecs / 60) % 60;
   var displayedHrs = Math.floor(currentSecs / 60 /60);

    if(displayedMin <= 9) displayedMin = "0" + displayedMin;
    if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
    currentSecs--;
    document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
    if(currentSecs !== -1) setTimeout(decrement,1000);
}

What is the difference between "::" "." and "->" in c++

You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:

cout << (*kwadrat).val1;

Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:

cout << kwadrat->val1;

These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.

AngularJS Directive Restrict A vs E

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

Type : Usage

A = <div Doc></div>

C = <div class="Doc"></div>

E = <Doc data="book_data"></Doc>

M = <!--directive:Doc -->

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

How to create a link to another PHP page

echo "<a href='index.php'>Index Page</a>";

if you wanna use html tag like anchor tag you have to put in echo

Get size of an Iterable in Java

I would go for it.next() for the simple reason that next() is guaranteed to be implemented, while remove() is an optional operation.

E next()

Returns the next element in the iteration.

void remove()

Removes from the underlying collection the last element returned by the iterator (optional operation).

Implements vs extends: When to use? What's the difference?

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}

Multiple selector chaining in jQuery?

$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

How to check if a column exists before adding it to an existing table in PL/SQL?

All the metadata about the columns in Oracle Database is accessible using one of the following views.

user_tab_cols; -- For all tables owned by the user

all_tab_cols ; -- For all tables accessible to the user

dba_tab_cols; -- For all tables in the Database.

So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..

DECLARE
  v_column_exists number := 0;  
BEGIN
  Select count(*) into v_column_exists
    from user_tab_cols
    where upper(column_name) = 'ADD_TMS'
      and upper(table_name) = 'EMP';
      --and owner = 'SCOTT --*might be required if you are using all/dba views

  if (v_column_exists = 0) then
      execute immediate 'alter table emp add (ADD_TMS date)';
  end if;
end;
/

If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..

If you have file1.sql

alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;

And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

What is <=> (the 'Spaceship' Operator) in PHP 7?

The <=> ("Spaceship") operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1

Firebase Permission Denied

By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.


You can change the rules so that the database is only readable/writeable by authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

See the quickstart for the Firebase Database security rules.

But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.

Allow unauthenticated access to your database

The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.

Sign in the user before accessing the database

For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:

firebase.auth().signInAnonymously().catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

And then attach your listeners when the sign-in is detected

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var userRef = app.dataInfo.child(app.users);
    
    var useridRef = userRef.child(app.userid);
    
    useridRef.set({
      locations: "",
      theme: "",
      colorScheme: "",
      food: ""
    });

  } else {
    // User is signed out.
    // ...
  }
  // ...
});

How to change button text or link text in JavaScript?

Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

Add days to JavaScript Date

If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:

_x000D_
_x000D_
var nextWeek = moment().add(7, 'days');_x000D_
alert(nextWeek);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
_x000D_
_x000D_
_x000D_

Reference: http://momentjs.com/docs/#/manipulating/add/

Extract parameter value from url using regular expressions

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i

Javascript how to parse JSON array

The answer with the higher vote has a mistake. when I used it I find out it in line 3 :

var counter = jsonData.counters[i];

I changed it to :

var counter = jsonData[i].counters;

and it worked for me. There is a difference to the other answers in line 3:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
    var counter = jsonData[i].counters;
    console.log(counter.counter_name);
}

How to check if a python module exists without importing it

I came across this question while searching for a way to check if a module is loaded from the command line and would like to share my thoughts for the ones coming after me and looking for the same:

Linux/UNIX script file method: make a file module_help.py:

#!/usr/bin/env python

help('modules')

Then make sure it's executable: chmod u+x module_help.py

And call it with a pipe to grep:

./module_help.py | grep module_name

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Interactive method: in the console load python

>>> help('module_name')

If found quit reading by typing q
To exit the python interactive session press Ctrl + D

Windows script file method also Linux/UNIX compatible, and better overall:

#!/usr/bin/env python

import sys

help(sys.argv[1])

Calling it from the command like:

python module_help.py site  

Would output:

Help on module site:

NAME site - Append module search paths for third-party packages to sys.path.

FILE /usr/lib/python2.7/site.py

MODULE DOCS http://docs.python.org/library/site

DESCRIPTION
...
:

and you'd have to press q to exit interactive mode.

Using it unknown module:

python module_help.py lkajshdflkahsodf

Would output:

no Python documentation found for 'lkajshdflkahsodf'

and exit.

How to escape comma and double quote at same time for CSV file?

If you're using CSVWriter. Check that you don't have the option

.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)

When I removed it the comma was showing as expected and not treating it as new column

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How do I expand the output display to see more columns of a pandas DataFrame?

I used these settings when scale of data is high.

# environment settings: 
pd.set_option('display.max_column',None)
pd.set_option('display.max_rows',None)
pd.set_option('display.max_seq_items',None)
pd.set_option('display.max_colwidth', 500)
pd.set_option('expand_frame_repr', True)

You can refer to the documentation here

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

Restful API service

Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service

Scrolling a div with jQuery

jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link

and complete documentation can be found here

Generate an integer that is not among four billion given ones

Statistically informed algorithms solve this problem using fewer passes than deterministic approaches.

If very large integers are allowed then one can generate a number that is likely to be unique in O(1) time. A pseudo-random 128-bit integer like a GUID will only collide with one of the existing four billion integers in the set in less than one out of every 64 billion billion billion cases.

If integers are limited to 32 bits then one can generate a number that is likely to be unique in a single pass using much less than 10 MB. The odds that a pseudo-random 32-bit integer will collide with one of the 4 billion existing integers is about 93% (4e9 / 2^32). The odds that 1000 pseudo-random integers will all collide is less than one in 12,000 billion billion billion (odds-of-one-collision ^ 1000). So if a program maintains a data structure containing 1000 pseudo-random candidates and iterates through the known integers, eliminating matches from the candidates, it is all but certain to find at least one integer that is not in the file.

How to find indices of all occurrences of one string in another in JavaScript?

If you just want to find the position of all matches I'd like to point you to a little hack:

_x000D_
_x000D_
var haystack = 'I learned to play the Ukulele in Lebanon.',
    needle = 'le',
    splitOnFound = haystack.split(needle).map(function (culm)
    {
        return this.pos += culm.length + needle.length
    }, {pos: -needle.length}).slice(0, -1); // {pos: ...} – Object wich is used as this

console.log(splitOnFound);
_x000D_
_x000D_
_x000D_

It might not be applikable if you have a RegExp with variable length but for some it might be helpful.

This is case sensitive. For case insensitivity use String.toLowerCase function before.

conflicting types error when compiling c program using gcc

You have to declare your functions before main()

(or declare the function prototypes before main())

As it is, the compiler sees my_print (my_string); in main() as a function declaration.

Move your functions above main() in the file, or put:

void my_print (char *);
void my_print2 (char *);

Above main() in the file.

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.

How do I set the default locale in the JVM?

In the answers here, up to now, we find two ways of changing the JRE locale setting:

  • Programatically, using Locale.setDefault() (which, in my case, was the solution, since I didn't want to require any action of the user):

    Locale.setDefault(new Locale("pt", "BR"));
    
  • Via arguments to the JVM:

    java -jar anApp.jar -Duser.language=pt-BR
    

But, just as reference, I want to note that, on Windows, there is one more way of changing the locale used by the JRE, as documented here: changing the system-wide language.

Note: You must be logged in with an account that has Administrative Privileges.

  1. Click Start > Control Panel.

  2. Windows 7 and Vista: Click Clock, Language and Region > Region and Language.

    Windows XP: Double click the Regional and Language Options icon.

    The Regional and Language Options dialog box appears.

  3. Windows 7: Click the Administrative tab.

    Windows XP and Vista: Click the Advanced tab.

    (If there is no Advanced tab, then you are not logged in with administrative privileges.)

  4. Under the Language for non-Unicode programs section, select the desired language from the drop down menu.

  5. Click OK.

    The system displays a dialog box asking whether to use existing files or to install from the operating system CD. Ensure that you have the CD ready.

  6. Follow the guided instructions to install the files.

  7. Restart the computer after the installation is complete.

Certainly on Linux the JRE also uses the system settings to determine which locale to use, but the instructions to set the system-wide language change from distro to distro.

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Trust Store vs Key Store - creating with keytool

There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore. But in theory it's fine to use one and the same file for trust- and keystores.

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

How to run shell script on host from docker container?

You can use the pipe concept, but use a file on the host and fswatch to accomplish the goal to execute a script on the host machine from a docker container. Like so (Use at your own risk):

#! /bin/bash

touch .command_pipe
chmod +x .command_pipe

# Use fswatch to execute a command on the host machine and log result
fswatch -o --event Updated .command_pipe | \
            xargs -n1 -I "{}"  .command_pipe >> .command_pipe_log  &

 docker run -it --rm  \
   --name alpine  \
   -w /home/test \
   -v $PWD/.command_pipe:/dev/command_pipe \
   alpine:3.7 sh

rm -rf .command_pipe
kill %1

In this example, inside the container send commands to /dev/command_pipe, like so:

/home/test # echo 'docker network create test2.network.com' > /dev/command_pipe

On the host, you can check if the network was created:

$ docker network ls | grep test2
8e029ec83afe        test2.network.com                            bridge              local

What's the difference between the Window.Loaded and Window.ContentRendered events

This is not about the difference between Window.ContentRendered and Window.Loaded but about what how the Window.Loaded event can be used:

I use it to avoid splash screens in all applications which need a long time to come up.

    // initializing my main window
    public MyAppMainWindow()
    {
        InitializeComponent();

        // Set the event
        this.ContentRendered += MyAppMainWindow_ContentRendered;
    }

    private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
    {
        // ... comes up quick when the controls are loaded and rendered

        // unset the event
        this.ContentRendered -= MyAppMainWindow_ContentRendered;

        // ... make the time comsuming init stuff here
    }

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

In httpd.conf, search for "ServerName". It's usually commented out by default on Mac. Just uncomment it and fill it in. Make sure you also have the name/ip combo set in /etc/hosts.

What is the proper use of an EventEmitter?

TL;DR:

No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.

Answer:

No, you should not subscribe manually to it.

EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

This is stated really clear in EventEmitter's documentation.

Use by directives and components to emit custom Events.

What's wrong about using it?

Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

His comment is in line with Rob's comment long time ago.

So, how to use it properly?

Simply use it to emit events from your component. Take a look a the following example.

@Component({
    selector : 'child',
    template : `
        <button (click)="sendNotification()">Notify my parent!</button>
    `
})
class Child {
    @Output() notifyParent: EventEmitter<any> = new EventEmitter();
    sendNotification() {
        this.notifyParent.emit('Some value to send to the parent');
    }
}

@Component({
    selector : 'parent',
    template : `
        <child (notifyParent)="getNotification($event)"></child>
    `
})
class Parent {
    getNotification(evt) {
        // Do something with the notification (evt) sent by the child!
    }
}

How not to use it?

class MyService {
    @Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}

Stop right there... you're already wrong...

Hopefully these two simple examples will clarify EventEmitter's proper usage.

Set the layout weight of a TextView programmatically

You have to use TableLayout.LayoutParams with something like this:

TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));

The last parameter is the weight.

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

How do I delete unpushed git commits?

Do a git rebase -i FAR_ENOUGH_BACK and drop the line for the commit you don't want.

How to set focus on an input field after rendering?

To move focus to a newly created element, you can store the element's ID in the state and use it to set autoFocus. e.g.

export default class DefaultRolesPage extends React.Component {

    addRole = ev => {
        ev.preventDefault();
        const roleKey = this.roleKey++;
        this::updateState({
            focus: {$set: roleKey},
            formData: {
                roles: {
                    $push: [{
                        id: null,
                        name: '',
                        permissions: new Set(),
                        key: roleKey,
                    }]
                }
            }
        })
    }

    render() {
        const {formData} = this.state;

        return (
            <GridForm onSubmit={this.submit}>
                {formData.roles.map((role, idx) => (
                    <GridSection key={role.key}>
                        <GridRow>
                            <GridCol>
                                <label>Role</label>
                                <TextBox value={role.name} onChange={this.roleName(idx)} autoFocus={role.key === this.state.focus}/>
                            </GridCol>
                        </GridRow>
                    </GridSection>
                ))}
            </GridForm>
        )
    }
}

This way none of the textboxes get focus on page load (like I want), but when you press the "Add" button to create a new record, then that new record gets focus.

Since autoFocus doesn't "run" again unless the component gets remounted, I don't have to bother unsetting this.state.focus (i.e. it won't keep stealing focus back as I update other states).

How do I get the opposite (negation) of a Boolean in Python?

The accepted answer here is the most correct for the given scenario.

It made me wonder though about simply inverting a boolean value in general. It turns out the accepted solution here works as one liner, and there's another one-liner that works as well. Assuming you have a variable "n" that you know is a boolean, the easiest ways to invert it are:

n = n is False

which was my original solution, and then the accepted answer from this question:

n = not n

The latter IS more clear, but I wondered about performance and hucked it through timeit - and it turns out at n = not n is also the FASTER way to invert the boolean value.

Newline in markdown table?

Just for those that are trying to do this on Jira. Just add \\ at the end of each line and a new line will be created:

|Something|Something else \\ that's rather long|Something else|

Will render this:

enter image description here

Source: Text breaks on Jira

Paging UICollectionView by cells, not screen

final class PagingFlowLayout: UICollectionViewFlowLayout {
    private var currentIndex = 0

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        let count = collectionView!.numberOfItems(inSection: 0)
        let currentAttribute = layoutAttributesForItem(
            at: IndexPath(item: currentIndex, section: 0)
            ) ?? UICollectionViewLayoutAttributes()

        let direction = proposedContentOffset.x > currentAttribute.frame.minX
        if collectionView!.contentOffset.x + collectionView!.bounds.width < collectionView!.contentSize.width || currentIndex < count - 1 {
            currentIndex += direction ? 1 : -1
            currentIndex = max(min(currentIndex, count - 1), 0)
        }

        let indexPath = IndexPath(item: currentIndex, section: 0)
        let closestAttribute = layoutAttributesForItem(at: indexPath) ?? UICollectionViewLayoutAttributes()

        let centerOffset = collectionView!.bounds.size.width / 2
        return CGPoint(x: closestAttribute.center.x - centerOffset, y: 0)
    }
}

What is the difference between signed and unsigned variables?

Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.

Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive and zero.

Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.

For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127.

Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.

In a bootstrap responsive page how to center a div

For actual version of Bootstrap 4.3.1 use

Style

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style type="text/css">
html, body {
    height: 100%;
}
</style>

Code

<div class="h-100 d-flex justify-content-center">
<div class="jumbotron my-auto">
<!-- example content -->
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Title</h4>
<p>Desc</p>
</div>
<!-- ./example content -->
</div>
</div

How to check if current thread is not main thread

Summarizing the solutions, I think that's the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

How to print the ld(linker) search path

I'm not sure that there is any option for simply printing the full effective search path.

But: the search path consists of directories specified by -L options on the command line, followed by directories added to the search path by SEARCH_DIR("...") directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:

If you're invoking ld directly:

  • The -L options are whatever you've said they are.
  • To see the linker script, add the --verbose option. Look for the SEARCH_DIR("...") directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld -- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)

If you're linking via gcc:

  • You can pass the -v option to gcc so that it shows you how it invokes the linker. In fact, it normally does not invoke ld directly, but indirectly via a tool called collect2 (which lives in one of its internal directories), which in turn invokes ld. That will show you what -L options are being used.
  • You can add -Wl,--verbose to the gcc options to make it pass --verbose through to the linker, to see the linker script as described above.

Use a URL to link to a Google map with a marker on it

This format works, but it doesn't seem to be an official way of doing so

http://maps.google.com/maps?q=loc:36.26577,-92.54324

Also you may want to take a look at this. They have a few answers and seem to indicate that this is the new method:

http://maps.google.com/maps?&z=10&q=36.26577+-92.54324&ll=36.26577+-92.54324

How can I avoid running ActiveRecord callbacks?

The only way to prevent all after_save callbacks is to have the first one return false.

Perhaps you could try something like (untested):

class MyModel < ActiveRecord::Base
  attr_accessor :skip_after_save

  def after_save
    return false if @skip_after_save
    ... blah blah ...
  end
end

...

m = MyModel.new # ... etc etc
m.skip_after_save = true
m.save

How to make a hyperlink in telegram without using bots?

Try this link format: https://t.me/[YourUserName]

I was looking for such a thing, BUT with text in (like the one that WhatsApp got)

Manually raising (throwing) an exception in Python

Another way to throw an exceptions is assert. You can use assert to verify a condition is being fulfilled if not then it will raise AssertionError. For more details have a look here.

def avg(marks):
    assert len(marks) != 0,"List is empty."
    return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

"query function not defined for Select2 undefined error"

This issue boiled down to how I was building my select2 select box. In one javascript file I had...

$(function(){
  $(".select2").select2();
});

And in another js file an override...

$(function(){
    var employerStateSelector = 
                $("#registration_employer_state").select2("destroy");
    employerStateSelector.select2({
    placeholder: 'Select a State...'
    });
});

Moving the second override into a window load event resolved the issue.

$( window ).load(function() {
  var employerStateSelector = 
              $("#registration_employer_state").select2("destroy");
  employerStateSelector.select2({
    placeholder: 'Select a State...'
  });
});

This issue blossomed inside a Rails application

right click context menu for datagridview

You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.

Then use a ContextMenu object to display you popup menu, customised for the current row.

Here's a quick and dirty example of what I mean...

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenu m = new ContextMenu();
        m.MenuItems.Add(new MenuItem("Cut"));
        m.MenuItems.Add(new MenuItem("Copy"));
        m.MenuItems.Add(new MenuItem("Paste"));

        int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;

        if (currentMouseOverRow >= 0)
        {
            m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
        }

        m.Show(dataGridView1, new Point(e.X, e.Y));

    }
}

How to code a BAT file to always run as admin mode?

convert your batch file into .exe with this tool: http://www.battoexeconverter.com/ then you can run it as administrator

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

Multidimensional Array [][] vs [,]

In the first instance you are trying to create what is called a jagged array.

double[][] ServicePoint = new double[10][9].

The above statement would have worked if it was defined like below.

double[][] ServicePoint = new double[10][]

what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.

enter image description here

http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx

The second one is basically a two dimensional array and the syntax is correct and acceptable.

  double[,] ServicePoint = new double[10,9];//<-ok (2)

And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error

Correct usage would be

ServicePoint[0][2] ,Refers to an item on the first row ,third column.

Pictorial rep of your two dimensional array

enter image description here

How do I format a Microsoft JSON date?

This uses a regular expression, and it works as well:

var date = new Date(parseInt(/^\/Date\((.*?)\)\/$/.exec(jsonDate)[1], 10));

javascript date + 7 days

Two problems here:

  1. seven_date is a number, not a date. 29 + 7 = 36
  2. getMonth returns a zero based index of the month. So adding one just gets you the current month number.

Position a CSS background image x pixels from the right?

Better for all background: url('../images/bg-menu-dropdown-top.png') left 20px top no-repeat !important;

PHP JSON String, escape Double Quotes for JS output

Another way would be to encode the quotes using htmlspecialchars:

$json_array = array(
    'title' => 'Example string\'s with "special" characters'
);

$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');

MySQL - DATE_ADD month interval

BETWEEN ... AND

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0.

The important part here is EQUAL to max., which 1st of July is.

Lightweight workflow engine for Java

I would like to add my comments. When you choose a ready engine, such as jBPM, Activity and others (there are plenty of them), then you have to spend some time learning the system itself, this may not be an easy task. Especially, when you need only to automate small piece of code.

Then, when an issue occurs you have to deal with the vendor's support, which is not as speedy as you would imagine. Even pay for some consultancy.

And, last, a most important reason, you have to develop in the ecosystem of the engine. Although, the vendors tend to say that their system are flexible to be incorporated into any systems, this may not be case. Eventually you end up re-writing your application to match with the BPM ecosystem.

bootstrap popover not showing on top of all elements

  $('[data-toggle="popover"]').popover({
        placement: 'top',
        boundary: 'viewport',
        trigger: 'hover',
        html: true,
        content: function () {
            let content = $(this).attr("data-popover-content");
            return $(content).html();
        }
    });,



`placement`: 'top',
`boundary`: 'viewport'
both needed

Select last N rows from MySQL

You can do it with a sub-query:

SELECT * FROM (
    SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC

This will select the last 50 rows from table, and then order them in ascending order.

Are lists thread-safe?

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

Font awesome is not showing icon

you need to put font-awesome file in css folder and change

href="../css/font-awesome.css" to href="css/font-awesome.css"

One more thing You can Replace this Font-awesome css File And and try this one

_x000D_
_x000D_
.social-media{
  list-style-type: none;
  padding: 0px;
  margin: 0px;
}

.social-media li .fa{ 
  background: #fff;
  color: #262626;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  text-align:center;
  line-height:50px; 
}

.social-media .fa:hover { 
  box-shadow: 5px 5px 5px #000; 
}

.social-media .fa.fa-twitter:hover{
  background:#55acee;
  color:#fff;
 
}

.social-media .fa.fa-facebook:hover{
  background:#3b5998;
  color:#fff;
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<ul class="social-media">
  <li><i class="fa fa-twitter fa-2x"></i></li>
  <li><i class="fa fa-facebook fa-2x"></i></li>
 
</ul>
_x000D_
_x000D_
_x000D_

PHP - Check if two arrays are equal

Use php function array_diff(array1, array2);

It will return a the difference between arrays. If its empty then they're equal.

example:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3'
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value4'
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print array = (0 => ['c'] => 'value4' ) 

Example 2:

$array1 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$array2 = array(
    'a' => 'value1',

    'b' => 'value2',

    'c' => 'value3',
 );

$diff = array_diff(array1, array2);

var_dump($diff); 

//it will print empty; 

Get SELECT's value and text in jQuery

You can do like this, to get the currently selected value:

$('#myDropdownID').val();

& to get the currently selected text:

$('#myDropdownID:selected').text();

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to add super privileges to mysql database?

On Centos 5 I was getting all sorts of errors trying to make changes to some variable values from the MySQL shell, after having logged in with the proper uid and pw (with root access). The error that I was getting was something like this:

mysql> -- Set some variable value, for example
mysql> SET GLOBAL general_log='ON';
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In a moment of extreme serendipity I did the following:

OS-Shell> sudo mysql                          # no DB uid, no DB pw

Kindly note that I did not provide the DB uid and password

mysql> show variables;
mysql> -- edit the variable of interest to the desired value, for example
mysql> SET GLOBAL general_log='ON';

It worked like a charm

Clearing the terminal screen?

Another kick at the can:

void setup(){     /*123456789 123456789 123456789 123456789 123*/
  String newRow="\n|________________________________________";
  String scrSiz="\n|\n|\n|\n|\n|\n|\n|\n|\n|\t";
  Serial.begin(115200);  
       // this baudrate should not have flicker but it does as seen when
       // the persistence of vision threshold is insufficiently exceeded
       // 115200 baud should display ~10000 cps or a char every 0.1 msec
       // each 'for' loop iteration 'should' print 65 chars. in < 7 msec
       // Serial.print() artifact inefficiencies are the flicker culprit
       // unfortunately '\r' does not render in the IDE's Serial Monitor

  Serial.print( scrSiz+"\n|_____ size screen vertically to fit _____"  );
  for(int i=0;i<30;i++){
     delay(1000); 
     Serial.print((String)scrSiz +i +"\t" + (10*i) +newRow);}
}
void loop(){}

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

Send inline image in email

An even more minimalistic example:

var linkedResource = new LinkedResource(@"C:\Image.jpg", MediaTypeNames.Image.Jpeg);

// My mail provider would not accept an email with only an image, adding hello so that the content looks less suspicious.
var htmlBody = $"hello<img src=\"cid:{linkedResource.ContentId}\"/>";
var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(linkedResource);

var mailMessage = new MailMessage
{
    From = new MailAddress("[email protected]"),
    To = { "[email protected]" },
    Subject = "yourSubject",
    AlternateViews = { alternateView }
};

var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);

Using C++ filestreams (fstream), how can you determine the size of a file?

I'm a novice, but this is my self taught way of doing it:

ifstream input_file("example.txt", ios::in | ios::binary)

streambuf* buf_ptr =  input_file.rdbuf(); //pointer to the stream buffer

input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()

size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.

How to make a gap between two DIV within the same column

Please pay attention to the comments after the 2 lines.

.box1 {
    display: block;
    padding: 10px;
    margin-bottom: 100px; /* SIMPLY SET THIS PROPERTY AS MUCH AS YOU WANT. This changes the space below box1 */
    text-align: justify;
}

.box2 {
    display: block;
    padding: 10px;
    text-align: justify;
    margin-top: 100px; /* OR ADD THIS LINE AND SET YOUR PROPER SPACE as the space above box2 */
}

What is the default database path for MongoDB?

I depends on the version and the distro.

For example the default download pre-2.2 from the MongoDB site uses: /data/db but the Ubuntu install at one point used to use: var/lib/mongodb.

I think these have been standardised now so that 2.2+ will only use data/db whether it comes from direct download on the site or from the repos.

asp.net Button OnClick event not firing

Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button. this should work

Polynomial time and exponential time

polynomial time O(n)^k means Number of operations are proportional to power k of the size of input

exponential time O(k)^n means Number of operations are proportional to the exponent of the size of input

Only mkdir if it does not exist

Try using this:-

mkdir -p dir;

NOTE:- This will also create any intermediate directories that don't exist; for instance,

Check out mkdir -p

or try this:-

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$Message" 1>&2
fi

simple HTTP server in Java using only Java SE API

Try this https://github.com/devashish234073/Java-Socket-Http-Server/blob/master/README.md

This API has creates an HTTP server using sockets.

  1. It gets a request from the browser as text
  2. Parses it to retrieve URL info, method, attributes, etc.
  3. Creates dynamic response using the URL mapping defined
  4. Sends the response to the browser.

For example the here's how the constructor in the Response.java class converts a raw response into an http response:

public Response(String resp){
    Date date = new Date();
    String start = "HTTP/1.1 200 OK\r\n";
    String header = "Date: "+date.toString()+"\r\n";
    header+= "Content-Type: text/html\r\n";
    header+= "Content-length: "+resp.length()+"\r\n";
    header+="\r\n";
    this.resp=start+header+resp;
}

How does python numpy.where() work?

np.where returns a tuple of length equal to the dimension of the numpy ndarray on which it is called (in other words ndim) and each item of tuple is a numpy ndarray of indices of all those values in the initial ndarray for which the condition is True. (Please don't confuse dimension with shape)

For example:

x=np.arange(9).reshape(3,3)
print(x)
array([[0, 1, 2],
      [3, 4, 5],
      [6, 7, 8]])
y = np.where(x>4)
print(y)
array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))


y is a tuple of length 2 because x.ndim is 2. The 1st item in tuple contains row numbers of all elements greater than 4 and the 2nd item contains column numbers of all items greater than 4. As you can see, [1,2,2,2] corresponds to row numbers of 5,6,7,8 and [2,0,1,2] corresponds to column numbers of 5,6,7,8 Note that the ndarray is traversed along first dimension(row-wise).

Similarly,

x=np.arange(27).reshape(3,3,3)
np.where(x>4)


will return a tuple of length 3 because x has 3 dimensions.

But wait, there's more to np.where!

when two additional arguments are added to np.where; it will do a replace operation for all those pairwise row-column combinations which are obtained by the above tuple.

x=np.arange(9).reshape(3,3)
y = np.where(x>4, 1, 0)
print(y)
array([[0, 0, 0],
   [0, 0, 1],
   [1, 1, 1]])

How to set the UITableView Section title programmatically (iPhone/iPad)?

Use the UITableViewDataSource method

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Zooming MKMapView to fit annotation pins?

You've got it right.

Find your maximum and minimum latitudes and longitudes, apply some simple arithmetic, and use MKCoordinateRegionMake.

For iOS 7 and above, use showAnnotations:animated:, from MKMapView.h:

// Position the map such that the provided array of annotations are all visible to the fullest extent possible. 
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

Importing CSV data using PHP/MySQL

i think the main things to remember about parsing csv is that it follows some simple rules:

a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

have a read of this post to see what i am talking about

it's actually very easy to do once you have the hang of it and becomes very useful.

Google Chrome redirecting localhost to https

Piggybacking off Adiyat Mubarak

Could not hard refresh as it was just refreshing on https. Follows some of the same steps.

1. Open chrome developer tools (ctrl + shift + i)
2. Network Tab at the top
3. Click Disable cache checkbox at the top (right under network tab for me).
4. Refresh page (while the developer tools is still open)

Global Angular CLI version greater than local version

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

Then in your Local project package:

rm -rf node_modules dist 
npm install --save-dev @angular/cli@latest
npm i 
ng update @angular/cli 
ng update @angular/core
npm install --save-dev @angular-devkit/build-angular

Was getting below error Error: Unexpected end of JSON input Unexpected end of JSON input Above steps helped from this post Can't update angular to version 6

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

How to get first N number of elements from an array

With LInQer you can do:

Enumerable.from(list).take(3).toArray();

Structs in Javascript

I made a small library to define struct if you work with ES6 compatibility.

It is a JKT parser you may checkout the project repository here JKT Parser

For an example you may create your struct like this

const Person = jkt`
    name: String
    age: Number
`

const someVar = Person({ name: "Aditya", age: "26" })

someVar.name // print "Aditya"
someVar.age // print 26 (integer)

someVar.toJSON() // produce json object with defined schema 

Twitter bootstrap scrollable modal

In case of using .modal {overflow-y: auto;}, would create additional scroll bar on the right of the page, when body is already overflowed.

The work around for this is to remove overflow from the body tag temporarily and set modal overflow-y to auto.

Example:

$('.myModalSelector').on('show.bs.modal', function () {

        // Store initial body overflow value
        _initial_body_overflow = $('body').css('overflow');

        // Let modal be scrollable
        $(this).css('overflow-y', 'auto');
        $('body').css('overflow', 'hidden');


    }).on('hide.bs.modal', function () {

        // Reverse previous initialization
        $(this).css('overflow-y', 'hidden');
        $('body').css('overflow', _initial_body_overflow);
});

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

Match whitespace but not newlines

The below regex would match white spaces but not of a new line character.

(?:(?!\n)\s)

DEMO

If you want to add carriage return also then add \r with the | operator inside the negative lookahead.

(?:(?![\n\r])\s)

DEMO

Add + after the non-capturing group to match one or more white spaces.

(?:(?![\n\r])\s)+

DEMO

I don't know why you people failed to mention the POSIX character class [[:blank:]] which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).

DEMO

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

It's all in your things.size() type. It isn't int, but size_t (it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int for x86_32.

Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.

It would be correct to write it like

for (size_t i = 0; i < things.size(); ++i) { /**/ }

or even faster

for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }

Change UITableView height dynamically

for resizing my table I went with this solution in my tableview controller witch is perfectly fine:

[objectManager getObjectsAtPath:self.searchURLString
                         parameters:nil
                            success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                NSArray* results = [mappingResult array];
                                self.eventArray = results;
                                NSLog(@"Events number at first: %i", [self.eventArray count]);
                                CGRect newFrame = self.activityFeedTableView.frame;
                                newFrame.size.height = self.cellsHeight + 30.0;
                                self.activityFeedTableView.frame = newFrame;

                                self.cellsHeight = 0.0;

                            }
                            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:[error localizedDescription]
                                                                               delegate:nil
                                                                      cancelButtonTitle:@"OK"
                                                                      otherButtonTitles:nil];
                                [alert show];
                                NSLog(@"Hit error: %@", error);
                            }];

The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?

The openssl extension is required for SSL/TLS protection

enter image description here You are running Composer with SSL/TLS protection disabled.

 composer config --global disable-tls true
 composer config --global disable-tls false

Password must have at least one non-alpha character

An expression like this:

[a-zA-Z]*[0-9\+\*][a-zA-Z0-9\+\*]*

should work just fine (obviously insert any additional special characters you want to allow or use ^ operator to match anything except letters/numbers); no need to use complicated lookarounds. This approach makes sense if you only want to allow a certain subset of special characters that you know are "safe", and disallow all others.

If you want to include all special characters except certain ones which you know are "unsafe", then it makes sense to use something like:

\w[^\\]*[^a-zA-Z\\][^\\]*

In this case, you are explicitly disallowing backslashes in your password and allowing any combination with at least one non-alphabetic character otherwise.

The expression above will match any string containing letters and at least one number or +,*. As for the "length of 8" requirement, theres really no reason to check that using regex.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

One main reason that recursive mutexes are useful is in case of accessing the methods multiple times by the same thread. For example, say if mutex lock is protecting a bank A/c to withdraw, then if there is a fee also associated with that withdrawal, then the same mutex has to be used.

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

Split a vector into chunks

Credit to @Sebastian for this function

chunk <- function(x,y){
         split(x, factor(sort(rank(row.names(x))%%y)))
         }

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

Pattern to match at least 1 upper case character, 1 digit and any special characters and the length between 8 to 63.

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]{8,63}$"

This pattern was used for JAVA programming.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

As @fijaaron says,

  1. GRANT ALL does not imply GRANT FILE
  2. GRANT FILE only works with *.*

So do

GRANT FILE ON *.* TO user;

What is the time complexity of indexing, inserting and removing from common data structures?

Information on this topic is now available on Wikipedia at: Search data structure

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

 * The cost to add or delete an element into a known location in the list 
   (i.e. if you have an iterator to the location) is O(1). If you don't 
   know the location, then you need to traverse the list to the location
   of deletion/insertion, which takes O(n) time. 

** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
   arbitrary element.

Map over object preserving keys

A mix fix for the underscore map bug :P

_.mixin({ 
    mapobj : function( obj, iteratee, context ) {
        if (obj == null) return [];
        iteratee = _.iteratee(iteratee, context);
        var keys = obj.length !== +obj.length && _.keys(obj),
            length = (keys || obj).length,
            results = {},
            currentKey;
        for (var index = 0; index < length; index++) {
          currentKey = keys ? keys[index] : index;
          results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        if ( _.isObject( obj ) ) {
            return _.object( results ) ;
        } 
        return results;
    }
}); 

A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function

or simply as me used it as a mixin

_.mapobj ( options , function( val, key, list ) 

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

How to send a html email with the bash command "sendmail"?

I understand you asked for sendmail but why not use the default mail? It can easily send html emails.

Works on: RHEL 5.10/6.x & CentOS 5.8

Example:

cat ~/campaigns/release-status.html | mail -s "$(echo -e "Release Status [Green]\nContent-Type: text/html")" [email protected] -v

CodeShare: http://www.codeshare.io/8udx5

Tensorflow image reading & display

(Can't comment, not enough reputation, but here is a modified version that worked for me)

To @HamedMP error about the No default session is registered you can use InteractiveSession to get rid of this error: https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession

And to @NumesSanguis issue with Image.show, you can use the regular PIL .show() method because fromarray returns an image object.

I do both below (note I'm using JPEG instead of PNG):

import tensorflow as tf
import numpy as np
from PIL import Image

filename_queue = tf.train.string_input_producer(['my_img.jpg']) #  list of files to read

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.

init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
    sess.run(init_op)

# Start populating the filename queue.

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

for i in range(1): #length of your filename list
  image = my_img.eval() #here is your image Tensor :) 

Image.fromarray(np.asarray(image)).show()

coord.request_stop()
coord.join(threads)

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

How do I get the fragment identifier (value after hash #) from a URL?

Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);

How to generate a core dump in Linux on a segmentation fault?

To check where the core dumps are generated, run:

sysctl kernel.core_pattern

or:

cat /proc/sys/kernel/core_pattern

where %e is the process name and %t the system time. You can change it in /etc/sysctl.conf and reloading by sysctl -p.

If the core files are not generated (test it by: sleep 10 & and killall -SIGSEGV sleep), check the limits by: ulimit -a.

If your core file size is limited, run:

ulimit -c unlimited

to make it unlimited.

Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:

Segmentation fault: 11 (core dumped)

See also: core dumped - but core file is not in current directory?


Ubuntu

In Ubuntu the core dumps are handled by Apport and can be located in /var/crash/. However, it is disabled by default in stable releases.

For more details, please check: Where do I find the core dump in Ubuntu?.

macOS

For macOS, see: How to generate core dumps in Mac OS X?

Could not autowire field in spring. why?

In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)

Can JavaScript connect with MySQL?

You can send AJAX requests to some server-side RESTful wrappers for MySQL, such as DBSlayer, PhpRestSQL or AlsoSQL (for Drizzle, a fork of MySQL).

"error: assignment to expression with array type error" when I assign a struct field (C)

typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

[----------------------------,------------------------------,----]
 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails

s1.name = "Paulo";

because the compiler knows that s1.name is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(s1.name,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with

[Paulo0----------------------,Rossi0-------------------------,0001]

strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create

[----,----,----]

This will now work because you are filling the struct with pointers.

s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this

[---4,--10,---1]

Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.

How can I make Jenkins CI with Git trigger on pushes to master?

In my current organization, we don't do this in master but do do it on both develop and release/ branches (we are using Git Flow), in order to generate snapshot builds.

As we are using a multi branch pipeline, we do this in the Jenkinsfile with the when{} syntax...

stage {
    when { 
        expression { 
            branch 'develop'
        }
    }
}

This is detailed in this blog post: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/#longer-pipeline

How do I set the value property in AngularJS' ng-options?

It is always painful for developers to with ng-options. For example: Getting an empty/blank selected value in the select tag. Especially when dealing with JSON objects in ng-options, it becomes more tedious. Here I have done some exercises on that.

Objective: Iterate array of JSON objects through ng-option and set selected first element.

Data:

someNames = [{"id":"1", "someName":"xyz"}, {"id":"2", "someName":"abc"}]

In the select tag I had to show xyz and abc, where xyz must be selected without much effort.

HTML:

<pre class="default prettyprint prettyprinted" style=""><code>
    &lt;select class="form-control" name="test" style="width:160px"    ng-options="name.someName for name in someNames" ng-model="testModel.test" ng-selected = "testModel.test = testModel.test || someNames[0]"&gt;
&lt;/select&gt;
</code></pre>

By above code sample, you might get out of this exaggeration.

Another reference:

Select distinct values from a table field

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

How to get error information when HttpWebRequest.GetResponse() fails

Is this possible using HttpWebRequest and HttpWebResponse?

You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.

So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

How to Find the Default Charset/Encoding in Java?

check

System.getProperty("sun.jnu.encoding")

it seems to be the same encoding as the one used in your system's command line.

Opening Android Settings programmatically

I used the code from the most upvoted answer:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.

The answer for 2020 and beyond (in Kotlin):

startActivity(Intent(Settings.ACTION_SETTINGS))

It works in my app, should also be working in yours without any unwanted consequences.

How to insert a file in MySQL database?

File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

Why shouldn't `&apos;` be used to escape single quotes?

If you need to write semantically correct mark-up, even in HTML5, you must not use &apos; to escape single quotes. Although, I can imagine you actually meant apostrophe rather then single quote.

single quotes and apostrophes are not the same, semantically, although they might look the same.

Here's one apostrophe.

Use &#39; to insert it if you need HTML4 support. (edited)

In British English, single quotes are used like this:

"He told me to 'give it a try'", I said.

Quotes come in pairs. You can use:

<p><q>He told me to <q>give it a try</q></q>, I said.<p>

to have nested quotes in a semantically correct way, deferring the substitution of the actual characters to the rendering engine. This substitution can then be affected by CSS rules, like:

q {
  quotes: '"' '"' '<' '>';
} 

An old but seemingly still relevant article about semantically correct mark-up: The Trouble With EM ’n EN (and Other Shady Characters).

(edited) This used to be:

Use ’ to insert it if you need HTML4 support.

But, as @James_pic pointed out, that is not the straight single quote, but the "Single curved quote, right".

Image UriSource and Data Binding

You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

And the class property is simply this

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            image.EndInit();
        }
        catch{
            return DependencyProperty.UnsetValue;
        }

        return image;
    }
}

I suppose it may be a little more work than the value converter, but it is another option.

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

MySQL - How to select data by string length

Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH() and CHARACTER_LENGTH() as well.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Other than the options mentioned above, there are a couple of other Solutions.

1. Modifying the project file (.CsProj) file

MSBuild supports the EnvironmentName Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.

Simply open the project file (*.csProj) and add the following XML.

<!-- Custom Property Group added to add the Environment name during publish
  The EnvironmentName property is used during the publish for the Environment variable in web.config
  -->
  <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
    <EnvironmentName>Development</EnvironmentName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
    <EnvironmentName>Production</EnvironmentName>
  </PropertyGroup>

Above code would add the environment name as Development for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production in the generated web.config file. More details here

2. Adding the EnvironmentName Property in the publish profiles.

We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

3. Command line options using dotnet publish

Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.

dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to reload a page using JavaScript

location.href = location.href;

How to create correct JSONArray in Java using JSONObject

I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.

String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);

Hope this helps :)

Retrieving parameters from a URL

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Qt C++ will show this error when you change a class such that it now inherits from QObject (ie so that it can now use signals/slots). Running qmake -r will call moc and fix this problem.

If you are working with others via some sort of version control, you will want to make some change to your .pro file (ie add/remove a blank line). When everyone else gets your changes and runs make, make will see that the .pro file has changed and automatically run qmake. This will save your teammates from repeating your frustration.

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

TL;DR

The object returned by range() is actually a range object. This object implements the iterator interface so you can iterate over its values sequentially, just like a generator, list, or tuple.

But it also implements the __contains__ interface which is actually what gets called when an object appears on the right hand side of the in operator. The __contains__() method returns a bool of whether or not the item on the left-hand-side of the in is in the object. Since range objects know their bounds and stride, this is very easy to implement in O(1).

Bootstrap date time picker

You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
   <div class="container">_x000D_
      <div class="row">_x000D_
        <div class='col-sm-6'>_x000D_
            <div class="form-group">_x000D_
                <div class='input-group date' id='datetimepicker'>_x000D_
                    <input type='text' class="form-control" />_x000D_
                    <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
                    </span>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            $(function () {_x000D_
                $('#datetimepicker').datepicker();_x000D_
            });_x000D_
        </script>_x000D_
      </div>_x000D_
   </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_