Programs & Examples On #Superfish

Superfish is a menu jQuery plugin that takes an existing pure CSS drop-down menu and adds a series of enhancements.

Generating random, unique values C#

randomNumber function return unqiue integer value between 0 to 100000

  bool check[] = new bool[100001];
  Random r = new Random();
  public int randomNumber() {
      int num = r.Next(0,100000);
       while(check[num] == true) {
             num = r.Next(0,100000);
     }
    check[num] = true;
   return num;
 }

Get pixel's RGB using PIL

Yes, this way:

im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

Forward slash in Java Regex

Double escaping is required when presented as a string.

Whenever I'm making a new regular expression I do a bunch of tests with online tools, for example: http://www.regexplanet.com/advanced/java/index.html

That website allows you to enter the regular expression, which it'll escape into a string for you, and you can then test it against different inputs.

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

android adb turn on wifi via adb

No need to edit any database directly, there is a command for it :)

svc wifi [enable|disable]

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

Best cross-browser method to capture CTRL+S with JQuery?

example:

shortcut.add("Ctrl+c",function() {
    alert('Ok...');
}
,{
    'type':'keydown',
    'propagate':false,
    'target':document
});

usage

<script type="text/javascript" src="js/shortcut.js"></script>

link for download: http://www.openjs.com/scripts/events/keyboard_shortcuts/#

How do I make an HTTP request in Swift?

Another option is the Alamofire lib that offers Chainable Request / Response methods.

https://github.com/Alamofire/Alamofire

Making a Request

import Alamofire

Alamofire.request(.GET, "http://httpbin.org/get")

Response Handling

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { request, response, data, error in
              print(request)
              print(response)
              print(error)
          }

Why not use tables for layout in HTML?

Data: use tables. Layout: use styles. Tables can render fastest with a very lean browser, that is, Links 2 or Lynx with no styling, just plain markup.

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

How to add a footer to the UITableView?

If you don't prefer the sticky bottom effect i would put it in viewDidLoad() https://stackoverflow.com/a/38176479/4127670

Image encryption/decryption using AES256 symmetric block ciphers

As mentioned by Nacho.L PBKDF2WithHmacSHA1 derivation is used as it is more secured.

import android.util.Base64;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncyption {

    private static final int pswdIterations = 10;
    private static final int keySize = 128;
    private static final String cypherInstance = "AES/CBC/PKCS5Padding";
    private static final String secretKeyInstance = "PBKDF2WithHmacSHA1";
    private static final String plainText = "sampleText";
    private static final String AESSalt = "exampleSalt";
    private static final String initializationVector = "8119745113154120";

    public static String encrypt(String textToEncrypt) throws Exception {

        SecretKeySpec skeySpec = new SecretKeySpec(getRaw(plainText, AESSalt), "AES");
        Cipher cipher = Cipher.getInstance(cypherInstance);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
        byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes());
        return Base64.encodeToString(encrypted, Base64.DEFAULT);
    }

    public static String decrypt(String textToDecrypt) throws Exception {

        byte[] encryted_bytes = Base64.decode(textToDecrypt, Base64.DEFAULT);
        SecretKeySpec skeySpec = new SecretKeySpec(getRaw(plainText, AESSalt), "AES");
        Cipher cipher = Cipher.getInstance(cypherInstance);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
        byte[] decrypted = cipher.doFinal(encryted_bytes);
        return new String(decrypted, "UTF-8");
    }

    private static byte[] getRaw(String plainText, String salt) {
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKeyInstance);
            KeySpec spec = new PBEKeySpec(plainText.toCharArray(), salt.getBytes(), pswdIterations, keySize);
            return factory.generateSecret(spec).getEncoded();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

}

Check whether number is even or odd

You can do like this:

boolean is_odd(int n) {
    return n % 2 == 1 || n % 2 == -1;
}

This is because Java has in its modulo operation the sign of the dividend, the left side: n. So for negatives and positives dividends, the modulo has the sign of them.

Of course, the bitwise operation is faster and optimized, simply document the line of code with two or three short words, which does it for readability.

Convert special characters to HTML in Javascript

var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 169, 61558, 8226, 61607);
var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "&trade;", "&copy;", "&bull;", "&bull;", "&bull;");

var TextCheck = {
    doCWBind:function(div){
        $(div).bind({
            bind:function(){
                TextCheck.cleanWord(div);
            },
            focus:function(){
                TextCheck.cleanWord(div);
            },
            paste:function(){
                TextCheck.cleanWord(div);
            }
        }); 
    },
    cleanWord:function(div){
        var output = $(div).val();
        for (i = 0; i < swapCodes.length; i++) {
            var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g");
            output = output.replace(swapper, swapStrings[i]);
        }
        $(div).val(output);
    }
}

Another one that we use now that works. One above I have it calling a script instead and returns the converted code. Only good on small textareas (meaning not a full on article/blog ect...)


For Above. Works on most chars.

var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 61558, 8226, 61607,161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 338, 339, 352, 353, 376, 402);
var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "&trade;", "&bull;", "&bull;", "&bull;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&#338;", "&#339;", "&#352;", "&#353;", "&#376;", "&#402;");

I create a javascript file that has a lot of functionality including the above. http://www.neotropicsolutions.com/JSChars.zip

All files needed are included. I added jQuery 1.4.4. Simply because I saw issues in other versions, yet to try them out.

Requires: jQuery & jQuery Impromptu from: http://trentrichardson.com/Impromptu/index.php

1. Word Count
2. Character Conversion
3. Checks to ensure this is not passed: "notsomeverylongstringmissingspaces"
4. Checks to make sure ALL IS NOT ALL UPPERCASE.
5. Strip HTML

    // Word Counter
    $.getScript('js/characters.js',function(){
            $('#adtxt').bind("keyup click blur focus change paste",
                function(event){
                    TextCheck.wordCount(30, "#adtxt", "#adtxt_count", event);
            });
            $('#adtxt').blur(
                function(event){
                    TextCheck.check_length('#adtxt'); // unsures properly spaces-not one long word
                    TextCheck.doCWBind('#adtxt');// char conversion
            });

            TextCheck.wordCount(30, "#adtxt", "#adtxt_count", false);
        });

    //HTML
    <textarea name="adtxt" id="adtxt" rows="10" cols="70" class="wordCount"></textarea>
<div id="adtxt_count" class="clear"></div>

    // Just Character Conversions:
    TextCheck.doCWBind('#myfield');

    // Run through form fields in a form for case checking.
    // Alerts user when field is blur'd.
    var labels = new Array("Brief Description","Website URL","Contact Name","Website","Email","Linkback URL");
    var checking = new Array("descr","title","fname","website","email","linkback");
    TextCheck.check_it(checking,labels);

    // Extra security to check again, make sure form is not submitted
    var pass = TextCheck.validate(checking,labels);
    if(pass){
        //do form actions
    }


    //Strip HTML
    <textarea name="adtxt" id="adtxt" rows="10" cols="70" onblur="TextCheck.stripHTML(this);"></textarea>

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

How do I turn off PHP Notices?

You can set ini_set('display_errors',0); in your script or define which errors you do want to display with error_reporting().

Setting table row height

If you are using Bootstrap, look at padding of your tds.

Setting the focus to a text field

I did it by setting an AncesterAdded event on the textField and the requesting focus in the window.

Getting input values from text box

you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.

<td id="pass"><label>Password</label></td>
<tr>
   <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>

see, both the td and the input share the id value pass.

Warning: Cannot modify header information - headers already sent by ERROR

You are trying to send headers information after outputing content.

If you want to do this, look for output buffering.

Therefore, look to use ob_start();

Kendo grid date column not formatting

just need putting the datatype of the column in the datasource

dataSource: {
      data: empModel.Value,
      pageSize: 10,
      schema:  {
                model: {
                    fields: {
                        DOJ: { type: "date" }
                            }
                       }
               }  
           }

and then your statement column:

 columns: [
    {
        field: "Name",
        width: 90,
        title: "Name"
    },

    {
        field: "DOJ",
        width: 90,
        title: "DOJ",
        type: "date",
        format:"{0:MM-dd-yyyy}" 
    }
]

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

Commenting code in Notepad++

Use shortcut: Ctrl+Q. You can customize in Settings

Execute PHP function with onclick

Solution without page reload

<?php
  function removeday() { echo 'Day removed'; }

  if (isset($_GET['remove'])) { return removeday(); }
?>


<!DOCTYPE html><html><title>Days</title><body>

  <a href="" onclick="removeday(event)" class="deletebtn">Delete</a>

  <script>
  async function removeday(e) {
    e.preventDefault(); 
    document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
  }
  </script>

</body></html>

How do I escape a string inside JavaScript code inside an onClick handler?

First, it would be simpler if the onclick handler was set this way:

<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
  document.getElementById("someLinkId").onClick = 
   function() {
      SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
    };

</script>

Then itemid and itemname need to be escaped for JavaScript (that is, " becomes \", etc.).

If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.

How do I login and authenticate to Postgresql after a fresh install?

If your database client connects with TCP/IP and you have ident auth configured in your pg_hba.conf check that you have an identd installed and running. This is mandatory even if you have only local clients connecting to "localhost".

Also beware that nowadays the identd may have to be IPv6 enabled for Postgresql to welcome clients which connect to localhost.

How to execute a bash command stored as a string with quotes and asterisk

Use an array, not a string, as given as guidance in BashFAQ #50.

Using a string is extremely bad security practice: Consider the case where password (or a where clause in the query, or any other component) is user-provided; you don't want to eval a password containing $(rm -rf .)!


Just Running A Local Command

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
"${cmd[@]}"

Printing Your Command Unambiguously

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'

Running Your Command Over SSH (Method 1: Using Stdin)

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host 'bash -s' <<<"$cmd_str"

Running Your Command Over SSH (Method 2: Command Line)

cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host "bash -c $cmd_str"

How can I safely create a nested directory?

I saw Heikki Toivonen and A-B-B's answers and thought of this variation.

import os
import errno

def make_sure_path_exists(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST or not os.path.isdir(path):
            raise

Create excel ranges using column numbers in vba?

In case you were looking to transform your column number into a letter:

Function ConvertToLetter(iCol As Integer) As String
    Dim iAlpha As Integer
    Dim iRemainder As Integer
    iAlpha = Int(iCol / 27)
    iRemainder = iCol - (iAlpha * 26)
    If iAlpha > 0 Then
        ConvertToLetter = Chr(iAlpha + 64)
    End If
    If iRemainder > 0 Then
        ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
    End If
End Function

This way you could do something like this:

Function selectColumnRange(colNum As Integer, targetWorksheet As Worksheet)
    Dim colLetter As String
    Dim testRange As Range
    colLetter = ConvertToLetter(colNum)
    testRange = targetWorksheet.Range(colLetter & ":" & colLetter).Select
End Function

That example function would select the entire column ( i.e. Range("A:A").Select)

Source: http://support.microsoft.com/kb/833402

How should I tackle --secure-file-priv in MySQL?

For mysql 8.0 version you can do this:

mysql.server stop
mysql.server start --secure-file-priv=''

It worked for me on Mac High Sierra.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations

How to "crop" a rectangular image into a square with CSS?

Using background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

How to navigate back to the last cursor position in Visual Studio Code?

The Keyboard Shortcut Commands are Go Forward and Go Back.


On Windows:

Alt+? .. navigate back

Alt+? .. navigate forward

On Mac:

Ctrl+- .. navigate back

Ctrl+Shift+- .. navigate forward

On Ubuntu Linux:

Ctrl+Alt+- .. navigate back

Ctrl+Shift+- .. navigate forward

Get height of div with no height set in css

Just a note in case others have the same problem.

I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().

var currentHeight = 0;
$(window).load(function() {
    //get the natural page height -set it in variable above.

    currentHeight = $('#js_content_container').outerHeight();

    console.log("set current height on load = " + currentHeight)
    console.log("content height function (should be 374)  = " + contentHeight());   

});

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

How do I get the application exit code from a Windows command line?

It's worth noting that .BAT and .CMD files operate differently.

Reading https://ss64.com/nt/errorlevel.html it notes the following:

There is a key difference between the way .CMD and .BAT batch files set errorlevels:

An old .BAT batch script running the 'new' internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only set ERRORLEVEL if an error occurs. So if you have two commands in the batch script and the first fails, the ERRORLEVEL will remain set even after the second command succeeds.

This can make debugging a problem BAT script more difficult, a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run [source].

This was causing me no end of grief as I was executing successive commands, but the ERRORLEVEL would remain unchanged even in the event of a failure.

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

After wasting many hours, I came across this!

jquery-ui-touch-punch

It translates tap events as click events. Remember to load the script after jquery.

I got this working on the iPad and iPhone

$('#movable').draggable({containment: "parent"});

Rotation of 3D vector?

Using pyquaternion is extremely simple; to install it (while still in python), run in your console:

import pip;
pip.main(['install','pyquaternion'])

Once installed:

  from pyquaternion import Quaternion
  v = [3,5,0]
  axis = [4,4,1]
  theta = 1.2 #radian
  rotated_v = Quaternion(axis=axis,angle=theta).rotate(v)

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

XmlSerializer: remove unnecessary xsi and xsd namespaces

Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.


After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To whit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the default namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.


This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label> is part of the same namespace as the rest of the document, in this case urn:Abracadabra:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

Then, later, in your code that uses the MyTypeWithNamespaces object to serialize it, you would call it as I did above:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

And the XmlSerializer would spit back out the same XML as shown immediately above with no additional namespaces in the output:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

IF statement: how to leave cell blank if condition is false ("" does not work)

The easiest solution is to use conditional formatting if the IF Statement comes back false to change the font of the results cell to whatever color background is. Yes, technically the cell isn't blank, but you won't be able to see it's contents.

How do I add a simple jQuery script to WordPress?

You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/

When you use jQuery don't forget use jquery noconflict mode

How to split the name string in mysql?

You can use bewlo one also:

SELECT SUBSTRING_INDEX(Name, ' ', 1) AS fname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name,' ', 2), ' ',-1) AS mname,
SUBSTRING_INDEX(Name, ' ', -1) as lname FROM mytable;

How can I get the current time in C#?

DateTime.Now.ToShortTimeString().ToString()

This Will give you DateTime as 10:50PM

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

The following untracked working tree files would be overwritten by merge, but I don't care

Update - a better version

This tool (https://github.com/mklepaczewski/git-clean-before-merge) will:

  • delete untracked files that are identical to their git pull equivalents,
  • revert changes to modified files who's modified version is identical to their git pull equivalents,
  • report modified/untracked files that differ from their git pull version,
  • the tool has the --pretend option that will not modify any files.

Old version

How this answer differ from other answers?

The method presented here removes only files that would be overwritten by merge. If you have other untracked (possibly ignored) files in the directory this method won't remove them.

The solution

This snippet will extract all untracked files that would be overwritten by git pull and delete them.

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} rm -rf "{}"

and then just do:

git pull

This is not git porcelain command so always double check what it would do with:

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} echo "{}"

Explanation - because one liners are scary:

Here's a breakdown of what it does:

  1. git pull 2>&1 - capture git pull output and redirect it all to stdout so we can easily capture it with grep.
  2. grep -E '^\s - the intent is to capture the list of the untracked files that would be overwritten by git pull. The filenames have a bunch of whitespace characters in front of them so we utilize it to get them.
  3. cut -f2- - remove whitespace from the beginning of each line captured in 2.
  4. xargs -I {} rm -rf "{}" - us xargs to iterate over all files, save their name in "{}" and call rm for each of them. We use -rf to force delete and remove untracked directories.

It would be great to replace steps 1-3 with porcelain command, but I'm not aware of any equivalent.

Fitting polynomial model to data in R

The easiest way to find the best fit in R is to code the model as:

lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)

After using step down AIC regression

lm.s <- step(lm.1)

How to detect internet speed in JavaScript?

Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:

navigator.connection.downlink

This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.

You can look at this and a couple of other related attributes here

Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail

A child container failed during start java.util.concurrent.ExecutionException

You must have packaged the servlet-api.jar along with the other libraries in your war file. You can verify this by opening up your war file and navigating to the WEB-INF/lib folder.

Ideally, you should not provide the servlet-api jar. The container, in your case Tomcat, is responsible for providing it at deploy time to your application. If you try to provide it as well, then issues arise due to version mismatch etc. Best practise is to just avoid packaging it. Remove it from the WEB-INF/lib.

Additional Information

If you are using maven for your packaging, then simply add the provided tag with the dependency and maven will make sure not to package it in the final war file. Something like

<dependency>
    <artifact>..
    <group> ...
    <version> ...
    <scope>provided</scope>
</<dependency>

How to make the first option of <select> selected with jQuery

// remove "selected" from any options that might already be selected
$('#target option[selected="selected"]').each(
    function() {
        $(this).removeAttr('selected');
    }
);


// mark the first option as selected
$("#target option:first").attr('selected','selected');

C# refresh DataGridView when updating or inserted on another form

// Form A
public void loaddata()
{
    //do what you do in load data in order to update data in datagrid
}

then on Form B define:

// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];

private void button1_Click(object sender, EventArgs e)
{
    obj.loaddata();
    datagridview1.Update();
    datagridview1.Refresh();
}

Read connection string from web.config

Add System.Configuration as a reference then:

 using System.Configuration;

 ...

 string conn = 
    ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

How to get streaming url from online streaming radio station

Shahar's answer was really helpful, but I found it quite tedious to do this all myself, so I made a nifty little Python program:

import re
import urllib2
import string
url1 = raw_input("Please enter a URL from Tunein Radio: ");
open_file = urllib2.urlopen(url1);
raw_file = open_file.read();
API_key = re.findall(r"StreamUrl\":\"(.*?),",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
use_key = urllib2.urlopen(str(API_key[0]));
key_content = use_key.read();
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print "I found " + str(total) + " streams.";
for element in raw_stream_url:
    print "Stream #" + str(i + 1);
    print "Stream stats:";
    print "Bandwidth: " + str(bandwidth[i]) + " kilobytes per second."
    print "Reliability: " + str(reliability[i]) + "%"
    print "HasPlaylist: " + str(isPlaylist[i]) + "."
    print "Stream codec: " + str(codec[i]) + "."
    print "This audio stream is " + tipe[i].lower() + "."
    print "Pure streaming URL: " + str(raw_stream_url[i]) + ".";
    i = i + 1
raw_input("Press enter to close TMUS.")

It's basically Shahar's solution automated.

Where are $_SESSION variables stored?

In my Ubuntu machine sessions are stored at

/var/lib/php/sessions

and you have to sudo ls in this directory only ls it will throw

ls: cannot open directory '.': Permission denied

And on my Windows Wamp server php sessions are stored in

C:\wamp64\tmp

and if you install standalone php on windows then there is no value set by default

session.save_path => no value => no value

How to Apply Gradient to background view of iOS Swift App

Here's a variation for setting this up in a reusable Util class file

In your Xcode project:

  1. Create a new Swift class call it UI_Util.swift, and populate it as follows:

    import Foundation
    import UIKit
    
    class UI_Util {
    
        static func setGradientGreenBlue(uiView: UIView) {
    
            let colorTop =  UIColor(red: 15.0/255.0, green: 118.0/255.0, blue: 128.0/255.0, alpha: 1.0).cgColor
            let colorBottom = UIColor(red: 84.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0).cgColor
    
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [ colorTop, colorBottom]
            gradientLayer.locations = [ 0.0, 1.0]
            gradientLayer.frame = uiView.bounds
    
            uiView.layer.insertSublayer(gradientLayer, at: 0)
        }
    }
    

  1. Now you can call the function from any ViewController like so:

    class AbcViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()                
            UI_Util.setGradientGreen(uiView: self.view)
        }                
    

Thanks to katwal-Dipak's answer for the function code

Where is nodejs log file?

If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name

That will show you STDOUT and STDERR.

Does Python's time.time() return the local or UTC timestamp?

time.time() return the unix timestamp. you could use datetime library to get local time or UTC time.

import datetime

local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

How can I exclude a directory from Visual Studio Code "Explore" tab?

I managed to remove the errors by disabling the validations:

{
    "javascript.validate.enable": false,
    "html.validate.styles": false,
    "html.validate.scripts": false,
    "css.validate": false,
    "scss.validate": false
}

Obs: My project is a PWA using StyledComponents, React, Flow, Eslint and Prettier.

HashSet vs LinkedHashSet

HashSet: Unordered actually. if u passing the parameter means

Set<Integer> set=new HashSet<Integer>();
for(int i=0;i<set.length;i++)
{
  SOP(set)`enter code here`
}

Out Put: May be 2,1,3 not predictable. next time another order.

LinkedHashSet() which produce FIFO Order.

How can I override inline styles with external CSS?

The only way to override inline style is by using !important keyword beside the CSS rule. The following is an example of it.

_x000D_
_x000D_
div {
        color: blue !important;
       /* Adding !important will give this rule more precedence over inline style */
    }
_x000D_
<div style="font-size: 18px; color: red;">
    Hello, World. How can I change this to blue?
</div>
_x000D_
_x000D_
_x000D_

Important Notes:

  • Using !important is not considered as a good practice. Hence, you should avoid both !important and inline style.

  • Adding the !important keyword to any CSS rule lets the rule forcefully precede over all the other CSS rules for that element.

  • It even overrides the inline styles from the markup.

  • The only way to override is by using another !important rule, declared either with higher CSS specificity in the CSS, or equal CSS specificity later in the code.

  • Must Read - CSS Specificity by MDN

How to color System.out.println output?

Here is a solution for Win32 Console.

1) Get JavaNativeAccess libraries here: https://github.com/twall/jna/

2) These two Java classes will do the trick.

Enjoy.

package com.stackoverflow.util;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;

public class Win32 {
    public static final int STD_INPUT_HANDLE = -10;
    public static final int STD_OUTPUT_HANDLE = -11;
    public static final int STD_ERROR_HANDLE = -12;

    public static final short CONSOLE_FOREGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_FOREGROUND_COLOR_BLUE         = 0x01;
    public static final short CONSOLE_FOREGROUND_COLOR_GREEN        = 0x02;
    public static final short CONSOLE_FOREGROUND_COLOR_AQUA         = 0x03;
    public static final short CONSOLE_FOREGROUND_COLOR_RED          = 0x04;
    public static final short CONSOLE_FOREGROUND_COLOR_PURPLE       = 0x05;
    public static final short CONSOLE_FOREGROUND_COLOR_YELLOW       = 0x06;
    public static final short CONSOLE_FOREGROUND_COLOR_WHITE        = 0x07;
    public static final short CONSOLE_FOREGROUND_COLOR_GRAY         = 0x08;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE   = 0x09;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN  = 0x0A;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA   = 0x0B;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED    = 0x0C;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
    public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;

    public static final short CONSOLE_BACKGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_BACKGROUND_COLOR_BLUE         = 0x10;
    public static final short CONSOLE_BACKGROUND_COLOR_GREEN        = 0x20;
    public static final short CONSOLE_BACKGROUND_COLOR_AQUA         = 0x30;
    public static final short CONSOLE_BACKGROUND_COLOR_RED          = 0x40;
    public static final short CONSOLE_BACKGROUND_COLOR_PURPLE       = 0x50;
    public static final short CONSOLE_BACKGROUND_COLOR_YELLOW       = 0x60;
    public static final short CONSOLE_BACKGROUND_COLOR_WHITE        = 0x70;
    public static final short CONSOLE_BACKGROUND_COLOR_GRAY         = 0x80;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE   = 0x90;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN  = 0xA0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA   = 0xB0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED    = 0xC0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
    public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;

    // typedef struct _COORD {
    //    SHORT X;
    //    SHORT Y;
    //  } COORD, *PCOORD;
    public static class COORD extends Structure {
        public short X;
        public short Y;
    }

    // typedef struct _SMALL_RECT {
    //    SHORT Left;
    //    SHORT Top;
    //    SHORT Right;
    //    SHORT Bottom;
    //  } SMALL_RECT;
    public static class SMALL_RECT extends Structure {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    // typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
    //    COORD      dwSize;
    //    COORD      dwCursorPosition;
    //    WORD       wAttributes;
    //    SMALL_RECT srWindow;
    //    COORD      dwMaximumWindowSize;
    //  } CONSOLE_SCREEN_BUFFER_INFO;
    public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;
    }

    // Source: https://github.com/twall/jna/nonav/javadoc/index.html
    public interface Kernel32 extends Library {
        Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

        // HANDLE WINAPI GetStdHandle(
        //        __in  DWORD nStdHandle
        //      );
        public int GetStdHandle(
                int nStdHandle);

        // BOOL WINAPI SetConsoleTextAttribute(
        //        __in  HANDLE hConsoleOutput,
        //        __in  WORD wAttributes
        //      );
        public boolean SetConsoleTextAttribute(
                int in_hConsoleOutput, 
                short in_wAttributes);

        // BOOL WINAPI GetConsoleScreenBufferInfo(
        //        __in   HANDLE hConsoleOutput,
        //        __out  PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
        //      );
        public boolean GetConsoleScreenBufferInfo(
                int in_hConsoleOutput,
                CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);

        // DWORD WINAPI GetLastError(void);
        public int GetLastError();
    }
}
package com.stackoverflow.util;

import java.io.PrintStream;

import com.stackoverflow.util.Win32.Kernel32;

public class ConsoleUtil {
    public static void main(String[] args)
    throws Exception {
        System.out.print("abc");
        static_color_print(
                System.out, 
                "def", 
                Win32.CONSOLE_BACKGROUND_COLOR_RED, 
                Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
        System.out.print("def");
        System.out.println();
    }

    private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null; 

    public static void static_save_settings() {
        if (null == _static_console_screen_buffer_info) {
            _static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
    }

    public static void static_restore_color()
    throws Exception {
        if (null == _static_console_screen_buffer_info) {
            throw new Exception("Internal error: Must save settings before restore");
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.SetConsoleTextAttribute(
                stdout_handle, 
                _static_console_screen_buffer_info.wAttributes);
    }

    public static void static_set_color(Short background_color, Short foreground_color) {
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        if (null == background_color || null == foreground_color) {
            Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info = 
                new Win32.CONSOLE_SCREEN_BUFFER_INFO();
            Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
            short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
            if (null == background_color) {
                short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
                background_color = new Short(current_bg_color);
            }
            if (null == foreground_color) {
                short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
                foreground_color = new Short(current_fg_color);
            }
        }
        short bg_and_fg_color = 
            (short) (background_color.shortValue() | foreground_color.shortValue());
        Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
    }

    public static<T> void static_color_print(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.print(value);
        }
        finally {
            static_restore_color();
        }
    }

    public static<T> void static_color_println(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.println(value);
        }
        finally {
            static_restore_color();
        }
    }
}

How can I declare a two dimensional string array?

There are many examples on working with arrays in C# here.

I hope this helps.

Thanks, Damian

How to find which version of Oracle is installed on a Linux server (In terminal)

A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.

cd / <-- Goto root directory
find . -print| grep -i dbm*.sql

Result varies on how you installed Oracle but mine displays this

/db/oracle

Goto the folder

less /db/oracle/db1/sqlplus/doc/README.htm

scroll down and you should see something like this

SQL*Plus Release Notes - Release 11.2.0.2

How to get ASCII value of string in C#

If you want the charcode for each character in the string, you could do something like this:

char[] chars = "9quali52ty3".ToCharArray();

Detect click outside Angular component

Improving @J. Frankenstein answear

_x000D_
_x000D_
  
  @HostListener('click')
  clickInside($event) {
    this.text = "clicked inside";
    $event.stopPropagation();
  }
  
  @HostListener('document:click')
  clickOutside() {
      this.text = "clicked outside";
  }
_x000D_
_x000D_
_x000D_

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Best way to represent a fraction in Java?

This function simplify using the eucledian algorithm is quite useful when defining fractions

 public Fraction simplify(){


     int safe;
     int h= Math.max(numerator, denominator);
     int h2 = Math.min(denominator, numerator);

     if (h == 0){

         return new Fraction(1,1);
     }

     while (h>h2 && h2>0){

          h = h - h2;
          if (h>h2){

              safe = h;
              h = h2;
              h2 = safe;

          }  

     }

  return new Fraction(numerator/h,denominator/h);

 }

Error loading the SDK when Eclipse starts

I removed the packages indicated in the api 22 in the sdk and the problem is not resolved.

I edited device.xml of Applications / Android / android-sdk-macosx / system-images / android-22 / android-wear / x86 and of Applications / Android / android-sdk-macosx / system-images / android-22 / android-wear / armeabi-v7a I removed the lines containing "d:skin"

Finally restart eclipse and the problem was resolved!

How to add default value for html <textarea>?

A few notes and clarifications:

  • placeholder='' inserts your text, but it is greyed out (in a tool-tip style format) and the moment the field is clicked, your text is replaced by an empty text field.

  • value='' is not a <textarea> attribute, and only works for <input> tags, ie, <input type='text'>, etc. I don't know why the creators of HTML5 decided not to incorporate that, but that's the way it is for now.

  • The best method for inserting text into <textarea> elements has been outlined correctly here as: <textarea> Desired text to be inserted into the field upon page load </textarea> When the user clicks the field, they can edit the text and it remains in the field (unlike placeholder='').

  • Note: If you insert text between the <textarea> and </textarea> tags, you cannot use placeholder='' as it will be overwritten by your inserted text.

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

var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();

What is meaning of negative dbm in signal strength?

I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.

With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:

|--------|-------------------|
| P(dBm) |        P(mW)      |
|--------|-------------------|
|    50  |  100000           |    
|    40  |   10000           |    strong transmitter
|    30  |    1000           |             ^  
|    20  |     100           |             |
|    10  |      10           |             |
|     0  |       1           |
|   -10  |       0.1         |
|   -20  |       0.01        |
|   -30  |       0.001       |
|   -40  |       0.0001      |
|   -50  |       0.00001     |             |
|   -60  |       0.000001    |             |
|   -70  |       0.0000001   |             v
|   -80  |       0.00000001  |    sensitive receiver
|   -90  |       0.000000001 |
|--------|-------------------|

When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.

When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.

Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).

Error C1083: Cannot open include file: 'stdafx.h'

Add #include "afxwin.h" in your source file. It will solve your issue.

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

Rollback a Git merge

If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.

The easiest way I felt was to:

  1. Take out a new branch from develop/master (where you merged)
  2. Revert the "revert" using git revert -m 1 xxxxxx (if the revert was merged using a branch) or using git revert xxxxxx if it was a simple revert
  3. The new branch should now have the changes you want to merge again.
  4. Make changes or merge this branch to develop/master

How to duplicate a git repository? (without forking)

See https://help.github.com/articles/duplicating-a-repository

Short version:

In order to make an exact duplicate, you need to perform both a bare-clone and a mirror-push:

mkdir foo; cd foo 
# move to a scratch dir

git clone --bare https://github.com/exampleuser/old-repository.git
# Make a bare clone of the repository

cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
# Mirror-push to the new repository

cd ..
rm -rf old-repository.git  
# Remove our temporary local repository

NOTE: the above will work fine with any remote git repo, the instructions are not specific to github

The above creates a new remote copy of the repo. Then clone it down to your working machine.

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Should I use <i> tag for icons instead of <span>?

Quentin's answer clearly states that i tag should not be used to define icons.

But, Holly suggested that span has no meaning in itself and voted in favor of i instead of span tag.

Few suggested to use img as it's semantic and contains alt tag. But, we should not also use img because even empty src sends a request to server. Read here

I think, the correct way would be,

<span class="icon-fb" role="img" aria-label="facebook"></span>

This solves the issue of no alt tag in span and makes it accessible to vision-impaired users. It's semantic and not misusing ( hacking ) any tag.

Creating an empty file in C#

You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.

File.Open("filename", FileMode.Create).Close();

Regex replace (in Python) - a simpler way?

Look in the Python re documentation for lookaheads (?=...) and lookbehinds (?<=...) -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.

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.

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

  • I used date.exe, and renamed it to date_unxutils.exe to avoid conflicts.

  • Put it inside bin folder next to the batch script.

Code

:: Add binaries to temp path
IF EXIST bin SET PATH=%PATH%;bin

:: Create UTC Timestamp string in a custom format
:: Example: 20210128172058
set timestamp_command='date_unxutils.exe -u +"%%Y%%m%%d%%H%%M%%S"'
FOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i
echo %timestamp%

Download UnxUtils

References

  • This awesome answer that I build upon.

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

How to set Python's default version to 3.x on OS X?

Changing the default python executable's version system-wide could break some applications that depend on python2.

However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put alias python='python3' in your ~/.profile, and then source ~/.profile in your ~/.bash_profile and/or your~/.zsh_profile with a line like:

[ -e ~/.profile ] && . ~/.profile

This way, your alias will work across shells.

With this, python command now invokes python3. If you want to invoke the "original" python (that refers to python2) on occasion, you can use command python, which will leaving the alias untouched, and works in all shells.

If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:

alias 2='python2'
alias 3='python3'

Tip: For scripts, instead of using a shebang like:

#!/usr/bin/env python

use:

#!/usr/bin/env python3

This way, the system will use python3 for running python executables.

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

Reading json files in C++

storing peoples like this

{"Anna" : { 
  "age": 18,
  "profession": "student"},
"Ben" : {
  "age" : "nineteen",
  "profession": "mechanic"}
 }

will cause problems, particularly if differents peoples have same name..

rather use array storing objects like this

{
  "peoples":[
       { 
           "name":"Anna",  
           "age": 18,
           "profession": "student"
       },
       {
           "name":"Ben",
           "age" : "nineteen",
           "profession": "mechanic"
       } 
  ]
}

like this, you can enumerates objects, or acces objects by numerical index. remember that json is storage structure, not dynamically sorter or indexer. use data stored in json to build indexes as you need and acces data.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

I faced the same problem, but for some reasons the .lock file in workspace was not getting deleted. Even creating a new workspace was also getting locked.

So what I did was cleaning the windows temp folder, the %PREFETCH% folder and %TEMP% locations. Restart the system and then it allowed to delete the .lock file.

Maybe it will help someone.

Check whether a value exists in JSON object

This example puts your JSON into proper format and does an existence check. I use jquery for convenience.

http://jsfiddle.net/nXFxC/

<!-- HTML -->
<span id="test">Hello</span><br>
<span id="test2">Hello</span>

//Javascript

$(document).ready(function(){
    var JSON = {"animals":[{"name":"cat"}, {"name":"dog"}]};

if(JSON.animals[1].name){      
$("#test").html("It exists");
}
if(!JSON.animals[2]){       
$("#test2").html("It doesn't exist");
}
});

Updating a java map entry

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the Javadocs:

V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

How to extract year and month from date in PostgreSQL without using to_char() function?

It is working for "greater than" functions not for less than.

For example:

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;

is working fine.

but for

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;

I am getting error.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;

How to check for a valid URL in Java?

validator package:

There seems to be a nice package by Yonatan Matalon called UrlUtil. Quoting its API:

isValidWebPageAddress(java.lang.String address, boolean validateSyntax, 
                      boolean validateExistance) 
Checks if the given address is a valid web page address.

Sun's approach - check the network address

Sun's Java site offers connect attempt as a solution for validating URLs.

Other regex code snippets:

There are regex validation attempts at Oracle's site and weberdev.com.

recyclerview No adapter attached; skipping layout

In Kotlin we had this weird illogical issue.

This didn't work:

 mBinding.serviceProviderCertificates.apply {
            adapter = adapter
            layoutManager =  LinearLayoutManager(activity)
        }

While this worked:

mBinding.serviceProviderCertificates.adapter = adapter
mBinding.serviceProviderCertificates.layoutManager = LinearLayoutManager(activity)

Once I get more after work hours, I will share more insights.

Is it possible to disable scrolling on a ViewPager

There is an easy fix for this one:

When you want to disable the viewpager scrolling then:

mViewPager.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View arg0, MotionEvent arg1) {
      return true;
   }
}); 

And when you want to re-enable it then:

mViewPager.setOnTouchListener(null);

That will do the trick.

iOS: Compare two dates

I take it you are asking what the return value is in the comparison function.

If the dates are equal then returning NSOrderedSame

If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending

If descending ( 2nd arg < 1st arg ) return NSOrderedDescending

How do I check if string contains substring?

I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/

I suggest another way(str.replace(s1, "") !== str):

_x000D_
_x000D_
var str = "Hello World!", s1 = "ello", s2 = "elloo";_x000D_
alert(str.replace(s1, "") !== str);_x000D_
alert(str.replace(s2, "") !== str);
_x000D_
_x000D_
_x000D_

Are list-comprehensions and functional functions faster than "for loops"?

Adding a twist to Alphii answer, actually the for loop would be second best and about 6 times slower than map

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        a += i**2
    return a

def square_sum3(numbers):
    a = 0
    map(lambda x: a+x**2, numbers)
    return a

def square_sum4(numbers):
    a = 0
    return [a+i**2 for i in numbers]

time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])

Main changes have been to eliminate the slow sum calls, as well as the probably unnecessary int() in the last case. Putting the for loop and map in the same terms makes it quite fact, actually. Remember that lambdas are functional concepts and theoretically shouldn't have side effects, but, well, they can have side effects like adding to a. Results in this case with Python 3.6.1, Ubuntu 14.04, Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz

0:00:00.257703 #Reduce
0:00:00.184898 #For loop
0:00:00.031718 #Map
0:00:00.212699 #List comprehension

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

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

Android device chooser - My device seems offline

Faced same problem in Windows with Nexus 7 device.

Simply killing adb.exe process from Task Manager solved my problem.

What is the difference between UNION and UNION ALL?

UNION removes duplicate records in other hand UNION ALL does not. But one need to check the bulk of data that is going to be processed and the column and data type must be same.

since union internally uses "distinct" behavior to select the rows hence it is more costly in terms of time and performance. like

select project_id from t_project
union
select project_id from t_project_contact  

this gives me 2020 records

on other hand

select project_id from t_project
union all
select project_id from t_project_contact

gives me more than 17402 rows

on precedence perspective both has same precedence.

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

Regular expression to limit number of characters to 10

It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.

How to force HTTPS using a web.config file

A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.

</configuration>
</system.webServer>
    <httpErrors>
        <clear/>
        <!--redirect if connected without SSL-->
        <error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
    </httpErrors>
</system.webServer>
</configuration>

Declaring and initializing arrays in C

It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.

for(i=0;i<N;i++)
{
     array[i] = i;
}

You can hard code and assign values like --array[0] = 1 and so on.

Memcpy can also be used if you have the data stored in an array already.

Best way to find the months between two dates

Here is a method:

def months_between(start_dt, stop_dt):
    month_list = []
    total_months = 12*(stop_dt.year-start_dt.year)+(stop_dt.month-start_d.month)+1
    if total_months > 0:
        month_list=[ datetime.date(start_dt.year+int((start_dt+i-1)/12), 
                                   ((start_dt-1+i)%12)+1,
                                   1) for i in xrange(0,total_months) ]
    return month_list

This is first computing the total number of months between the two dates, inclusive. Then it creates a list using the first date as the base and performs modula arithmetic to create the date objects.

font size in html code

you dont need those quotes

<td style="padding-left: 5px;padding-bottom:3px; font-size: 35px;"> <b>Datum:</b><br/>
                        November 2010 </td>

Java: Identifier expected

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then "run" the class from your IDE

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

If you are not using "-XX:HeapDumpPath" option then in case of JBoss EAP/As by default the heap dump file will be generated in "JBOSS_HOME/bin" directory.

How to output in CLI during execution of PHP Unit tests?

For some cases one could use something like that to output something to the console

class yourTests extends PHPUnit_Framework_TestCase
{
    /* Add Warnings */
    protected function addWarning($msg, Exception $previous = null)
    {
        $add_warning = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
        $add_warning->addWarning($this, $msg, time());
        $this->setTestResultObject($add_warning);
    }

    /* Add errors */
    protected function addError($msg, Exception $previous = null)
    {
        $add_error = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_error->addError($this, $msg, time());
        $this->setTestResultObject($add_error);
    }

    /* Add failures */
    protected function addFailure($msg, Exception $previous = null)
    {
        $add_failure = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_failure->addFailure($this, $msg, time());
        $this->setTestResultObject($add_failure);
    }

    public function test_messages()
    {
        $this->addWarning("Your warning message!");
        $this->addError("Your error message!");
        $this->addFailure("Your Failure message");
    }

    /* Or just mark test states! */
    public function test_testMarking()
    {
        $this->markTestIncomplete();
        $this->markTestSkipped();
    }
}

How to use icons and symbols from "Font Awesome" on Native Android Application

If you want programmatic setText without add string to string.xml

see its hexadecimal code here:

http://fortawesome.github.io/Font-Awesome/cheatsheet/

replace &#xf066; to 0xf066

 Typeface typeface = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
    textView.setTypeface(typeface);
    textView.setText(new String(new char[]{0xf006 }));

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try one of these:

  1. Use column alias:

    ORDER BY RadioServiceCodeId,RadioService

  2. Use column position:

    ORDER BY 1,2

You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.

Running a command in a new Mac OS X Terminal window

A colleague asked me how to open A LOT of ssh sessions at once. I used cobbal's answer to write this script:

tmpdir=$( mktemp -d )
trap '$DEBUG rm -rf $tmpdir ' EXIT
index=1

{
cat <<COMMANDS
ssh user1@host1
ssh user2@host2
COMMANDS
} | while read command
do 
  COMMAND_FILE=$tmpdir/$index.command
  index=$(( index + 1 ))
  echo $command > $COMMAND_FILE
  chmod +x  $COMMAND_FILE
  open $COMMAND_FILE
done
sleep 60

By updating the list of commands ( they don't have to be ssh invocations ), you will get an additional open window for every command executed. The sleep 60 at the end is there to keep the .command files around while they are being executed. Otherwise, the shell completes too quickly, executing the trap to delete the temp directory ( created by mktemp ) before the launched sessions have an opportunity to read the files.

Firefox 'Cross-Origin Request Blocked' despite headers

Just add

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

to the .htaccess file in the root of the website you are trying to connect with.

How to save a plot into a PDF file without a large margin around

It seems to me that all approaches (file exchange solutions unconsidered) here are lacking the essential step, or finally leading to it via some blurry workarounds.

The figure size needs to equal the paper size and the white margins are gone.

A = hgload('myFigure.fig');

% set desired output size
set(A, 'Units','centimeters')
height = 15;
width = 19;

% the last two parameters of 'Position' define the figure size
set(A, 'Position',[25 5 width height],...
       'PaperSize',[width height],...
       'PaperPositionMode','auto',...
       'InvertHardcopy', 'off',...
       'Renderer','painters'...     %recommended if there are no alphamaps
   );

saveas(A,'printout','pdf')

Will give you a pdf output as your figure appears, in exactly the size you want. If you want to get it even tighter you can combine this solution with the answer of b3.

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Change the Bootstrap Modal effect

 body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
        <label>Entrances</label>
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            </optgroup>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            </optgroup>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            </optgroup>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            </optgroup>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>
            </optgroup>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
            </optgroup>
          </select>
       </div>
        <div class="form-group">
        <label>Exits</label>
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            </optgroup>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            </optgroup>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            </optgroup>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            </optgroup>        
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            </optgroup>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>
            </optgroup>

          </select>
       </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    </form>

      <a class="btn btn-black " href="http://demo.nhembram.com/bootstrap-modal-animation-with-animate-css/index.html" target="_blank">View FullPage</a>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <script>
    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    };
    $('#myModal').on('show.bs.modal', function (e) {
      var anim = $('#entrance').val();
          testAnim(anim);
    });
    $('#myModal').on('hide.bs.modal', function (e) {
      var anim = $('#exit').val();
          testAnim(anim);
    });
    </script>

<style>
body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}
</style>

Count the frequency that a value occurs in a dataframe column

@metatoaster has already pointed this out. Go for Counter. It's blazing fast.

import pandas as pd
from collections import Counter
import timeit
import numpy as np

df = pd.DataFrame(np.random.randint(1, 10000, (100, 2)), columns=["NumA", "NumB"])

Timers

%timeit -n 10000 df['NumA'].value_counts()
# 10000 loops, best of 3: 715 µs per loop

%timeit -n 10000 df['NumA'].value_counts().to_dict()
# 10000 loops, best of 3: 796 µs per loop

%timeit -n 10000 Counter(df['NumA'])
# 10000 loops, best of 3: 74 µs per loop

%timeit -n 10000 df.groupby(['NumA']).count()
# 10000 loops, best of 3: 1.29 ms per loop

Cheers!

IIS7 Cache-Control

I use this

<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="500.00:00:00" />
</staticContent>

to cache static content for 500 days with public cache-control header.

JavaScript implementation of Gzip

Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).


I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.

// LZW-compress a string
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

// Decompress an LZW-encoded string
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

"Line contains NULL byte" in CSV reader (Python)

Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

Using AES encryption in C#

For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in Getting AES encryption to work across Javascript and C#.

EDIT
a side note: Javascript Cryptography considered harmful. Worth the read.

Basic http file downloading and saving to disk in python?

For Python3+ URLopener is deprecated. And when used you will get error as below:

url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'

So, try:

import urllib.request 
urllib.request.urlretrieve(url, filename)

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Move top 1000 lines from text file to a new file using Unix shell commands

Out of curiosity, I found a box with a GNU version of sed (v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s

This is the Linux I was working with:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux

For this test, at least, it looks like sed is slower than the tail approach (27 sec vs ~14 sec).

Ripple effect on Android Lollipop CardView

  android:foreground="?android:attr/selectableItemBackgroundBorderless"
   android:clickable="true"
   android:focusable="true"

Only working api 21 and use this not use this list row card view

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

In my case:

PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous            = NO;

Was trying to do this with dispatch_group

How to connect Robomongo to MongoDB

Here's what we do:

  • Create a new connection, set the name, IP address and the appropriate port:

    Connection setup

  • Set up authentication, if required

    Authentication settings

  • Optionally set up other available settings for SSL, SSH, etc.

  • Save and connect

Format Date/Time in XAML in Silverlight

In SL5 I found this to work:

<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

You have to add a MySQL jdbc driver to the classpath.

Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.

You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

another solution is to build a new list

List<Dog> dogs = new ArrayList<Dog>(); 
List<Animal> animals = new ArrayList<Animal>(dogs);
animals.add(new Cat());

Jackson overcoming underscores in favor of camel-case

The current best practice is to configure Jackson within the application.yml (or properties) file.

Example:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE

If you have more complex configuration requirements, you can also configure Jackson programmatically.

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        // insert other configurations
    }

} 

RandomForestClassfier.fit(): ValueError: could not convert string to float

You can't pass str to your model fit() method. as it mentioned here

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

Try transforming your data to float and give a try to LabelEncoder.

Giving graphs a subtitle in matplotlib

I don't think there is anything built-in, but you can do it by leaving more space above your axes and using figtext:

axes([.1,.1,.8,.7])
figtext(.5,.9,'Foo Bar', fontsize=18, ha='center')
figtext(.5,.85,'Lorem ipsum dolor sit amet, consectetur adipiscing elit',fontsize=10,ha='center')

ha is short for horizontalalignment.

How can I force a hard reload in Chrome for Android

Mentioning this because you mentioned "when developing".

You can control the mobile device via your Chrome Desktop Browser.

Visit chrome://inspect/#devices on your desktop. And Inspect the device that's connected to your desktop. Agree when asked for permission.

You should now see a full fledged Devtool window for the current page on mobile device.

Now, Use the hard reload shortcut (Cmd+Shift+R) on desktop to do hard reload on mobile device!

document.getElementByID is not a function

It's getElementById()

Note the lower-case d in Id.

What does asterisk * mean in Python?

See Function Definitions in the Language Reference.

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

Also, see Function Calls.

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa
b = testb
c = testc
('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

def foo(a,b,c,**args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

Prints:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

And

def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

Prints:

a=testa
b=testb
c=testc
args=('excess',)

SQL Inner-join with 3 tables?

If you have 3 tables with the same ID to be joined, I think it would be like this:

SELECT * FROM table1 a
JOIN table2 b ON a.ID = b.ID
JOIN table3 c ON a.ID = c.ID

Just replace * with what you want to get from the tables.

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

'invalid value encountered in double_scalars' warning, possibly numpy

In my case, I found out it was division by zero.

Installing SetupTools on 64-bit Windows

Get the file register.py from this gist. Save it on your C drive or D drive, go to CMD to run it with:

'python register.py'

Then you will be able to install it.

How to open a new window on form submit

The code you have given, needs to be corrected. In form tag you have to enclosed the onClick attribute value in double quote:

"window.open('google.htm','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');"

You also need to take care that first parameter of window.open should also be enclosed using quotes.

How to Determine the Screen Height and Width in Flutter

The below code doesn't return the correct screen size sometimes:

MediaQuery.of(context).size

I tested on SAMSUNG SM-T580, which returns {width: 685.7, height: 1097.1} instead of the real resolution 1920x1080.

Please use:

import 'dart:ui';

window.physicalSize;

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.


In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>::class.java)

To convert this array into List, just use .toList() method

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

None of the solutions so far completely worked for me when I tried (sometimes, only buggy on secondary loads), but as a workaround, using an object element as described here, then wrapping in a scrollable div, then setting the object to a very high height (5000px) did the job for me. It's a big workaround and doesn't work incredibly well (for starters, pages over 5000px would cause issues -- 10000px completely broke it for me though) but it seems to get the job done in some of my test cases:

var style = 'left: ...px; top: ...px; ' +
        'width: ...px; height: ...px; border: ...';

if (isIOs) {
    style += '; overflow: scroll !important; -webkit-overflow-scrolling: touch !important;';
    html = '<div style="' + style + '">' +
           '<object type="text/html" data="http://example.com" ' +
           'style="width: 100%; height: 5000px;"></object>' +
           '</div>';
}
else {
    style += '; overflow: auto;';
    html = '<iframe src="http://example.com" ' +
           'style="' + style + '"></iframe>';
}

Here's hoping Apple will fix the Safari iFrame issues.

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

How to force Chrome's script debugger to reload javascript?

If you're running a local server on Apache, you can get what look like caching problems. This happened to me when I had a Apache server running under Vagrant (in virtualbox).

Just add the following lines to your config file (/etc/httpd/conf/httpd.conf or equivalent):

#Disable image serving for network mounted drive
EnableSendfile off

Note that it's worth searching through the config file to see if EnableSendfile is set to on anywhere else.

Remove header and footer from window.print()

In Chrome it's possible to hide this automatic header/footer using

@page { margin: 0; }

Since the contents will extend to page's limits, the page printing header/footer will be absent. You should, of course, in this case, set some margins/paddings in your body element so that the content won't extend all the way to the page's edge. Since common printers just can't get no-margins printing and it's probably not what you want, you should use something like this:

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

As Martin pointed out in a comment, if the page have a long element that scrolls past one page (like a big table), the margin is ignored and the printed version will look weird.

At the time original of this answer (May 2013), it only worked on Chrome, not sure about it now, never needed to try again. If you need support for a browser that can't hable, you can create a PDF on the fly and print that (you can create a self-printing PDF embedding JavaScript on it), but that's a huge hassle.

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Two models in one view in ASP MVC 3

you can't declare two model on one view, try to use Html.Action("Person", "[YourController]") & Html.Action("Order", "[YourController]").

Good luck.

Chrome refuses to execute an AJAX script due to wrong MIME type

For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:

var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
    ContentTypeProvider = provider
});

Spring Boot Adding Http Request Interceptors

To add interceptor to a spring boot application, do the following

  1. Create an interceptor class

    public class MyCustomInterceptor implements HandlerInterceptor{
    
        //unimplemented methods comes here. Define the following method so that it     
        //will handle the request before it is passed to the controller.
    
        @Override
        public boolean preHandle(HttpServletRequest request,HttpServletResponse  response){
        //your custom logic here.
            return true;
        }
    }
    
  2. Define a configuration class

    @Configuration
    public class MyConfig extends WebMvcConfigurerAdapter{
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
        }
    }
    
  3. Thats it. Now all your requests will pass through the logic defined under preHandle() method of MyCustomInterceptor.

Print to standard printer from Python?

To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.

Please have a look at the below link that should give a good start:

http://frank.zinepal.com/printing-directly-to-a-network-printer

Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.

http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165

How to convert CSV to JSON in Node.js

Step 1:

Install node module: npm install csvtojson --save

Step 2:

var Converter = require("csvtojson").Converter;

var converter = new Converter({});

converter.fromFile("./path-to-your-file.csv",function(err,result){

    if(err){
        console.log("Error");
        console.log(err);  
    } 
    var data = result;

    //to check json
    console.log(data);
});

Overlapping elements in CSS

You can use relative positioning to overlap your elements. However, the space they would normally occupy will still be reserved for the element:

<div style="background-color:#f00;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:relative;top:-50px;left:50px;">
    RELATIVE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>

In the example above, there will be a block of white space between the two 'DEFAULT POSITIONED' elements. This is caused, because the 'RELATIVE POSITIONED' element still has it's space reserved.

If you use absolute positioning, your elements will not have any space reserved, so your element will actually overlap, without breaking your document:

<div style="background-color:#f00;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
    ABSOLUTE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>

Finally, you can control which elements are on top of the others by using z-index:

<div style="z-index:10;background-color:#f00;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>
<div style="z-index:5;background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
    ABSOLUTE POSITIONED
</div>
<div style="z-index:0;background-color:#00f;width:200px;height:100px;">
    DEFAULT POSITIONED
</div>

Sorting a DropDownList? - C#, ASP.NET

Try it

-------Store Procedure-----(SQL)

USE [Your Database]
GO


CRATE PROC [dbo].[GetAllDataByID]

@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)

{

      if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();

                YourtableRepository tableRepo = new YourtableRepository();

                int conuntryInfoID=1;

                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();

            }
        }

-------LINQ Helper Class----

public class TableRepository

   {

        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(ID).ToList();
            }
            return table;
        }
    }

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

Regular expression to match characters at beginning of line only

(?i)^[ \r\n]*CTR

(?i) -- case insensitive -- Remove if case sensitive.
[ \r\n]  -- ignore space and new lines
* -- 0 or more times the same
CTR - your starts with string.

scrollable div inside container

_x000D_
_x000D_
function start() {_x000D_
 document.getElementById("textBox1").scrollTop +=5;_x000D_
    scrolldelay = setTimeout(function() {start();}, 40);_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
_x000D_
function reset(){_x000D_
 var loc = document.getElementById("textBox1").scrollTop;_x000D_
 document.getElementById("textBox1").scrollTop -= loc;_x000D_
 clearTimeout(scrolldelay);_x000D_
}_x000D_
//adjust height of paragraph in css_x000D_
//element textbox in div_x000D_
//adjust speed at scrolltop and start 
_x000D_
_x000D_
_x000D_

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

Printing the correct number of decimal points with cout

Just a minor point; put the following in the header

using namespace std;

then

std::cout << std::fixed << std::setprecision(2) << d;

becomes simplified to

cout << fixed << setprecision(2) << d;

XAMPP - MySQL shutdown unexpectedly

When you're not running XAMPP as an administrator, shutting down MySQL frequently causes corruption which means you have to repair or delete your tables. To avoid this you need to either run XAMPP as an administrator, or use the proper command prompt method for shutting down MySQL.

You can delete ibdata1 as Kratos suggests, but this can leave you with a broken database as other pieces of your database are still in the /mysql/data/ folder. In my case, this residual data stopped me successfully installing WordPress.

A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents.

Addendum: To ensure that you don't forget to run XAMPP as an administrator you can right click the XAMPP shortcut, go to Properties, then Advanced, and finally tick Run as administrator.

How to check if android checkbox is checked within its onClick method (declared in XML)?

<CheckBox
      android:id="@+id/checkBox1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Fees Paid Rs100:"
      android:textColor="#276ca4"
      android:checked="false"
      android:onClick="checkbox_clicked" />

Main Activity from here

   public class RegistA extends Activity {
CheckBox fee_checkbox;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_regist);
 fee_checkbox = (CheckBox)findViewById(R.id.checkBox1);// Fee Payment Check box
}

checkbox clicked

     public void checkbox_clicked(View v)
     {

         if(fee_checkbox.isChecked())
         {
            // true,do the task 

         }
         else
         {

         }

     }

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

How to fix Cannot find module 'typescript' in Angular 4?

I was able to solve this problem by removing node_modules then running npm install

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

Error: java.lang.NoSuchMethodError: javax.persistence.JoinTable.indexes()[Ljavax/persistence/Index;

The only thing that solved my problem was removing the following dependency in pom.xml: <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency>

And replace it for:

<dependency>
  <groupId>javax.persistence</groupId>
  <artifactId>persistence-api</artifactId>
  <version>1.0.2</version>
</dependency>

Hope it helps someone.

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

From inside of a Docker container, how do I connect to the localhost of the machine?

Edit: I ended up prototyping out the concept on GitHub. Check out: https://github.com/sivabudh/system-in-a-box


First, my answer is geared towards 2 groups of people: those who use a Mac, and those who use Linux.

The host network mode doesn't work on a Mac. You have to use an IP alias, see: https://stackoverflow.com/a/43541681/2713729

What is a host network mode? See: https://docs.docker.com/engine/reference/run/#/network-settings

Secondly, for those of you who are using Linux (my direct experience was with Ubuntu 14.04 LTS and I'm upgrading to 16.04 LTS in production soon), yes, you can make the service running inside a Docker container connect to localhost services running on the Docker host (eg. your laptop).

How?

The key is when you run the Docker container, you have to run it with the host mode. The command looks like this:

docker run --network="host" -id <Docker image ID>

When you do an ifconfig (you will need to apt-get install net-tools your container for ifconfig to be callable) inside your container, you will see that the network interfaces are the same as the one on Docker host (eg. your laptop).

It's important to note that I'm a Mac user, but I run Ubuntu under Parallels, so using a Mac is not a disadvantage. ;-)

And this is how you connect NGINX container to the MySQL running on a localhost.

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

How to make Twitter Bootstrap menu dropdown on hover rather than click

The jQuery solution is good, but it will need to either deal with on click events (for mobile or tablet) as hover won't work properly... Could maybe do some window re-size detection?

Andres Ilich's answer seems to work well, but it should be wrapped in a media query:

@media (min-width: 980px) {

    .dropdown-menu .sub-menu {
        left: 100%;
        position: absolute;
        top: 0;
        visibility: hidden;
        margin-top: -1px;
    }

    .dropdown-menu li:hover .sub-menu {
        visibility: visible;
    }

    .dropdown:hover .dropdown-menu {
        display: block;
    }

    .nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
        margin-top: 0;
    }

    .navbar .sub-menu:before {
        border-bottom: 7px solid transparent;
        border-left: none;
        border-right: 7px solid rgba(0, 0, 0, 0.2);
        border-top: 7px solid transparent;
        left: -7px;
        top: 10px;
    }
    .navbar .sub-menu:after {
        border-top: 6px solid transparent;
        border-left: none;
        border-right: 6px solid #fff;
        border-bottom: 6px solid transparent;
        left: 10px;
        top: 11px;
        left: -6px;
    }
}

How to properly URL encode a string in PHP?

You can use URL Encoding Functions PHP has the

rawurlencode() 

function

ASP has the

Server.URLEncode() 

function

In JavaScript you can use the

encodeURIComponent() 

function.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

REST API - Bulk Create or Update in single request

You probably will need to use POST or PATCH, because it is unlikely that a single request that updates and creates multiple resources will be idempotent.

Doing PATCH /docs is definitely a valid option. You might find using the standard patch formats tricky for your particular scenario. Not sure about this.

You could use 200. You could also use 207 - Multi Status

This can be done in a RESTful way. The key, in my opinion, is to have some resource that is designed to accept a set of documents to update/create.

If you use the PATCH method I would think your operation should be atomic. i.e. I wouldn't use the 207 status code and then report successes and failures in the response body. If you use the POST operation then the 207 approach is viable. You will have to design your own response body for communicating which operations succeeded and which failed. I'm not aware of a standardized one.

Laravel Password & Password_Confirmation Validation

try confirmed and without password_confirmation rule:

$this->validate($request, [
        'name' => 'required|min:3|max:50',
        'email' => 'email',
        'vat_number' => 'max:13',
        'password' => 'confirmed|min:6',
    ]);

How to determine device screen size category (small, normal, large, xlarge) using code?

Jeff Gilfelt's answer as a static helper method:

private static String getSizeName(Context context) {
    int screenLayout = context.getResources().getConfiguration().screenLayout;
    screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;

    switch (screenLayout) {
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        return "small";
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        return "normal";
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        return "large";
    case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
        return "xlarge";
    default:
        return "undefined";
    }
}

Pointers in C: when to use the ampersand and the asterisk?

Put simply

  • & means the address-of, you will see that in placeholders for functions to modify the parameter variable as in C, parameter variables are passed by value, using the ampersand means to pass by reference.
  • * means the dereference of a pointer variable, meaning to get the value of that pointer variable.
int foo(int *x){
   *x++;
}

int main(int argc, char **argv){
   int y = 5;
   foo(&y);  // Now y is incremented and in scope here
   printf("value of y = %d\n", y); // output is 6
   /* ... */
}

The above example illustrates how to call a function foo by using pass-by-reference, compare with this

int foo(int x){
   x++;
}

int main(int argc, char **argv){
   int y = 5;
   foo(y);  // Now y is still 5
   printf("value of y = %d\n", y); // output is 5
   /* ... */
}

Here's an illustration of using a dereference

int main(int argc, char **argv){
   int y = 5;
   int *p = NULL;
   p = &y;
   printf("value of *p = %d\n", *p); // output is 5
}

The above illustrates how we got the address-of y and assigned it to the pointer variable p. Then we dereference p by attaching the * to the front of it to obtain the value of p, i.e. *p.