Programs & Examples On #Security trimming

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

PHP form - on submit stay on same page

There are two ways of doing it:

  1. Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)

    if(isset($_POST['submit'])) {
        // Enter the code you want to execute after the form has been submitted
        // Display Success or Failure message (if any)
      } else {
        // Display the Form and the Submit Button
    }
    
  2. Using AJAX Form Submission which is a little more difficult for a beginner than method #1.

Convert String to SecureString

You can follow this:

string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();

How to check if all inputs are not empty with jQuery

You can do it.here is code

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="UTF-8">
 <title></title>
 <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
    }
});

if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

  return isFormValid;
 }  
 </script>
</head>
 <body>
 <div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
   </form>
  </div>
 </body>
 </html> 

How to append one file to another in Linux from the shell?

You can also do this without cat, though honestly cat is more readable:

>> file1 < file2

The >> appends STDIN to file1 and the < dumps file2 to STDIN.

How can I strip first and last double quotes?

find the position of the first and the last " in your string

>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')

>>> s[l+1:r]
'" " " ""\\1" " "" "'

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

querySelector and querySelectorAll are a relatively new APIs, whereas getElementById and getElementsByClassName have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.

As for the :, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.

How to search in array of object in mongodb

The right way is:

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

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

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

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

How to convert JSON to a Ruby hash

What about the following snippet?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

Is it possible to disable scrolling on a ViewPager

In my case of using ViewPager 2 alpha 2 the below snippet works

viewPager.isUserInputEnabled = false

Ability to disable user input (setUserInputEnabled, isUserInputEnabled)

refer to this for more changes in viewpager2 1.0.0-alpha02

Also some changes were made latest version ViewPager 2 alpha 4

orientation and isUserScrollable attributes are no longer part of SavedState

refer to this for more changes in viewpager2#1.0.0-alpha04

Run as java application option disabled in eclipse

Had the same problem. I apparently wrote the Main wrong:

public static void main(String[] args){

I missed the [] and that was the whole problem.

Check and recheck the Main function!

How to read response headers in angularjs?

According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"

See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]

Regarding Java switch statements - using return and omitting breaks in each case

From human intelligence view your code is fine. From static code analysis tools view there are multiple returns, which makes it harder to debug. e.g you cannot set one and only breakpoint immediately before return.

Further you would not hard code the 4 slider steps in an professional app. Either calculate the values by using max - min, etc., or look them up in an array:

public static final double[] SLIDER_VALUES = {1.0, 0.9, 0.8, 0.7, 0.6};
public static final double SLIDER_DEFAULT = 1.0;


private double translateSlider(int sliderValue) {
  double result = SLIDER_DEFAULT;
  if (sliderValue >= 0 && sliderValue < SLIDER_VALUES.length) {
      ret = SLIDER_VALUES[sliderValue];
  }

  return result;
}

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

Difference between InvariantCulture and Ordinal string comparison

Another handy difference (in English where accents are uncommon) is that an InvariantCulture comparison compares the entire strings by case-insensitive first, and then if necessary (and requested) distinguishes by case after first comparing only on the distinct letters. (You can also do a case-insensitive comparison, of course, which won't distinguish by case.) Corrected: Accented letters are considered to be another flavor of the same letters and the string is compared first ignoring accents and then accounting for them if the general letters all match (much as with differing case except not ultimately ignored in a case-insensitive compare). This groups accented versions of the otherwise same word near each other instead of completely separate at the first accent difference. This is the sort order you would typically find in a dictionary, with capitalized words appearing right next to their lowercase equivalents, and accented letters being near the corresponding unaccented letter.

An ordinal comparison compares strictly on the numeric character values, stopping at the first difference. This sorts capitalized letters completely separate from the lowercase letters (and accented letters presumably separate from those), so capitalized words would sort nowhere near their lowercase equivalents.

InvariantCulture also considers capitals to be greater than lower case, whereas Ordinal considers capitals to be less than lowercase (a holdover of ASCII from the old days before computers had lowercase letters, the uppercase letters were allocated first and thus had lower values than the lowercase letters added later).

For example, by Ordinal: "0" < "9" < "A" < "Ab" < "Z" < "a" < "aB" < "ab" < "z" < "Á" < "Áb" < "á" < "áb"

And by InvariantCulture: "0" < "9" < "a" < "A" < "á" < "Á" < "ab" < "aB" < "Ab" < "áb" < "Áb" < "z" < "Z"

What's the maximum value for an int in PHP?

(a little bit late, but could be useful)

Only trust PHP_INT_MAX and PHP_INT_SIZE, this value vary on your arch (32/64 bits) and your OS...

Any other "guess" or "hint" can be false.

How can I jump to class/method definition in Atom text editor?

I also had the same problem. And I find the solution:

CTRL+ALT+G

Update:

Thanks to @Joost, install Atom package python-tools to make it work

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

How do I base64 encode (decode) in C?

I wrote one for use with C++, it's very fast, works with streams, free, and open source:

https://tmplusplus.svn.sourceforge.net/svnroot/tmplusplus/trunk/src/

Feel free to use it if it fits your purpose.

Edit: Added code inline by request.

The performance boost is acieved by using a lookup table for encoding and decoding. _UINT8 is an unsigned char on most OS's.

/** Static Base64 character encoding lookup table */
const char CBase64::encodeCharacterTable[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/** Static Base64 character decoding lookup table */
const char CBase64::decodeCharacterTable[256] = {
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
    ,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1}; 

/*!
\brief Encodes binary data to base 64 character data
\param in The data to encode
\param out The encoded data as characters
*/
void CBase64::Encode(std::istream &in, std::ostringstream &out)
{
    char buff1[3];
    char buff2[4];
    _UINT8 i=0, j;
    while(in.readsome(&buff1[i++], 1))
        if (i==3)
        {
            out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];
            out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];
            out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];
            out << encodeCharacterTable[buff1[2] & 0x3f];
            i=0;
        }

    if (--i)
    {
        for(j=i;j<3;j++) buff1[j] = '\0';

        buff2[0] = (buff1[0] & 0xfc) >> 2;
        buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);
        buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);
        buff2[3] = buff1[2] & 0x3f;

        for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];

        while(i++<3) out << '=';
    }

}

/*!
\brief Decodes base 64 character data to binary data
\param in The character data to decode
\param out The decoded data
*/
void CBase64::Decode(std::istringstream &in, std::ostream &out)
{
    char buff1[4];
    char buff2[4];
    _UINT8 i=0, j;

    while(in.readsome(&buff2[i], 1) && buff2[i] != '=')
    {
        if (++i==4)
        {
            for (i=0;i!=4;i++)
                buff2[i] = decodeCharacterTable[buff2[i]];

            out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));
            out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));
            out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);

            i=0;
        }
    }

    if (i) 
    {
        for (j=i;j<4;j++) buff2[j] = '\0';
        for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];

        buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);
        buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);
        buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];

        for (j=0;j<(i-1); j++) out << (char)buff1[j];
    }
}

Div Height in Percentage

There is the semicolon missing (;) after the "50%"

but you should also notice that the percentage of your div is connected to the div that contains it.

for instance:

<div id="wrapper">
  <div class="container">
   adsf
  </div>
</div>

#wrapper {
  height:100px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

if you have:

adsf

#wrapper {
  height:400px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

then you .container will be 200px. 50% of the wrapper.

So you may want to look at the divs "wrapping" your ".container"...

querySelector, wildcard element match?

I just wrote this short script; seems to work.

/**
 * Find all the elements with a tagName that matches.
 * @param {RegExp} regEx  regular expression to match against tagName
 * @returns {Array}       elements in the DOM that match
 */
function getAllTagMatches(regEx) {
  return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) { 
    return el.tagName.match(regEx);
  });
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

How to get rows count of internal table in abap?

The functional module EM_GET_NUMBER_OF_ENTRIES will also provide the row count. It takes 1 parameter - the table name.

How do you truncate all tables in a database using TSQL?

Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

Using getopts to process long and short command line options

The built-in getopts command is still, AFAIK, limited to single-character options only.

There is (or used to be) an external program getopt that would reorganize a set of options such that it was easier to parse. You could adapt that design to handle long options too. Example usage:

aflag=no
bflag=no
flist=""
set -- $(getopt abf: "$@")
while [ $# -gt 0 ]
do
    case "$1" in
    (-a) aflag=yes;;
    (-b) bflag=yes;;
    (-f) flist="$flist $2"; shift;;
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*)  break;;
    esac
    shift
done

# Process remaining non-option arguments
...

You could use a similar scheme with a getoptlong command.

Note that the fundamental weakness with the external getopt program is the difficulty of handling arguments with spaces in them, and in preserving those spaces accurately. This is why the built-in getopts is superior, albeit limited by the fact it only handles single-letter options.

Extract filename and extension in Bash

~% FILE="example.tar.gz"

~% echo "${FILE%%.*}"
example

~% echo "${FILE%.*}"
example.tar

~% echo "${FILE#*.}"
tar.gz

~% echo "${FILE##*.}"
gz

For more details, see shell parameter expansion in the Bash manual.

Excel column number from column name

You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.

Example code:

Activesheet.Range("TableName[ColumnName]").Copy

You can also use :

activesheet.listobjects("TableName[ColumnName]").Copy

You can even use this reference system in worksheet formulas as well. Its very dynamic.

Hope this helps!

How to combine date from one field with time from another field - MS SQL Server

To combine date from a datetime column and time from another datetime column this is the best fastest solution for you:

select cast(cast(DateColumn as date) as datetime) + cast(TimeColumn as datetime) from YourTable

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

Get device token for push notification

Objective C for iOS 13+, courtesy of Wasif Saood's answer

Copy and paste below code into AppDelegate.m to print the device APN token.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUInteger dataLength = deviceToken.length;
  if (dataLength == 0) {
    return;
  }
  const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  NSLog(@"APN token:%@", hexString);
}

How do I loop through items in a list box and then remove those item?

How about:

foreach(var s in listBox1.Items.ToArray())
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}

The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.

find all the name using mysql query which start with the letter 'a'

try using CHARLIST as shown below:

select distinct name from artists where name RLIKE '^[abc]';

use distinct only if you want distinct values only. To read about it Click here.

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

you need make sure -(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated and -(void)endAppearanceTransition is create together in the class.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Before and BeforeClass in JUnit

The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.

SampleClass

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

MySQL: How to reset or change the MySQL root password?

Most of the answers on this topic are outdated; two major changes have occurred in MySQL up until the writing of this answer:

1- the 'Password' field in the user table has been replaced by 'authentication_string' column.

2- the 'Password' encryption function : PASSWORD("of some text") is deprecated.

Please refer to this link for further information:dev.mysql.com/doc/refman/8.0/en/resetting-permissions.html

How to use ArrayList's get() method

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of Strings:

List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");

Which can be visualised as: A visual representation of the array list Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1 So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

HTML if image is not found

its works for me that if you dont want to use alt attribute if image break then you can use this piece of code and set accordingly.

<h1>
  <a> 
   <object data="~/img/Logo.jpg" type="image/png">
     Your Custom Text Here
   </object>
  </a>
</h1>

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

How to copy a file to multiple directories using the gnu cp command

I like to copy a file into multiple directories as such: cp file1 /foo/; cp file1 /bar/; cp file1 /foo2/; cp file1 /bar2/ And copying a directory into other directories: cp -r dir1/ /foo/; cp -r dir1/ /bar/; cp -r dir1/ /foo2/; cp -r dir1/ /bar2/

I know it's like issuing several commands, but it works well for me when I want to type 1 line and walk away for a while.

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

how to remove new lines and returns from php string?

You have to wrap \n or \r in "", not ''. When using single quotes escape sequences will not be interpreted (except \' and \\).

The manual states:

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

  • \n linefeed (LF or 0x0A (10) in ASCII)

  • \r carriage return (CR or 0x0D (13) in ASCII)\

  • (...)

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

How to make an AlertDialog in Flutter?

If you want beautiful and responsive alert dialog then you can use flutter packages like

rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert

These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.

Flatten an irregular list of lists

Although an elegant and very pythonic answer has been selected I would present my solution just for the review:

def flat(l):
    ret = []
    for i in l:
        if isinstance(i, list) or isinstance(i, tuple):
            ret.extend(flat(i))
        else:
            ret.append(i)
    return ret

Please tell how good or bad this code is?

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

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Automatically start forever (node) on system restart

This case is valid for Debian.

Add the following to /etc/rc.local

/usr/bin/sudo -u {{user}} /usr/local/bin/forever start {{app path}}

  • {{user}} replaces your username.
  • {{app path}} replaces your app path. For example, /var/www/test/app.js

How to clear exisiting dropdownlist items when its content changes?

Please use the following

ddlCity.Items.Clear();

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Rebasing remote branches in Git

You can disable the check (if you're really sure you know what you're doing) by using the --force option to git push.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

How can I tell jackson to ignore a property for which I don't have control over the source code?

If you want to ALWAYS exclude certain properties for any class, you could use setMixInResolver method:

    @JsonIgnoreProperties({"id", "index", "version"})
    abstract class MixIn {
    }

    mapper.setMixInResolver(new ClassIntrospector.MixInResolver(){
        @Override
        public Class<?> findMixInClassFor(Class<?> cls) {
            return MixIn.class;  
        }

        @Override
        public ClassIntrospector.MixInResolver copy() {
            return this;
        }
    });

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

This tutorial is very useful. To give a quick summary:

  1. Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors

  2. In your WebApiConfig.cs file, add config.EnableCors() to the Register() method.

  3. Add an attribute to the controllers you need to handle cors:

[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

While variable is not defined - wait

Here's an example where all the logic for waiting until the variable is set gets deferred to a function which then invokes a callback that does everything else the program needs to do - if you need to load variables before doing anything else, this feels like a neat-ish way to do it, so you're separating the variable loading from everything else, while still ensuring 'everything else' is essentially a callback.

var loadUser = function(everythingElse){
    var interval = setInterval(function(){
      if(typeof CurrentUser.name !== 'undefined'){
        $scope.username = CurrentUser.name;
        clearInterval(interval);
        everythingElse();
      }
    },1);
  };

  loadUser(function(){

    //everything else

  });

How to draw a path on a map using kml file?

In above code, you don't pass the kml data to your mapView anywhere in your code, as far as I can see. To display the route, you should parse the kml data i.e. via SAX parser, then display the route markers on the map.

See the code below for an example, but it's not complete though - just for you as a reference and get some idea.

This is a simple bean I use to hold the route information I will be parsing.

package com.myapp.android.model.navigation;

import java.util.ArrayList;
import java.util.Iterator;


public class NavigationDataSet { 

private ArrayList<Placemark> placemarks = new ArrayList<Placemark>();
private Placemark currentPlacemark;
private Placemark routePlacemark;

public String toString() {
    String s= "";
    for (Iterator<Placemark> iter=placemarks.iterator();iter.hasNext();) {
        Placemark p = (Placemark)iter.next();
        s += p.getTitle() + "\n" + p.getDescription() + "\n\n";
    }
    return s;
}

public void addCurrentPlacemark() {
    placemarks.add(currentPlacemark);
}

public ArrayList<Placemark> getPlacemarks() {
    return placemarks;
}

public void setPlacemarks(ArrayList<Placemark> placemarks) {
    this.placemarks = placemarks;
}

public Placemark getCurrentPlacemark() {
    return currentPlacemark;
}

public void setCurrentPlacemark(Placemark currentPlacemark) {
    this.currentPlacemark = currentPlacemark;
}

public Placemark getRoutePlacemark() {
    return routePlacemark;
}

public void setRoutePlacemark(Placemark routePlacemark) {
    this.routePlacemark = routePlacemark;
}

}

And the SAX Handler to parse the kml:

package com.myapp.android.model.navigation;

import android.util.Log;
import com.myapp.android.myapp;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.myapp.android.model.navigation.NavigationDataSet;
import com.myapp.android.model.navigation.Placemark;


public class NavigationSaxHandler extends DefaultHandler{ 

 // =========================================================== 
 // Fields 
 // =========================================================== 

 private boolean in_kmltag = false; 
 private boolean in_placemarktag = false; 
 private boolean in_nametag = false;
 private boolean in_descriptiontag = false;
 private boolean in_geometrycollectiontag = false;
 private boolean in_linestringtag = false;
 private boolean in_pointtag = false;
 private boolean in_coordinatestag = false;

 private StringBuffer buffer;

 private NavigationDataSet navigationDataSet = new NavigationDataSet(); 

 // =========================================================== 
 // Getter & Setter 
 // =========================================================== 

 public NavigationDataSet getParsedData() {
      navigationDataSet.getCurrentPlacemark().setCoordinates(buffer.toString().trim());
      return this.navigationDataSet; 
 } 

 // =========================================================== 
 // Methods 
 // =========================================================== 
 @Override 
 public void startDocument() throws SAXException { 
      this.navigationDataSet = new NavigationDataSet(); 
 } 

 @Override 
 public void endDocument() throws SAXException { 
      // Nothing to do
 } 

 /** Gets be called on opening tags like: 
  * <tag> 
  * Can provide attribute(s), when xml was like: 
  * <tag attribute="attributeValue">*/ 
 @Override 
 public void startElement(String namespaceURI, String localName, 
           String qName, Attributes atts) throws SAXException { 
      if (localName.equals("kml")) { 
           this.in_kmltag = true;
      } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = true; 
           navigationDataSet.setCurrentPlacemark(new Placemark());
      } else if (localName.equals("name")) { 
           this.in_nametag = true;
      } else if (localName.equals("description")) { 
          this.in_descriptiontag = true;
      } else if (localName.equals("GeometryCollection")) { 
          this.in_geometrycollectiontag = true;
      } else if (localName.equals("LineString")) { 
          this.in_linestringtag = true;              
      } else if (localName.equals("point")) { 
          this.in_pointtag = true;          
      } else if (localName.equals("coordinates")) {
          buffer = new StringBuffer();
          this.in_coordinatestag = true;                        
      }
 } 

 /** Gets be called on closing tags like: 
  * </tag> */ 
 @Override 
 public void endElement(String namespaceURI, String localName, String qName) 
           throws SAXException { 
       if (localName.equals("kml")) {
           this.in_kmltag = false; 
       } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = false;

       if ("Route".equals(navigationDataSet.getCurrentPlacemark().getTitle())) 
               navigationDataSet.setRoutePlacemark(navigationDataSet.getCurrentPlacemark());
        else navigationDataSet.addCurrentPlacemark();

       } else if (localName.equals("name")) { 
           this.in_nametag = false;           
       } else if (localName.equals("description")) { 
           this.in_descriptiontag = false;
       } else if (localName.equals("GeometryCollection")) { 
           this.in_geometrycollectiontag = false;
       } else if (localName.equals("LineString")) { 
           this.in_linestringtag = false;              
       } else if (localName.equals("point")) { 
           this.in_pointtag = false;          
       } else if (localName.equals("coordinates")) { 
           this.in_coordinatestag = false;
       }
 } 

 /** Gets be called on the following structure: 
  * <tag>characters</tag> */ 
 @Override 
public void characters(char ch[], int start, int length) { 
    if(this.in_nametag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setTitle(new String(ch, start, length));            
    } else 
    if(this.in_descriptiontag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setDescription(new String(ch, start, length));          
    } else
    if(this.in_coordinatestag){        
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        //navigationDataSet.getCurrentPlacemark().setCoordinates(new String(ch, start, length));
        buffer.append(ch, start, length);
    }
} 
}

and a simple placeMark bean:

package com.myapp.android.model.navigation;

public class Placemark {

String title;
String description;
String coordinates;
String address;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getCoordinates() {
    return coordinates;
}
public void setCoordinates(String coordinates) {
    this.coordinates = coordinates;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}

Finally the service class in my model that calls the calculation:

package com.myapp.android.model.navigation;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.myapp.android.myapp;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class MapService {

public static final int MODE_ANY = 0;
public static final int MODE_CAR = 1;
public static final int MODE_WALKING = 2;


public static String inputStreamToString (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}


public static NavigationDataSet calculateRoute(Double startLat, Double startLng, Double targetLat, Double targetLng, int mode) {
    return calculateRoute(startLat + "," + startLng, targetLat + "," + targetLng, mode);
}

public static NavigationDataSet calculateRoute(String startCoords, String targetCoords, int mode) {
    String urlPedestrianMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&dirflg=w&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlPedestrianMode: "+urlPedestrianMode);

    String urlCarMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlCarMode: "+urlCarMode);

    NavigationDataSet navSet = null;
    // for mode_any: try pedestrian route calculation first, if it fails, fall back to car route
    if (mode==MODE_ANY||mode==MODE_WALKING) navSet = MapService.getNavigationDataSet(urlPedestrianMode);
    if (mode==MODE_ANY&&navSet==null||mode==MODE_CAR) navSet = MapService.getNavigationDataSet(urlCarMode);
    return navSet;
}

/**
 * Retrieve navigation data set from either remote URL or String
 * @param url
 * @return navigation set
 */
public static NavigationDataSet getNavigationDataSet(String url) {

    // urlString = "http://192.168.1.100:80/test.kml";
    Log.d(myapp.APP,"urlString -->> " + url);
    NavigationDataSet navigationDataSet = null;
    try
        {           
        final URL aUrl = new URL(url);
        final URLConnection conn = aUrl.openConnection();
        conn.setReadTimeout(15 * 1000);  // timeout for reading the google maps data: 15 secs
        conn.connect();

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        SAXParser sp = spf.newSAXParser(); 

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /* Create a new ContentHandler and apply it to the XML-Reader*/ 
        NavigationSaxHandler navSax2Handler = new NavigationSaxHandler(); 
        xr.setContentHandler(navSax2Handler); 

        /* Parse the xml-data from our URL. */ 
        xr.parse(new InputSource(aUrl.openStream()));

        /* Our NavigationSaxHandler now provides the parsed data to us. */ 
        navigationDataSet = navSax2Handler.getParsedData(); 

        /* Set the result to be displayed in our GUI. */ 
        Log.d(myapp.APP,"navigationDataSet: "+navigationDataSet.toString());

    } catch (Exception e) {
        // Log.e(myapp.APP, "error with kml xml", e);
        navigationDataSet = null;
    }   

    return navigationDataSet;
}

}

Drawing:

/**
 * Does the actual drawing of the route, based on the geo points provided in the nav set
 *
 * @param navSet     Navigation set bean that holds the route information, incl. geo pos
 * @param color      Color in which to draw the lines
 * @param mMapView01 Map view to draw onto
 */
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {

    Log.d(myapp.APP, "map color before: " + color);        

    // color correction for dining, make it darker
    if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
    Log.d(myapp.APP, "map color after: " + color);

    Collection overlaysToAddAgain = new ArrayList();
    for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
        Object o = iter.next();
        Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
        if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
            // mMapView01.getOverlays().remove(o);
            overlaysToAddAgain.add(o);
        }
    }
    mMapView01.getOverlays().clear();
    mMapView01.getOverlays().addAll(overlaysToAddAgain);

    String path = navSet.getRoutePlacemark().getCoordinates();
    Log.d(myapp.APP, "path=" + path);
    if (path != null && path.trim().length() > 0) {
        String[] pairs = path.trim().split(" ");

        Log.d(myapp.APP, "pairs.length=" + pairs.length);

        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height

        Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);

        if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO 

        try {
            GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
            mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
            GeoPoint gp1;
            GeoPoint gp2 = startGP;

            for (int i = 1; i < pairs.length; i++) // the last one would be crash
            {
                lngLat = pairs[i].split(",");

                gp1 = gp2;

                if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                        && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

                    // for GeoPoint, first:latitude, second:longitude
                    gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

                    if (gp2.getLatitudeE6() != 22200000) { 
                        mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
                        Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
                    }
                }
                // Log.d(myapp.APP,"pair:" + pairs[i]);
            }
            //routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
            mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
        } catch (NumberFormatException e) {
            Log.e(myapp.APP, "Cannot draw route.", e);
        }
    }
    // mMapView01.getOverlays().addAll(routeOverlays); // use the default color
    mMapView01.setEnabled(true);
}

This is the RouteOverlay class:

package com.myapp.android.activity.map.nav;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class RouteOverlay extends Overlay { 

private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) { // GeoPoint is a int. (6E)
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    defaultColor = 999; // no defaultColor
}

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) {
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    this.defaultColor = defaultColor;
}

public void setText(String t) {
    this.text = t;
}

public void setBitmap(Bitmap bitmap) { 
    this.img = bitmap;
}

public int getMode() {
    return mode;
}

@Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) {
    Projection projection = mapView.getProjection();
    if (shadow == false) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Point point = new Point();
        projection.toPixels(gp1, point);
        // mode=1&#65306;start
        if(mode==1) {
            if(defaultColor==999)
            paint.setColor(Color.BLACK); // Color.BLUE
            else
            paint.setColor(defaultColor);
            RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
            point.x + mRadius, point.y + mRadius);
            // start point
            canvas.drawOval(oval, paint);
        }
        // mode=2&#65306;path
        else if(mode==2) {
            if(defaultColor==999)
            paint.setColor(Color.RED);
            else
            paint.setColor(defaultColor);
            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
        }
        /* mode=3&#65306;end */
        else if(mode==3) {
            /* the last path */

            if(defaultColor==999)
                paint.setColor(Color.BLACK);  // Color.GREEN
            else
                paint.setColor(defaultColor);

            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
            RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
            point2.x + mRadius,point2.y + mRadius);
            /* end point */
            paint.setAlpha(255);
            canvas.drawOval(oval, paint);
        }
    }
    return super.draw(canvas, mapView, shadow, when);
}

}

Loop through an array php

foreach($array as $item=>$values){
     echo $values->filepath;
    }

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Ruby capitalize every word first letter

Another option is to use a regex and gsub, which takes a block:

'one TWO three foUR'.gsub(/\w+/, &:capitalize)

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Stringifying a null value in ActionScript will give the string "NULL". My suspicion is that someone has decided that it is, therefore, a good idea to decode the string "NULL" as null, causing the breakage you see here -- probably because they were passing in null objects and getting strings in the database, when they didn't want that (so be sure to check for that kind of bug, too).

How to get text with Selenium WebDriver in Python

To print the text my text you can use either of the following Locator Strategies:

  • Using class_name and get_attribute("textContent"):

    print(driver.find_element(By.CLASS_NAME, "current-stage").get_attribute("textContent"))
    
  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "span.current-stage").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//span[@class='current-stage']").text)
    

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CLASS_NAME and get_attribute("textContent"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, "current-stage"))).get_attribute("textContent"))
    
  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.current-stage"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='current-stage']"))).get_attribute("innerHTML"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


References

Link to useful documentation:

Switch case on type c#

The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()).

public static void TestTypeSwitch()
{
    var ts = new TypeSwitch()
        .Case((int x) => Console.WriteLine("int"))
        .Case((bool x) => Console.WriteLine("bool"))
        .Case((string x) => Console.WriteLine("string"));

    ts.Switch(42);     
    ts.Switch(false);  
    ts.Switch("hello"); 
}

Here is the machinery required to make it work.

public class TypeSwitch
{
    Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
    public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; } 
    public void Switch(object x) { matches[x.GetType()](x); }
}

copying all contents of folder to another folder using batch file?

I see a lot of answers suggesting the use of xcopy. But this is unnecessary. As the question clearly mentions that the author wants THE CONTENT IN THE FOLDER not the folder itself to be copied in this case we can -:

copy "C:\Folder1" *.*  "D:\Folder2"

Thats all xcopy can be used for if any subdirectory exists in C:\Folder1

How can I symlink a file in Linux?

If you are in the directory where you want to create symlink, then ignore second path.

cd myfolder
ln -s target

It will create symlink of target inside myfolder.

General syntax

ln -s TARGET LINK_NAME

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

android.widget.Switch - on/off event listener?

there are two ways,

  1. using xml onclick view Add Switch in XML as below:

    <Switch
    android:id="@+id/switch1"
    android:onClick="toggle"/>
    

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; //outside oncreate
    toggle =(Switch) findViewById(R.id.switch1); // inside oncreate

    public void toggle(View view) //outside oncreate
    {
        if( toggle.isChecked() ){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                start.setBackgroundColor(getColor(R.color.gold));
                stop.setBackgroundColor(getColor(R.color.white));
            }
        }
        else
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                stop.setBackgroundColor(getColor(R.color.gold));
                start.setBackgroundColor(getColor(R.color.white));
            }
        }
    }
  1. using on click listener

Add Switch in XML as below:

In YourActivity Class (For E.g MainActivity.java)

    Switch toggle; // outside oncreate
    toggle =(Switch) findViewById(R.id.switch1);  // inside oncreate


    toggle.setOnClickListener(new View.OnClickListener() {   // inside oncreate
        @Override
        public void onClick(View view) {

            if( toggle.isChecked() ){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    start.setBackgroundColor(getColor(R.color.gold));
                }
            }
            else
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    stop.setBackgroundColor(getColor(R.color.gold));
                }
            }

        }

    });

Pass accepts header parameter to jquery ajax

I use jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] ) for example:

var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Failed to obtain JSON data from server: " + err );
  }); /* failed to get JSON */

getJSON is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

Switching from zsh to bash on OSX, and back again?

I switch between zsh and bash somewhat frequently. For a while, I used to have to source my bash_profile every switch. Then I found out you can (typically) do

exec bash --login

or just

exec bash -l

Get class name of object as string in Swift

To get class name as String declare your class as following

@objc(YourClassName) class YourClassName{}

And get class name using following syntax

NSStringFromClass(YourClassName)

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

http post - how to send Authorization header?

Here is the detailed answer to the question:

Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).

There is more than one way we can pass data into the headers. The syntax is different but all means the same.

// Option 1 
 const httpOptions = {
   headers: new HttpHeaders({
     'Authorization': 'my-auth-token',
     'ID': emp.UserID,
   })
 };


// Option 2

let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');    

let options = {headers:httpHeaders};


// Option 1
   return this.http.post(this.url + 'testMethod', body,httpOptions)

// Option 2
   return this.http.post(this.url + 'testMethod', body,options)

In the call you can find the field passed as a header as shown in the image below : enter image description here

Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)

  • Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access

  • Response for preflight does not have HTTP ok status.

Find my detailed answer at https://stackoverflow.com/a/52620468/3454221

How to efficiently build a tree from a flat structure?

Most of the answers assume you are looking to do this outside of the database. If your trees are relatively static in nature and you just need to somehow map the trees into the database, you may want to consider using nested set representations on the database side. Check out books by Joe Celko (or here for an overview by Celko).

If tied to Oracle dbs anyway, check out their CONNECT BY for straight SQL approaches.

With either approach, you could completely skip mapping the trees before you load the data up in the database. Just thought I would offer this up as an alternative, it may be completely inappropriate for your specific needs. The whole "proper order" part of the original question somewhat implies you need the order to be "correct" in the db for some reason? This might push me towards handling the trees there as well.

How to sort in mongoose?

As of Mongoose 3.8.x:

model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });

Where:

criteria can be asc, desc, ascending, descending, 1, or -1

Note: Use quotation marks or double quote

use "asc", "desc", "ascending", "descending", 1, or -1

When to use dynamic vs. static libraries

Ulrich Drepper's paper on "How to Write Shared Libraries" is also good resource that details how best to take advantage of shared libraries, or what he refers to as "Dynamic Shared Objects" (DSOs). It focuses more on shared libraries in the ELF binary format, but some discussions are suitable for Windows DLLs as well.

How to disable a particular checkstyle rule for a particular line of code?

Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

For instance, if in my checkstyle-config.xml I have:

<module name="NoWhitespaceBefore"/>

I cannot use:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

How do I force Kubernetes to re-pull an image?

Now, the command kubectl rollout restart deploy YOUR-DEPLOYMENT combined with a imagePullPolicy: Always policy will allow you to restart all your pods with a latest version of your image.

How do I "decompile" Java class files?

For OSX I recommend: jarzilla or JD-GUI

They both allow you to view jar,war,etc. file content and decompiles any class files inside of them.

Jarzilla: https://code.google.com/p/jarzilla/
JD-GUI: http://jd.benow.ca/

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

Bootstrap 3 2-column form layout

You can use the bootstrap grid system. as Yoann said


 <div class="container">
    <div class="row">
        <form role="form">
           <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputEmail1">Name</label>
                        <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                    </div>
                    <div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
                        <label for="exampleInputPassword1">Confirm Password</label>
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
                    </div>
          </form>
         <div class="clearfix">
      </div>
    </div>
</div>

How do I download the Android SDK without downloading Android Studio?

What worked for me on Windows:

  1. Downloaded command line tools from https://developer.android.com/studio/index.html
  2. Put the whole tools folder from the ZIP archive to C:\Program Files (x86)\Android SDK\
  3. Launched tools\android.bat as administrator, which opened the usual SDK Manager window
  4. Installed required components. The files were downloaded to ...\Android SDK\ directory (that is build-tools, platforms, platform-tools, etc. directories appeared alongside tools inside ...\Android SDK\)
  5. Opened the Android project in Intellij IDEA, navigated to File->Project Structure->SDKs, and added Android SDK by directing to ...\Android SDK\ directory

JSON Post with Customized HTTPHeader Field

Just wanted to update this thread for future developers.

JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.

Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.

Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...

<some folder>\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\xyz.h"

On the other hand let's say your file structure looks like this...

<some folder>\include\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\include\xyz.h"

Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h> you should probably change it to #include "xyz.h"

android lollipop toolbar: how to hide/show the toolbar while scrolling?

The answer is straightforward. Just implement OnScrollListenerand hide/show your toolbar in the listener. For example, if you have listview/recyclerview/gridview, then follow the example.

In your MainActivity Oncreate method, initialize the toolbar.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
}

And then implement the OnScrollListener

public RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        boolean hideToolBar = false;
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (hideToolBar) {
                ((ActionBarActivity)getActivity()).getSupportActionBar().hide();
            } else {
                ((ActionBarActivity)getActivity()).getSupportActionBar().show();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 20) {
                hideToolBar = true;

            } else if (dy < -5) {
                hideToolBar = false;
            }
        }
    };

I got the idea from: https://stackoverflow.com/a/27063901/1079773

How to get date, month, year in jQuery UI datepicker?

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

What's the difference between align-content and align-items?

The align-items property of flex-box aligns the items inside a flex container along the cross axis just like justify-content does along the main axis. (For the default flex-direction: row the cross axis corresponds to vertical and the main axis corresponds to horizontal. With flex-direction: column those two are interchanged respectively).

Here's an example of how align-items:center looks:

align-items: center

But align-content is for multi line flexible boxes. It has no effect when items are in a single line. It aligns the whole structure according to its value. Here's an example for align-content: space-around;: enter image description here

And here's how align-content: space-around; with align-items:center looks: enter image description here

Note the 3rd box and all other boxes in first line change to vertically centered in that line.

Here are some codepen links to play with:

http://codepen.io/asim-coder/pen/MKQWbb

http://codepen.io/asim-coder/pen/WrMNWR

Here's a super cool pen which shows and lets you play with almost everything in flexbox.

What is the fastest way to create a checksum for large files in C#

You're doing something wrong (probably too small read buffer). On a machine of undecent age (Athlon 2x1800MP from 2002) that has DMA on disk probably out of whack (6.6M/s is damn slow when doing sequential reads):

Create a 1G file with "random" data:

# dd if=/dev/sdb of=temp.dat bs=1M count=1024    
1073741824 bytes (1.1 GB) copied, 161.698 s, 6.6 MB/s

# time sha1sum -b temp.dat
abb88a0081f5db999d0701de2117d2cb21d192a2 *temp.dat

1m5.299s

# time md5sum -b temp.dat
9995e1c1a704f9c1eb6ca11e7ecb7276 *temp.dat

1m58.832s

This is also weird, md5 is consistently slower than sha1 for me (reran several times).

mssql '5 (Access is denied.)' error during restoring database

I recently had this problem. The fix for me was to go to the Files page of the Restore Database dialog and check "Relocate all files to folder".

Restore Database dialog

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Get HTML code using JavaScript with a URL

First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).

In PHP, this is how you do it:

file_get_contents($theUrl);

In javascript, there is three ways :

Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/

var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);

Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/

var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
    alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});

]4

How do I rotate the Android emulator display?

Ubuntu 12.10 (Quantal Quetzal): [LEFT Ctrl] + F12.

For some reason NumLock isn't working on a new install on a Dell XPS 8500, but the above worked.

How to return a value from try, catch, and finally?

To return a value when using try/catch you can use a temporary variable, e.g.

public static double add(String[] values) {
    double sum = 0.0;
    try {
        int length = values.length;
        double arrayValues[] = new double[length];
        for(int i = 0; i < length; i++) {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
        }
    } catch(NumberFormatException e) {
        e.printStackTrace();
    } catch(RangeException e) {
        throw e;
    } finally {
        System.out.println("Thank you for using the program!");
    }
    return sum;
}

Else you need to have a return in every execution path (try block or catch block) that has no throw.

APT command line interface-like yes/no input?

on 2.7, is this too non-pythonic?

if raw_input('your prompt').lower()[0]=='y':
   your code here
else:
   alternate code here

it captures any variation of Yes at least.

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.

Leave off the parenthesis when including the directive in your html:

<my-directive callback="someFunction" />

Then "unwrap" the function in your directive's link or controller. here is an example:

app.directive("myDirective", function() {

    return {
        restrict: "E",
        scope: {
            callback: "&"                              
        },
        template: "<div ng-click='callback(data)'></div>", // call function this way...
        link: function(scope, element, attrs) {
            // unwrap the function
            scope.callback = scope.callback(); 

            scope.data = "data from somewhere";

            element.bind("click",function() {
                scope.$apply(function() {
                    callback(data);                        // ...or this way
                });
            });
        }
    }
}]);    

The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:

<outer-directive callback="someFunction" >
    <middle-directive callback="callback" >
        <inner-directive callback="callback" />
    </middle-directive>
</outer-directive>

Then you would end up with something like this in your inner-directive:

callback()()()(data); 

Which would fail in other nesting scenarios.

I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters

I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.

How to check the installed version of React-Native

Use react-native info It shows all system and libraries information...

Result :-

System:
    OS: Linux 5.4 Ubuntu 20.04.1 LTS (Focal Fossa)
    CPU: (4) x64 Intel(R) Core(TM) i3-6006U CPU @ 2.00GHz
    Memory: 787.22 MB / 11.59 GB
    Shell: 5.0.17 - /bin/bash
  Binaries:
    Node: 12.18.4 - /usr/bin/node
    Yarn: 1.22.4 - /usr/bin/yarn
    npm: 6.14.6 - /usr/bin/npm
    Watchman: Not Found
  SDKs:
    Android SDK:
      API Levels: 22, 26, 27, 28, 29
      Build Tools: 26.0.2, 28.0.3, 29.0.2, 29.0.3, 30.0.0, 30.0.0
      System Images: android-R | Google Play Intel x86 Atom
      Android NDK: 21.1.6352462
  IDEs:
    Android Studio: Not Found
  Languages:
    Java: 11.0.8 - /usr/bin/javac
    Python: Not Found
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.13.1 => 16.13.1 
    react-native: 0.63.3 => 0.63.3 
  npmGlobalPackages:
    *react-native*: Not Found

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment


Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.


Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.


Source 1 (further reading): https://www.baeldung.com/maven-wrapper

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:

os.popen(command).read()

How to force two figures to stay on the same page in LaTeX?

Try using the float package and then the [H] option for your figure.

\usepackage{float}

...

\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}

as already suggested by this insightful answer!

https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text

An efficient way to Base64 encode a byte array?

    public void ProcessRequest(HttpContext context)
    {
        string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        MemoryStream str = new MemoryStream();

        context.Response.Clear();
        Byte[] bytes = (Byte[])dr[0];
        string d = System.Text.Encoding.Default.GetString(bytes);
        byte[] bytes2 = Convert.FromBase64String(d);
        //context.Response.Write(d);
        Image img = Image.FromStream(new MemoryStream(bytes2));
        img.Save(context.Response.OutputStream, ImageFormat.Png);
        context.Response.Flush();
        str.WriteTo(context.Response.OutputStream);
        str.Dispose();
        str.Close();
        conn.Close();
        context.Response.End();
    }

How can I join on a stored procedure?

Here's a terrible idea for you.

Use an alias, create a new linked server from your server to its own alias.

Now you can do:

select a.SomeColumns, b.OtherColumns
from LocalDb.dbo.LocalTable a
inner join (select * from openquery([AliasToThisServer],'
exec LocalDb.dbo.LocalStoredProcedure
') ) b
on a.Id = b.Id

Remove all multiple spaces in Javascript and replace with single space

you all forget about quantifier n{X,} http://www.w3schools.com/jsref/jsref_regexp_nxcomma.asp

here best solution

str = str.replace(/\s{2,}/g, ' ');

Using %s in C correctly - very basic level

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

Read SQL Table into C# DataTable

Centerlized Model: You can use it from any where!

You just need to call Below Format From your function to this class

DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);

That's it. it's perfect method.

public class DbConnectionHelper {
   public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
    string connString = @ "your connection string here";
    //Object Declaration
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter sda = new SqlDataAdapter();
    try {
     //Get Connection string and Make Connection
     con.ConnectionString = connString; //Get the Connection String
     if (con.State == ConnectionState.Closed) {
      con.Open(); //Connection Open
     }
     if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
     {
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.CommandText = Query;
      if (p.Length > 0) // If Any parameter is there means, we need to add.
      {
       for (int i = 0; i < p.Length; i++) {
        cmd.Parameters.Add(p[i]);
       }
      }
     }
     if (cmdText == CommandType.Text) // Type : Text
     {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = Query;
     }
     if (cmdText == CommandType.TableDirect) //Type: Table Direct
     {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = Query;
     }
     cmd.Connection = con; //Get Connection in Command
     sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
     sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
     con.Close(); //Connection Close
    } catch (Exception ex) {

     throw ex; //Here you need to handle Exception
    }
    return ds;
   }
  }

Styling an anchor tag to look like a submit button

Style your change the Submit button to an anchor tag instead and submit using javascript:

<a class="link-button" href="javascript:submit();">Submit</a>
<a class="link-button" href="some_url">Cancel</a>

function submit() {
    var form = document.getElementById("form_id");
    form.submit();
}

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

onMeasure custom view explanation

actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:

  • EXACTLY match_parent is EXACTLY + size of the parent
  • AT_MOST wrap_content results in an AT_MOST MeasureSpec
  • UNSPECIFIED never triggered

In case of an horizontal scroll view, your code will work.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)

Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:

 RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]

Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Install pdo for postgres Ubuntu

PDO driver for PostgreSQL is now included in the debian package php5-dev. The above steps using Pecl no longer works.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

Below is worked for me on macos mojave 10.14.6 version

I installed current jdk(https://www.oracle.com/java/technologies/javase-downloads.html)

Then do respectively;

  • vim .bash_profile
  • add "export JAVA_HOME=$(/usr/libexec/java_home)" to bash_profile
  • source .bash_profile

it is done. And you can check the version with java -version command.

How do I apply the for-each loop to every character in a String?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));    

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

Why use forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

We could also use codePoints() to print, see this answer for more details.

Mark error in form using Bootstrap

Generally showing the error near where the error occurs is best. i.e. if someone has an error with entering their email, you highlight the email input box.

This article has a couple good examples. http://uxdesign.smashingmagazine.com/2011/05/27/getting-started-with-defensive-web-design/

Also twitter bootstrap has some nice styling that helps with that (scroll down to the Validation states section) http://twitter.github.com/bootstrap/base-css.html#forms

Highlighting each input box is a bit more complicated, so the easy way would be to just put an bootstrap alert at the top with details of what the user did wrong. http://twitter.github.com/bootstrap/components.html#alerts

How to create UILabel programmatically using Swift?

An alternative using a closure to separate out the code into something a bit neater using Swift 4:

class theViewController: UIViewController {

    /** Create the UILabel */
    var theLabel: UILabel = {
        let label = UILabel()
        label.lineBreakMode = .byWordWrapping
        label.textColor = UIColor.white
        label.textAlignment = .left
        label.numberOfLines = 3
        label.font = UIFont(name: "Helvetica-Bold", size: 22)
        return label
    }()

    override func viewDidLoad() {
        /** Add theLabel to the ViewControllers view */
        view.addSubview(theLabel)
    }

    override func viewDidLayoutSubviews() {
        /* Set the frame when the layout is changed */
        theLabel.frame = CGRect(x: 0,
                                y: 0,
                                width: view.frame.width - 30,
                                height: 24)
    }
}

As a note, attributes for theLabel can still be changed whenever using functions in the VC. You're just setting various defaults inside the closure and minimizing clutter in functions like viewDidLoad()

Oracle client ORA-12541: TNS:no listener

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

How to split an integer into an array of digits?

I'd rather not turn an integer into a string, so here's the function I use for this:

def digitize(n, base=10):
    if n == 0:
        yield 0
    while n:
        n, d = divmod(n, base)
        yield d

Examples:

tuple(digitize(123456789)) == (9, 8, 7, 6, 5, 4, 3, 2, 1)
tuple(digitize(0b1101110, 2)) == (0, 1, 1, 1, 0, 1, 1)
tuple(digitize(0x123456789ABCDEF, 16)) == (15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

As you can see, this will yield digits from right to left. If you'd like the digits from left to right, you'll need to create a sequence out of it, then reverse it:

reversed(tuple(digitize(x)))

You can also use this function for base conversion as you split the integer. The following example splits a hexadecimal number into binary nibbles as tuples:

import itertools as it
tuple(it.zip_longest(*[digitize(0x123456789ABCDEF, 2)]*4, fillvalue=0)) == ((1, 1, 1, 1), (0, 1, 1, 1), (1, 0, 1, 1), (0, 0, 1, 1), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 0, 1), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (0, 0, 1, 0), (1, 1, 0, 0), (0, 1, 0, 0), (1, 0, 0, 0))

Note that this method doesn't handle decimals, but could be adapted to.

CSS background-image-opacity?

If the background doesn't have to repeat, you can use the sprite technique (sliding-doors) where you put all the images with differing opacity into one (next to each other) and then just shift them around with background-position.

Or you could declare the same partially transparent background image more than once, if your target browser supports multiple backgrounds (Firefox 3.6+, Safari 1.0+, Chrome 1.3+, Opera 10.5+, Internet Explorer 9+). The opacity of those multiple images should add up, the more backgrounds you define.

This process of combining transparencies is called Alpha Blending and calculated as (thanks @IainFraser):

a? = a1 + a2(1-a1) where a ranges between 0 and 1.

Why is char[] preferred over String for passwords?

Character arrays (char[]) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0's, the password is secure.

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

How to get week numbers from dates?

Using only base, I wrote the following function.

Note:

  1. Assumes Mon is day number 1 in the week
  2. First week is week 1
  3. Returns 0 if week is 52 from last year

Fine-tune to suit your needs.

findWeekNo <- function(myDate){
  # Find out the start day of week 1; that is the date of first Mon in the year
  weekday <- switch(weekdays(as.Date(paste(format(as.Date(myDate),"%Y"),"01-01", sep = "-"))),
                    "Monday"={1},
                    "Tuesday"={2},
                    "Wednesday"={3},
                    "Thursday"={4},
                    "Friday"={5},
                    "Saturday"={6},
                    "Sunday"={7}
  )

  firstMon <- ifelse(weekday==1,1, 9 - weekday )

  weekNo <- floor((as.POSIXlt(myDate)$yday - (firstMon-1))/7)+1
  return(weekNo)
}


findWeekNo("2017-01-15") # 2

Best way to check for null values in Java?

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && foo.bar()) {
//do something
}

Open File Dialog, One Filter for Multiple Excel Extensions?

If you want to merge the filters (eg. CSV and Excel files), use this formula:

OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";

Or if you want to see XML or PDF files in one time use this:

of.Filter = @" XML or PDF |*.xml;*.pdf";

Optimal number of threads per core

I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.

From Wikipedia:

Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.

Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.

If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).

This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.

Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).

Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).

I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

Should 'using' directives be inside or outside the namespace?

This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.

First, remember that a namespace declaration with periods, like:

namespace MyCorp.TheProduct.SomeModule.Utilities
{
    ...
}

is entirely equivalent to:

namespace MyCorp
{
    namespace TheProduct
    {
        namespace SomeModule
        {
            namespace Utilities
            {
                ...
            }
        }
    }
}

If you wanted to, you could put using directives on all of these levels. (Of course, we want to have usings in only one place, but it would be legal according to the language.)

The rule for resolving which type is implied, can be loosely stated like this: First search the inner-most "scope" for a match, if nothing is found there go out one level to the next scope and search there, and so on, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error).

Now, let's be explicit about what this means in a concrete example with the two major conventions.

(1) With usings outside:

using System;
using System.Collections.Generic;
using System.Linq;
//using MyCorp.TheProduct;  <-- uncommenting this would change nothing
using MyCorp.TheProduct.OtherModule;
using MyCorp.TheProduct.OtherModule.Integration;
using ThirdParty;

namespace MyCorp.TheProduct.SomeModule.Utilities
{
    class C
    {
        Ambiguous a;
    }
}

In the above case, to find out what type Ambiguous is, the search goes in this order:

  1. Nested types inside C (including inherited nested types)
  2. Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
  3. Types in namespace MyCorp.TheProduct.SomeModule
  4. Types in MyCorp.TheProduct
  5. Types in MyCorp
  6. Types in the null namespace (the global namespace)
  7. Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty

The other convention:

(2) With usings inside:

namespace MyCorp.TheProduct.SomeModule.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using MyCorp.TheProduct;                           // MyCorp can be left out; this using is NOT redundant
    using MyCorp.TheProduct.OtherModule;               // MyCorp.TheProduct can be left out
    using MyCorp.TheProduct.OtherModule.Integration;   // MyCorp.TheProduct can be left out
    using ThirdParty;

    class C
    {
        Ambiguous a;
    }
}

Now, search for the type Ambiguous goes in this order:

  1. Nested types inside C (including inherited nested types)
  2. Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
  3. Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty
  4. Types in namespace MyCorp.TheProduct.SomeModule
  5. Types in MyCorp
  6. Types in the null namespace (the global namespace)

(Note that MyCorp.TheProduct was a part of "3." and was therefore not needed between "4." and "5.".)

Concluding remarks

No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority.

Also, if a nested namespace has the same name as a type, it can cause problems.

It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings.

Visual Studio's templates, by default, put the usings outside of the namespace (for example if you make VS generate a new class in a new file).

One (tiny) advantage of having usings outside is that you can then utilize the using directives for a global attribute, for example [assembly: ComVisible(false)] instead of [assembly: System.Runtime.InteropServices.ComVisible(false)].

Python - Create list with numbers between 2 values?

I got here because I wanted to create a range between -10 and 10 in increments of 0.1 using list comprehension. Instead of doing an overly complicated function like most of the answers above I just did this

simple_range = [ x*0.1 for x in range(-100, 100) ]

By changing the range count to 100 I now get my range of -10 through 10 by using the standard range function. So if you need it by 0.2 then just do range(-200, 200) and so on etc

Android webview launches browser when calling loadurl

Answering my question based on the suggestions from Maudicus and Hit.

Check the WebView tutorial here. Just implement the web client and set it before loadUrl. The simplest way is:

myWebView.setWebViewClient(new WebViewClient());

For more advanced processing for the web content, consider the ChromeClient.

What is a 'NoneType' object?

In Python, to represent the absence of a value, you can use the None value types.NoneType.None

How to compile LEX/YACC files on Windows?

the easiest method is to download and install cygwin and download gcc and flex packages during installation. Then to run a lex file for eg. abc.l

we write

flex abc.l
gcc lex.yy.c -o abc.exe
./abc.exe

UML diagram shapes missing on Visio 2013

I think because it's Standard's ver.

I don't know if you write your code in VS. But if you did, just go to ARCHITECTURE - new Diagram. & choose yours, & the VS 'll take the care of the rest :)

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

How do I wrap text in a span?

You should use white-space with display table

Example:
    legend {
        display:table; /* Enable line-wrapping in IE8+ */
        white-space:normal; /* Enable line-wrapping in old versions of some other browsers */
    }

Cannot add or update a child row: a foreign key constraint fails

That error occurs when you want to add a foreign key with values that don't exist in the primary key of the parent table. You must be sure that the new foreign key UserID in table2 has values that exist in the table1 primary key, sometimes by default it is null or equal to 0.

You could first update all the fields of the foreign key in table2 with a value that exists in the primary key of table1.

update table2 set UserID = 1 where UserID is null

If you want to add different UserIDs you must modify each row with the values you want.

How to set background color of HTML element using css properties in JavaScript

You can try this

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";

Example.

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff

JSFIDDLE

postgresql port confusion 5433 or 5432?

I ran into this problem as well, it ended up that I had two postgres servers running at the same time. I uninstalled one of them and changed the port back to 5432 and works fine now.

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

How to output an Excel *.xls file from classic ASP

There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.

How to make gradient background in android

First you need to create a gradient.xml as follows

<shape>
    <gradient android:angle="270" android:endColor="#181818" android:startColor="#616161" />

    <stroke android:width="1dp" android:color="#343434" />
</shape>

Then you need to mention above gradient in the background of layout.As follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/gradient"
    >   
</LinearLayout>

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You need MouseClick instead of Click event handler, reference.

switch (e.Button) {

    case MouseButtons.Left:
    // Left click
    break;

    case MouseButtons.Right:
    // Right click
    break;
    ...
}

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You need to add JQuery js before adding bootstrap js file, because BootStrap use jqueries function. So make sure to load first jquery js and then bootstap js file.

<!-- JQuery Core JavaScript -->
<script src="app/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="app/js/bootstrap.min.js"></script>

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Border length smaller than div width?

Another way to do this (in modern browsers) is with a negative spread box-shadow. Check out this updated fiddle: http://jsfiddle.net/WuZat/290/

box-shadow: 0px 24px 3px -24px magenta;

I think the safest and most compatible way is the accepted answer above, though. Just thought I'd share another technique.

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

How to inspect FormData?

ES6+ solutions:

To see the structure of form data:

console.log([...formData])

To see each key-value pair:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}

Getting DOM element value using pure JavaScript

There is no difference if we look on effect - value will be the same. However there is something more...

Solution 3:

_x000D_
_x000D_
function doSomething() {_x000D_
  console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
_x000D_
_x000D_

if DOM element has id then you can use it in js directly

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

This happened to me when I imported a Java 1.8 project from Eclipse Luna into Eclipse Kepler.

  1. Right click on project > Build path > configure build path...
  2. Select the Libraries tab, you should see the Java 1.8 jre with an error
  3. Select the java 1.8 jre and click the Remove button
  4. Add Library... > JRE System Library > Next > workspace default > Finish
  5. Click OK to close the properties window
  6. Go to the project menu > Clean... > OK

Et voilà, that worked for me.

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

how to check the version of jar file?

You can filter version from the MANIFEST file using

unzip -p my.jar META-INF/MANIFEST.MF | grep 'Bundle-Version'

Can an Option in a Select tag carry multiple values?

Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.

In what cases will HTTP_REFERER be empty

HTTP_REFERER - sent by the browser, stating the last page the browser viewed!

If you trusting [HTTP_REFERER] for any reason that is important, you should not, since it can be faked easily:

  1. Some browsers limit access to not allow HTTP_REFERER to be passed
  2. Type a address in the address bar will not pass the HTTP_REFERER
  3. open a new browser window will not pass the HTTP_REFERER, because HTTP_REFERER = NULL
  4. has some browser addon that blocks it for privacy reasons. Some firewalls and AVs do to.

Try this firefox extension, you'll be able to set any headers you want:

@Master of Celebration:

Firefox:

extensions: refspoof, refontrol, modify headers, no-referer

Completely disable: the option is available in about:config under "network.http.sendRefererHeader" and you want to set this to 0 to disable referer passing.

Google chrome / Chromium:

extensions: noref, spoofy, external noreferrer

Completely disable: Chnage ~/.config/google-chrome/Default/Preferences or ~/.config/chromium/Default/Preferences and set this:

{
   ...
   "enable_referrers": false,
   ...
}

Or simply add --no-referrers to shortcut or in cli:

google-chrome --no-referrers

Opera:

Completely disable: Settings > Preferences > Advanced > Network, and uncheck "Send referrer information"

Spoofing web service:

http://referer.us/

Standalone filtering proxy (spoof any header):

Privoxy

Spoofing http_referer when using wget

‘--referer=url’

Spoofing http_referer when using curl

-e, --referer

Spoofing http_referer wth telnet

telnet www.yoursite.com 80 (press return)
GET /index.html HTTP/1.0 (press return)
Referer: http://www.hah-hah.com (press return)
(press return again)

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

Simple file write function in C++

This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before main the following line:

int writeFile();

this tells the compiler that there exist a function named writeFile that will be defined somewhere, that returns an int and that accepts no parameters.

Alternatively you can define first the function writeFile and then main because in this case when the compiler gets to main already knows your function.

Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...

struct Foo {
    void bar() {
        if (baz() != 99) {
            std::cout << "Hey!";
        }
    }

    int baz() {
        return 42;
    }
};

In this case the compiler has no problem analyzing the definition of bar even if it depends on a function baz that is declared later in the source code.

How to write a UTF-8 file with Java?

Try this

Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}

Embedding VLC plugin on HTML page

I found this:

<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2"  width="100%"        
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>

I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...

and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object

Another thing to check is that the address for the video file is correct....

How do I put text on ProgressBar?

I have written a no blinking/flickering TextProgressBar

You can find the source code here: https://github.com/ukushu/TextProgressBar

enter image description here

WARNING: It's a little bit buggy! But still, I think it's better than another answers here. As I have no time for fixes, if you will do sth with them, please send me update by some way:) Thanks.

Samples:

enter image description here enter image description here no blinking/flickering TextProgressBar

no blinking/flickering TextProgressBar enter image description here enter image description here

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Base table or view not found: 1146 Table Laravel 5

I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

What is the best way to prevent session hijacking?

The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.

At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.

I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:

SessionUUID, Serial Num, Current Date/Time

Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.

Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.

How can I convert string to datetime with format specification in JavaScript?

You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.

Reference:

1. moment library: https://momentjs.com/

2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript

convertDate(date) {
        var momentDate = moment(date).format('hh : mm A');
        return momentDate;
}

and you can call this method like:

this.convertDate('2020-05-01T10:31:18.837Z');

I hope it helps. Enjoy coding.

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

Changing width property of a :before css selector using JQuery

You may try to inherit property from the base class:

_x000D_
_x000D_
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
    var element = document.getElementById('box');_x000D_
    width += 0.0625;_x000D_
    element.style.width = width + 'em';_x000D_
    if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
    /* Set property */_x000D_
    width:4em;_x000D_
    height:2em;_x000D_
    background-color:#d42;_x000D_
    position:relative;_x000D_
}_x000D_
.box:after {_x000D_
    /* Inherit property */_x000D_
    width:inherit;_x000D_
    content:"";_x000D_
    height:1em;_x000D_
    background-color:#2b4;_x000D_
    position:absolute;_x000D_
    top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
_x000D_
_x000D_

Use PHP composer to clone git repo

If you want to use a composer.json from GitHub you would look at this example (under the VCS section).

The package section is for packages that do not have the composer.json. However, you didn't follow that example as well or it would also have worked. Do read what it says about package repositories:

Basically, you define the same information that is included in the composer repository's packages.json, but only for a single package. Again, the minimum required fields are name, version, and either of dist or source.

How to include a child object's child object in Entity Framework 5

With EF Core in .NET Core you can use the keyword ThenInclude :

return DatabaseContext.Applications
 .Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);

Include childs from childrens collection :

return DatabaseContext.Applications
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
 .Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);

How to remove extension from string (only real extension!)

http://php.net/manual/en/function.pathinfo.php

$filename = pathinfo('filename.md.txt', PATHINFO_FILENAME); // returns 'filename.md'

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

What is InputStream & Output Stream? Why and when do we use them?

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

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

var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
    indices.push(result.index);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {_x000D_
    var searchStrLen = searchStr.length;_x000D_
    if (searchStrLen == 0) {_x000D_
        return [];_x000D_
    }_x000D_
    var startIndex = 0, index, indices = [];_x000D_
    if (!caseSensitive) {_x000D_
        str = str.toLowerCase();_x000D_
        searchStr = searchStr.toLowerCase();_x000D_
    }_x000D_
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {_x000D_
        indices.push(index);_x000D_
        startIndex = index + searchStrLen;_x000D_
    }_x000D_
    return indices;_x000D_
}_x000D_
_x000D_
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");_x000D_
_x000D_
document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

What are the differences between normal and slim package of jquery?

At this time, the most authoritative answer appears to be in this issue, which states "it is a custom build of jQuery that excludes effects, ajax, and deprecated code." Details will be announced with jQuery 3.0.

I suspect that the rationale for excluding these components of the jQuery library is in recognition of the increasingly common scenario of jQuery being used in conjunction with another JS framework like Angular or React. In these cases, the usage of jQuery is primarily for DOM traversal and manipulation, so leaving out those components that are either obsolete or are provided by the framework gains about a 20% reduction in file size.

how to start the tomcat server in linux?

Use ./catalina.sh start to start Tomcat. Do ./catalina.sh to get the usage.

I am using apache-tomcat-6.0.36.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

In my case I substitute it with utf8_general_ci with sed like this:

sed -i 's/utf8_0900_ai_ci/utf8_general_ci/g' MY_DB.sql 
sed -i 's/utf8mb4_unicode_520_ci/utf8_general_ci/g' MY_DB.sql 

After that, I can import it without any issue.

Javascript Date: next month

You may probably do this way

var currentMonth = new Date().getMonth();

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here 

}

How do you check current view controller class in Swift?

Try this

if self is MyViewController {        

}

How to retrieve an element from a set without removing it?

How about s.copy().pop()? I haven't timed it, but it should work and it's simple. It works best for small sets however, as it copies the whole set.

How to find Current open Cursors in Oracle

Total cursors open, by session:

select a.value, s.username, s.sid, s.serial#
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic#  and s.sid=a.sid
and b.name = 'opened cursors current';

Source: http://www.orafaq.com/node/758

As far as I know queries on v$ views are based on pseudo-tables ("x$" tables) that point directly to the relevant portions of the SGA, so you can't get more accurate than that; however this also means that it is point-in-time (i.e. dirty read).

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This should do it for you.

<div id="nav-wrap">
    <ul id="nav">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</div>

#nav-wrap {
    float: left;
    height: 87px;
    width: 900px;
}

#nav {
    display: inline;
    height: 87px;
    width: 100%;
}

.nav-item {
    float: left;
    height: 87px;
    line-height: 87px;
    text-align: center;
    text-decoration: none;
    width: 150px;

}

CALL command vs. START with /WAIT option

This is what I found while running batch files in parallel (multiple instances of the same bat file at the same time with different input parameters) :

Lets say that you have an exe file that performs a long task called LongRunningTask.exe

If you call the exe directly from the bat file, only the first call to the LongRunningTask will succed, while the rest will get an OS error "File is already in use by the process"

If you use this command:

start /B /WAIT "" "LongRunningTask.exe" "parameters"

You will be able to run multiple instances of the bat and exe, while still waiting for the task to finish before the bat continues executing the remaining commands. The /B option is to avoid creating another window, the empty quotes are needed in order to the command to work, see the reference below.

Note that if you don´t use the /WAIT in the start, the LongRunningTask will be executed at the same time than the remaining commands in the batch file, so it might create problems if one of these commands requires the output of the LongRunningTask

Resuming :

This can´t run in parallel :

  • call LongRunningTask.exe

This will run in parallel and will be ok as far as there are no data dependencies between the output of the command and the rest of the bat file :

  • start /B "" "LongRunningTask.exe" "parameters"

This will run in parallel and wait for the task to finish, so you can use the output :

  • start /B /WAIT "" "LongRunningTask.exe" "parameters"

Reference for the start command : How can I run a program from a batch file without leaving the console open after the program start?