Programs & Examples On #Mmx

MMX is a single instruction, multiple data (SIMD) instruction set designed by Intel, introduced in 1997 with their P5-based Pentium line of microprocessors, designated as "Pentium with MMX Technology"

Mailx send html message

If you use AIX try this This will attach a text file and include a HTML body If this does not work catch the output in the /var/spool/mqueue

#!/usr/bin/kWh
if (( $# < 1 ))
 then
  echo "\n\tSyntax: $(basename) MAILTO SUBJECT BODY.html ATTACH.txt "
  echo "\tmailzatt"
  exit
fi
export MAILTO=${[email protected]}
MAILFROM=$(whoami)
SUBJECT=${2-"mailzatt"}
export BODY=${3-/apps/bin/attch.txt}
export ATTACH=${4-/apps/bin/attch.txt}
export HST=$(hostname)
#export BODY="/wrk/stocksum/report.html"
#export ATTACH="/wrk/stocksum/Report.txt"
#export MAILPART=`uuidgen` ## Generates Unique ID
#export MAILPART_BODY=`uuidgen` ## Generates Unique ID
export MAILPART="==".$(date +%d%S)."===" ## Generates Unique ID
export MAILPART_BODY="==".$(date +%d%Sbody)."===" ## Generates Unique ID
(
echo "To: $MAILTO"
 echo "From: mailmate@$HST "
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
 echo ""
 echo ""
 echo "--$MAILPART_BODY"
 echo "Content-Type: text/html"
 echo "Content-Disposition: inline"
 cat $BODY
 echo ""
 echo "--$MAILPART_BODY--"
 echo ""
 echo "--$MAILPART"
 echo "Content-Type: text/plain"
 echo "Content-Disposition: attachment; filename=\"$(basename $ATTACH)\""
 echo ""
 cat $ATTACH
 echo ""
 echo "--${MAILPART}--"
  ) | /usr/sbin/sendmail -t

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Here is assembly code:

7f0b024734be:       48 8d 14 f5 00 00 00    lea    rdx,[rsi*8]
7f0b024734c5:       00
7f0b024734c6:       48 03 13                add    rdx,QWORD PTR [rbx]
7f0b024734c9:       48 8d 7a 10             lea    rdi,[rdx+16]
7f0b024734cd:       8b 5f 08                mov    ebx,DWORD PTR [rdi+8]
7f0b024734d0:       89 d8                   mov    eax,ebx
7f0b024734d2:       c1 f8 03                sar    eax,0x3
7f0b024734d5:       85 db                   test   ebx,ebx
7f0b024734d7:       0f 8e cb 05 00 00       jle    0x7f0b02473aa8

And what it does is:

rdx = 0x00007f0a808d4ed2 * 8; // equals 0x0003F854046A7690. WTF???
rdx = rdx + something from old gen heap; // results 0x000600007f090486
rdi = rdx + 16; // results 0x000600007f090496
ebx = something from edi address (0x000600007f090496) + 8

Well I've had a look at the address map and there is nothing mapped to 0x000600007f090496 which is why you are getting a SEGV. Are you getting the same error with 1.6.0_26 JVM? Can you try it on a 32bit JVM? Looks like a JVM issue to me. Why would it do the first rdx=0x0... * 8 thing?

How do I monitor the computer's CPU, memory, and disk usage in Java?

Along the lines of what I mentioned in this post. I recommend you use the SIGAR API. I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a GPL 2 Apache 2.0 license. Check it out. I have a feeling it will meet your needs.

Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.

How to stop app that node.js express 'npm start'

When I tried the suggested solution I realized that my app name was truncated. I read up on process.title in the nodejs documentation (https://nodejs.org/docs/latest/api/process.html#process_process_title) and it says

On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

My app does not use any arguments, so I can add this line of code to my app.js

process.title = process.argv[2];

and then add these few lines to my package.json file

  "scripts": {
    "start": "node app.js this-name-can-be-as-long-as-it-needs-to-be",
    "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be"
  },

to use really long process names. npm start and npm stop work, of course npm stop will always terminate all running processes, but that is ok for me.

Using Panel or PlaceHolder

A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.

COALESCE Function in TSQL

There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/

Android: checkbox listener

Translation of the accepted answer by Chris into Kotlin:

val checkBox: CheckBox = findViewById(R.id.chk)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
    // Code here 
}

how to prevent adding duplicate keys to a javascript array

function check (list){
    var foundRepeatingValue = false;
    var newList = [];
    for(i=0;i<list.length;i++){
        var thisValue = list[i];
        if(i>0){
            if(newList.indexOf(thisValue)>-1){
                foundRepeatingValue = true;
                console.log("getting repeated");
                return true;
            }
       } newList.push(thisValue);
    } return false;
}

 

var list1 = ["dse","dfg","dse"];
check(list1);

Output:

getting repeated
true

How can I parse a string with a comma thousand separator to a number?

This converts a number in whatever locale to normal number. Works for decimals points too:

function numberFromLocaleString(stringValue, locale){
    var parts = Number(1111.11).toLocaleString(locale).replace(/\d+/g,'').split('');
    if (stringValue === null)
        return null;
    if (parts.length==1) {
        parts.unshift('');
    }   
    return Number(String(stringValue).replace(new RegExp(parts[0].replace(/\s/g,' '),'g'), '').replace(parts[1],"."));
}
//Use default browser locale
numberFromLocaleString("1,223,333.567") //1223333.567

//Use specific locale
numberFromLocaleString("1 223 333,567", "ru") //1223333.567

How to check if JSON return is empty with jquery

if (!json[0]) alert("JSON empty");

Listing only directories in UNIX

The following

find * -maxdepth 0 -type d

basically filters the expansion of '*', i.e. all entries in the current dir, by the -type d condition.

Advantage is that, output is same as ls -1 *, but only with directories and entries do not start with a dot

Java synchronized method lock on object, or method?

The lock accessed is on the object, not on the method. Which variables are accessed within the method is irrelevant.

Adding "synchronized" to the method means the thread running the code must acquire the lock on the object before proceeding. Adding "static synchronized" means the thread running the code must acquire the lock on the class object before proceeding. Alternatively you can wrap code in a block like this:

public void addA() {
    synchronized(this) {
        a++;
    }
}

so that you can specify the object whose lock must be acquired.

If you want to avoid locking on the containing object you can choose between:

Firebase cloud messaging notification not received by device

You have placed your service outside the application tag. Change bottom to this.

<service
    android:name=".NotificationGenie">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

</application>

Checking host availability by using ping in bash scripts

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Save multiple sheets to .pdf

Similar to Tim's answer - but with a check for 2007 (where the PDF export is not installed by default):

Public Sub subCreatePDF()

    If Not IsPDFLibraryInstalled Then
        'Better show this as a userform with a proper link:
        MsgBox "Please install the Addin to export to PDF. You can find it at http://www.microsoft.com/downloads/details.aspx?familyid=4d951911-3e7e-4ae6-b059-a2e79ed87041". 
        Exit Sub
    End If

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ActiveWorkbook.Path & Application.PathSeparator & _
        ActiveSheet.Name & " für " & Range("SelectedName").Value & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

Private Function IsPDFLibraryInstalled() As Boolean
'Credits go to Ron DeBruin (http://www.rondebruin.nl/pdf.htm)
    IsPDFLibraryInstalled = _
        (Dir(Environ("commonprogramfiles") & _
        "\Microsoft Shared\OFFICE" & _
        Format(Val(Application.Version), "00") & _
        "\EXP_PDF.DLL") <> "")
End Function

SQLAlchemy: print the actual query

We can use compile method for this purpose. From the docs:

from sqlalchemy.sql import text
from sqlalchemy.dialects import postgresql

stmt = text("SELECT * FROM users WHERE users.name BETWEEN :x AND :y")
stmt = stmt.bindparams(x="m", y="z")

print(stmt.compile(dialect=postgresql.dialect(),compile_kwargs={"literal_binds": True}))

Result:

SELECT * FROM users WHERE users.name BETWEEN 'm' AND 'z'

Warning from docs:

Never use this technique with string content received from untrusted input, such as from web forms or other user-input applications. SQLAlchemy’s facilities to coerce Python values into direct SQL string values are not secure against untrusted input and do not validate the type of data being passed. Always use bound parameters when programmatically invoking non-DDL SQL statements against a relational database.

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

How to stop default link click behavior with jQuery

You can use e.preventDefault(); instead of e.stopPropagation();

JavaScript variable assignments from tuples

Here is a version of Matthew James Davis's answer with the Python tuple methods added in:

_x000D_
_x000D_
class Tuple extends Array { 
  constructor(...items) { 
    super(...items); 
    Object.freeze(this);
  }
  toArray() {
    return [...this];
  }
  toString() {
    return '('+super.toString()+')';
  }
  count(item) {
    var arr = this.toArray();
    var result = 0;
    for(var i = 0; i < arr.length; i++) {
       if(arr[i] === item) {
         result++;
       }
    }
    return result;
  }

  

  
}

   let tuple = new Tuple("Jim", 35);
   let [name,age] = tuple;

console.log("tuple:"+tuple)
console.log("name:"+name)
console.log("age:"+age)
_x000D_
_x000D_
_x000D_

How to search images from private 1.0 registry in docker?

Was able to get everything in my private registry back by searching just for 'library':

docker search [my.registry.host]:[port]/library

Returns (e.g.):

NAME                    DESCRIPTION   STARS     OFFICIAL   AUTOMATED
library/custom-image                  0                    
library/another-image                 0                    
library/hello-world                   0

Multiple returns from a function

Does PHP still use "out parameters"? If so, you can use the syntax to modify one or more of the parameters going in to your function then. You would then be free to use the modified variable after your function returns.

How to change already compiled .class file without decompile?

Sometime we need to compile one single file out of thousand files to fix the problem. In such a case, One can create same folder structure like class path, decompile the file into java or copy java file from source code. Make required changes, compile one particular file into class with all dependency/classes in place and finally replace the class file. Finally restart the container. Once war is exploded file will not be replaced.

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

SOAP and REST both refer to ways for different systems to talk to each other.

REST does this using techniques that resemble the communication that your browser has with web servers: using GET to request a web page, POSTing in form fields, etc.

SOAP provides for something similar but does everything through sending blocks of XML back and forth. Another key component of SOAP is WSDL which is an XML document that describes what functions and data elements are supported. WSDLs can be used to programmatically "discover" what functions are supported as well as to generate programming code stubs.

How to calculate the difference between two dates using PHP?

I'm using the following function which I wrote, when PHP 5.3 (respectively date_diff()) is not available:

        function dateDifference($startDate, $endDate)
        {
            $startDate = strtotime($startDate);
            $endDate = strtotime($endDate);
            if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate)
                return false;

            $years = date('Y', $endDate) - date('Y', $startDate);

            $endMonth = date('m', $endDate);
            $startMonth = date('m', $startDate);

            // Calculate months
            $months = $endMonth - $startMonth;
            if ($months <= 0)  {
                $months += 12;
                $years--;
            }
            if ($years < 0)
                return false;

            // Calculate the days
            $measure = ($months == 1) ? 'month' : 'months';
            $days = $endDate - strtotime('+' . $months . ' ' . $measure, $startDate);
            $days = date('z', $days);   

            return array($years, $months, $days);
        }

How to get main window handle from process id?

Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.

Convert XML String to Object

If you have the xsd of the xml message then you can generate c# classes using the .Net xsd.exe tool.

This .Net classes can then be used to generate the xml.

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

Bootstrap 3 hidden-xs makes row narrower

How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.

<div class="container">
    <div class="row">
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col1
        </div>
        <div class="col-xs-4 col-sm-2" align="center">
            Col2
        </div>
        <div class="hidden-xs col-sm-6 col-md-5" align="center">
            Col3
        </div>
        <div class="visible-md col-md-3 " align="center">
            Col4
        </div>
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col5
        </div>
    </div>
</div>

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

Convert pem key to ssh-rsa format

To answer my own question, after posting on openssl mailing list got this:

Here is C code to convert from an OpenSSL public key to an OpenSSH public key. You can grab the code from this link and compile it yourself:

static unsigned char pSshHeader[11] = { 0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2D, 0x72, 0x73, 0x61};

static int SshEncodeBuffer(unsigned char *pEncoding, int bufferLen, unsigned char* pBuffer)
{
   int adjustedLen = bufferLen, index;
   if (*pBuffer & 0x80)
   {
      adjustedLen++;
      pEncoding[4] = 0;
      index = 5;
   }
   else
   {
      index = 4;
   }
   pEncoding[0] = (unsigned char) (adjustedLen >> 24);
   pEncoding[1] = (unsigned char) (adjustedLen >> 16);
   pEncoding[2] = (unsigned char) (adjustedLen >>  8);
   pEncoding[3] = (unsigned char) (adjustedLen      );
   memcpy(&pEncoding[index], pBuffer, bufferLen);
   return index + bufferLen;
}

int main(int argc, char**  argv)
{
   int iRet = 0;
   int nLen = 0, eLen = 0;
   int encodingLength = 0;
   int index = 0;
   unsigned char *nBytes = NULL, *eBytes = NULL;
   unsigned char* pEncoding = NULL;
   FILE* pFile = NULL;
   EVP_PKEY *pPubKey = NULL;
   RSA* pRsa = NULL;
   BIO *bio, *b64;

   ERR_load_crypto_strings(); 
   OpenSSL_add_all_algorithms();

   if (argc != 3)
   {
      printf("usage: %s public_key_file_name ssh_key_description\n", argv[0]);
      iRet = 1;
      goto error;
   }

   pFile = fopen(argv[1], "rt");
   if (!pFile)
   {
      printf("Failed to open the given file\n");
      iRet = 2;
      goto error;
   }

   pPubKey = PEM_read_PUBKEY(pFile, NULL, NULL, NULL);
   if (!pPubKey)
   {
      printf("Unable to decode public key from the given file: %s\n", ERR_error_string(ERR_get_error(), NULL));
      iRet = 3;
      goto error;
   }

   if (EVP_PKEY_type(pPubKey->type) != EVP_PKEY_RSA)
   {
      printf("Only RSA public keys are currently supported\n");
      iRet = 4;
      goto error;
   }

   pRsa = EVP_PKEY_get1_RSA(pPubKey);
   if (!pRsa)
   {
      printf("Failed to get RSA public key : %s\n", ERR_error_string(ERR_get_error(), NULL));
      iRet = 5;
      goto error;
   }

   // reading the modulus
   nLen = BN_num_bytes(pRsa->n);
   nBytes = (unsigned char*) malloc(nLen);
   BN_bn2bin(pRsa->n, nBytes);

   // reading the public exponent
   eLen = BN_num_bytes(pRsa->e);
   eBytes = (unsigned char*) malloc(eLen);
   BN_bn2bin(pRsa->e, eBytes);

   encodingLength = 11 + 4 + eLen + 4 + nLen;
   // correct depending on the MSB of e and N
   if (eBytes[0] & 0x80)
      encodingLength++;
   if (nBytes[0] & 0x80)
      encodingLength++;

   pEncoding = (unsigned char*) malloc(encodingLength);
   memcpy(pEncoding, pSshHeader, 11);

   index = SshEncodeBuffer(&pEncoding[11], eLen, eBytes);
   index = SshEncodeBuffer(&pEncoding[11 + index], nLen, nBytes);

   b64 = BIO_new(BIO_f_base64());
   BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
   bio = BIO_new_fp(stdout, BIO_NOCLOSE);
   BIO_printf(bio, "ssh-rsa ");
   bio = BIO_push(b64, bio);
   BIO_write(bio, pEncoding, encodingLength);
   BIO_flush(bio);
   bio = BIO_pop(b64);
   BIO_printf(bio, " %s\n", argv[2]);
   BIO_flush(bio);
   BIO_free_all(bio);
   BIO_free(b64);

error:
   if (pFile)
      fclose(pFile);
   if (pRsa)
      RSA_free(pRsa);
   if (pPubKey)
      EVP_PKEY_free(pPubKey);
   if (nBytes)
      free(nBytes);
   if (eBytes)
      free(eBytes);
   if (pEncoding)
      free(pEncoding);

   EVP_cleanup();
   ERR_free_strings();
   return iRet;
}

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

iOS 7: UITableView shows under status bar

Here is a Swift 2.3. (Xcode 8.0) solution. I have created a subclass of UITableView.

class MYCustomTableView: UITableView
{   
    override func drawRect(rect: CGRect) {
        super.drawRect(rect)
        contentInset    = UIEdgeInsetsZero
    }
}

The content Inset should always be Zero (by default). I am setting it Zero manually. You can also add a check method which makes the check and if it is anything other than what you want it to be just get the correct rect. The change will reflect only when the tableview is drawn (which does not happen often).

Don't forget to update the TableView in your IB (in the TableViewController or just TableView inside your ViewController).

Python Requests throwing SSLError

If you want to remove the warnings, use the code below.

import urllib3

urllib3.disable_warnings()

and verify=False with request.get or post method

Chrome not rendering SVG referenced via <img> tag

For me setting width / height to the img worked. <asp:Image runat="server" ID="Icon" Style="max-width: 50px; max-height: 50px; position: relative;" />

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

There's a nice bookmarklet called Visual Event that can show you all the events attached to an element. It has color-coded highlights for different types of events (mouse, keyboard, etc.). When you hover over them, it shows the body of the event handler, how it was attached, and the file/line number (on WebKit and Opera). You can also trigger the event manually.

It can't find every event because there's no standard way to look up what event handlers are attached to an element, but it works with popular libraries like jQuery, Prototype, MooTools, YUI, etc.

What is Activity.finish() method doing exactly?

Various answers and notes are claiming that finish() can skip onPause() and onStop() and directly execute onDestroy(). To be fair, the Android documentation on this (http://developer.android.com/reference/android/app/Activity.html) notes "Activity is finishing or being destroyed by the system" which is pretty ambiguous but might suggest that finish() can jump to onDestroy().

The JavaDoc on finish() is similarly disappointing (http://developer.android.com/reference/android/app/Activity.html#finish()) and does not actually note what method(s) are called in response to finish().

So I wrote this mini-app below which logs each state upon entry. It includes a button which calls finish() -- so you can see the logs of which methods get fired. This experiment would suggested that finish() does indeed also call onPause() and onStop(). Here is the output I get:

2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO? User just clicked button to initiate finish() 
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStop 
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onDestroy

package com.mvvg.apps.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndroidLifecycle extends Activity {

    private static final String TAG = "LIFECYCLE_DEMO";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "INSIDE: onCreate");
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
        Button button = new Button(this);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "User just clicked button to initiate finish()");
                finish();
            }

        });

        layout.addView(button);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "INSIDE: onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "INSIDE: onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "INSIDE: onDestroy");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "INSIDE: onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "INSIDE: onResume");
    }

}

Autowiring fails: Not an managed Type

Refering to Oliver Gierke's hint:

When the manipulation of the persistance.xml does the trick, then you created a normal java-class instead of a entity-class.

When creating a new entity-class then the entry in the persistance.xml should be set by Netbeans (in my case).

But as mentioned by Oliver Gierke you can add the entry later to the persistance.xml (if you created a normal java-class).

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

What's the difference between a single precision and double precision floating point operation?

Double precision means the numbers takes twice the word-length to store. On a 32-bit processor, the words are all 32 bits, so doubles are 64 bits. What this means in terms of performance is that operations on double precision numbers take a little longer to execute. So you get a better range, but there is a small hit on performance. This hit is mitigated a little by hardware floating point units, but its still there.

The N64 used a MIPS R4300i-based NEC VR4300 which is a 64 bit processor, but the processor communicates with the rest of the system over a 32-bit wide bus. So, most developers used 32 bit numbers because they are faster, and most games at the time did not need the additional precision (so they used floats not doubles).

All three systems can do single and double precision floating operations, but they might not because of performance. (although pretty much everything after the n64 used a 32 bit bus so...)

Why does SSL handshake give 'Could not generate DH keypair' exception?

If the server supports a cipher that does not include DH, you can force the client to select that cipher and avoid the DH error. Such as:

String pickedCipher[] ={"TLS_RSA_WITH_AES_256_CBC_SHA"};
sslsocket.setEnabledCipherSuites(pickedCipher);

Keep in mind that specifying an exact cipher is prone to breakage in the long run.

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

Difference between a View's Padding and Margin

In addition to all the correct answers above, one other difference is that padding increases the clickable area of a view, whereas margins do not. This is useful if you have a smallish clickable image but want to make the click handler forgiving.

For eg, see this image of my layout with an ImageView (the Android icon) where I set the paddingBotton to be 100dp (the image is the stock launcher mipmap ic_launcher). With the attached click handler I was able to click way outside and below the image and still register a click.

enter image description here

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Instead of overriding the library search path at runtime with LD_LIBRARY_PATH, you could instead bake it into the binary itself with rpath. If you link with GCC adding -Wl,-rpath,<libdir> should do the trick, if you link with ld it's just -rpath <libdir>.

How to redirect and append both stdout and stderr to a file with Bash?

In Bash 4 (as well as ZSH 4.3.11):

cmd &>>outfile

just out of box

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to easily initialize a list of Tuples?

One technique I think is a little easier and that hasn't been mentioned before here:

var asdf = new [] { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
}.ToList();

I think that's a little cleaner than:

var asdf = new List<Tuple<int, string>> { 
    (Age: 1, Name: "cow"), 
    (Age: 2, Name: "bird")
};

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"Your Date Format"];

set the format to return is....

yyyy-MM-dd return 2015-12-17 date

yyyy-MMM-dd return 2015-Dec-17 date

yy-MM-dd return 15-12-17 date

dd-MM-yy return 17-12-15 date

dd-MM-yyyy return 17-12-2015 date

yyyy-MMM-dd HH:mm:ss return 2015-Dec-17 08:07:13 date and time

yyyy-MMM-dd HH:mm return 2015-Dec-17 08:07 date and time

For more Details Data and Time Format for Click Now.

Thank you.....

Android webview & localStorage

A solution that works on my Android 4.2.2, compiled with build target Android 4.4W:

WebSettings settings = webView.getSettings();
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    File databasePath = getDatabasePath("yourDbName");
    settings.setDatabasePath(databasePath.getPath());
}

CSS: Control space between bullet and <li>

To summarise the other answers here – if you want finer control over the space between bullets and the text in a <li> list item, your options are:

(1) Use a background image:

<style type="text/css">
li {
    list-style-type:none;
    background-image:url(bullet.png);
}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • You can use any image you want for the bullet
  • You can use CSS background-position to position the image pretty much anywhere you want in relation to the text, using pixels, ems or %

Disadvantages:

  • Adds an extra (albeit small) image file to your page, increasing the page weight
  • If a user increases the text size on their browser, the bullet will stay at the original size. It'll also likely get further out of position as the text size increases
  • If you're developing a 'responsive' layout using only percentages for widths, it could be difficult to get the bullet exactly where you want it over a range of screen widths

2. Use padding on the <li> tag

<style type="text/css">
ul {padding-left:1em}
li {padding-left:1em}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • No image = 1 less file to download
  • By adjusting the padding on the <li>, you can add as much extra horizontal space between the bullet and the text as you like
  • If the user increases the text size, the spacing and bullet size should scale proportionally

Disadvantages:

  • Can't move the bullet any closer to the text than the browser default
  • Limited to shapes and sizes of CSS's built-in bullet types
  • Bullet must be same colour as the text
  • No control over vertical positioning of the bullet

(3) Wrap the text in an extra <span> element

<style type="text/css">
li {
    padding-left:1em;
    color:#f00; /* red bullet */
}
li span {
    display:block;
    margin-left:-0.5em;
    color:#000; /* black text */
}
</style>

<ul>
    <li><span>Some text</span></li>
</ul>

Advantages:

  • No image = 1 less file to download
  • You get more control over the position of the bullet than with option (2) – you can move it closer to the text (although despite my best efforts it seems you can't alter the vertical position by adding padding-top to the <span>. Someone else may have a workaround for this, though...)
  • The bullet can be a different colour to the text
  • If the user increases their text size, the bullet should scale in proportion (providing you set the padding & margin in ems not px)

Disadvantages:

  • Requires an extra unsemantic element (this will probably lose you more friends on SO than it will in real life ;) but it's annoying for those who like their code to be as lean and efficient as possible, and it violates the separation of presentation and content that HTML / CSS is supposed to offer)
  • No control over the size and shape of the bullet

Here's hoping for some new list-style features in CSS4, so we can create smarter bullets without resorting to images or exta mark-up :)

Not an enclosing class error Android Studio

String user_email = email.getText().toString().trim();
firebaseAuth
    .createUserWithEmailAndPassword(user_email,user_password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()) {
                Toast.makeText(RegistraionActivity.this, "Registration sucessful", Toast.LENGTH_SHORT).show();
                startActivities(new Intent(RegistraionActivity.this,MainActivity.class));
            }else{
                Toast.makeText(RegistraionActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
            }
        }
    });

How to keep console window open

If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:

if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();

Like other answers have stated, the call to Console.ReadLine() will keep the window open until enter is pressed, but Console.ReadLine() will only be called if the debugger is attached.

The default XML namespace of the project must be the MSBuild XML namespace

If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017 Agent queue.

how to mysqldump remote db from local machine

mysqldump from remote server use SSL

1- Security with SSL

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote_2'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '3333333' REQUIRE SSL;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote_2'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote_2 \
 --password=3333333 \
 --master-data \
 --set-gtid-purged \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=REQUIRED \
 --result-file=/home/db_1.sql

====================================

2 - Security with SSL (REQUIRE X509)

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '1111111' REQUIRE X509;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote \
 --password=1111111 \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=VERIFY_CA \
 --ssl-ca=/usr/local/mysql/data/ssl/ca.pem \
 --ssl-cert=/usr/local/mysql/data/ssl/client-cert.pem \
 --ssl-key=/usr/local/mysql/data/ssl/client-key.pem \
 --result-file=/home/db_name.sql

[Note]

On local server

/usr/local/mysql/data/ssl/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem

Copy this files from remote server for (REQUIRE X509) or if SSL without (REQUIRE X509) do not copy


On remote server

/usr/local/mysql/data/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28  ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  client-key.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  private_key.pem
-rw-r--r-- 1 mysql mysql  451 Apr 16 22:28  public_key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  server-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  server-key.pem

my.cnf

[mysqld]
# SSL
ssl_ca=/usr/local/mysql/data/ca.pem
ssl_cert=/usr/local/mysql/data/server-cert.pem
ssl_key=/usr/local/mysql/data/server-key.pem

Increase Password Security

https://dev.mysql.com/doc/refman/8.0/en/password-security-user.html

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

How to insert strings containing slashes with sed?

replace.txt should be

s/?page=/\/page\//g
s/&//g

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I had this problem before, and the reason is very simple: Check your variables, if there were strings, so put it in quotes '$your_string_variable_here' ,, if it were numerical keep it without any quotes. for example, if I had these data: $name ( It will be string ) $phone_number ( It will be numerical ) So, it will be like that:

$query = "INSERT INTO users (name, phone) VALUES ('$name', $phone)"; Just like that and it will be fixed ^_^

RegEx - Match Numbers of Variable Length

Try this:

{[0-9]{1,3}:[0-9]{1,3}}

The {1,3} means "match between 1 and 3 of the preceding characters".

Logical operators for boolean indexing in Pandas

TLDR; Logical Operators in Pandas are &, | and ~, and parentheses (...) is important!

Python's and, or and not logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.

So the following in python (exp1 and exp2 are expressions which evaluate to a boolean result)...

exp1 and exp2              # Logical AND
exp1 or exp2               # Logical OR
not exp1                   # Logical NOT

...will translate to...

exp1 & exp2                # Element-wise logical AND
exp1 | exp2                # Element-wise logical OR
~exp1                      # Element-wise logical NOT

for pandas.

If in the process of performing logical operation you get a ValueError, then you need to use parentheses for grouping:

(exp1) op (exp2)

For example,

(df['col1'] == x) & (df['col2'] == y) 

And so on.


Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: & for logical AND, | for logical OR, and ~ for logical NOT.

Consider the following setup:

np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df

   A  B  C
0  5  0  3
1  3  7  9
2  3  5  2
3  4  7  6
4  8  8  1

Logical AND

For df above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.

Overloaded Bitwise & Operator
Before continuing, please take note of this particular excerpt of the docs, which state

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses, since by default Python will evaluate an expression such as df.A > 2 & df.B < 3 as df.A > (2 & df.B) < 3, while the desired evaluation order is (df.A > 2) & (df.B < 3).

So, with this in mind, element wise logical AND can be implemented with the bitwise operator &:

df['A'] < 5

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'] > 5

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

(df['A'] < 5) & (df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

And the subsequent filtering step is simply,

df[(df['A'] < 5) & (df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators < and >. See the section of Operator Precedence in the python docs.

If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as

df['A'] < 5 & df['B'] > 5

It is parsed as

df['A'] < (5 & df['B']) > 5

Which becomes,

df['A'] < something_you_dont_want > 5

Which becomes (see the python docs on chained operator comparison),

(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)

Which becomes,

# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2

Which throws

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

So, don't make that mistake!1

Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:

df['A'].lt(5)

0     True
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'].gt(5)

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

df['A'].lt(5) & df['B'].gt(5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

See the section on Flexible Comparisons.. To summarise, we have

+------------------------------+
¦    ¦ Operator   ¦ Function   ¦
¦----+------------+------------¦
¦  0 ¦ >          ¦ gt         ¦
+----+------------+------------¦
¦  1 ¦ >=         ¦ ge         ¦
+----+------------+------------¦
¦  2 ¦ <          ¦ lt         ¦
+----+------------+------------¦
¦  3 ¦ <=         ¦ le         ¦
+----+------------+------------¦
¦  4 ¦ ==         ¦ eq         ¦
+----+------------+------------¦
¦  5 ¦ !=         ¦ ne         ¦
+------------------------------+

Another option for avoiding parentheses is to use DataFrame.query (or eval):

df.query('A < 5 and B > 5')

   A  B  C
1  3  7  9
3  4  7  6

I have extensively documented query and eval in Dynamic Expression Evaluation in pandas using pd.eval().

operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__ which corresponds to the bitwise operator.

import operator 

operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5) 

0    False
1     True
2    False
3     True
4    False
dtype: bool

df[operator.and_(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

You won't usually need this, but it is useful to know.

Generalizing: np.logical_and (and logical_and.reduce)
Another alternative is using np.logical_and, which also does not need parentheses grouping:

np.logical_and(df['A'] < 5, df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
Name: A, dtype: bool

df[np.logical_and(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

np.logical_and is a ufunc (Universal Functions), and most ufuncs have a reduce method. This means it is easier to generalise with logical_and if you have multiple masks to AND. For example, to AND masks m1 and m2 and m3 with &, you would have to do

m1 & m2 & m3

However, an easier option is

np.logical_and.reduce([m1, m2, m3])

This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):

import operator

cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]

m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m 
# array([False,  True, False,  True, False])

df[m]
   A  B  C
1  3  7  9
3  4  7  6

1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.


Logical OR

For the df above, say you'd like to return all rows where A == 3 or B == 7.

Overloaded Bitwise |

df['A'] == 3

0    False
1     True
2     True
3    False
4    False
Name: A, dtype: bool

df['B'] == 7

0    False
1     True
2    False
3     True
4    False
Name: B, dtype: bool

(df['A'] == 3) | (df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[(df['A'] == 3) | (df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

If you haven't yet, please also read the section on Logical AND above, all caveats apply here.

Alternatively, this operation can be specified with

df[df['A'].eq(3) | df['B'].eq(7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

operator.or_
Calls Series.__or__ under the hood.

operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[operator.or_(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

np.logical_or
For two conditions, use logical_or:

np.logical_or(df['A'] == 3, df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df[np.logical_or(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

For multiple masks, use logical_or.reduce:

np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False,  True,  True,  True, False])

df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

Logical NOT

Given a mask, such as

mask = pd.Series([True, True, False])

If you need to invert every boolean value (so that the end result is [False, False, True]), then you can use any of the methods below.

Bitwise ~

~mask

0    False
1    False
2     True
dtype: bool

Again, expressions need to be parenthesised.

~(df['A'] == 3)

0     True
1    False
2    False
3     True
4     True
Name: A, dtype: bool

This internally calls

mask.__invert__()

0    False
1    False
2     True
dtype: bool

But don't use it directly.

operator.inv
Internally calls __invert__ on the Series.

operator.inv(mask)

0    False
1    False
2     True
dtype: bool

np.logical_not
This is the numpy variant.

np.logical_not(mask)

0    False
1    False
2     True
dtype: bool

Note, np.logical_and can be substituted for np.bitwise_and, logical_or with bitwise_or, and logical_not with invert.

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

How to deselect a selected UITableView cell?

This should work:

[tableView deselectRowAtIndexPath:indexpath1 animated:NO];

Just make sure materialTable and tableView are pointing to the same object.

Is materials connected to the tableView in Interface Builder?

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

Refresh Excel VBA Function Results

Some more information on the F9 keyboard shortcuts for calculation in Excel

  • F9 Recalculates all worksheets in all open workbooks
  • Shift+ F9 Recalculates the active worksheet
  • Ctrl+Alt+ F9 Recalculates all worksheets in all open workbooks (Full recalculation)
  • Shift + Ctrl+Alt+ F9 Rebuilds the dependency tree and does a full recalculation

Reading and displaying data from a .txt file

If you want to take some shortcuts you can use Apache Commons IO:

import org.apache.commons.io.FileUtils;

String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);

:-)

Import Error: No module named numpy

this is the problem of the numpy's version, please check out $CAFFE_ROOT/python/requirement.txt. Then exec: sudo apt-get install python-numpy>=x.x.x, this problem will be sloved.

Vertical rulers in Visual Studio Code

In v1.43 is the ability to separately color the vertical rulers.

See issue Support multiple rulers with different colors - (in settings.json):

"editor.rulers": [
  {
    "column": 80,
    "color": "#ff00FF"
  },
  100,  // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
  {
    "column": 120,
    "color": "#ff0000"
  },
], 

How do I verify/check/test/validate my SSH passphrase?

You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add.

Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d.

Get last 30 day records from today date in SQL Server

You can use DateDiff for this. The where clause in your query would look like:

where DATEDIFF(day,pdate,GETDATE()) < 31

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

can you host a private repository for your organization to use with npm?

Verdaccio is what I was looking for and it deserves it's own answer ;) It is an actively maintained fork of Sinopia (highly upvoted answer here). It is a npm registry as a npm package, and can be found

here: https://github.com/verdaccio/verdaccio,
here: https://www.verdaccio.org,
and on port number: 4873

Run using PM2

npm i -g verdaccio pm2
pm2 start --name verdaccio `which verdaccio`
pm2 save

Run using docker

docker run -it --rm --detach --name verdaccio -p 4873:4873 verdaccio/verdaccio

Run using Helm

helm repo add verdaccio https://charts.verdaccio.org
helm repo update
helm install verdaccio/verdaccio

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

How to grant all privileges to root user in MySQL 8.0

I had this same issue, which led me here. In particular, for local development, I wanted to be able to do mysql -u root -p without sudo. I don't want to create a new user. I want to use root from a local PHP web app.

The error message is misleading, as there was nothing wrong with the default 'root'@'%' user privileges.

Instead, as several people mentioned in the other answers, the solution was simply to set bind-address=0.0.0.0 instead of bind-address=127.0.0.1 in my /etc/mysql/mysql.conf.d/mysqld.cnf config. No changes were otherwise required.

Scroll to bottom of div with Vue.js

2021 easy solution that won't hurt your brain... use el.scrollIntoView()

Here is a fiddle.

This solution will not hurt your brain having to think about scrollTop or scrollHeight, has smooth scrolling built in, and even works in IE.

scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'}) to get smooth scrolling.

methods: {
  scrollToElement() {
    const el = this.$el.getElementsByClassName('scroll-to-me')[0];

    if (el) {
      // Use el.scrollIntoView() to instantly scroll to the element
      el.scrollIntoView({behavior: 'smooth'});
    }
  }
}

Then if you wanted to scroll to this element on page load you could call this method like this:

mounted() {
  this.scrollToElement();
}

Else if you wanted to scroll to it on a button click or some other action you could call it the same way:

<button @click="scrollToElement">scroll to me</button>

The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.

How to style child components from parent component's CSS file?

If you want to be more targeted to the actual child component than you should do the follow. This way, if other child components share the same class name, they won't be affected.

Plunker: https://plnkr.co/edit/ooBRp3ROk6fbWPuToytO?p=preview

For example:

import {Component, NgModule } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>I'm the host parent</h2>
      <child-component class="target1"></child-component><br/>
      <child-component class="target2"></child-component><br/>
      <child-component class="target3"></child-component><br/>
      <child-component class="target4"></child-component><br/>
      <child-component></child-component><br/>
    </div>
  `,
  styles: [`

  /deep/ child-component.target1 .child-box {
      color: red !important; 
      border: 10px solid red !important;
  }  

  /deep/ child-component.target2 .child-box {
      color: purple !important; 
      border: 10px solid purple !important;
  }  

  /deep/ child-component.target3 .child-box {
      color: orange !important; 
      border: 10px solid orange !important;
  }  

  /* this won't work because the target component is spelled incorrectly */
  /deep/ xxxxchild-component.target4 .child-box {
      color: orange !important; 
      border: 10px solid orange !important;
  }  

  /* this will affect any component that has a class name called .child-box */
  /deep/ .child-box {
      color: blue !important; 
      border: 10px solid blue !important;
  }  


  `]
})
export class App {
}

@Component({
  selector: 'child-component',
  template: `
    <div class="child-box">
      Child: This is some text in a box
    </div>
  `,
  styles: [`
    .child-box {
      color: green;    
      border: 1px solid green;
    }
  `]
})
export class ChildComponent {
}


@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, ChildComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

Hope this helps!

codematrix

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
    
    Task.Factory.ContinueWhenAll( 
       tasks,
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);
       }
    );
    

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
             {
             //...
             });
          },  
          TaskCreationOptions.AttachedToParent
    );
    
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

Cannot run Eclipse; JVM terminated. Exit code=13

I was using Eclipse Juno and I didn't remember if it was 32 or 64 bits. I installed Java 32 bits and that's why it failed. I then installed Java 64 bits and Eclipse Juno is working again.

I also removed any java or jre reference in my environment variables (PATH).

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

How to find the lowest common ancestor of two nodes in any binary tree?

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root) return NULL;
  if (root == p || root == q) return root;
  Node *L = LCA(root->left, p, q);
  Node *R = LCA(root->right, p, q);
  if (L && R) return root;  // if p and q are on both sides
  return L ? L : R;  // either one of p,q is on one side OR p,q is not in L&R subtrees
}

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

How do I put a border around an Android textview?

This may help you.

<RelativeLayout
    android:id="@+id/textbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@android:color/darker_gray" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_margin="3dp"
        android:background="@android:color/white"
        android:gravity="center"
        android:text="@string/app_name"
        android:textSize="20dp" />

</RelativeLayout

Socket transport "ssl" in PHP not enabled

Success!

After checking the log files and making sure the permissions on php_openssl.dll were correct, I googled the warning and found more things to try.

So I:

  • added C:\PHP\ext to the Windows path
  • added libeay32.dll and ssleay32.dll to C:\WINDOWS\system32\inetsrv
  • rebooted the server

I'm not sure which of these fixed my problem, but it's definately fixed now! :)

I found these things to try on this page: http://php.net/manual/en/install.windows.extensions.php

Thanks for your help!

A server with the specified hostname could not be found

I got this error message when "/" from my URL is missing . Hope this help someone.

ex: actual URL is "https://www.myweb.com/login" .My URL which "https://www.myweb.comlogin" caused this error

What are carriage return, linefeed, and form feed?

Those are non-printing characters, relating to the concept of "new line". \n is linefeed. \r is carriage return. On different platforms they have different meanings, relative to a valid new line. In windows, a new line is \r\n. In linux, \n. In mac, \r.

In practice, you put them in any string, and it will have effect on the print-out of the string.

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

If/else else if in Jquery for a condition

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <form name="myform">
    Enter your name
    <input type="text" name="inputbox" id='textBox' value="" />
    <input type="button" name="button" class="member" value="Click1" />
    <input type="button" name="button" value="Click2" onClick="testResults()" />
  </form>
  <script>
    function testResults(n) {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    }
    $(document).on('click', '.member', function () {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    });
  </script>

How to find whether MySQL is installed in Red Hat?

Type mysql --version to see if it is installed.

To find location use find -name mysql.

How to Read and Write from the Serial Port

SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.

Example Code:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

Security of REST authentication schemes

If you require the hash of the body as one of the parameters in the URL and that URL is signed via a private key, then a man-in-the-middle attack would only be able to replace the body with content that would generate the same hash. Easy to do with MD5 hash values now at least and when SHA-1 is broken, well, you get the picture.

To secure the body from tampering, you would need to require a signature of the body, which a man-in-the-middle attack would be less likely to be able to break since they wouldn't know the private key that generates the signature.

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

How to use orderby with 2 fields in linq?

VB.NET

 MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)

OR

  From l In MyList Order By l.StartDate Ascending, l.EndDate Descending

C++11 reverse range-based for-loop

Does this work for you:

#include <iostream>
#include <list>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator_range.hpp>

int main(int argc, char* argv[]){

  typedef std::list<int> Nums;
  typedef Nums::iterator NumIt;
  typedef boost::range_reverse_iterator<Nums>::type RevNumIt;
  typedef boost::iterator_range<NumIt> irange_1;
  typedef boost::iterator_range<RevNumIt> irange_2;

  Nums n = {1, 2, 3, 4, 5, 6, 7, 8};
  irange_1 r1 = boost::make_iterator_range( boost::begin(n), boost::end(n) );
  irange_2 r2 = boost::make_iterator_range( boost::end(n), boost::begin(n) );


  // prints: 1 2 3 4 5 6 7 8 
  for(auto e : r1)
    std::cout << e << ' ';

  std::cout << std::endl;

  // prints: 8 7 6 5 4 3 2 1
  for(auto e : r2)
    std::cout << e << ' ';

  std::cout << std::endl;

  return 0;
}

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

jquery json to string?

I use

$.param(jsonObj)

which gets me the string.

Pushing empty commits to remote

You won't face any terrible consequence, just the history will look kind of confusing.

You could change the commit message by doing

git commit --amend
git push --force-with-lease # (as opposed to --force, it doesn't overwrite others' work)

BUT this will override the remote history with yours, meaning that if anybody pulled that repo in the meanwhile, this person is going to be very mad at you...

Just do it if you are the only person accessing the repo.

Use Excel pivot table as data source for another Pivot Table

  • Make your first pivot table.

  • Select the first top left cell.

  • Create a range name using offset:

    OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))

  • Make your second pivot with your range name as source of data using F3.

If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot

GFGDT

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

Best way of invoking getter by reflection

I think this should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

Get the value of checked checkbox?

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
    alert(value);
}

How to change font size in html?

Give them a class and add your style to the class.

<style>
  p {
    color: red;
  }
  .paragraph1 {
    font-size: 18px;
  }
  .paragraph2 {
    font-size: 13px;
  }
</style>

<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>

Check this EXAMPLE

How to display HTML <FORM> as inline element?

Move your form tag just outside the paragraph and set margins / padding to zero:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

How to make a <ul> display in a horizontal row

#ul_top_hypers li {
  display: flex;
}

Add a summary row with totals

You could use the ROLLUP operator

SELECT  CASE 
            WHEN (GROUPING([Type]) = 1) THEN 'Total'
            ELSE [Type] END AS [TYPE]
        ,SUM([Total Sales]) as Total_Sales
From    Before
GROUP BY
        [Type] WITH ROLLUP

How to disable horizontal scrolling of UIScrollView?

Use this single line.

self.automaticallyAdjustsScrollViewInsets = NO;

Programmatically center TextView text

For dynamically center

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

How to sanity check a date in Java

As shown by @Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.

However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:

Invalid characters in the date string Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.

Years: 2, 3 or 4 digits? You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")

A Strict Solution with the Standard Library

So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.

  Date parseDate(String maybeDate, String format, boolean lenient) {
    Date date = null;

    // test date string matches format structure using regex
    // - weed out illegal characters and enforce 4-digit year
    // - create the regex based on the local format string
    String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
    reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
    if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {

      // date string matches format structure, 
      // - now test it can be converted to a valid date
      SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
      sdf.applyPattern(format);
      sdf.setLenient(lenient);
      try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
    } 
    return date;
  } 

  // used like this:
  Date date = parseDate( "21/5/2009", "d/M/yyyy", false);

Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:

Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();

Joda Time - Better Alternative?

I've been hearing about joda time recently and thought I'd compare. Two points:

  1. Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat
  2. Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own DateTimeFormatter for this purpose)

It's quite simple to use:

import org.joda.time.format.*;
import org.joda.time.DateTime;

org.joda.time.DateTime parseDate(String maybeDate, String format) {
  org.joda.time.DateTime date = null;
  try {
    DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
    date =  fmt.parseDateTime(maybeDate);
  } catch (Exception e) { }
  return date;
}

How to create an on/off switch with Javascript/CSS?

Initial answer from 2013

If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like those.

Modern 2018 Switch

How to set the timeout for a TcpClient?

You would need to use the async BeginConnect method of TcpClient instead of attempting to connect synchronously, which is what the constructor does. Something like this:

var client = new TcpClient();
var result = client.BeginConnect("remotehost", this.Port, null, null);

var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

if (!success)
{
    throw new Exception("Failed to connect.");
}

// we have connected
client.EndConnect(result);

How to read keyboard-input?

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2. Same Python 3 code as above, but with extensive explanatory comments:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

Related/Cross-Linked:

  1. PySerial non-blocking read loop

PHP XML how to output nice format

// ##### IN SUMMARY #####

$xmlFilepath = 'test.xml';
echoFormattedXML($xmlFilepath);

/*
 * echo xml in source format
 */
function echoFormattedXML($xmlFilepath) {
    header('Content-Type: text/xml'); // to show source, not execute the xml
    echo formatXML($xmlFilepath); // format the xml to make it readable
} // echoFormattedXML

/*
 * format xml so it can be easily read but will use more disk space
 */
function formatXML($xmlFilepath) {
    $loadxml = simplexml_load_file($xmlFilepath);

    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($loadxml->asXML());
    $formatxml = new SimpleXMLElement($dom->saveXML());
    //$formatxml->saveXML("testF.xml"); // save as file

    return $formatxml->saveXML();
} // formatXML

$(window).scrollTop() vs. $(document).scrollTop()

I've just had some of the similar problems with scrollTop described here.

In the end I got around this on Firefox and IE by using the selector $('*').scrollTop(0);

Not perfect if you have elements you don't want to effect but it gets around the Document, Body, HTML and Window disparity. If it helps...

How can I get a favicon to show up in my django app?

In template file

{% load static %}

Then within <head> tag

<link rel="shortcut icon" href="{%  static 'favicon.ico' %}">

This assumes that you have static files configured appropiately in settings.py.


Note: older versions of Django use load staticfiles, not load static.

postgresql - replace all instances of a string within text field

The Regular Expression Way

If you need stricter replacement matching, PostgreSQL's regexp_replace function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).

I will use flags i and g for case-insensitive and global matching, respectively. I will also use \m and \M to match the beginning and the end of a word, respectively.

There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
-->                    Cat bobdog cat cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
-->                    dog bobcat cat cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
-->                    Cat bobdog dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
-->                    dog bobdog dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
-->                    dog bobcat dog dogs dogfish

SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
-->                    dog bobdog dog cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
-->                    dog bobcat dog cats catfish

SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
-->                    dog bobcat dog dogs catfish

Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.

Check out the current PostgreSQL pattern matching docs for all the details.

Update entire column with replacement text

Given my examples, maybe the safest option would be:

UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');

Detect the Internet connection is offline?

There are 2 answers forthis for two different senarios:-

  1. If you are using JavaScript on a website(i.e; or any front-end part) The simplest way to do it is:

    <h2>The Navigator Object</h2>
    
    <p>The onLine property returns true if the browser is online:</p>
    
    <p id="demo"></p>
    
    <script>
      document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
    </script>
    

  2. But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.

    The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

ASP MVC href to a controller/view

Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod

 <a href="~/Home/Download_Excel_File" />

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

How to make Firefox headless programmatically in Selenium with Python?

from selenium.webdriver.firefox.options import Options

if __name__ == "__main__":
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='geckodriver', firefox_options=options) 
    wait = WebDriverWait(driver, timeout=10)
    driver.get('http://www.google.com')

Tested, works as expected and this is from Official - Headless Mode | Mozilla

How can I get date in application run by node.js?

Node.js is a server side JS platform build on V8 which is chrome java-script runtime.

It leverages the use of java-script on servers too.

You can use JS Date() function or Date class.

Facebook Javascript SDK Problem: "FB is not defined"

Try Asynchronous Loading: http://developers.facebook.com/docs/reference/javascript/fb.init/

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId  : 'YOUR APP ID',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
  };

  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

addEventListener vs onclick

element.onclick = function() { /* do stuff */ }

element.addEventListener('click', function(){ /* do stuff */ },false);

They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.

The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties. Example is shown here,

Try it: https://jsfiddle.net/fjets5z4/5/

In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like – that’s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).

However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.

var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");

clickEvent.onclick = function(){
    window.alert("1 is not called")
}
clickEvent.onclick = function(){
    window.alert("1 is not called, 2 is called")
}

EventListener.addEventListener("click",function(){
    window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
    window.alert("2 is also called")
})

C# catch a stack overflow exception

From the MSDN page on StackOverflowExceptions:

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager Interface and Hosting the Common Language Runtime.

How do I get the current username in .NET using C#?

I totally second the other answers, but I would like to highlight one more method which says

String UserName = Request.LogonUserIdentity.Name;

The above method returned me the username in the format: DomainName\UserName. For example, EUROPE\UserName

Which is different from:

String UserName = Environment.UserName;

Which displayed in the format: UserName

And finally:

String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

which gave: NT AUTHORITY\IUSR (while running the application on IIS server) and DomainName\UserName (while running the application on a local server).

SQL Inner Join On Null Values

Are you committed to using the Inner join syntax?

If not you could use this alternative syntax:

SELECT * 
FROM Y,X
WHERE (X.QID=Y.QID) or (X.QUID is null and Y.QUID is null)

Are 64 bit programs bigger and faster than 32 bit versions?

In addition to having more registers, 64-bit has SSE2 by default. This means that you can indeed perform some calculations in parallel. The SSE extensions had other goodies too. But I guess the main benefit is not having to check for the presence of the extensions. If it's x64, it has SSE2 available. ...If my memory serves me correctly.

How to convert a single char into an int

Any problems with the following way of doing it?

int CharToInt(const char c)
{
    switch (c)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    default:
        return 0;
    }
}

Save PHP variables to a text file

Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).

Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.

$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));

A quick and easy way to join array elements with a separator (the opposite of split) in Java

This options is fast and clear:

  public static String join(String separator, String... values) {
    StringBuilder sb = new StringBuilder(128);
    int end = 0;
    for (String s : values) {
      if (s != null) {
        sb.append(s);
        end = sb.length();
        sb.append(separator);
      }
    }
    return sb.substring(0, end);
  }

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

How can I save multiple documents concurrently in Mongoose/Node.js?

Use async parallel and your code will look like this:

  async.parallel([obj1.save, obj2.save, obj3.save], callback);

Since the convention is the same in Mongoose as in async (err, callback) you don't need to wrap them in your own callbacks, just add your save calls in an array and you will get a callback when all is finished.

If you use mapLimit you can control how many documents you want to save in parallel. In this example we save 10 documents in parallell until all items are successfully saved.

async.mapLimit(myArray, 10, function(document, next){
  document.save(next);
}, done);

Textarea to resize based on content length

You may also try contenteditable attribute onto a normal p or div. Not really a textarea but it will auto-resize without script.

_x000D_
_x000D_
.divtext {
    border: ridge 2px;
    padding: 5px;
    width: 20em;
    min-height: 5em;
    overflow: auto;
}
_x000D_
<div class="divtext" contentEditable>Hello World</div>
_x000D_
_x000D_
_x000D_

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

C# send a simple SSH command

SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();

//using SSH.Net

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

How can I run a php without a web server?

For windows system you should be able to run php by following below steps:

  1. Download php version you want to use and put it in c:\php.
  2. append ;c:\php to your system path using cmd or gui.
  3. call $ php -S localhost:8000 command in a folder which you want to serve the pages from.

Detect & Record Audio in Python

The pyaudio website has many examples that are pretty short and clear: http://people.csail.mit.edu/hubert/pyaudio/

Update 14th of December 2019 - Main example from the above linked website from 2017:


"""PyAudio Example: Play a WAVE file."""

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()

Apply multiple functions to multiple groupby columns

This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.

The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                         'height': [9.1, 6.0, 9.5, 34.0],
                         'weight': [7.9, 7.5, 9.9, 198.0]})
 
agg_dict = {
    "min_height": pd.NamedAgg(column='height', aggfunc='min'),
    "max_height": pd.NamedAgg(column='height', aggfunc='max'),
    "average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)
}

animals.groupby("kind").agg(**agg_dict)

The Result

      min_height  max_height  average_weight
kind                                        
cat          9.1         9.5            8.90
dog          6.0        34.0          102.75

Uncaught TypeError: Cannot read property 'value' of null

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)

What does %~dp0 mean, and how does it work?

An example would be nice - here's a trivial one

for %I in (*.*) do @echo %~xI

it lists only the EXTENSIONS of each file in current folder

for more useful variable combinations (also listed in previous response) from the CMD prompt execute: HELP FOR which contains this snippet

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

How to remove the default link color of the html hyperlink 'a' tag?

I had this challenge when I was working on a Rails 6 application using Bootstrap 4.

My challenge was that I didn't want this styling to override the default link styling in the application.

So I created a CSS file called custom.css or custom.scss.

And then defined a new CSS rule with the following properties:

.remove_link_colour {
  a, a:hover, a:focus, a:active {
      color: inherit;
      text-decoration: none;
  }
}

Then I called this rule wherever I needed to override the default link styling.

<div class="product-card__buttons">
  <button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
  <button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>

This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.

That's all.

I hope this helps

Class method differences in Python: bound, unbound and static

The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error. If you want the equivalent of a static method you can use a class method. There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.

How to check radio button is checked using JQuery?

Check this one out, too:

$(document).ready(function() { 
  if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) { 
      //its checked 
  } 
});

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

Inserting values into a SQL Server database using ado.net via C#

Following Code will work for "Inserting values into a SQL Server database using ado.net via C#"

// Your Connection string
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

// Collecting Values
string firstName="Name",
    lastName="LastName",
    userName="UserName",
    password="123",
    gender="Male",
    contact="Contact";
int age=26; 

// Query to be executed
string query = "Insert Into dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FN, @LN, @UN, @Pass, @Age, @Gender, @Contact) ";

    // instance connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // add parameters and their values
        cmd.Parameters.Add("@FN", System.Data.SqlDbType.NVarChar, 100).Value = firstName;
        cmd.Parameters.Add("@LN", System.Data.SqlDbType.NVarChar, 100).Value = lastName;
        cmd.Parameters.Add("@UN", System.Data.SqlDbType.NVarChar, 100).Value = userName;
        cmd.Parameters.Add("@Pass", System.Data.SqlDbType.NVarChar, 100).Value = password;
        cmd.Parameters.Add("@Age", System.Data.SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", System.Data.SqlDbType.NVarChar, 100).Value = gender;
        cmd.Parameters.Add("@Contact", System.Data.SqlDbType.NVarChar, 100).Value = contact;

        // open connection, execute command and close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }    

How to measure height, width and distance of object using camera?

If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.

Even newspaper is printed with some marks on the corners.

You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.

Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.

How can I create an editable combo box in HTML/Javascript?

try doing this

<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2"  style="width: 140px;
    position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
        <div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
    onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
    top: 0px; left: 0px; z-index: 1; width: 165px;">
    <option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>

please look at following example fiddle

How should I throw a divide by zero exception in Java without actually dividing by zero?

Something like:

if(divisor == 0) {
  throw new ArithmeticException("Division by zero!");
}

build-impl.xml:1031: The module has not been deployed

  • Close Netbeans.
  • Delete all libraries in the folder "yourprojectfolder"\build\web\WEB-INF\lib
  • Open Netbeans.
  • Clean and Build project.
  • Deploy project.

PHP Unset Array value effect on other indexes

The Key Disappears, whether it is numeric or not. Try out the test script below.

<?php
    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d

    unset($t[1]);

    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d
?>

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Error while installing json gem 'mkmf.rb can't find header files for ruby'

In Fedora 21 and up, you simply open a terminal and install the Ruby Development files as root.

dnf install ruby-devel

Best way to replace multiple characters in a string?

Here is a python3 method using str.translate and str.maketrans:

s = "abc&def#ghi"
print(s.translate(str.maketrans({'&': '\&', '#': '\#'})))

The printed string is abc\&def\#ghi.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I had the same issue (mysql 5.6 on mac) with 'can't rmdir..'-errors when dropping databases. Leaving an empty database directory not possible to get rid of. Thanks @Framework and @Beel for the solutions.

I first deleted the db directory from the Terminal in (/Applications/XAMPP/xamppfiles/var/mysql).

For further db drops, I also deleted the empty test file. In my case the file was called NOTEMPTY but still containing 0:

sudo ls -al test
total 0
drwxrwx---   3 _mysql  _mysql  102 Mar 26 16:50 .
drwxrwxr-x  18 _mysql  _mysql  612 Apr  7 13:34 ..
-rw-rw----   1 _mysql  _mysql    0 Jun 26  2013 NOTEMPTY

Chmod first and then

sudo rm -rf test/NOTEMPTY

No problems dropping databases after that

How to remove an element from a list by index

One can either use del or pop, but I prefer del, since you can specify index and slices, giving the user more control over the data.

For example, starting with the list shown, one can remove its last element with del as a slice, and then one can remove the last element from the result using pop.

>>> l = [1,2,3,4,5]
>>> del l[-1:]
>>> l
[1, 2, 3, 4]
>>> l.pop(-1)
4
>>> l
[1, 2, 3]

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How to change the Text color of Menu item in Android?

Simply add this to your theme

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:itemTextAppearance">@style/AppTheme.ItemTextStyle</item>
</style>

<style name="AppTheme.ItemTextStyle" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@color/orange_500</item>
</style>

Tested on API 21

How to display JavaScript variables in a HTML page without document.write

Similar to above, but I used (this was in CSHTML):

JavaScript:

var value = "Hello World!"<br>
$('.output').html(value);

CSHTML:

<div class="output"></div>

How to store a large (10 digits) integer?

you can use long or double.

&& (AND) and || (OR) in IF statements

No it won't, Java will short-circuit and stop evaluating once it knows the result.

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

If you use JDK 8+, there is a one line lambda solution:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}

How to select the first element of a set with JSTL?

Using begin and end seemed to work for me to select a range of elements. This gives me three separate lists. The first list with items 1-9, second list with items 10-18, and the last list with items 11-25.

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="0" end="8" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="9" end="17" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="18" end="25" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

Change the selected value of a drop-down list with jQuery

These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.

Things are a little more complicated if this isn't the case.

To read the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex");

To set the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex", 1);

Note that the prop() feature requires JQuery v1.6 or later.

Let's see how you would use these two functions.

Supposing you had a drop down list of month names.

<select id="listOfMonths">
  <option id="JAN">January</option>
  <option id="FEB">February</option>
  <option id="MAR">March</option>
</select>

You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:

<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />

And here's the JavaScript which these buttons would run:

function btnPrevMonth_Click() {
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    if (selectedIndex > 0) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
    }
}
function btnNextMonth_Click() {
    //  Note:  the JQuery "prop" function requires JQuery v1.6 or later
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    var itemsInDropDownList = $("#listOfMonths option").length;

    //  If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
    if (selectedIndex < (itemsInDropDownList - 1)) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
    }
}

My site is also useful for showing how to populate a drop down list with JSON data:

http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

Pass accepts header parameter to jquery ajax

The other answers do not answer the actual question, but rather provide workarounds which is a shame because it literally takes 10 seconds to figure out what the correct syntax for accepts parameter.

The accepts parameter takes an object which maps the dataType to the Accept header. In your case you don't need to even need to pass the accepts object, as setting the data type to json should be sufficient. However if you do want to configure a custom Accept header this is what you do:

accepts: {"*": "my custom mime type" },

How do I know? Open jquery's source code and search for "accepts". The very first find tells you all you need to know:

    accepts: {
        "*": allTypes,
        text: "text/plain",
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript"
    },

As you see the are default mappings to text, html, xml and json data types.

How to upload files to server using JSP/Servlet?

Without component or external Library in Tomcat 6 o 7

Enabling Upload in the web.xml file:

http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <multipart-config>
      <max-file-size>3145728</max-file-size>
      <max-request-size>5242880</max-request-size>
    </multipart-config>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

AS YOU CAN SEE:

    <multipart-config>
      <max-file-size>3145728</max-file-size>
      <max-request-size>5242880</max-request-size>
    </multipart-config>

Uploading Files using JSP. Files:

In the html file

<form method="post" enctype="multipart/form-data" name="Form" >

  <input type="file" name="fFoto" id="fFoto" value="" /></td>
  <input type="file" name="fResumen" id="fResumen" value=""/>

In the JSP File or Servlet

    InputStream isFoto = request.getPart("fFoto").getInputStream();
    InputStream isResu = request.getPart("fResumen").getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buf[] = new byte[8192];
    int qt = 0;
    while ((qt = isResu.read(buf)) != -1) {
      baos.write(buf, 0, qt);
    }
    String sResumen = baos.toString();

Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I've been quite happy with Swing for the desktop applications I've been involved in. However, I do share your view on Swing not offering advanced components. What I've done in these cases is to go for JIDE. It's not free, but not that pricey either and it gives you a whole lot more tools under your belt. Specifically, they do offer a filterable TreeTable.

How the int.TryParse actually works

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

Differences in boolean operators: & vs && and | vs ||

In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.

If both operands mismatch, a compile time error is thrown.

The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:

if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }

source: java programming lang 4th ed

How to set editor theme in IntelliJ Idea

OK I found the problem, I was checking in the wrong place which is for the whole IDE's look and feel at File->Settings->Appearance

The correct place to change the editor appearance is through File->Settings->Editor->Colors &Fonts and then choose the scheme there. The imported settings appear there :)

Note: The theme site seems to have moved.

Add a CSS border on hover without moving the element

Add a border to the regular item, the same color as the background, so that it cannot be seen. That way the item has a border: 1px whether it is being hovered or not.

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST some data to www.abc.com/blog and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog from the same user. So it'll give the 409 error.

How to do a recursive find/replace of a string with awk or sed?

I just needed this and was not happy with the speed of the available examples. So I came up with my own:

cd /var/www && ack-grep -l --print0 subdomainA.example.com | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

Ack-grep is very efficient on finding relevant files. This command replaced ~145 000 files with a breeze whereas others took so long I couldn't wait until they finish.

Centering Bootstrap input fields

Using offsets is not desired for responsive websites.

Use a flexbox with justify content center:

<div class="row d-flex justify-content-center">
  <input></input>
</div>

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

jQuery Ajax POST example with PHP

I have one other idea.

Which the URL that of PHP files which provided the download file. Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file. So you can get the event of it.

It is working via ajax with the same second request.}

Wait for a process to finish

There is no builtin feature to wait for any process to finish.

You could send kill -0 to any PID found, so you don't get puzzled by zombies and stuff that will still be visible in ps (while still retrieving the PID list using ps).

Disable a link in Bootstrap

If what you're trying to do is disable an a link, there is no option to do this. I think you can find an answer that will work for you in this question here.

One option here is to use

<a href="/" onclick="return false;">123n</a>

Disabled href tag

How to get distinct results in hibernate with joins and row-based limiting (paging)?

A small improvement to @FishBoy's suggestion is to use the id projection, so you don't have to hard-code the identifier property name.

criteria.setProjection(Projections.distinct(Projections.id()));

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

use Values either while creating variable X or while encoding as mentioned above

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')

dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values

Pandas dataframe get first row of each group

If you only need the first row from each group we can do with drop_duplicates, Notice the function default method keep='first'.

df.drop_duplicates('id')
Out[1027]: 
    id   value
0    1   first
3    2   first
5    3   first
9    4  second
11   5   first
12   6   first
15   7  fourth

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

If you have already tried all the other logical solutions on this page, then double check this. In my app.config I had a reference to an old framework.

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

should have been

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The project tab correctly showed v4.0 but the app.config was not committed to our repo with that change. To fix it, I changed the framework to something else and back to 4.0 again, which updated my app.config file.

Why does "pip install" inside Python raise a SyntaxError?

To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).

Convert blob to base64

var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
     base64data = reader.result;
     console.log(base64data);
}

How to initialize a struct in accordance with C programming language standards

void function(void) {
  MY_TYPE a;
  a.flag = true;
  a.value = 15;
  a.stuff = 0.123;
}

How to stop process from .BAT file?

taskkill /F /IM notepad.exe this is the best way to kill the task from task manager.

Iterating over JSON object in C#

You can use the JsonTextReader to read the JSON and iterate over the tokens:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

Remove a child with a specific attribute, in SimpleXML for PHP

Since I encountered the same fatal error as Gerry and I'm not familiar with DOM, I decided to do it like this:

$item = $xml->xpath("//seg[@id='A12']");
$page = $xml->xpath("/data");
$id = "A12";

if (  count($item)  &&  count($page) ) {
    $item = $item[0];
    $page = $page[0];

     // find the numerical index within ->children().
    $ch = $page->children();
    $ch_as_array = (array) $ch;

    if (  count($ch_as_array)  &&  isset($ch_as_array['seg'])  ) {
        $ch_as_array = $ch_as_array['seg'];
        $index_in_array = array_search($item, $ch_as_array);
        if (  ($index_in_array !== false)
          &&  ($index_in_array !== null)
          &&  isset($ch[$index_in_array])
          &&  ($ch[$index_in_array]['id'] == $id)  ) {

             // delete it!
            unset($ch[$index_in_array]);

            echo "<pre>"; var_dump($xml); echo "</pre>";
        }
    }  // end of ( if xml object successfully converted to array )
}  // end of ( valid item  AND  section )

Unable to Connect to GitHub.com For Cloning

Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.

How to add default signature in Outlook

Need to add a reference to Microsoft.Outlook. it is in Project references, from the visual basic window top menu.

Private Sub sendemail_Click()

  Dim OutlookApp As Outlook.Application
  Dim OutlookMail As Outlook.MailItem

  Set OutlookApp = New Outlook.Application
  Set OutlookMail = OutlookApp.CreateItem(olMailItem)

  With OutlookMail
    .Display
    .To = email
    .Subject = "subject"

    Dim wdDoc As Object     ' Word.Document
    Dim wdRange As Object   ' Word.Range
    Set wdDoc = .GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0) ' Create Range at character position 0 with length of 0 character s.

    ' if you need rtl:
    wdRange.Paragraphs.ReadingOrder = 0 ' 0 is rtl , 1 is ltr

    wdRange.InsertAfter "mytext"
  End With

End Sub

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

Autoplay audio files on an iPad with HTML5

Works with jQuery, tested on Ipad v.5.1.1

$('video').get(0).play();

You have to append/remove the video element from the page.

How to insert element into arrays at specific position?

Simplest solution, if you want to insert (an element or array) after a certain key:

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}

So, if you have:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

And execute:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

You'll have:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)