Programs & Examples On #Getelementsbyname

In JavaScript and VBScript, the getElementsByName is a function which is used to access all HTML elements with a specified name. Two different elements can be declared with same name unlike their Id which must be defined unique. Tag getElementsByName can be used for usage related problems of getElementsByName function.

Copy output of a JavaScript variable to the clipboard

Very useful. I modified it to copy a JavaScript variable value to clipboard:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);

    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

Set custom HTML5 required field validation message

You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.

[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
    emailElement.addEventListener('invalid', function() {
        var message = this.value + 'is not a valid email address';
        emailElement.setCustomValidity(message)
    }, false);

    emailElement.addEventListener('input', function() {
        try{emailElement.setCustomValidity('')}catch(e){}
    }, false);
    });

The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.

Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.

Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/ Hope that helps!

TypeScript: casting HTMLElement

var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];    

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

Making a button invisible by clicking another button in HTML

Try this

<input type="button" onclick="demoShow()" value="edit" />
<script type="text/javascript"> 
function demoShow()
{p2.style.visibility="hidden";}
</script>
<input id="p2" type="submit" value="submit" name="submit" />

http://jsbin.com/gurolawu/1/

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

Uncaught TypeError: Cannot read property 'value' of undefined

First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like

if (typeof document.getElementsByName("username")[0] != 'undefined')

Similarly for the other element password.

Executing Javascript code "on the spot" in Chrome?

Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

How to create json by JavaScript for loop?

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

Why is my element value not getting changed? Am I using the wrong function?

As the plural in getElementsByName() implies, does it always return list of elements that have this name. So when you have an input element with that name:

<input type="text" name="Tue">

And it is the first one with that name, you have to use document.getElementsByName('Tue')[0] to get the first element of the list of elements with this name.

Beside that are properties case sensitive and the correct spelling of the value property is .value.

How do I check in SQLite whether a table exists?

See this:

SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;

How to uninstall pip on OSX?

In my case I ran the following command and it worked (not that I was expecting it to):

sudo pip uninstall pip

Which resulted in:

Uninstalling pip-6.1.1:
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
  <and all the other stuff>
  ...

  /usr/local/bin/pip
  /usr/local/bin/pip2
  /usr/local/bin/pip2.7
Proceed (y/n)? y
  Successfully uninstalled pip-6.1.1

How can I add an image file into json object?

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    messageText = (TextView) findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"
            + uploadFileName + "'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "",
                    "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("uploading started.....");
                        }
                    });

                    uploadFile(uploadFilePath + "" + uploadFileName);

                }
            }).start();
        }
    });
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
                + uploadFileName);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        + uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false); // Don't use a Cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(connection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            // + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + " http://www.androidexample.com/media/uploads/"
                                + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(UploadToServer.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadToServer.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadToServer.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

PHP FILE

<?php
$target_path  = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>

minimum double value in C/C++

A truly portable C++ solution

As from C++11 you can use numeric_limits<double>::lowest(). According to the standard, it returns exactly what you're looking for:

A finite value x such that there is no other finite value y where y < x.
Meaningful for all specializations in which is_bounded != false.

Online demo


Lots of non portable C++ answers here !

There are many answers going for -std::numeric_limits<double>::max().

Fortunately, they will work well in most of the cases. Floating point encoding schemes decompose a number in a mantissa and an exponent and most of them (e.g. the popular IEEE-754) use a distinct sign bit, which doesn't belong to the mantissa. This allows to transform the largest positive in the smallest negative just by flipping the sign:

enter image description here

Why aren't these portable ?

The standard doesn't impose any floating point standard.

I agree that my argument is a little bit theoretic, but suppose that some excentric compiler maker would use a revolutionary encoding scheme with a mantissa encoded in some variations of a two's complement. Two's complement encoding are not symmetric. for example for a signed 8 bit char the maximum positive is 127, but the minimum negative is -128. So we could imagine some floating point encoding show similar asymmetric behavior.

I'm not aware of any encoding scheme like that, but the point is that the standard doesn't guarantee that the sign flipping yields the intended result. So this popular answer (sorry guys !) can't be considered as fully portable standard solution ! /* at least not if you didn't assert that numeric_limits<double>::is_iec559 is true */

C++/CLI Converting from System::String^ to std::string

This worked for me:

#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;

Sorting an array in C?

The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Transform DateTime into simple Date in Ruby on Rails

For old Ruby (1.8.x):

myDate = Date.parse(myDateTime.to_s)

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Changing the child element's CSS when the parent is hovered

I have what i think is a better solution, since it is scalable to more levels, as many as wanted, not only two or three.

I use borders, but it can also be done with whateever style wanted, like background-color.

With the border, the idea is to:

  • Have a different border color only one div, the div over where the mouse is, not on any parent, not on any child, so it can be seen only such div border in a different color while the rest stays on white.

You can test it at: http://jsbin.com/ubiyo3/13

And here is the code:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Hierarchie Borders MarkUp</title>
<style>

  .parent { display: block; position: relative; z-index: 0;
            height: auto; width: auto; padding: 25px;
          }

  .parent-bg { display: block; height: 100%; width: 100%; 
               position: absolute; top: 0px; left: 0px; 
               border: 1px solid white; z-index: 0; 
             }
  .parent-bg:hover { border: 1px solid red; }

  .child { display: block; position: relative; z-index: 1; 
           height: auto; width: auto; padding: 25px;
         }

  .child-bg { display: block; height: 100%; width: 100%; 
              position: absolute; top: 0px; left: 0px; 
              border: 1px solid white; z-index: 0; 
            }
  .child-bg:hover { border: 1px solid red; }

  .grandson { display: block; position: relative; z-index: 2; 
              height: auto; width: auto; padding: 25px;
            }

  .grandson-bg { display: block; height: 100%; width: 100%; 
                 position: absolute; top: 0px; left: 0px; 
                 border: 1px solid white; z-index: 0; 
               }
  .grandson-bg:hover { border: 1px solid red; }

</style>
</head>
<body>
  <div class="parent">
    Parent
    <div class="child">
      Child
      <div class="grandson">
        Grandson
        <div class="grandson-bg"></div>
      </div>
      <div class="child-bg"></div>
    </div>
    <div class="parent-bg"></div>
  </div>
</body>
</html>

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

Automatically scroll down chat div

I prefer to use Vanilla JS

let chatWrapper = document.querySelector('#chat-messages');
chatWrapper.scrollTo(0, chatWrapper.offsetHeight );

where element.scrollTo(x-coord, y-coord)

Get folder name from full file path

Try this

var myFolderName = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

How to add column to numpy array

If you have an array, a of say 210 rows by 8 columns:

a = numpy.empty([210,8])

and want to add a ninth column of zeros you can do this:

b = numpy.append(a,numpy.zeros([len(a),1]),1)

ImageView rounded corners

Your MainActivity.java is like this:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);

You should to first get your image from Resource as Bitmap or Drawable.

If get as Bitmap:

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);

Or if get as Drawable:

Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);

Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:

package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:[email protected]
public class Newreza{
    int a,x,y;
    float bmr;
    public Bitmap setEffect(Bitmap bm,float radius,int color){
        bm=bm.copy(Bitmap.Config.ARGB_8888,true);
        bmr=radius*bm.getWidth();
        for(y=0;y<bmr;y++){
            a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=0;y<bmr;y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        return bm;
    }
    public Drawable setEffect(Drawable d,float radius,int color){
        return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
    }
}

Just notice that replace your package name with first line in the code.

It %100 works, because is written in details :)

Android Studio with Google Play Services

I copied the play libs files from the google-play-services_lib to my project libs directory:

  • google-play-services.jar
  • google-play-services.jar.properties.

Then selected them, right-click, "Add as libraries".

How to find rows that have a value that contains a lowercase letter

--For Sql

SELECT *
FROM tablename
WHERE tablecolumnname LIKE '%[a-z]%';

What are the special dollar sign shell variables?

Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.

#!/bin/bash

echo "parameter 0 --> $0" ; exit 0

Output:

parameter 0 --> ./mytry.sh

This is on a current (year 2016) version of Bash, via Slackware 14.2

How to create Gmail filter searching for text only at start of subject line?

Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(

There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.

Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.

With the current search facility brackets of any form () {} [] are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb) and [aaa|bbb] are equivalent and will both find words aaa or bbb. Most other punctuation characters, including \, are treated as a space or a word-separator, + - : and " do have special meaning though, see the help.

As of 2016, only the form "{term1 term2}" is documented for this, and is equivalent to the search "term1 OR term2".

You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor to get the complete source).

You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.

For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected] it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)

The difference between the Runnable and Callable interfaces in Java

Difference between Callable and Runnable are following:

  1. Callable is introduced in JDK 5.0 but Runnable is introduced in JDK 1.0
  2. Callable has call() method but Runnable has run() method.
  3. Callable has call method which returns value but Runnable has run method which doesn't return any value.
  4. call method can throw checked exception but run method can't throw checked exception.
  5. Callable use submit() method to put in task queue but Runnable use execute() method to put in the task queue.

typedef struct vs struct definitions

I see some clarification is in order on this. C and C++ do not define types differently. C++ was originally nothing more than an additional set of includes on top of C.

The problem that virtually all C/C++ developers have today, is a) universities are no longer teaching the fundamentals, and b) people don't understand the difference between a definition and a declaration.

The only reason such declarations and definitions exist is so that the linker can calculate address offsets to the fields in the structure. This is why most people get away with code that is actually written incorrectly-- because the compiler is able to determine addressing. The problem arises when someone tries to do something advance, like a queue, or a linked list, or piggying-backing an O/S structure.

A declaration begins with 'struct', a definition begins with 'typedef'.

Further, a struct has a forward declaration label, and a defined label. Most people don't know this and use the forward declaration label as a define label.

Wrong:

struct myStruct
   {
   int field_1;
   ...
   };

They've just used the forward declaration to label the structure-- so now the compiler is aware of it-- but it isn't an actual defined type. The compiler can calculate the addressing-- but this isn't how it was intended to be used, for reasons I will show momentarily.

People who use this form of declaration, must always put 'struct' in practicly every reference to it-- because it isn't an offical new type.

Instead, any structure that does not reference itself, should be declared and defined this way only:

typedef struct
   {
   field_1;
   ...
   }myStruct;

Now it's an actual type, and when used you can use at as 'myStruct' without having to prepend it with the word 'struct'.

If you want a pointer variable to that structure, then include a secondary label:

typedef struct
   {
   field_1;
   ...
   }myStruct,*myStructP;

Now you have a pointer variable to that structure, custom to it.

FORWARD DECLARATION--

Now, here's the fancy stuff, how the forward declaration works. If you want to create a type that refers to itself, like a linked list or queue element, you have to use a forward declaration. The compiler doesn't consider the structure defined until it gets to the semicolon at the very end, so it's just declared before that point.

typedef struct myStructElement
   {
   myStructElement*  nextSE;
   field_1;
   ...
   }myStruct;

Now, the compiler knows that although it doesn't know what the whole type is yet, it can still reference it using the forward reference.

Please declare and typedef your structures correctly. There's actually a reason.

Reload chart data via JSON with Highcharts

Actually maybe you should choose the function update is better.
Here's the document of function update http://api.highcharts.com/highcharts#Series.update

You can just type code like below:

chart.series[0].update({data: [1,2,3,4,5]})

These code will merge the origin option, and update the changed data.

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

How to check null objects in jQuery

use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)

Creating a dictionary from a CSV file

You need a Python DictReader class. More help can be found from here

import csv

with open('file_name.csv', 'rt') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row

Adding a dictionary to another

The most obvious way is:

foreach(var kvp in NewAnimals)
   Animals.Add(kvp.Key, kvp.Value); 
  //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue

Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;

foreach(var kvp in NewAnimals)
   animalsAsCollection.Add(kvp);

It's a pity the class doesn't have anAddRangemethod likeList<T> does.

Command to get latest Git commit hash from a branch

you can git fetch nameofremoterepo, then git log

and personally, I alias gitlog to git log --graph --oneline --pretty --decorate --all. try out and see if it fits you

Getting the 'external' IP address in Java

I am not sure if you can grab that IP from code that runs on the local machine.

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

Use a webservice like AWS and others

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

Add an index (numeric ID) column to large data frame

Well, if I understand you correctly. You can do something like the following.

To show it, I first create a data.frame with your example

df <- 
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")

df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")  

You can then run one of the following lines to add a column (at the end of the data.frame) with the row number as the generated user id. The second lines simply adds leading zeros.

df$generated_uid  <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))

If you absolutely want the generated user id to be the first column, you can add the column like so:

df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)

or simply rearrage the columns.

How to run a cronjob every X minutes?

2 steps to check if a cronjob is working :

  1. Login on the server with the user that execute the cronjob
  2. Manually run php command :

    /usr/bin/php /mydomain.in/cromail.php

And check if any error is displayed

Header set Access-Control-Allow-Origin in .htaccess doesn't work

After spending half a day with nothing working. Using a header check service though everything was working. The firewall at work was stripping them

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

How to force cp to overwrite without confirmation

Another way to call the command without the alias is to use the command builtin in bash.

command cp -rf /zzz/zzz/*

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

How to stop the Timer in android?

It says timer() is not available on android? You might find this article useful.

http://developer.android.com/resources/articles/timed-ui-updates.html


I was wrong. Timer() is available. It seems you either implement it the way it is one shot operation:

schedule(TimerTask task, Date when) // Schedule a task for single execution.

Or you cancel it after the first execution:

cancel()  // Cancels the Timer and all scheduled tasks.

http://developer.android.com/reference/java/util/Timer.html

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

Xcode 10.3 Solution

The following error messages apply:

iPhone is busy: Preparing debugger support for iPhone Xcode will continue when iPhone is finished.

An error was encountered while attempting to communicate with this device. (The service is invalid.) Please try rebooting and reconnecting the device. (0xE8000022).


Follow the steps in Jayprakash Dubey's post above

and

  • Close Xcode;

  • Delete contents of DerivedData folder ~/Library/Developer/Xcode/DerivedData

  • Restart Xcode & iPhone

  • Pair Xcode & iPhone again

  • & run application

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

is there a css hack for safari only NOT chrome?

Replace your class in (.myClass)

/* Safari only */ .myClass:not(:root:root) { enter code here }

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

What are the differences between git remote prune, git prune, git fetch --prune, etc

git remote prune and git fetch --prune do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.

However it doesn't touch the local branches you have checked out, that you can simply delete with

git branch -d  random_branch_I_want_deleted

Replace -d by -D if the branch is not merged elsewhere

git prune does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.

Troubleshooting BadImageFormatException

I am surprised that no-one else has mentioned this so I am sharing in case none of the above help (my case).

What was happening was that an VBCSCompiler.exe instance was somehow stuck and was in fact not releasing the file handles to allow new instances to correctly write the new files and was causing the issue. This became apparent when I tried to delete the "bin" folder and it was complaining that another process was using files in there.

Closed VS, opened task manager, looked and terminated all VBCSCompiler instances and deleted the "bin" folder to get back to where I was.

Reference: https://developercommunity.visualstudio.com/content/problem/117596/vbcscompilerexe-process-stays-runing-after-exiting.html

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

What is ".NET Core"?

The current documentation has a good explanation of what .NET Core is, areas to use and so on. The following characteristics best define .NET Core:

Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.

Cross-platform: Runs on Windows, macOS and Linux; can be ported to other OSes. The supported operating systems (OSes), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.

Command-line tools: All product scenarios can be exercised at the command-line.

Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.

Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.

Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support

And here is what .NET Core includes:

A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interoperability and other basic services.

A set of framework libraries, which provide primitive data types, application composition types and fundamental utilities.

A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.

The 'dotnet' application host, which is used to launch .NET Core applications. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.

Java : Sort integer array without using Arrays.sort()

You can find so many different sorting algorithms in internet, but if you want to fix your own solution you can do following changes in your code:

Instead of:

 orderedNums[greater]=tenNums[indexL];

you need to do this:

while (orderedNums[greater] == tenNums[indexL]) {
     greater++;
}
orderedNums[greater] = tenNums[indexL];

This code basically checks if that particular index is occupied by a similar number, then it will try to find next free index.

Note: Since the default value in your sorted array elements is 0, you need to make sure 0 is not in your list. otherwise you need to initiate your sorted array with an especial number that you sure is not in your list e.g: Integer.MAX_VALUE

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

This error

docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown.

occurs when creating a docker image from base image eg. scratch. This is because the resulting image does not have a shell to execute the image. If your use:

ENV EXECUTABLE hello
cmd [$EXECUTABLE]

in your docker file, docker uses /bin/sh to parse the input string. and hence the error. Inspecting on the image, your will find:

$docker inspect <image-name>
"Entrypoint": [
                "/bin/sh",
                "-c",
                "[$HM_APP]"
            ]

This means that the ENTRYPOINT or CMD arguments will be parsed using /bin/sh -c. The solution that worked for me is to parse the command as a JSON array of string e.g.

cmd ["hello"]

and inspecting the image again:

"Entrypoint": [
                "hello"
            ]

This removes the dependence on /bin/sh the docker app can now execute the binary file. Example:

FROM scratch

# Environmental variables

# Copy files
ADD . /
# Home dir
WORKDIR /bin

EXPOSE 8083
ENTRYPOINT ["hospitalms"]

Hope this helps someone in future.

How to set cellpadding and cellspacing in table with CSS?

The padding inside a table-divider (TD) is a padding property applied to the cell itself.

CSS

td, th {padding:0}

The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.

CSS

table, td, th {border-collapse:separate}
table {border-spacing:6px}

Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

Generate random colors (RGB)

Inspired by other answers this is more correct code that produces integer 0-255 values and appends alpha=255 if you need RGBA:

tuple(np.random.randint(256, size=3)) + (255,)

If you just need RGB:

tuple(np.random.randint(256, size=3))

How can I declare enums using java

public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

socket connect() vs bind()

I think it would help your comprehension if you think of connect() and listen() as counterparts, rather than connect() and bind(). The reason for this is that you can call or omit bind() before either, although it's rarely a good idea to call it before connect(), or not to call it before listen().

If it helps to think in terms of servers and clients, it is listen() which is the hallmark of the former, and connect() the latter. bind() can be found - or not found - on either.

If we assume our server and client are on different machines, it becomes easier to understand the various functions.

bind() acts locally, which is to say it binds the end of the connection on the machine on which it is called, to the requested address and assigns the requested port to you. It does that irrespective of whether that machine will be a client or a server. connect() initiates a connection to a server, which is to say it connects to the requested address and port on the server, from a client. That server will almost certainly have called bind() prior to listen(), in order for you to be able to know on which address and port to connect to it with using connect().

If you don't call bind(), a port and address will be implicitly assigned and bound on the local machine for you when you call either connect() (client) or listen() (server). However, that's a side effect of both, not their purpose. A port assigned in this manner is ephemeral.

An important point here is that the client does not need to be bound, because clients connect to servers, and so the server will know the address and port of the client even though you are using an ephemeral port, rather than binding to something specific. On the other hand, although the server could call listen() without calling bind(), in that scenario they would need to discover their assigned ephemeral port, and communicate that to any client that it wants to connect to it.

I assume as you mention connect() you're interested in TCP, but this also carries over to UDP, where not calling bind() before the first sendto() (UDP is connection-less) also causes a port and address to be implicitly assigned and bound. One function you cannot call without binding is recvfrom(), which will return an error, because without an assigned port and bound address, there is nothing to receive from (or too much, depending on how you interpret the absence of a binding).

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

How do you join tables from two different SQL Server instances in one SQL query

The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

SELECT *
FROM server1table
    INNER JOIN server2.database.dbo.server2table ON .....

How do I automatically set the $DISPLAY variable for my current session?

Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.

PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
    export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"}  $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
    echo "DISPLAY set to $DISPLAY"
else
    echo "Could not set DISPLAY"
fi
unset PID

You should just be able to drop that in your .bashrc file.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You're using the wrong post parameters:

    var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
                      ^^^^-$_POST['name']
                                       ^^^^--$_POST['name']
                                      etc....

The javascript/html IDs are irrelevant to the actual POST, especially when you're building your own data string and don't use those same IDs.

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

Groovy / grails how to determine a data type?

Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass() method.

How can I run a windows batch file but hide the command window?

To self-hide already running script you'll need getCmdPid.bat and windowoMode.bat

@echo off

echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode hidden

echo --other commands--
pause

Here I've compiled all ways that I know to start a hidden process with batch without external tools.With a ready to use scripts (some of them rich on options) , and all of them form command line.Where is possible also the PID is returned .Used tools are IEXPRESS,SCHTASKS,WScript.Shell,Win32_Process and JScript.Net - but all of them wrapped in a .bat files.

Delete all records in a table of MYSQL in phpMyAdmin

You have 2 options delete and truncate :

  1. delete from mytable

    This will delete all the content of the table, not reseting the autoincremental id, this process is very slow. If you want to delete specific records append a where clause at the end.

  2. truncate myTable

    This will reset the table i.e. all the auto incremental fields will be reset. Its a DDL and its very fast. You cannot delete any specific record through truncate.

Is there a way to remove the separator line from a UITableView?

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}

Getting the first character of a string with $str[0]

I've used that notation before as well, with no ill side effects and no misunderstandings. It makes sense -- a string is just an array of characters, after all.

Path of currently executing powershell script

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}

Correctly determine if date string is a valid date in that format

Use in simple way with php prebuilt function:

function checkmydate($date) {
  $tempDate = explode('-', $date);
  // checkdate(month, day, year)
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

   checkmydate('2015-12-01'); //true
   checkmydate('2015-14-04'); //false

How to click an element in Selenium WebDriver using JavaScript

Cross browser testing java scripts

public class MultipleBrowser {

    public WebDriver driver= null;
    String browser="mozilla";
    String url="https://www.omnicard.com";

    @BeforeMethod
    public void LaunchBrowser() {

        if(browser.equalsIgnoreCase("mozilla"))
            driver= new FirefoxDriver();
        else if(browser.equalsIgnoreCase("safari"))
            driver= new SafariDriver();
        else if(browser.equalsIgnoreCase("chrome"))
            //System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
            driver= new ChromeDriver(); 
        driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
        driver.navigate().to(url);
    }

}

but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .

HowTo Generate List of SQL Server Jobs and their owners

If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view

SELECT *
 from  msdb..sysjobs_view s 
 left join master.sys.syslogins l on s.owner_sid = l.sid

or

SELECT *, SUSER_SNAME(s.owner_sid) AS owner
 from  msdb..sysjobs_view s 

Java, How to add values to Array List used as value in HashMap

You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).

However, if you don't want to use an external lib, then you would do something like this:

if (map.get(id) == null) { //gets the value for an id)
    map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList

map.get(id).add(value); //adds value to list.

Predict() - Maybe I'm not understanding it

Thanks Hong, that was exactly the problem I was running into. The error you get suggests that the number of rows is wrong, but the problem is actually that the model has been trained using a command that ends up with the wrong names for parameters.

This is really a critical detail that is entirely non-obvious for lm and so on. Some of the tutorial make reference to doing lines like lm(olive$Area@olive$Palmitic) - ending up with variable names of olive$Area NOT Area, so creating an entry using anewdata<-data.frame(Palmitic=2) can't then be used. If you use lm(Area@Palmitic,data=olive) then the variable names are right and prediction works.

The real problem is that the error message does not indicate the problem at all:

Warning message: 'anewdata' had 1 rows but variable(s) found to have X rows

date format yyyy-MM-ddTHH:mm:ssZ

"o" format is different for DateTime vs DateTimeOffset :(

DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"

DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"

My final answer is

DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
DateTime.UtcNow.ToString("o")              //for DateTime type

Printing 1 to 1000 without loop or conditionals

#include <stdio.h>

static void (*f[2])(int);
static void p(int i)
{ 
    printf("%d\n", i);
}

static void e(int i)
{
    exit(0);
}

static void r(int i)
{ 
    f[(i-1)/1000](i);
    r(i+1);
}

int main(int argc, char* argv[])
{
    f[0] = p;
    f[1] = e;
    r(1);
}

How can I convert an integer to a hexadecimal string in C?

The following code takes an integer and makes a string out of it in hex format:

int  num = 32424;
char hex[5];

sprintf(hex, "%x", num);
puts(hex);

gives

7ea8

How to declare an array in Python?

You don't declare anything in Python. You just use it. I recommend you start out with something like http://diveintopython.net.

call a static method inside a class?

In the later PHP version self::staticMethod(); also will not work. It will throw the strict standard error.

In this case, we can create object of same class and call by object

here is the example

class Foo {

    public function fun1() {
        echo 'non-static';   
    }

    public static function fun2() {
        echo (new self)->fun1();
    }
}

How to style a div to be a responsive square?

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.

Singleton design pattern vs Singleton beans in Spring container

Singleton beans in Spring and classes based on Singleton design pattern are quite different.

Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader where as the scope of a Spring singleton bean is described as 'per container per bean'. Singleton scope in Spring means that this bean will be instantiated only once by Spring. Spring container merely returns the same instance again and again for subsequent calls to get the bean.

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

Reshaping data.frame from wide to long format

With tidyr_1.0.0, another option is pivot_longer

library(tidyr)
pivot_longer(df1, -c(Code, Country), values_to = "Value", names_to = "Year")
# A tibble: 10 x 4
#   Code  Country     Year  Value 
#   <fct> <fct>       <chr> <fct> 
# 1 AFG   Afghanistan 1950  20,249
# 2 AFG   Afghanistan 1951  21,352
# 3 AFG   Afghanistan 1952  22,532
# 4 AFG   Afghanistan 1953  23,557
# 5 AFG   Afghanistan 1954  24,555
# 6 ALB   Albania     1950  8,097 
# 7 ALB   Albania     1951  8,986 
# 8 ALB   Albania     1952  10,058
# 9 ALB   Albania     1953  11,123
#10 ALB   Albania     1954  12,246

data

df1 <- structure(list(Code = structure(1:2, .Label = c("AFG", "ALB"), class = "factor"), 
    Country = structure(1:2, .Label = c("Afghanistan", "Albania"
    ), class = "factor"), `1950` = structure(1:2, .Label = c("20,249", 
    "8,097"), class = "factor"), `1951` = structure(1:2, .Label = c("21,352", 
    "8,986"), class = "factor"), `1952` = structure(2:1, .Label = c("10,058", 
    "22,532"), class = "factor"), `1953` = structure(2:1, .Label = c("11,123", 
    "23,557"), class = "factor"), `1954` = structure(2:1, .Label = c("12,246", 
    "24,555"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

javac not working in windows command prompt

for /d %i in ("\Program Files\Java\jdk*") do set JAVA_HOME=%i
set JAVA_HOME

this solution worked to me

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Thanks for the original answer here. With python 3 the following line of code:

print(json.dumps(result_dict,ensure_ascii=False))

was ok. Consider trying not writing too much text in the code if it's not imperative.

This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html

basically install he_IL or whatever language locale on ubuntu check it is not installed

locale -a 

install it where XX is your language

sudo apt-get install language-pack-XX

For example:

sudo apt-get install language-pack-he

add the following text to /etc/apache2/envvrs

export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'

Than you would hopefully not get python errors on from apache like:

print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?

Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

How can I require at least one checkbox be checked before a form can be submitted?

<ul>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>

<script type="text/javascript">
$(document).ready(function(){
    var checkboxes = $('.checkboxes');
    checkboxes.change(function(){
        if($('.checkboxes:checked').length>0) {
            checkboxes.removeAttr('required');
        } else {
            checkboxes.attr('required', 'required');
        }
    });
});
</script>

Unable to load DLL 'SQLite.Interop.dll'

I had the same issue. Please follow these steps:

  1. Make sure you have installed System.Data.SQLite.Core package by SQLite Development Team from NuGet.
  2. Go to project solution and try to locate build folder inside packages folder
  3. Check your project framework and pick the desired SQLite.Interop.dll and place it in your debug/release folder

Reference

How can I convert an HTML element to a canvas element?

Sorry, the browser won't render HTML into a canvas.

It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.

To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

How to create JSON object using jQuery

How to get append input field value as json like

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

Reset ID autoincrement ? phpmyadmin

I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.

ALTER TABLE users DROP id

The above sql can be run via sql query or as php. This will delete the id column.

Then re add it again, via the code below:

ALTER TABLE  `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST

Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.

ojdbc14.jar vs. ojdbc6.jar

The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.

How to use PowerShell select-string to find more than one pattern in a file?

If you want to match the two words in either order, use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'

If Failed always comes after VendorEnquiry on the line, just use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

How do I select text nodes with jQuery?

I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue conditional to your filter function, like a simple $.trim(this.nodevalue) !== '':

$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });

http://jsfiddle.net/ptp6m97v/

Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen &shy; character, newlines \n, tabs, etc.), you can try using a Regular Expression. For example, \S will match any non-whitespace characters:

$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });

Difference between \b and \B in regex

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

Source: http://www.regular-expressions.info/wordboundaries.html

Difference between Java SE/EE/ME?

According to the Oracle's documentation, there are actually four Java platforms:

  • Java Platform, Standard Edition (Java SE)
  • Java Platform, Enterprise Edition (Java EE)
  • Java Platform, Micro Edition (Java ME)
  • JavaFX

Java SE is for developing desktop applications and it is the foundation for developing in Java language. It consists of development tools, deployment technologies, and other class libraries and toolkits used in Java applications. Java EE is built on top of Java SE, and it is used for developing web applications and large-scale enterprise applications. Java ME is a subset of the Java SE. It provides an API and a small-footprint virtual machine for running Java applications on small devices. JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. It is a recent addition to the family of Java platforms.

Strictly speaking, these platforms are specifications; they are norms, not software. The Java Platform, Standard Edition Development Kit (JDK) is an official implementation of the Java SE specification, provided by Oracle. There are also other implementations, like OpenJDK and IBM's J9.

People new to Java download a JDK for their platform and operating system (Oracle's JDK is available for download here.)

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");
System.out.println(df.format(date));

OPTION (RECOMPILE) is Always Faster; Why?

Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.

  1. STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.

  2. PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.

  3. INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.

  4. ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.

  5. THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.

In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

Running a CMD or BAT in silent mode

I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)

That should answer your question.

Here it is:


From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---| 

Update after Tammen's feedback:

If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

How to get .pem file from .key and .crt files?

Additionally, if you don't want it to ask for a passphrase, then need to run the following command:

openssl rsa -in server.key -out server.key

Object comparison in JavaScript

Here is my version, pretty much stuff from this thread is integrated (same counts for the test cases):

Object.defineProperty(Object.prototype, "equals", {
    enumerable: false,
    value: function (obj) {
        var p;
        if (this === obj) {
            return true;
        }

        // some checks for native types first

        // function and sring
        if (typeof(this) === "function" || typeof(this) === "string" || this instanceof String) { 
            return this.toString() === obj.toString();
        }

        // number
        if (this instanceof Number || typeof(this) === "number") {
            if (obj instanceof Number || typeof(obj) === "number") {
                return this.valueOf() === obj.valueOf();
            }
            return false;
        }

        // null.equals(null) and undefined.equals(undefined) do not inherit from the 
        // Object.prototype so we can return false when they are passed as obj
        if (typeof(this) !== typeof(obj) || obj === null || typeof(obj) === "undefined") {
            return false;
        }

        function sort (o) {
            var result = {};

            if (typeof o !== "object") {
                return o;
            }

            Object.keys(o).sort().forEach(function (key) {
                result[key] = sort(o[key]);
            });

            return result;
        }

        if (typeof(this) === "object") {
            if (Array.isArray(this)) { // check on arrays
                return JSON.stringify(this) === JSON.stringify(obj);                
            } else { // anyway objects
                for (p in this) {
                    if (typeof(this[p]) !== typeof(obj[p])) {
                        return false;
                    }
                    if ((this[p] === null) !== (obj[p] === null)) {
                        return false;
                    }
                    switch (typeof(this[p])) {
                    case 'undefined':
                        if (typeof(obj[p]) !== 'undefined') {
                            return false;
                        }
                        break;
                    case 'object':
                        if (this[p] !== null 
                                && obj[p] !== null 
                                && (this[p].constructor.toString() !== obj[p].constructor.toString() 
                                        || !this[p].equals(obj[p]))) {
                            return false;
                        }
                        break;
                    case 'function':
                        if (this[p].toString() !== obj[p].toString()) {
                            return false;
                        }
                        break;
                    default:
                        if (this[p] !== obj[p]) {
                            return false;
                        }
                    }
                };

            }
        }

        // at least check them with JSON
        return JSON.stringify(sort(this)) === JSON.stringify(sort(obj));
    }
});

Here is my TestCase:

    assertFalse({}.equals(null));
    assertFalse({}.equals(undefined));

    assertTrue("String", "hi".equals("hi"));
    assertTrue("Number", new Number(5).equals(5));
    assertFalse("Number", new Number(5).equals(10));
    assertFalse("Number+String", new Number(1).equals("1"));

    assertTrue([].equals([]));
    assertTrue([1,2].equals([1,2]));
    assertFalse([1,2].equals([2,1]));
    assertFalse([1,2].equals([1,2,3]));

    assertTrue(new Date("2011-03-31").equals(new Date("2011-03-31")));
    assertFalse(new Date("2011-03-31").equals(new Date("1970-01-01")));

    assertTrue({}.equals({}));
    assertTrue({a:1,b:2}.equals({a:1,b:2}));
    assertTrue({a:1,b:2}.equals({b:2,a:1}));
    assertFalse({a:1,b:2}.equals({a:1,b:3}));

    assertTrue({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
    assertFalse({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}.equals({1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));

    assertTrue("Function", (function(x){return x;}).equals(function(x){return x;}));
    assertFalse("Function", (function(x){return x;}).equals(function(y){return y+2;}));

    var a = {a: 'text', b:[0,1]};
    var b = {a: 'text', b:[0,1]};
    var c = {a: 'text', b: 0};
    var d = {a: 'text', b: false};
    var e = {a: 'text', b:[1,0]};
    var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
    var i = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var j = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var k = {a: 'text', b: null};
    var l = {a: 'text', b: undefined};

    assertTrue(a.equals(b));
    assertFalse(a.equals(c));
    assertFalse(c.equals(d));
    assertFalse(a.equals(e));
    assertTrue(f.equals(g));
    assertFalse(h.equals(g));
    assertTrue(i.equals(j));
    assertFalse(d.equals(k));
    assertFalse(k.equals(l));

Resolving tree conflict

Basically, tree conflicts arise if there is some restructure in the folder structure on the branch. You need to delete the conflict folder and use svn clean once. Hope this solves your conflict.

json_encode/json_decode - returns stdClass instead of Array in PHP

There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).

The concrete code is by Michal Migurski and by Matt Knapp:

Configuring Git over SSH to login once

I had to clone a git repo from a server that did not allow login vie ssh key but only with a user/password. I found no way to configure the Git Plugin to use a simple user/password combination so i added the the following shell command as pre-build step on a linux build machine which depends on the tool expect (apt-get install expect):

THIS IS NOT A GOOD WAY OF SOLVING THIS PROBLEM AS YOUR PASSWORD IS SHOWN AS CLEAR TEXT IN THE CONFIGURATION AND LOGS OF THE JENKINS JOB! ONLY USE IT IF THERE IS NO WAY TO CONFIGURE RSA-KEY AUTHENTIFICATION OR OTHER CONFIGURATION POSSIBILITES!

rm -rf $WORKSPACE &&
expect -c 'set timeout -1; spawn git clone USER@MYHOST:/MYPATH/MYREPO.git $WORKSPACE; expect "password:" {send "MYPASSWORD\r"}; expect eof'

Delete last commit in bitbucket

In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).

Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:

On git:

git revert <commit>

On mercurial:

hg backout <REV>

EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.

Should I add the Visual Studio .suo and .user files to source control?

You cannot source-control the .user files, because that's user specific. It contains the name of remote machine and other user-dependent things. It's a vcproj related file.

The .suo file is a sln related file and it contains the "solution user options" (startup project(s), windows position (what's docked and where, what's floating), etc.)

It's a binary file, and I don't know if it contains something "user related".

In our company we do not take those files under source control.

Remove all special characters except space from a string using JavaScript

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ??????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

Validate IPv4 address in Java

If it is IP4, you can use a regular expression as follows:

^(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)\\.){3}(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)$.

The thread has exited with code 0 (0x0) with no unhandled exception

In order to complete BlueM's accepted answer, you can desactivate it here:

Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off

Best way to check if MySQL results returned in PHP?

One way to do it is to check what mysql_num_rows returns. A minimal complete example would be the following:

if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
    // there are results in $result
} else {
    // no results
}

But it's recommended that you check the return value of mysql_query and handle it properly in the case it's false (which would be caused by an error); probably by also calling mysql_error and logging the error somewhere.

How to increase IDE memory limit in IntelliJ IDEA on Mac?

Some addition to the top answer here https://stackoverflow.com/posts/13581526/revisions

  1. Change memory as you wish in .vmoptions
  2. Enable memory view as told here https://stackoverflow.com/a/39563251/5515861

And you'll have something like this in the bottom right

enter image description here

Turn on torch/flash on iPhone

This work's very well.. hope it help's someone !

-(IBAction)flashlight:(id)sender {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device hasTorch] && [device hasFlash]){

        if (device.torchMode == AVCaptureTorchModeOff) {

            [sender setTitle:@"Torch Off" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

            AVCaptureSession *cam = [[AVCaptureSession alloc] init];

            [cam beginConfiguration];
            [device lockForConfiguration:nil];

            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];

            [cam addInput:flashInput];
            [cam addOutput:output];

            [device unlockForConfiguration];

            [cam commitConfiguration];
            [cam startRunning];

            [self setTorchSession:cam];
        }
        else {
            [sender setTitle:@"Torch On" forState:UIControlStateNormal];
            [_torchSession stopRunning];
        }
    }
}

Reverse HashMap keys and values in Java

They all are unique, yes

If you're sure that your values are unique you can iterate over the entries of your old map .

Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
    myNewHashMap.put(entry.getValue(), entry.getKey());
}

Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :

BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");

BiMap<String, Character> myBiMapInversed = myBiMap.inverse();

As is out, you can also do it this way :

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, String> mapInversed = 
    map.entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))

Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:

Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();

How to remove an element from a list by index

You probably want pop:

a = ['a', 'b', 'c', 'd']
a.pop(1)

# now a is ['a', 'c', 'd']

By default, pop without any arguments removes the last item:

a = ['a', 'b', 'c', 'd']
a.pop()

# now a is ['a', 'b', 'c']

How do I set the background color of Excel cells using VBA?

Do a quick 'record macro' to see the color number associated with the color you're looking for (yellow highlight is 65535). Then erase the code and put

Sub Name()
Selection.Interior.Color = 65535 '(your number may be different depending on the above)
End Sub

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

AngularJS: How do I manually set input to $valid in controller?

You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.

What you should do is to set the validity of the input element. Like so;

addItem.capabilities.$setValidity("youAreFat", false);

Now the input (and so the form) is invalid. You can also see which error causes invalidation.

addItem.capabilities.errors.youAreFat == true;

How to get the IP address of the docker host from inside a docker container

TLDR for Mac and Windows

docker run -it --rm alpine nslookup host.docker.internal

... prints the host's IP address ...

nslookup: can't resolve '(null)': Name does not resolve

Name:      host.docker.internal
Address 1: 192.168.65.2

Details

On Mac and Windows, you can use the special DNS name host.docker.internal.

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

How to print a certain line of a file with PowerShell?

You can use the -TotalCount parameter of the Get-Content cmdlet to read the first n lines, then use Select-Object to return only the nth line:

Get-Content file.txt -TotalCount 9 | Select-Object -Last 1;

Per the comment from @C.B. this should improve performance by only reading up to and including the nth line, rather than the entire file. Note that you can use the aliases -First or -Head in place of -TotalCount.

String comparison - Android

You can use, contentEquals() function. It may help you..

Text Editor For Linux (Besides Vi)?

for multiple tab text editor "medit" is the best . its like notepad++ in windows . for stylish and good looking "schite Text editor " is best .

Easy way to make a confirmation dialog in Angular?

I'm pretty late to the party, but here is another implementation using : https://stackblitz.com/edit/angular-confirmation-dialog

confirmation-dialog.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

  constructor(private modalService: NgbModal) { }

  public confirm(
    title: string,
    message: string,
    btnOkText: string = 'OK',
    btnCancelText: string = 'Cancel',
    dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
    const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.message = message;
    modalRef.componentInstance.btnOkText = btnOkText;
    modalRef.componentInstance.btnCancelText = btnCancelText;

    return modalRef.result;
  }

}

confirmation-dialog.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-confirmation-dialog',
  templateUrl: './confirmation-dialog.component.html',
  styleUrls: ['./confirmation-dialog.component.scss'],
})
export class ConfirmationDialogComponent implements OnInit {

  @Input() title: string;
  @Input() message: string;
  @Input() btnOkText: string;
  @Input() btnCancelText: string;

  constructor(private activeModal: NgbActiveModal) { }

  ngOnInit() {
  }

  public decline() {
    this.activeModal.close(false);
  }

  public accept() {
    this.activeModal.close(true);
  }

  public dismiss() {
    this.activeModal.dismiss();
  }

}

confirmation-dialog.component.html

<div class="modal-header">
  <h4 class="modal-title">{{ title }}</h4>
    <button type="button" class="close" aria-label="Close" (click)="dismiss()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {{ message }}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
    <button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
  </div>

Use the dialog like this:

public openConfirmationDialog() {
    this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
    .then((confirmed) => console.log('User confirmed:', confirmed))
    .catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
  }

How can I pass an argument to a PowerShell script?

# ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}

How to upload a project to Github

Steps to upload project to git:-

step1-open cmd and change current working directory to your project location.

step2-Initialize your project directory as a Git repository.

$ git init

step3-Add files in your local repository.

$ add .

step4-Commit the files that you've staged in your local repository.

$ git commit -m "First commit"

step5-Copy the remote repository url.

step6-add the remote repository url as origin in your local location.

$ git add origin copied_remote_repository_url

step7-confirm your origin is updated ot not.

$ git remote show origin

step8-push the changed to your github repository

$ git push origin master.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Using File.listFiles with FileNameExtensionFilter

One-liner in java 8 syntax:

pdfTestDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

1 = false and 0 = true?

I'm not sure if I'm answering the question right, but here's a familiar example:

The return type of GetLastError() in Windows is nonzero if there was an error, or zero otherwise. The reverse is usually true of the return value of the function you called.

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

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

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

How to check if any value is NaN in a Pandas DataFrame

I've been using the following and type casting it to a string and checking for the nan value

   (str(df.at[index, 'column']) == 'nan')

This allows me to check specific value in a series and not just return if this is contained somewhere within the series.

Searching if value exists in a list of objects using Linq

Using Linq you have many possibilities, here one without using lambdas:

//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
         where customer.FirstName == "John"
         select customer).Any();

Is it possible to disable the network in iOS Simulator?

There are two way to disable IOS Simulator internet:

  • Unplug your network connection
  • Turn Wi-Fi off

It's the simplest way

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Here is an example of flat badges that play well with zurb foundation css framework
Note: you might have to adjust the height for different fonts.

http://jsfiddle.net/jamesharrington/xqr5nx1o/

The Magic sauce!

.label {
  background:#EA2626;
  display:inline-block;
  border-radius: 12px;
  color: white;
  font-weight: bold;
  height: 17px; 
  padding: 2px 3px 2px 3px;
  text-align: center;
  min-width: 16px;
}

How do I get cURL to not show the progress bar?

curl -s http://google.com > temp.html

works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:

curl  http://google.com 2>/dev/null > temp.html

Execute jQuery function after another function completes

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

So, you pass a function as parameter (callback) that will be called in that if before return.

Also, this is a good article about callbacks.

_x000D_
_x000D_
function Typer(callback)_x000D_
{_x000D_
    var srcText = 'EXAMPLE ';_x000D_
    var i = 0;_x000D_
    var result = srcText[i];_x000D_
    var interval = setInterval(function() {_x000D_
        if(i == srcText.length - 1) {_x000D_
            clearInterval(interval);_x000D_
            callback();_x000D_
            return;_x000D_
        }_x000D_
        i++;_x000D_
        result += srcText[i].replace("\n", "<br />");_x000D_
        $("#message").html(result);_x000D_
    },_x000D_
    100);_x000D_
    return true;_x000D_
        _x000D_
    _x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
    alert("Play BGM function");_x000D_
    $('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
    playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFIDDLE

show and hide divs based on radio button click

You're on the right track, but you forgot two things:

  1. add the desc classes to your description divs
  2. You have numeric values for the input but text for the id.

I have fixed the above and also added a line to initially hide() the third description div.

Check it out in action - http://jsfiddle.net/VgAgu/3/

HTML

<div id="myRadioGroup">
    2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
    3 Cars<input type="radio" name="cars" value="3" />

    <div id="Cars2" class="desc">
        2 Cars Selected
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        3 Cars
    </div>
</div>

JQuery

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

RE error: illegal byte sequence on Mac OS X

My workaround had been using gnu sed. Worked fine for my purposes.

How to get the current time as datetime

Using Date Formatter -Swift 3.0

//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)


//Time    
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)

Update Date and Time Every Seconds

override func viewDidLoad() {
super.viewDidLoad()

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(DateAndTime.action), userInfo: nil, repeats: true)

       }

func action()
    {
    //Date
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
    labelfordate.text = String(dateString)


    //Time
    let timeFormatter = DateFormatter()
    timeFormatter.timeStyle = .medium
    let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
    labelfortime.text = String(timeString)

    }

Note: DateAndTime in the Timer code is the Class name.

Split pandas dataframe in two if it has more than 10 rows

This will return the split DataFrames if the condition is met, otherwise return the original and None (which you would then need to handle separately). Note that this assumes the splitting only has to happen one time per df and that the second part of the split (if it is longer than 10 rows (meaning that the original was longer than 20 rows)) is OK.

df_new1, df_new2 = df[:10, :], df[10:, :] if len(df) > 10 else df, None

Note you can also use df.head(10) and df.tail(len(df) - 10) to get the front and back according to your needs. You can also use various indexing approaches: you can just provide the first dimensions index if you want, such as df[:10] instead of df[:10, :] (though I like to code explicitly about the dimensions you are taking). You can can also use df.iloc and df.ix to index in similar ways.

Be careful about using df.loc however, since it is label-based and the input will never be interpreted as an integer position. .loc would only work "accidentally" in the case when you happen to have index labels that are integers starting at 0 with no gaps.

But you should also consider the various options that pandas provides for dumping the contents of the DataFrame into HTML and possibly also LaTeX to make better designed tables for the presentation (instead of just copying and pasting). Simply Googling how to convert the DataFrame to these formats turns up lots of tutorials and advice for exactly this application.

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

SQL MAX of multiple columns?

Either of the two samples below will work:

SELECT  MAX(date_columns) AS max_date
FROM    ( (SELECT   date1 AS date_columns
           FROM     data_table         )
          UNION
          ( SELECT  date2 AS date_columns
            FROM    data_table
          )
          UNION
          ( SELECT  date3 AS date_columns
            FROM    data_table
          )
        ) AS date_query

The second is an add-on to lassevk's answer.

SELECT  MAX(MostRecentDate)
FROM    ( SELECT    CASE WHEN date1 >= date2
                              AND date1 >= date3 THEN date1
                         WHEN date2 >= date1
                              AND date2 >= date3 THEN date2
                         WHEN date3 >= date1
                              AND date3 >= date2 THEN date3
                         ELSE date1
                    END AS MostRecentDate
          FROM      data_table
        ) AS date_query 

Difference between dates in JavaScript

By using the Date object and its milliseconds value, differences can be calculated:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

You can get the number of seconds (as a integer/whole number) by dividing the milliseconds by 1000 to convert it to seconds then converting the result to an integer (this removes the fractional part representing the milliseconds):

var seconds = parseInt((b-a)/1000);

You could then get whole minutes by dividing seconds by 60 and converting it to an integer, then hours by dividing minutes by 60 and converting it to an integer, then longer time units in the same way. From this, a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit can be created:

function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i]/time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    }; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). 
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

If you're wondering what the input parameters provided above for the second Date object are, see their names below:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

As noted in the comments of this solution, you don't necessarily need to provide all these values unless they're necessary for the date you wish to represent.

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Capture event onclose browser

Men, use this:

if(myWindow.closed){
    callback();
    return;
}

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

Updated answer that will solve your problem and also just a general good how-to for installing Oracle Java 7 on Ubuntu can be found here: http://www.wikihow.com/Install-Oracle-Java-on-Ubuntu-Linux

What is the purpose of "&&" in a shell command?

Furthermore, you also have || which is the logical or, and also ; which is just a separator which doesn't care what happend to the command before.

$ false || echo "Oops, fail"
Oops, fail

$ true || echo "Will not be printed"
$  

$ true && echo "Things went well"
Things went well

$ false && echo "Will not be printed"
$

$ false ; echo "This will always run"
This will always run

Some details about this can be found here Lists of Commands in the Bash Manual.

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

Uses of content-disposition in an HTTP response header

This header is defined in RFC 2183, so that would be the best place to start reading.

Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.

How do I disable a Button in Flutter?

You can also use the AbsorbPointer, and you can use it in the following way:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

If you want to know more about this widget, you can check the following link Flutter Docs

What is the best regular expression to check if a string is a valid URL?

The best regular expression for URL for me would be:

"(([\w]+:)?//)?(([\d\w]|%[a-fA-F\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?"

Chart.js - Formatting Y axis

Chart.js 2.X.X

I know this post is old. But if anyone is looking for more flexible solution, here it is

var options = {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    callback: function(label, index, labels) {
                        return Intl.NumberFormat().format(label);
                        // 1,350

                        return Intl.NumberFormat('hi', { 
                            style: 'currency', currency: 'INR', minimumFractionDigits: 0, 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350

                        // return Intl.NumberFormat('hi', {
                            style: 'currency', currency: 'INR', currencyDisplay: 'symbol', minimumFractionDigits: 2 
                        }).format(label).replace(/^(\D+)/, '$1 ');
                        // ? 1,350.00
                    }
                }
            }]
        }
    }

'hi' is Hindi. Check here for other locales argument
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation#locales_argument

for more currency symbol
https://www.currency-iso.org/en/home/tables/table-a1.html

Javascript Iframe innerHTML

You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.

http://www-jo.se/f.pfleger/forcecors

AngularJS : When to use service instead of factory

Even when they say that all services and factories are singleton, I don't agree 100 percent with that. I would say that factories are not singletons and this is the point of my answer. I would really think about the name that defines every component(Service/Factory), I mean:

A factory because is not a singleton, you can create as many as you want when you inject, so it works like a factory of objects. You can create a factory of an entity of your domain and work more comfortably with this objects which could be like an object of your model. When you retrieve several objects you can map them in this objects and it can act kind of another layer between the DDBB and the AngularJs model.You can add methods to the objects so you oriented to objects a little bit more your AngularJs App.

Meanwhile a service is a singleton, so we can only create 1 of a kind, maybe not create but we have only 1 instance when we inject in a controller, so a service provides more like a common service(rest calls,functionality.. ) to the controllers.

Conceptually you can think like services provide a service, factories can create multiple instances(objects) of a class

Conveniently map between enum and int / String

given:

public enum BonusType { MONTHLY(0), YEARLY(1), ONE_OFF(2) }

BonusType bonus = YEARLY;

System.out.println(bonus.Ordinal() + ":" + bonus)

Output: 1:YEARLY

How to drop all tables in a SQL Server database?

How about dropping the entire database and then creating it again? This works for me.

DROP DATABASE mydb;
CREATE DATABASE mydb;

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

_x000D_
_x000D_
function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
_x000D_
_x000D_

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

_x000D_
_x000D_
function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    },_x000D_
    date = str.split(" ");_x000D_
_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
_x000D_
_x000D_

How do I get the YouTube video ID from a URL?

i wrote a function for that below:

function getYoutubeUrlId (url) {
    const urlObject = new URL(url);
    let urlOrigin = urlObject.origin;
    let urlPath = urlObject.pathname;

    if (urlOrigin.search('youtu.be') > -1) {
        return urlPath.substr(1);
    }

    if (urlPath.search('embed') > -1) {
        // Örnegin "/embed/wCCSEol8oSc" ise "wCCSEol8oSc" return eder.
        return urlPath.substr(7);
    }

   
    return urlObject.searchParams.get('v');
},

https://gist.github.com/semihkeskindev/8a4339c27203c5fabaf2824308c7868f

The pipe ' ' could not be found angular2 custom pipe

I have created a module for pipes in the same directory where my pipes are present

import { NgModule } from '@angular/core';
///import pipe...
import { Base64ToImage, TruncateString} from './'  

   @NgModule({
        imports: [],
        declarations: [Base64ToImage, TruncateString],
        exports: [Base64ToImage, TruncateString]
    })

    export class SharedPipeModule { }   

Now import that module in app.module:

import {SharedPipeModule} from './pipe/shared.pipe.module'
 @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

Now it can be used by importing the same in the nested module

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

What does the exclamation mark do before the function?

The function:

function () {}

returns nothing (or undefined).

Sometimes we want to call a function right as we create it. You might be tempted to try this:

function () {}()

but it results in a SyntaxError.

Using the ! operator before the function causes it to be treated as an expression, so we can call it:

!function () {}()

This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way:

(function () {})()

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

Custom pagination view in Laravel 5

If you want to customize your pagination link using next and prev. You can see at Paginator.php Inside it, there's some method I'm using Laravel 7

<a href="{{ $paginator->previousPageUrl() }}" < </a>
<a href="{{ $paginator->nextPageUrl() }}" > </a>

To limit items, in controller using paginate()

$paginator = Model::paginate(int);

AttributeError: 'module' object has no attribute

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone

Run PowerShell scripts on remote PC

The accepted answer didn't work for me but the following did:

>PsExec.exe \\<SERVER FQDN> -u <DOMAIN\USER> -p <PASSWORD> /accepteula cmd 
    /c "powershell -noninteractive -command gci c:\"

Example from here

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

Difference between window.location.href, window.location.replace and window.location.assign

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.

Setting java locale settings

If you ever want to check what locale or character set java is using this is built into the JVM:

java -XshowSettings -version

and it will dump out loads of the settings it's using. This way you can check your LANG and LC_* values are getting picked up correctly.

Set the text in a span

Give an ID to your span and then change the text of target span.

$("#StatusTitle").text("Info");
$("#StatusTitleIcon").removeClass("fa-exclamation").addClass("fa-info-circle"); 

<i id="StatusTitleIcon" class="fa fa-exclamation fa-fw"></i>
<span id="StatusTitle">Error</span>

Here "Error" text will become "Info" and their fontawesome icons will be changed as well.

Delete the first three rows of a dataframe in pandas

You can use python slicing, but note it's not in-place.

In [15]: import pandas as pd
In [16]: import numpy as np
In [17]: df = pd.DataFrame(np.random.random((5,2)))
In [18]: df
Out[18]:
          0         1
0  0.294077  0.229471
1  0.949007  0.790340
2  0.039961  0.720277
3  0.401468  0.803777
4  0.539951  0.763267

In [19]: df[3:]
Out[19]:
          0         1
3  0.401468  0.803777
4  0.539951  0.763267

How do I use Wget to download all images into a single folder, from a URL?

Try this:

wget -nd -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.somedomain.com

Here is some more information:

-nd prevents the creation of a directory hierarchy (i.e. no directories).

-r enables recursive retrieval. See Recursive Download for more information.

-P sets the directory prefix where all files and directories are saved to.

-A sets a whitelist for retrieving only certain file types. Strings and patterns are accepted, and both can be used in a comma separated list (as seen above). See Types of Files for more information.

Java: How to check if object is null?

It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

What is a regular expression for a MAC Address?

A little hard on the eyes, but this:

/^(?:[[:xdigit:]]{2}([-:]))(?:[[:xdigit:]]{2}\1){4}[[:xdigit:]]{2}$/

will enforce either all colons or all dashes for your MAC notation.

(A simpler regex approach might permit A1:B2-C3:D4-E5:F6, for example, which the above rejects.)

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

How to hide the keyboard when I press return key in a UITextField?

set delegate of UITextField, and over ride, textFieldShouldReturn method, in that method just write following two lines:

[textField resignFirstResponder];
return YES;

that's it. Before writing a code dont forget to set delegate of a UITextField and set Return key type to "Done" from properties window.(command + shift + I).

Not able to start Genymotion device

I'm using Windows 10 and had the same problem. I resolved it updating the VirtualBox to version 5.1.5. I hope it can help.

Opening a folder in explorer and selecting a file

It might be a bit of a overkill but I like convinience functions so take this one:

    public static void ShowFileInExplorer(FileInfo file) {
        StartProcess("explorer.exe", null, "/select, "+file.FullName.Quote());
    }
    public static Process StartProcess(FileInfo file, params string[] args) => StartProcess(file.FullName, file.DirectoryName, args);
    public static Process StartProcess(string file, string workDir = null, params string[] args) {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.FileName = file;
        proc.Arguments = string.Join(" ", args);
        Logger.Debug(proc.FileName, proc.Arguments); // Replace with your logging function
        if (workDir != null) {
            proc.WorkingDirectory = workDir;
            Logger.Debug("WorkingDirectory:", proc.WorkingDirectory); // Replace with your logging function
        }
        return Process.Start(proc);
    }

This is the extension function I use as <string>.Quote():

static class Extensions
{
    public static string Quote(this string text)
    {
        return SurroundWith(text, "\"");
    }
    public static string SurroundWith(this string text, string surrounds)
    {
        return surrounds + text + surrounds;
    }
}

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

time delayed redirect?

Include this code somewhere when you slide to your 'section' called blog.

$("#myLink").click(function() {
    setTimeout(function() {
        window.navigate("the url of the page you want to navigate back to");
    }, 2000);
});

Where myLink is the id of your href.

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

How to run a Powershell script from the command line and pass a directory as a parameter

you are calling a script file not a command so you have to use -file eg :

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

for PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

Launch custom android application from android browser

The following link gives information on launching the app (if installed) directly from browser. Otherwise it directly opens up the app in play store so that user can seamlessly download.

https://developer.chrome.com/multidevice/android/intents

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

VB.NET: how to prevent user input in a ComboBox

Set the ReadOnly attribute to true.

Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.

How to change the background-color of jumbrotron?

You don't necessarily have to use custom CSS (or even worse inline CSS), in Bootstrap 4 you can use the utility classes for colors, like:

<div class="jumbotron bg-dark text-white">
...

And if you need other colors than the default ones, just add additional bg-classes using the same naming convention. This keeps the code neat and understandable.

You might also need to set text-white on child-elements inside the jumbotron, like headings.

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

Get current working directory in a Qt application

To add on to KaZ answer, Whenever I am making a QML application I tend to add this to the main c++

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardPaths>

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;

// get the applications dir path and expose it to QML 

QUrl appPath(QString("%1").arg(app.applicationDirPath()));
engine.rootContext()->setContextProperty("appPath", appPath);


// Get the QStandardPaths home location and expose it to QML 
QUrl userPath;
   const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
   if (usersLocation.isEmpty())
       userPath = appPath.resolved(QUrl("/home/"));
   else
      userPath = QString("%1").arg(usersLocation.first());
   engine.rootContext()->setContextProperty("userPath", userPath);

   QUrl imagePath;
      const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
      if (picturesLocation.isEmpty())
          imagePath = appPath.resolved(QUrl("images"));
      else
          imagePath = QString("%1").arg(picturesLocation.first());
      engine.rootContext()->setContextProperty("imagePath", imagePath);

      QUrl videoPath;
      const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation);
      if (moviesLocation.isEmpty())
          videoPath = appPath.resolved(QUrl("./"));
      else
          videoPath = QString("%1").arg(moviesLocation.first());
      engine.rootContext()->setContextProperty("videoPath", videoPath);

      QUrl homePath;
      const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
      if (homesLocation.isEmpty())
          homePath = appPath.resolved(QUrl("/"));
      else
          homePath = QString("%1").arg(homesLocation.first());
      engine.rootContext()->setContextProperty("homePath", homePath);

      QUrl desktopPath;
      const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
      if (desktopsLocation.isEmpty())
          desktopPath = appPath.resolved(QUrl("/"));
      else
          desktopPath = QString("%1").arg(desktopsLocation.first());
      engine.rootContext()->setContextProperty("desktopPath", desktopPath);

      QUrl docPath;
      const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
      if (docsLocation.isEmpty())
          docPath = appPath.resolved(QUrl("/"));
      else
          docPath = QString("%1").arg(docsLocation.first());
      engine.rootContext()->setContextProperty("docPath", docPath);


      QUrl tempPath;
      const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
      if (tempsLocation.isEmpty())
          tempPath = appPath.resolved(QUrl("/"));
      else
          tempPath = QString("%1").arg(tempsLocation.first());
      engine.rootContext()->setContextProperty("tempPath", tempPath);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}

Using it in QML

....
........
............
Text{
text:"This is the applications path: " + appPath
+ "\nThis is the users home directory: " + homePath
+ "\nThis is the Desktop path: " desktopPath;
}

Eclipse - Failed to create the java virtual machine

You can also try closing other programs. :)

It's pretty simple, but worked for me. In my case the VM just don't had enough memory to run, and i got the same message. So i had to clean up the ram, by closing unnecessary programs.

CSV file written with Python has blank lines between each row

When using Python 3 the empty lines can be avoid by using the codecs module. As stated in the documentation, files are opened in binary mode so no change of the newline kwarg is necessary. I was running into the same issue recently and that worked for me:

with codecs.open( csv_file,  mode='w', encoding='utf-8') as out_csv:
     csv_out_file = csv.DictWriter(out_csv)

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

How to pause for specific amount of time? (Excel/VBA)

You can use Application.wait now + timevalue("00:00:01") or Application.wait now + timeserial(0,0,1)

How to send an HTTPS GET Request in C#

Add ?var1=data1&var2=data2 to the end of url to submit values to the page via GET:

using System.Net;
using System.IO;

string url = "https://www.example.com/scriptname.php?var1=hello";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

php check if array contains all array values from another array

How about this:

function array_keys_exist($searchForKeys = array(), $searchableArray) {
    $searchableArrayKeys = array_keys($searchableArray);

    return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); 
}

How do I get the color from a hexadecimal color code using .NET?

in asp.net:

color_black = (Color)new ColorConverter().ConvertFromString("#FF76B3");

Get item in the list in Scala?

Please use parenthesis () to access the list elements list_name(index)