Programs & Examples On #Afp

AFP stands for "Advanced Function Printing" and "Apple Filing Protocol"

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

Java 7 introduced stricter verification and changed the class format a bit—to contain a stack map used to verify that code is correct. The exception you see means that some method doesn't have a valid stack map.

Java version or bytecode instrumentation could both be to blame. Usually this means that a library used by the application generates invalid bytecode that doesn't pass the stricter verification. So nothing else than reporting it as a bug to the library can be done by the developer.

As a workaround you can add -noverify to the JVM arguments in order to disable verification. In Java 7 it was also possible to use -XX:-UseSplitVerifier to use the less strict verification method, but that option was removed in Java 8.

Play audio with Python

Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:

from AppKit import NSSound

sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()

One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.

from time import sleep

sleep(sound.duration())

Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.

pip install playsound

Then run it like this:

from playsound import playsound
playsound('/path/to/file.wav', block = False)

MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.

When should I use curly braces for ES6 import?

Dan Abramov's answer explains about the default exports and named exports.

Which to use?

Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

However, in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references. Named exports is also preferred for utilities.

Overall use whatever you prefer.

Additional

Default export is actually a named export with name default, so default export can be imported as:

import {default as Sample} from '../Sample.js';

How to sort a list of objects based on an attribute of the objects?

A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator
except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=keyfun, reverse=True) # sort in-place

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

font-family: 'Open Sans'; font-weight: 600; important to change to a different font-family

Where is the Docker daemon log?

The below solution worked for me in Ubuntu 20.04

Logs stored in: /var/lib/docker/containers/<container id>/<container id>-json.log

To know container Id: $ docker ps

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

use property UseSimpleDictionaryFormat on DataContractJsonSerializer and set it to true.

Does the job :)

How to remove all of the data in a table using Django

If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.

See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/

how to set the background image fit to browser using html

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}

Setting a max height on a table

<table  style="border: 1px solid red">
            <thead>
                <tr>
                    <td>Header stays put, no scrolling</td>
                </tr>
            </thead>
            <tbody id="tbodyMain" style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
                <tr>
                    <td>cell 1/1</td>
                    <td>cell 1/2</td>
                </tr>
                <tr>
                    <td>cell 2/1</td>
                    <td>cell 2/2</td>
                </tr>
                <tr>
                    <td>cell 3/1</td>
                    <td>cell 3/2</td>
                </tr>
            </tbody>
        </table>


Javascript Section

<script>
$(document).ready(function(){
   var maxHeight = Math.max.apply(null, $("body").map(function () { return $(this).height(); }).get());
   // alert(maxHeight);
    var borderheight =3 ; 
    // Added some pixed into maxheight 
    // If you set border then need to add this "borderheight" to maxheight varialbe
   $("#tbodyMain").css("min-height", parseInt(maxHeight + borderheight) + "px");             
});

</script>


please, refer How to set maximum possible height to your Table Body
Fiddle Here

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

Install .ipa to iPad with or without iTunes

If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.

Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios

Disabling Minimize & Maximize On WinForm?

Set MaximizeBox and MinimizeBox form properties to False

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

How can I return NULL from a generic method in C#?

Take the recommendation of the error... and either user default(T) or new T.

You will have to add in a comparison in your code to ensure that it was a valid match if you go that route.

Otherwise, potentially consider an output parameter for "match found".

How to upsert (update or insert) in SQL Server 2005

You could do this with an INSTEAD OF INSERT trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:

CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END

Is it possible to read from a InputStream with a timeout?

I would question the problem statement rather than just accept it blindly. You only need timeouts from the console or over the network. If the latter you have Socket.setSoTimeout() and HttpURLConnection.setReadTimeout() which both do exactly what is required, as long as you set them up correctly when you construct/acquire them. Leaving it to an arbitrary point later in the application when all you have is the InputStream is poor design leading to a very awkward implementation.

How to reference a file for variables using Bash?

For preventing naming conflicts, only import the variables that you need:

variableInFile () {
    variable="${1}"
    file="${2}"

    echo $(
        source "${file}";
        eval echo \$\{${variable}\}
    )
}

How to split data into trainset and testset randomly?

from sklearn.model_selection import train_test_split
import numpy

with open("datafile.txt", "rb") as f:
   data = f.read().split('\n')
   data = numpy.array(data)  #convert array to numpy type array

   x_train ,x_test = train_test_split(data,test_size=0.5)       #test_size=0.5(whole_data)

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

in my case, it was a confilict with IntelliJ , I've resolved it by building the project from command line and it worked!

How to fix 'Microsoft Excel cannot open or save any more documents'

I had this same issue, there was no issue regarding memory in my server machine, Finally i was able to fix it by following steps

  1. In your application hosting server, go to its "Component Services"
  2. enter image description here

3.Find "Microsoft Excel Application" in right side.

4.Open its properties by right click

5.Under Identity tab select the option interactive user and click Ok button.

Check once again. Hope it helps

NOTE: But now you may end up with another COM error "Retrieving the COM class factory for component...". In that case Just set the Identity to this User and enter the username and password of a user who has sufficient rights. In my case I entered a user of power user group.

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

Use the UITableViewDataSource method

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

How to compare objects by multiple fields

Following blog given good chained Comparator example

http://www.codejava.net/java-core/collections/sorting-a-list-by-multiple-attributes-example

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * This is a chained comparator that is used to sort a list by multiple
 * attributes by chaining a sequence of comparators of individual fields
 * together.
 *
 */
public class EmployeeChainedComparator implements Comparator<Employee> {

    private List<Comparator<Employee>> listComparators;

    @SafeVarargs
    public EmployeeChainedComparator(Comparator<Employee>... comparators) {
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        for (Comparator<Employee> comparator : listComparators) {
            int result = comparator.compare(emp1, emp2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}

Calling Comparator:

Collections.sort(listEmployees, new EmployeeChainedComparator(
                new EmployeeJobTitleComparator(),
                new EmployeeAgeComparator(),
                new EmployeeSalaryComparator())
        );

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

How do I exit a foreach loop in C#?

Look at this code, it can help you to get out of the loop fast!

foreach (var name in parent.names)
{
   if (name.lastname == null)
   {
      Violated = true;
      this.message = "lastname reqd";
      break;
   }
   else if (name.firstname == null)
   {
      Violated = true;
      this.message = "firstname reqd";
      break;
   }
}

What does the 'static' keyword do in a class?

main() is a static method which has two fundamental restrictions:

  1. The static method cannot use a non-static data member or directly call non-static method.
  2. this() and super() cannot be used in static context.

    class A {  
        int a = 40; //non static
        public static void main(String args[]) {  
            System.out.println(a);  
        }  
    }
    

Output: Compile Time Error

Cross-Origin Read Blocking (CORB)

Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page.

First Make sure these resources are served with a correct "Content-Type", i.e, for JSON MIME type - "text/json", "application/json", HTML MIME type - "text/html".

Second: set mode to cors i.e, mode:cors

The fetch would look something like this

 fetch("https://example.com/api/request", {
            method: 'POST',
            body: JSON.stringify(data),
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                "Accept": 'application/json',
            }
        })
    .then((data) => data.json())
    .then((resp) => console.log(resp))
    .catch((err) => console.log(err))

references: https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md

https://www.chromium.org/Home/chromium-security/corb-for-developers

Best practice to validate null and empty collection in Java

Personally, I prefer to use empty collections instead of null and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

In JPA 2.0 if you want to delete an address if you removed it from a User entity you can add orphanRemoval=true (instead of CascadeType.REMOVE) to your @OneToMany.

More explanation between orphanRemoval=true and CascadeType.REMOVE is here.

PKIX path building failed: unable to find valid certification path to requested target

Java 8 Solution: I just had this problem and solved it by adding the remote site's certificate to my Java keystore. My solution was based on the solution at the myshittycode blog, which was based on a previous solution in mykong's blog. These blog article solutions boil down to downloading a program called InstallCert, which is a Java class you can run from the command line to obtain the certificate. You then proceed to install the certificate in Java's keystore.

The InstallCert Readme worked perfectly for me. You just need to run the following commands:

  1. javac InstallCert.java
  2. java InstallCert [host]:[port] (Enter the given list number of the certificate you want to add in the list when you run the command - likely just 1)
  3. keytool -exportcert -alias [host]-1 -keystore jssecacerts -storepass changeit -file [host].cer
  4. sudo keytool -importcert -alias [host] -keystore [path to system keystore] -storepass changeit -file [host].cer

See the referenced README file for an example if need be.

How to automatically select all text on focus in WPF TextBox?

Try putting this in the constructor of whatever control is housing your textbox:

Loaded += (sender, e) =>
{
    MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    myTextBox.SelectAll();
}

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

How do you find out the type of an object (in Swift)?

Swift 3:

if unknownType is MyClass {
   //unknownType is of class type MyClass
}

"python" not recognized as a command

I had the same problem for a long time. I just managed to resolve it.

So, you need to select your Path, like the others said above. What I did:

Open a command window. Write set path=C:\Python24 (put the location and the version for your python). Now type python, It should work.

The annoying part with this is that you have to type it every time you open the CMD.

I tried to do the permanent one (with the changes in the Environmental variables) but for me its not working.

Insert text with single quotes in PostgreSQL

String literals

Escaping single quotes ' by doubling them up -> '' is the standard way and works of course:

'user's log'     -- incorrect syntax (unbalanced quote)
'user''s log'

In old versions or if you still run with standard_conforming_strings = off or, generally, if you prepend your string with E to declare Posix escape string syntax, you can also escape with the backslash \:

E'user\'s log'

Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:

'escape '' with '''''
$$escape ' with ''$$

To further avoid confusion among dollar-quotes, add a unique token to each pair:

$token$escape ' with ''$token$

Which can be nested any number of levels:

$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$

Pay attention if the $ character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.

That is all very useful for writing plpgsql functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. @Craig's answer has more on that. More details:

Values inside Postgres

When dealing with values inside the database, there are a couple of useful functions to quote strings properly:

  • quote_literal() or quote_nullable() - the latter outputs the string NULL for null input. (There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.)
  • format() with the format specifier %L is equivalent to quote_nullable().
    Like: format('%L', string_var)
  • concat() or concat_ws() are typically no good for this purpose as those do not escape nested single quotes and backslashes.

Multi-line string with extra space (preserved indentation)

it will work if you put it as below:

AA='first line
\nsecond line 
\nthird line'
echo $AA
output:
first line
second line
third line

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

VBA test if cell is in a range

Here is another option to see if a cell exists inside a range. In case you have issues with the Intersect solution as I did.

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then
    'The individual cell exists in the named range
Else
    'The individual cell does not exist in the named range
End If

InStr is a VBA function that checks if a string exists within another string.

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

Running a script inside a docker container using shell script

If you want to run the same command on multiple instances you can do this :

for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done

Unit test naming best practices

I like Roy Osherove's naming strategy. It's the following:

[UnitOfWork_StateUnderTest_ExpectedBehavior]

It has every information needed on the method name and in a structured manner.

The unit of work can be as small as a single method, a class, or as large as multiple classes. It should represent all the things that are to be tested in this test case and are under control.

For assemblies, I use the typical .Tests ending, which I think is quite widespread and the same for classes (ending with Tests):

[NameOfTheClassUnderTestTests]

Previously, I used Fixture as suffix instead of Tests, but I think the latter is more common, then I changed the naming strategy.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.

For example:

| v   | a   |  b  |   c |
+-----+-----+-----+-----+
| 1   | 1   |  1  |   1 |
| 10  | 10  | 10  |  10 |
| 100 | 100 | 100 | 100 |

Here a, b and c are using TINYINT(1), TINYINT(2) and TINYINT(3) respectively. As you can see, it pads the values on the left side using the display width.

It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1) still accepts [-128 .. 127].

How to Ping External IP from Java Android

I tried following code, which works for me.

private boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }

Bootstrap 3 Slide in Menu / Navbar on Mobile

Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

_x000D_
_x000D_
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
  $navMenuCont = $($(this).data('target'));_x000D_
  $navMenuCont.animate({_x000D_
    'width': 'toggle'_x000D_
  }, 350);_x000D_
  $(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
  $(".navbar-toggle").trigger("click");_x000D_
  $(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
//     $('ul.nav li.dropdown').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
//     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
_x000D_
//     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
//         event.preventDefault();_x000D_
//         event.stopPropagation();_x000D_
//         $(this).parent().siblings().removeClass('open');_x000D_
//         $(this).parent().toggleClass('open');_x000D_
//         $('b', this).toggleClass("caret caret-up");_x000D_
//     });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
//     if( $(this).width() >= 767) {_x000D_
//         $('ul.nav li.dropdown').hover(function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//         }, function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//         });_x000D_
//     }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
  // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
  //     event.preventDefault();_x000D_
  //     event.stopPropagation();_x000D_
  //     $(this).parent().siblings().removeClass('open');_x000D_
  //     $(this).parent().toggleClass('open');_x000D_
  //     $('b', this).toggleClass("caret caret-up");_x000D_
  // });_x000D_
_x000D_
  $('ul.nav li.dropdown').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
  $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
  #slide-navbar-collapse {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 15px;_x000D_
    z-index: 999999;_x000D_
    width: 280px;_x000D_
    height: 100%;_x000D_
    background-color: #f9f9f9;_x000D_
    overflow: auto;_x000D_
    bottom: 0;_x000D_
    max-height: inherit;_x000D_
  }_x000D_
  .menu-overlay {_x000D_
    display: none;_x000D_
    background-color: #000;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    opacity: 0.5;_x000D_
    filter: alpha(opacity=50);_x000D_
    /* IE7 & 8 */_x000D_
    position: fixed;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    z-index: 49;_x000D_
  }_x000D_
  .navbar-fixed-top {_x000D_
    position: initial !important;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu {_x000D_
    background-color: #ffffff;_x000D_
  }_x000D_
  ul.nav.navbar-nav li {_x000D_
    border-bottom: 1px solid #eee;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
  .navbar-nav .open .dropdown-menu>li>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 5px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 10px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
  border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
  padding: 0px;_x000D_
  margin: 0px;_x000D_
  border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
  font-weight: bold !important;_x000D_
  padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 9px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
  li.dropdown-submenu>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
  li.dropdown>a:before {_x000D_
    content: "\f107";_x000D_
    font-family: FontAwesome;_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 12px;_x000D_
    font-size: 15px;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
  <head>_x000D_
    <title>Bootstrap Example</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container-fluid">_x000D_
        <!-- Brand and toggle get grouped for better mobile display -->_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
          <a class="navbar-brand" href="#">Brand</a>_x000D_
        </div>_x000D_
        <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
        <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
          </ul>_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.navbar-collapse -->_x000D_
      </div>_x000D_
      <!-- /.container-fluid -->_x000D_
    </nav>_x000D_
    <div class="menu-overlay"></div>_x000D_
    <div class="col-md-12">_x000D_
      <h1>Resize the window to see the result</h1>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference JS fiddle

Display Last Saved Date on worksheet

You can also simple add the following into the Header or Footer of the Worksheet

Last Saved: &[Date] &[Time]

Creating a new ArrayList in Java

If you just want a list:

ArrayList<Class> myList = new ArrayList<Class>();

If you want an arraylist of a certain length (in this case size 10):

List<Class> myList = new ArrayList<Class>(10);

If you want to program against the interfaces (better for abstractions reasons):

List<Class> myList = new ArrayList<Class>();

Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

Deep copy of a dict in python

How about:

import copy
d = { ... }
d2 = copy.deepcopy(d)

Python 2 or 3:

Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = copy.deepcopy(my_dict)
>>> my_dict['a'][2] = 7
>>> my_copy['a'][2]
3
>>>

How to use ConcurrentLinkedQueue?

Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.

Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.

How to reset form body in bootstrap modal box?

Just set the empty values to the input fields when modal is hiding.

$('#Modal_Id').on('hidden', function () {
   $('#Form_Id').find('input[type="text"]').val('');
});

Java Switch Statement - Is "or"/"and" possible?

From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case. For that you need to use the below function:

Character.toLowerCase(c);

Can the Android drawable directory contain subdirectories?

#!/usr/bin/env ruby

# current dir should be drawable-hdpi/ etc

# nuke all symlinks
Dir.foreach('.') {|f|
    File.delete(f) if File.symlink?(f)
}

# symlink all resources renaming with underscores
Dir.glob("**/*.png") {|f|
    system "ln -s #{f} #{f.gsub('/', '_')}" if f.include?("/")
}

How to generate unique id in MySQL?

 <?php
    $hostname_conn = "localhost";
    $database_conn = "user_id";
    $username_conn = "root";
    $password_conn = "";
     $conn = mysql_pconnect($hostname_conn, $username_conn,   $password_conn) or trigger_error(mysql_error(),E_USER_ERROR); 
   mysql_select_db($database_conn,$conn);
   // run an endless loop      
    while(1) {       
    $randomNumber = rand(1, 999999);// generate unique random number               
    $query = "SELECT * FROM tbl_rand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'";  // check if it exists in database   
    $res =mysql_query($query,$conn);       
    $rowCount = mysql_num_rows($res);
     // if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
    if($rowCount < 1) {
    $con = mysql_connect ("localhost","root");      
    mysql_select_db("user_id", $con);       
    $sql = "insert into tbl_rand(the_number) values('".$randomNumber."')";      
    mysql_query ($sql,$con);        
    mysql_close ($con);
    break;
    }   
}
  echo "inserted unique number into Data_base. use it as ID";
   ?>

How to get the path of a running JAR file?

Something that is frustrating is that when you are developing in Eclipse MyClass.class.getProtectionDomain().getCodeSource().getLocation() returns the /bin directory which is great, but when you compile it to a jar, the path includes the /myjarname.jar part which gives you illegal file names.

To have the code work both in the ide and once it is compiled to a jar, I use the following piece of code:

URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
    myFile = new File(applicationRootPath, "filename");
}
else{
    myFile = new File(applicationRootPath.getParentFile(), "filename");
}

Retrieve filename from file descriptor in C

I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

We do, instead, have a F_GETPATH command for fcntl:

 F_GETPATH          Get the path of the file descriptor Fildes.  The argu-
                    ment must be a buffer of size MAXPATHLEN or greater.

So to get the file associated to a file descriptor, you can use this snippet:

#include <sys/syslimits.h>
#include <fcntl.h>

char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
    // do something with the file path
}

Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.

IntelliJ IDEA generating serialVersionUID

After spending some time on Serialization, I find that, we should not generate serialVersionUID with some random value, we should give it a meaningful value.

Here is a details comment on this. I am coping the comment here.

Actually, you should not be "generating" serial version UIDs. It is a dumb "feature" that stems from the general misunderstanding of how that ID is used by Java. You should be giving these IDs meaningful, readable values, e.g. starting with 1L, and incrementing them each time you think the new version of the class should render all previous versions (that might be previously serialized) obsolete. All utilities that generate such IDs basically do what the JVM does when the ID is not defined: they generate the value based on the content of the class file, hence coming up with unreadable meaningless long integers. If you want each and every version of your class to be distinct (in the eyes of the JVM) then you should not even specify the serialVersionUID value isnce the JVM will produce one on the fly, and the value of each version of your class will be unique. The purpose of defining that value explicitly is to tell the serialization mechanism to treat different versions of the class that have the same SVUID as if they are the same, e.g. not to reject the older serialized versions. So, if you define the ID and never change it (and I assume that's what you do since you rely on the auto-generation, and you probably never re-generate your IDs) you are ensuring that all - even absolutely different - versions of your class will be considered the same by the serialization mechanism. Is that what you want? If not, and if you indeed want to have control over how your objects are recognized, you should be using simple values that you yourself can understand and easily update when you decide that the class has changed significantly. Having a 23-digit value does not help at all.

Hope this helps. Good luck.

Undo git update-index --assume-unchanged <file>

Nothing here that is not covered. But would like to add my 2 cents. At times, I run a build and it changes lot of files and then I want to work on something, so this command really helps me a lot.

git update-index --assume-unchanged `git status | grep modified | sed 's|modified:||g'| xargs`

Hope someone else find it useful as well.

How to secure the ASP.NET_SessionId cookie?

If the entire site uses HTTPS, your sessionId cookie is as secure as the HTTPS encryption at the very least. This is because cookies are sent as HTTP headers, and when using SSL, the HTTP headers are encrypted using the SSL when being transmitted.

How to handle windows file upload using Selenium WebDriver?

        webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
        webDriver.SwitchTo().ActiveElement().SendKeys(fileName);

worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

Convert from ASCII string encoded in Hex to plain ASCII?

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i'm just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now...

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they'll help).

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

If someone would need a one liner:

iwr -Uri 'https://api.github.com/user' -Headers @{ Authorization = "Basic "+ [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("user:pass")) }

Check if string contains \n Java

For portability, you really should do something like this:

public static final String NEW_LINE = System.getProperty("line.separator")
.
.
.
word.contains(NEW_LINE);

unless you're absolutely certain that "\n" is what you want.

no default constructor exists for class

If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you do define a constructor, (even if it does take one or more arguments) the compiler will not synthesize a constructor for you -- at that point, you've taken responsibility for constructing objects of that class, so the compiler "steps back", so to speak, and leaves that job to you.

You have two choices. You need to either provide a default constructor, or you need to supply the correct parameter when you define an object. For example, you could change your constructor to look something like:

Blowfish(BlowfishAlgorithm algorithm = CBC);

...so the ctor could be invoked without (explicitly) specifying an algorithm (in which case it would use CBC as the algorithm).

The other alternative would be to explicitly specify the algorithm when you define a Blowfish object:

class GameCryptography { 
    Blowfish blowfish_;
public:
    GameCryptography() : blowfish_(ECB) {}
    // ...
};

In C++ 11 (or later) you have one more option available. You can define your constructor that takes an argument, but then tell the compiler to generate the constructor it would have if you didn't define one:

class GameCryptography { 
public:

    // define our ctor that takes an argument
    GameCryptography(BlofishAlgorithm); 

    // Tell the compiler to do what it would have if we didn't define a ctor:
    GameCryptography() = default;
};

As a final note, I think it's worth mentioning that ECB, CBC, CFB, etc., are modes of operation, not really encryption algorithms themselves. Calling them algorithms won't bother the compiler, but is unreasonably likely to cause a problem for others reading the code.

Instagram API: How to get all user media?

See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.

Automapper missing type map configuration or unsupported mapping - Error

In your class AutoMapper profile, you need to create a map for your entity and viewmodel.

ViewModel To Domain Model Mappings:

This is usually in AutoMapper/DomainToViewModelMappingProfile

In Configure(), add a line like

Mapper.CreateMap<YourEntityViewModel, YourEntity>();

Domain Model To ViewModel Mappings:

In ViewModelToDomainMappingProfile, add:

Mapper.CreateMap<YourEntity, YourEntityViewModel>();

Gist example

Getting a better understanding of callback functions in JavaScript

Callbacks are about signals and "new" is about creating object instances.

In this case it would be even more appropriate to execute just "callback();" than "return new callback()" because you aren't doing anything with a return value anyway.

(And the arguments.length==3 test is really clunky, fwiw, better to check that callback param exists and is a function.)

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How to convert a plain object into an ES6 Map?

Yes, the Map constructor takes an array of key-value pairs.

Object.entries is a new Object static method available in ES2017 (19.1.2.5).

const map = new Map(Object.entries({foo: 'bar'}));

map.get('foo'); // 'bar'

It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome

If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:

Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);

Is JavaScript object-oriented?

I think when you can follow the same or similar design patterns as a true OO language like Java/C#, you can pretty much call it an OO language. Some aspects are obviously different but you can still use very well established OO design pattersn.

Removing element from array in component state

You can use this function, if you want to remove the element (without index)

removeItem(item) {
  this.setState(prevState => {
    data: prevState.data.filter(i => i !== item)
  });
}

Configuring angularjs with eclipse IDE

Configuration worked with Eclipse Mars 4.5 version.

1) Install Eclipse Mars 4.5 from https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/mars2 This comes with Tern and embedded Node.js server

2) Install AngularJS Eclipse plugin from Eclipse Marketplace

3) Configure node.js server to the embedded nodejs server within Eclipse (found in the eclipse plugins folder) at Windows-> Preferences -> JavaScript -> Tern -> Server -> node.js. No extra configurations are required.

4) Test configuration in a html or javascript file. https://github.com/angelozerr/angularjs-eclipse

How to get the body's content of an iframe in Javascript?

Chalkey is correct, you need to use the src attribute to specify the page to be contained in the iframe. Providing you do this, and the document in the iframe is in the same domain as the parent document, you can use this:

var e = document.getElementById("id_description_iframe");
if(e != null) {
   alert(e.contentWindow.document.body.innerHTML);
}

Obviously you can then do something useful with the contents instead of just putting them in an alert.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

How do I give ASP.NET permission to write to a folder in Windows 7?

Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.

If you are using II7 (and I guess you do) do the following.

  1. Open IIS7
  2. Select Website for which you need to modify permissions
  3. Go to Basic Settings and see which application pool you're using.
  4. Go to Application pools and find application pool from #3
  5. Find system account used for running this application pool (Identity column)
  6. Navigate to your storage folder in IIS, select it and click on Edit Permissions (under Actions sub menu on the right)
  7. Open security tab and add needed permissions only for user you identified in #3

Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool

Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.

Configure active profile in SpringBoot via Maven

The Maven profile and the Spring profile are two completely different things. Your pom.xml defines spring.profiles.active variable which is available in the build process, but not at runtime. That is why only the default profile is activated.

How to bind Maven profile with Spring?

You need to pass the build variable to your application so that it is available when it is started.

  1. Define a placeholder in your application.properties:

    [email protected]@
    

    The @spring.profiles.active@ variable must match the declared property from the Maven profile.

  2. Enable resource filtering in you pom.xml:

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        …
    </build>
    

    When the build is executed, all files in the src/main/resources directory will be processed by Maven and the placeholder in your application.properties will be replaced with the variable you defined in your Maven profile.

For more details you can go to my post where I described this use case.

Fitting a density curve to a histogram in R

Such thing is easy with ggplot2

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

or to mimic the result from Dirk's solution

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()

Importing a CSV file into a sqlite3 database table using Python

You can do this using blaze & odo efficiently

import blaze as bz
csv_path = 'data.csv'
bz.odo(csv_path, 'sqlite:///data.db::data')

Odo will store the csv file to data.db (sqlite database) under the schema data

Or you use odo directly, without blaze. Either ways is fine. Read this documentation

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

Concatenating two std::vectors

If your goal is simply to iterate over the range of values for read-only purposes, an alternative is to wrap both vectors around a proxy (O(1)) instead of copying them (O(n)), so they are promptly seen as a single, contiguous one.

std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };

VecProxy<int> AB(A, B);  // ----> O(1)!

for (size_t i = 0; i < AB.size(); i++)
    std::cout << AB[i] << " ";  // ----> 1 2 3 4 5 10 20 30

Refer to https://stackoverflow.com/a/55838758/2379625 for more details, including the 'VecProxy' implementation as well as pros & cons.

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

A common mistake during development of an android app running on a Virtual Device on your dev machine is to forget that the virtual device is not the same host as your dev machine. So if your server is running on your dev machine you cannot use a "http://localhost/..." url as that will look for the server endpoint on the virtual device not your dev machine.

How does Google reCAPTCHA v2 work behind the scenes?

May I present my guess, since this is not a open technology.

Google says it's about combing information from before, during, after to distinguish human from robot. But I am more interested about that final click on the check box.

Say, the POST data (solved CAPTCHA) has a field called fingerprint, a string calculated from user behavior. I think there may be a field about that check box location. I guess this check box is in a coordinate system randomly generated by Google back-end and encrypted by the public key of my site. So, a robot may "guess/calculate" a location about this box, but when site owner makes the GET query with private key to verify user identity, Google will decrypt the coordinate system and say if the user click on the right place. So, only one possible right click(with some offsets, it's a square box) location in this random coordinate system owned by only Google and site owners.

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

Show/hide 'div' using JavaScript

A simple example with a Button to scroll up. It will only scroll if the javascript is active, which is an event listening to the scroll type.

_x000D_
_x000D_
document.getElementById('btn').style.display='none'

window.addEventListener('scroll', (event) => {
    console.log(scrollY)
    document.getElementById('btn').style.display='inline'
})
_x000D_
a
long<br>
text<br>
comes<br>
long<br>
text<br>
again

<button id=btn class = 'btn btn-primary' onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
_x000D_
_x000D_
_x000D_

Live in action here

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

Could not find default endpoint element

I had the same issue and it was solved only when the host application and the dll that used that endpoint had the same service reference name.

How to set image in circle in swift

For Swift 4:

import UIKit

extension UIImageView {

func makeRounded() {
    let radius = self.frame.width/2.0
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
   }
}

What is a 'workspace' in Visual Studio Code?

I just installed Visual Studio Code v1.25.1. on a Windows 7 Professional SP1 machine. I wanted to understand workspaces in detail, so I spent a few hours figuring out how they work in this version of Visual Studio Code. I thought the results of my research might be of interest to the community.

First, workspaces are referred to by Microsoft in the Visual Studio Code documentation as "multi-root workspaces." In plain English that means "a multi-folder (A.K.A "root") work environment." A Visual Studio Code workspace is simply a collection of folders - any collection you desire, in any order you wish. The typical collection of folders constitutes a software development project. However, a folder collection could be used for anything else for which software code is being developed.

The mechanics behind how Visual Studio Code handles workspaces is a bit complicated. I think the quickest way to convey what I learned is by giving you a set of instructions that you can use to see how workspaces work on your computer. I am assuming that you are starting with a fresh install of Visual Studio Code v1.25.1. If you are using a production version of Visual Studio Code I don't recommend that you follow my instructions because you may lose some or all of your existing Visual Studio Code configuration! If you already have a test version of Visual Studio Code v1.25.1 installed, **and you are willing to lose any configuration that already exists, the following must be done to revert your Visual Studio Code to a fresh installation state:

Delete the following folder (if it exists):

  C:\Users\%username%\AppData\Roaming\Code\Workspaces (where "%username%" is the name of the currently logged-on user)

You will be adding folders to Visual Studio Code to create a new workspace. If any of the folders you intend to use to create this new workspace have previously been used with Visual Studio Code, please delete the ".vscode" subfolder (if it exists) within each of the folders that will be used to create the new workspace.

Launch Visual Studio Code. If the Welcome page is displayed, close it. Do the same for the Panel (a horizontal pane) if it is displayed. If you received a message that Git isn't installed click "Remind me later." If displayed, also close the "Untitled" code page that was launched as the default code page. If the Explorer pane is not displayed click "View" on the main menu then click "Explorer" to display the Explorer pane. Inside the Explorer pane you should see three (3) View headers - Open Editors, No Folder Opened, and Outline (located at the very bottom of the Explorer pane). Make sure that, at a minimum, the open editors and no folder opened view headers are displayed.

Visual Studio Code displays a button that reads "Open Folder." Click this button and select a folder of your choice. Visual Studio Code will refresh and the name of your selected folder will have replaced the "No Folder Opened" View name. Any folders and files that exist within your selected folder will be displayed beneath the View name.

Now open the Visual Studio Code Preferences Settings file. There are many ways to do this. I'll use the easiest to remember which is menu FilePreferencesSettings. The Settings file is displayed in two columns. The left column is a read-only listing of the default values for every Visual Studio Code feature. The right column is used to list the three (3) types of user settings. At this point in your test only two user settings will be listed - User Settings and Workspace Settings. The User Settings is displayed by default. This displays the contents of your User Settings .json file. To find out where this file is located, simply hover your mouse over the "User Settings" listing that appears under the OPEN EDITORS View in Explorer. This listing in the OPEN EDITORS View is automatically selected when the "User Settings" option in the right column is selected. The path should be:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

This settings.json file is where the User Settings for Visual Studio Code are stored.

Now click the Workspace Settings option in the right column of the Preferences listing. When you do this, a subfolder named ".vscode" is automatically created in the folder you added to Explore a few steps ago. Look at the listing of your folder in Explorer to confirm that the .vscode subfolder has been added. Inside the new .vscode subfolder is another settings.json file. This file contains the workspace settings for the folder you added to Explorer a few steps ago.

At this point you have a single folder whose User Settings are stored at:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

and whose Workspace Settings are stored at:

C:\TheLocationOfYourFolder\settings.json

This is the configuration when a single folder is added to a new installation of Visual Studio Code. Things get messy when we add a second (or greater) folder. That's because we are changing Visual Studio Code's User Settings and Workspace Settings to accommodate multiple folders. In a single-folder environment only two settings.json files are needed as listed above. But in a multi-folder environment a .vscode subfolder is created in each folder added to Explorer and a new file, "workspaces.json," is created to manage the multi-folder environment. The new "workspaces.json" file is created at:

c:\Users\%username%\AppData\Roaming\Code\Workspaces\%workspace_id%\workspaces.json

The "%workspaces_id%" is a folder with a unique all-number name.

In the Preferences right column there now appears three user setting options - User Settings, Workspace Settings, and Folder Settings. The function of User Settings remains the same as for a single-folder environment. However, the settings file behind the Workspace Settings has been changed from the settings.json file in the single folder's .vscode subfolder to the workspaces.json file located at the workspaces.json file path shown above. The settings.json file located in each folder's .vscode subfolder is now controlled by a third user setting, Folder Options. This is a drop-down selection list that allows for the management of each folder's settings.json file located in each folder's .vscode subfolder. Please note: the .vscode subfolder will not be created in newly-added explorer folders until the newly-added folder has been selected at least once in the folder options user setting.

Notice that the Explorer single folder name has bee changed to "UNTITLED (WORKSPACE)." This indicates the following:

  1. A multi-folder workspace has been created with the name "UNTITLED (WORKSPACE)
  2. The workspace is named "UNTITLED (WORKSPACE)" to communicate that the workspace has not yet been saved as a separate, unique, workspace file
  3. The UNTITLED (WORKSPACE) workspace can have folders added to it and removed from it but it will function as the ONLY workspace environment for Visual Studio Code

The full functionality of Visual Studio Code workspaces is only realized when a workspace is saved as a file that can be reloaded as needed. This provides the capability to create unique multi-folder workspaces (e.g., projects) and save them as files for later use! To do this select menu FileSave Workspace As from the main menu and save the current workspace configuration as a unique workspace file. If you need to create a workspace "from scratch," first save your current workspace configuration (if needed) then right-click each Explorer folder name and click "Remove Folder from Workspace." When all folders have been removed from the workspace, add the folders you require for your new workspace. When you finish adding new folders, simply save the new workspace as a new workspace file.

An important note - Visual Studio Code doesn't "revert" to single-folder mode when only one folder remains in Explorer or when all folders have been removed from Explorer when creating a new workspace "from scratch." The multi-folder workspace configuration that utilizes three user preferences remains in effect. This means that unless you follow the instructions at the beginning of this post, Visual Studio Code can never be returned to a single-folder mode of operation - it will always remain in multi-folder workspace mode.

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

For users which have flavors in the project and found this thread:

Notice, that if your module dependency has different flavors, you should use one of the strategies:

  1. Module that tightens dependencies should have the same flavors and dimensions as the dependency module
  2. You should explicitly indicate which configuration you target in the module

Like that:

dependencies {
    compile project(path: ':module', configuration:'alphaDebug') 
}

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()

JavaScript equivalent to printf/String.Format

+1 Zippo with the exception that the function body needs to be as below or otherwise it appends the current string on every iteration:

String.prototype.format = function() {
    var formatted = this;
    for (var arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

How to deploy a war file in JBoss AS 7?

Actually, for the latest JBOSS 7 AS, we need a .dodeploy marker even for archives. So add a marker to trigger the deployment.

In my case, I added a Hello.war.deployed file in the same directory and then everything worked fine.

Hope this helps someone!

Can I remove the URL from my print css, so the web address doesn't print?

Remove the url from header and footer using below method

 @page { size: letter;  margin-top: 4mm;margin-bottom: 4mm }

MySQL - count total number of rows in php

Either use COUNT in your MySQL query or do a SELECT * FROM table and do:

$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

dropzone.js - how to do something after ALL files are uploaded

this.on("totaluploadprogress", function(totalBytes, totalBytesSent){


                    if(totalBytes == 100) {

                        //all done! call func here
                    }
                });

c# write text on bitmap

If you want wrap your text, then you should draw your text in a rectangle:

RectangleF rectF1 = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1);

See: https://msdn.microsoft.com/en-us/library/baw6k39s(v=vs.110).aspx

Creating a script for a Telnet session?

Check for the SendCommand tool.

You can use it as follows:

perl sendcommand.pl -i login.txt -t cisco -c "show ip route"

How to have EditText with border in Android Lollipop

For correct work your shape should be with selector and item tags

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
            <stroke android:width="1dp"
                    android:color="@color/shape_border_active"/>
        </shape>
    </item>

</selector>

JS search in object values

You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:

    var data = [
       { "foo": "bar",   "bar": "sit" },
       { "foo": "lorem", "bar": "ipsum" },
       { "foo": "dolor", "bar": "amet" }
    ],
    res1 = JSON.search( data, '//*[contains(name(), 'r')]/..' ),
    res2 = JSON.search( data, '//*[contains(., 'lo')]' );

/*
res1 = [
    { "foo": "bar",   "bar": "sit" },
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

/*
res2 = [
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

Here is a working fiddle;
http://jsfiddle.net/hbi99/2kHDZ/

DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:

http://www.defiantjs.com/#xpath_evaluator

how to toggle (hide/show) a table onClick of <a> tag in java script

You are always passing in true to the toggleMethod, so it will always "show" the table. I would create a global variable that you can flip inside the toggle method instead.

Alternatively you can check the visibility state of the table instead of an explicit variable

How to Apply Gradient to background view of iOS Swift App

Try This , It's working for me,

  var gradientView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 35))
  let gradientLayer:CAGradientLayer = CAGradientLayer()
  gradientLayer.frame.size = self.gradientView.frame.size
  gradientLayer.colors = 
  [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] 
  //Use diffrent colors
  gradientView.layer.addSublayer(gradientLayer)

enter image description here

You can add starting and end point of gradient color.

    gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)

enter image description here

For more detail description refer Best Answer or you can follow CAGradientLayer From Apple

Hopes This is help for some one.

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

Getting the absolute path of the executable, using C#?

On my side, I used, with a form application:

String Directory = System.Windows.Forms.Application.StartupPath;

it takes the application startup path.

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

Pandas "Can only compare identically-labeled DataFrame objects" error

Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

One solution is to sort the index first (Note: some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

Note: == is also sensitive to the order of columns, so you may have to use sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

Note: This can still raise (if the index/columns aren't identically labelled after sorting).

JavaScript file upload size validation

JQuery example provided in this thread was extremely outdated, and google wasn't helpful at all so here is my revision:

 <script type="text/javascript">
        $('#image-file').on('change', function() {
            console.log($(this)[0].files[0].name+' file size is: ' + $(this)[0].files[0].size/1024/1024 + 'Mb');
        });
    </script>

Validation of file extension before uploading file

You can create an array that includes the filetype that is needed and use $.inArray() in jQuery to check if filetype exist in array.

var imageType = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];  

// Given that file is a file object and file.type is string 
// like "image/jpeg", "image/png", or "image/gif" and so on...

if (-1 == $.inArray(file.type.split('/')[1], imageType)) {
  console.log('Not an image type');
}

fatal: The current branch master has no upstream branch

First use git pull origin your_branch_name Then use git push origin your_branch_name

Static Initialization Blocks

You can execute bits of code once for a class before an object is constructed in the static blocks.

E.g.

class A {
  static int var1 = 6;
  static int var2 = 9;
  static int var3;
  static long var4;

  static Date date1;
  static Date date2;

  static {
    date1 = new Date();

    for(int cnt = 0; cnt < var2; cnt++){
      var3 += var1;
    }

    System.out.println("End first static init: " + new Date());
  }
}

get selected value in datePicker and format it

var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);

Scroll Element into View with Selenium

In most of the situation for scrolling this code will work.

WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
js.executeScript("arguments[0].click();",element);

Getting checkbox values on submit

foreach is the best way to get array of values.

here the example code: html code:

<form action="send.php" method="post">
    Red<input type="checkbox" name="color[]" id="color" value="red">
    Green<input type="checkbox" name="color[]" id="color" value="green">
    Blue<input type="checkbox" name="color[]" id="color" value="blue">
    Cyan<input type="checkbox" name="color[]" id="color" value="cyan">
    Magenta<input type="checkbox" name="color[]" id="color" value="Magenta">
    Yellow<input type="checkbox" name="color[]" id="color" value="yellow">
    Black<input type="checkbox" name="color[]" id="color" value="black">
    <input type="submit" value="submit">
</form>

phpcode:

<?php

$name = $POST['color'];



foreach ($name as $color){ 
    echo $color."<br />";
}

?>

Select a date from date picker using Selenium webdriver

This code should work properly to get the current date from the calendar.

String today=getCurrentDay(); //function 
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));

    for (WebElement cell: columns) {
      String z=cell.getAttribute("class").toString();
      if(z.equalsIgnoreCase("day")){
      if (cell.getText().equals(today)) {
        cell.click();
        break;
      }
    }

private String getCurrentDay() {
 Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
 //Get Current Day as a number
 int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
 System.out.println("Today Int: " + todayInt +"\n");

 //Integer to String Conversion
 String todayStr = Integer.toString(todayInt);
 return todayStr;
}

When should I use "this" in a class?

The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.

SQL query to select dates between two dates

Really all sql dates should be in yyyy-MM-dd format for the most accurate results.

PHP - Session destroy after closing browser

Use a keep alive.

On login:

session_start();
$_SESSION['last_action'] = time();

An ajax call every few (eg 20) seconds:

windows.setInterval(keepAliveCall, 20000);

Server side keepalive.php:

session_start();
$_SESSION['last_action'] = time();

On every other action:

session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
  // destroy the session and quit
}

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

Check if XML Element exists

//if the problem is "just" to verify that the element exist in the xml-file before you //extract the value you could do like this

XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");

        if (YOURTEMPVARIABLE.Count > 0 )
        {
            doctype = YOURTEMPVARIABLE[0].InnerXml;

        }
        else
        {
            doctype = "";
        }

How to open in default browser in C#

update the registry with current version of explorer
@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"

public enum BrowserEmulationVersion
{
    Default = 0,
    Version7 = 7000,
    Version8 = 8000,
    Version8Standards = 8888,
    Version9 = 9000,
    Version9Standards = 9999,
    Version10 = 10000,
    Version10Standards = 10001,
    Version11 = 11000,
    Version11Edge = 11001
}

key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

How to get a Color from hexadecimal Color String

I use this and it works great for me for setting any color I want.

public static final int MY_COLOR = Color.rgb(255, 102, 153);

Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.

Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.

Linux command (like cat) to read a specified quantity of characters

Here's a simple script that wraps up using the dd approach mentioned here:

extract_chars.sh

#!/usr/bin/env bash

function show_help()
{
  IT="
extracts characters X to Y from stdin or FILE
usage: X Y {FILE}

e.g. 

2 10 /tmp/it     => extract chars 2-10 from /tmp/it
EOF
  "
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

FROM=$1
TO=$2
COUNT=`expr $TO - $FROM + 1`

if [ -z "$3" ]
then
  dd skip=$FROM count=$COUNT bs=1 2>/dev/null
else
  dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null 
fi

Google.com and clients1.google.com/generate_204

Many applications access this URL to determine if they have a connection that only leads to a captive portal.

The idea is that any captive portal thinks this is a "normal" website, and then redirects you to its portal site, which is returned with a status 200. If an application tries to access any normal website, it is confronted with a totally unexpected response and may have problems figuring out what's wrong. However, with this URL it's easy: If you get status 200, you are inside a captive portal, and you can tell your user to do something about it (usually either log in to the portal using a browser, or turn WiFi off and rely on 3G, if they are using a phone). If you get status 204, you got connected to Google, so your application is actually connected to the internet.

Microsoft and Apple use a slightly different approach; they both have some URLs that return a very specific short text message with a status 200, so instead of accessing the Google url you can for example go to "captive.apple.com" and check for status 200 with data = "Success" and nothing else. If you get status 200 and not exactly that data then you are again in a captive portal.

Syntax for creating a two-dimensional array in Java

These types of arrays are known as jagged arrays in Java:

int[][] multD = new int[3][];
multD[0] = new int[3];
multD[1] = new int[2];
multD[2] = new int[5];

In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:

 int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};

You can easily iterate all elements in your array:

for (int i = 0; i<multD.length; i++) {
    for (int j = 0; j<multD[i].length; j++) {
        System.out.print(multD[i][j] + "\t");
    }
    System.out.println();
}

CSS3 selector :first-of-type with class name?

This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.

p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }

The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.

More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

No value accessor for form control

enter image description here

enter image description here

You can see formControlName in label , removing this solved my problem

FileSystemWatcher Changed event is raised twice

Code with customizable disabling of the time interval of blocking the second watcher raising and without blocking over watchers if they exist:

    namespace Watcher
    {
        class Static
        {
            public static DateTime lastDomain { get; set; }
            public static string lastDomainStr { get; set; }
        }
        public partial class Form1 : Form
       {
            int minMs = 20;//time for blocking in ms
            public Form1()
            {
                InitializeComponent();
                Static.lastDomain = new DateTime(1970, 1, 1, 0, 0, 0);
                Static.lastDomainStr = "";  
                Start();
            }
             private void Start()//Start watcher
             {
                //...
                domain.Changed += new FileSystemEventHandler(Domain);
                domain.EnableRaisingEvents = true;
                //...you second unblocked watchers
                second.Changed += new FileSystemEventHandler(Second);
                second.EnableRaisingEvents = true;
             }
             private void Domain(object source, FileSystemEventArgs e)
             {
                if (now.Subtract(Static.lastDomain).TotalMilliseconds < minMs && Static.lastDomainStr == e.FullPath)return;
                 //...you code here
                 /* if you need form access
                 this.Invoke(new MethodInvoker(() =>{ textBox1.Text = "...";}));
                 */
                 Static.lastDomain = DateTime.Now;
                 Static.lastDomainStr = e.FullPath;
             }
             private void Second(object source, FileSystemEventArgs e)
             {
                  //...Second rised
             }
       }
    }

IE11 prevents ActiveX from running

IE displays a active x warning and ask for permission if you allow it to run or not. To overcome this the only solution is to;

  1. Open Internet Explorer.
  2. Click the Tools menu, and then click Internet Options.
  3. On the Security tab, click the Custom level button.
  4. Scroll down the Security Settings list until you see ActiveX controls and plug-ins.
  5. For Automatic prompting for ActiveX controls, click Enable.
  6. Scroll down to Download signed ActiveX controls and click Enable or Prompt.
  7. Scroll down to Run ActiveX controls and plug-ins and click Enable or Prompt.
  8. Scroll down to Script ActiveX controls marked safe for scripting and click Enable or Prompt.
  9. Click OK, and then click OK again.

There is no way to overcome this issue except changing manually Internet explorer settings. Try checking if plugin works fine while changed settings. If its still not working or not showing any warning is display try checking console for other errors which are not related to active x. Good luck!

How to add content to html body using JS?

I Just came across to a similar to this question solution with included some performance statistics.

It seems that example below is faster:

_x000D_
_x000D_
document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');
_x000D_
_x000D_
_x000D_

InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.

enter image description here

Reference: 1) Performance stats 2) API - insertAdjacentHTML

I hope this will help.

How to search for string in an array

Another option would be use a dictionary instead of an array:

Dim oNames As Object
Set oNames = CreateObject("Scripting.Dictionary")
'You could if need be create this automatically from an existing Array
'The 1 is just a dummy value, we just want the names as keys
oNames.Add "JOHN", 1
oNames.Add "BOB", 1
oNames.Add "JAMES", 1
oNames.Add "PHILIP", 1

As this would then get you a one-liner of

oNames.Exists("JOHN")

The advantage a dictionary provides is exact matching over partial matching from Filter. Say if you have the original list of names in an Array, but were looking for "JO" or "PHIL" who were actually two new people in addition to the four we started with. In this case, Filter(oNAMES, "JO") will match "JOHN" which may not be desired. With a dictionary, it won't.

Dart/Flutter : Converting timestamp

I tested this one and it works

// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be

Better way to sort array in descending order

class Program
{
    private static int[] table;

    static void Main(string[] args)
    {
        int[] ints = new int[] { 6, 2, 5, 99, 55 };

       table = ints.OrderByDescending(x => x).ToArray();

        foreach (var item in table)
        {
            Console.WriteLine(item);
        }

    }

eclipse stuck when building workspace

Eclipse often freezes for me at 44% if I'm debugging Android over USB. When disconnecting the device, Eclipse starts.

Comparing two joda DateTime instances

DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.

file_get_contents() Breaks Up UTF-8 Characters

Try this too

 $url = 'http://www.domain.com/';
    $html = file_get_contents($url);

    //Change encoding to UTF-8 from ISO-8859-1
    $html = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $html);

Find an object in array?

SWIFT 5

Check if the element exists

if array.contains(where: {$0.name == "foo"}) {
   // it exists, do something
} else {
   //item could not be found
}

Get the element

if let foo = array.first(where: {$0.name == "foo"}) {
   // do something with foo
} else {
   // item could not be found
}

Get the element and its offset

if let foo = array.enumerated().first(where: {$0.element.name == "foo"}) {
   // do something with foo.offset and foo.element
} else {
   // item could not be found
}

Get the offset

if let fooOffset = array.firstIndex(where: {$0.name == "foo"}) {
    // do something with fooOffset
} else {
    // item could not be found
}

React-Router External link

Using React with Typescript you get an error as the function must return a react element, not void. So I did it this way using the Route render method (and using React router v4):

redirectToHomePage = (): null => {
    window.location.reload();
    return null;
  };    
<Route exact path={'/'} render={this.redirectToHomePage} />

Where you could instead also use window.location.assign(), window.location.replace() etc

What exactly do "u" and "r" string flags do, and what are raw string literals?

There are two types of string in python: the traditional str type and the newer unicode type. If you type a string literal without the u in front you get the old str type which stores 8-bit characters, and with the u in front you get the newer unicode type that can store any Unicode character.

The r doesn't change the type at all, it just changes how the string literal is interpreted. Without the r, backslashes are treated as escape characters. With the r, backslashes are treated as literal. Either way, the type is the same.

ur is of course a Unicode string where backslashes are literal backslashes, not part of escape codes.

You can try to convert a Unicode string to an old string using the str() function, but if there are any unicode characters that cannot be represented in the old string, you will get an exception. You could replace them with question marks first if you wish, but of course this would cause those characters to be unreadable. It is not recommended to use the str type if you want to correctly handle unicode characters.

Disable Logback in SpringBoot

Just add logback.xml configuration in your classpath and add all your configuration with root appender added. Once the Spring boot completes the bean loading, it will start logging based on your configuration.

DIV height set as percentage of screen?

Try using Viewport Height

div {
    height:100vh; 
}

It is already discussed here in detail

insert multiple rows into DB2 database

None of the above worked for me, the only one working was

insert into tableName  
select 11, 'BALOO' from sysibm.sysdummy1 union all
select 22, nullif('','') AS nullColumn from sysibm.sysdummy1

The nullif is used since it is not possible to pass null in the select statement otherwise.

Iterate over object in Angular

If someone is wondering how to work with multidimensional object, here is the solution.

lets assume we have following object in service

getChallenges() {
    var objects = {};
    objects['0'] = { 
        title: 'Angular2', 
        description : "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
    };

    objects['1'] = { 
        title: 'AngularJS', 
        description : "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
    };

    objects['2'] = { 
        title: 'Bootstrap',
        description : "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    };
    return objects;
}

in component add following function

challenges;

constructor(testService : TestService){
    this.challenges = testService.getChallenges();
}
keys() : Array<string> {
    return Object.keys(this.challenges);
}

finally in view do following

<div *ngFor="#key of keys();">
    <h4 class="heading">{{challenges[key].title}}</h4>
    <p class="description">{{challenges[key].description}}</p>
</div>

jQuery scroll() detect when user stops scrolling

Rob W suggected I check out another post here on stack that was essentially a similar post to my original one. Which reading through that I found a link to a site:

http://james.padolsey.com/javascript/special-scroll-events-for-jquery/

This actually ended up helping solve my problem very nicely after a little tweaking for my own needs, but over all helped get a lot of the guff out of the way and saved me about 4 hours of figuring it out on my own.

Seeing as this post seems to have some merit, I figured I would come back and provide the code found originally on the link mentioned, just in case the author ever decided to go a different direction with the site and ended up taking down the link.

(function(){

    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    special.scrollstart = {
        setup: function() {

            var timer,
                handler =  function(evt) {

                    var _self = this,
                        _args = arguments;

                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        jQuery.event.handle.apply(_self, _args);
                    }

                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);

                };

            jQuery(this).bind('scroll', handler).data(uid1, handler);

        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };

    special.scrollstop = {
        latency: 300,
        setup: function() {

            var timer,
                    handler = function(evt) {

                    var _self = this,
                        _args = arguments;

                    if (timer) {
                        clearTimeout(timer);
                    }

                    timer = setTimeout( function(){

                        timer = null;
                        evt.type = 'scrollstop';
                        jQuery.event.handle.apply(_self, _args);

                    }, special.scrollstop.latency);

                };

            jQuery(this).bind('scroll', handler).data(uid2, handler);

        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };

})();

Tick symbol in HTML/XHTML

You can add a little white one with a Base64 Encoded GIF (online generator here):

url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")

With Chrome, for instance, I use it to style the checkbox control:

INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}

INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}

INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}

If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:

<img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.

In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.

Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.

1.The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226). Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

  1. Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime? The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state: 1) If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061 2) If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy. a. This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds). 3) If the Windows Update service is in a non-ready state, you can see errors reflecting that. a. We recently investigated a failure with an error code indicating the WUSA service was shutting down.

  2. To identify if the prerequisite KB2919355 is installed there are 2 options: Registry key: 64bit hive HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14 CurrentState = 112 32bit hive HKLM\SOFTWARE[WOW6432Node]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14 CurrentState = 112

Or check the file version of: C:\Windows\SysWOW64\wuaueng.dll C:\Windows\System32\wuaueng.dll 7.9.9600.17031 or later

How to get the current loop index when using Iterator?

Here's a way to do it using your own variable and keeping it concise:

List<String> list = Arrays.asList("zero", "one", "two");

int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
    String s = it.next();
    System.out.println(i + ": " + s);
}

Output (you guessed it):

0: zero
1: one
2: two

The advantage is that you don't increment your index within the loop (although you need to be careful to only call Iterator#next once per loop - just do it at the top).

Clear android application user data

// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);

if(sdDir.exists())
    deleteRecursive(sdDir);




// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
        deleteRecursive(child);

    fileOrDirectory.delete();
}

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

SVN 405 Method Not Allowed

The currently added directory is already committed in the repository. So delete the directory in the repository and commit the same directory again.

apache mod_rewrite is not working or not enabled

To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.

<Directory /var/www>
   # Required if running apache > 2.4
   Require all granted

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:

<Directory /var/www>
   # Required if running apache 2.2
   Order allow,deny
   Allow from all

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

Note that an ErrorDocument 404 directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.

Excel date to Unix timestamp

None of the current answers worked for me because my data was in this format from the unix side:

2016-02-02 19:21:42 UTC

I needed to convert this to Epoch to allow referencing other data which had epoch timestamps.

  1. Create a new column for the date part and parse with this formula

    =DATEVALUE(MID(A2,6,2) & "/" & MID(A2,9,2) & "/" & MID(A2,1,4)) 
    
  2. As other Grendler has stated here already, create another column

    =(B2-DATE(1970,1,1))*86400 
    
  3. Create another column with just the time added together to get total seconds:

    =(VALUE(MID(A2,12,2))*60*60+VALUE(MID(A2,15,2))*60+VALUE(MID(A2,18,2)))
    
  4. Create a last column that just adds the last two columns together:

    =C2+D2
    

How to group an array of objects by key

Here is a solution inspired from Collectors.groupingBy() in Java:

_x000D_
_x000D_
function groupingBy(list, keyMapper) {_x000D_
  return list.reduce((accummalatorMap, currentValue) => {_x000D_
    const key = keyMapper(currentValue);_x000D_
    if(!accummalatorMap.has(key)) {_x000D_
      accummalatorMap.set(key, [currentValue]);_x000D_
    } else {_x000D_
      accummalatorMap.set(key, accummalatorMap.get(key).push(currentValue));_x000D_
    }_x000D_
    return accummalatorMap;_x000D_
  }, new Map());_x000D_
}
_x000D_
_x000D_
_x000D_

This will give a Map object.

_x000D_
_x000D_
// Usage_x000D_
_x000D_
const carMakers = groupingBy(cars, car => car.make);
_x000D_
_x000D_
_x000D_

Could not resolve Spring property placeholder

Ensure 'idm.url' is set in property file and the property file is loaded

jQuery: Check if div with certain class name exists

You can simplify this by checking the first object that is returned from JQuery like so:

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

In this case if there is a truthy value at the first ([0]) index, then assume class exists.

Edit 04/10/2013: I've created a jsperf test case here.

Reference member variables as class members

Is there a name to describe this idiom?

There is no name for this usage, it is simply known as "Reference as class member".

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

Yes and also scenarios where you want to associate the lifetime of one object with another object.

Is this generally good practice? Are there any pitfalls to this approach?

Depends on your usage. Using any language feature is like "choosing horses for courses". It is important to note that every (almost all) language feature exists because it is useful in some scenario.
There are a few important points to note when using references as class members:

  • You need to ensure that the referred object is guaranteed to exist till your class object exists.
  • You need to initialize the member in the constructor member initializer list. You cannot have a lazy initialization, which could be possible in case of pointer member.
  • The compiler will not generate the copy assignment operator=() and you will have to provide one yourself. It is cumbersome to determine what action your = operator shall take in such a case. So basically your class becomes non-assignable.
  • References cannot be NULL or made to refer any other object. If you need reseating, then it is not possible with a reference as in case of a pointer.

For most practical purposes (unless you are really concerned of high memory usage due to member size) just having a member instance, instead of pointer or reference member should suffice. This saves you a whole lot of worrying about other problems which reference/pointer members bring along though at expense of extra memory usage.

If you must use a pointer, make sure you use a smart pointer instead of a raw pointer. That would make your life much easier with pointers.

Cursor inside cursor

Do you do any more fetches? You should show those as well. You're only showing us half the code.

It should look like:

FETCH NEXT FROM @Outer INTO ...
WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE @Inner...
  OPEN @Inner
  FETCH NEXT FROM @Inner INTO ...
  WHILE @@FETCH_STATUS = 0
  BEGIN
  ...
    FETCH NEXT FROM @Inner INTO ...
  END
  CLOSE @Inner
  DEALLOCATE @Inner
  FETCH NEXT FROM @Outer INTO ...
END
CLOSE @Outer
DEALLOCATE @Outer

Also, make sure you do not name the cursors the same... and any code (check your triggers) that gets called does not use a cursor that is named the same. I've seen odd behavior from people using 'theCursor' in multiple layers of the stack.

How to count the NaN values in a column in pandas DataFrame

Hope this helps,

import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[np.nan,2,np.nan], 'd':[np.nan,np.nan,np.nan]})

enter image description here

df.isnull().sum()/len(df) * 100

enter image description here

Thres = 40
(df.isnull().sum()/len(df) * 100 ) < Thres

enter image description here

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

Multiple file upload in php

I know this is an old post but some further explanation might be useful for someone trying to upload multiple files... Here is what you need to do:

  • Input name must be be defined as an array i.e. name="inputName[]"
  • Input element must have multiple="multiple" or just multiple
  • In your PHP file use the syntax "$_FILES['inputName']['param'][index]"
  • Make sure to look for empty file names and paths, the array might contain empty strings. Use array_filter() before count.

Here is a down and dirty example (showing just relevant code)

HTML:

<input name="upload[]" type="file" multiple="multiple" />

PHP:

//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.

// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);

// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {

  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a file path
  if ($tmpFilePath != ""){
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {

      //Handle other code here

    }
  }
}

Hope this helps out!

How to uninstall Ruby from /usr/local?

sudo make uninstall did the trick for me using the Ruby 2.4 tar from the official downloads page.

How can I redirect a php page to another php page?

While all of the other answers work, they all have one big problem: it is up to the browser to decide what to do if they encounter a Location header. Usually browser stop processing the request and redirect to the URI indicated with the Location header. But a malicious user could just ignore the Location header and continue its request. Furthermore there may be other things that cause the php interpreter to continue evaluating the script past the Location header, which is not what you intended.

Image this:

<?php
if (!logged_id()) {
    header("Location:login.php");
}

delete_everything();
?>

What you want and expected is that not logged in users are redirected to the login page, so that only logged in users can delete_everything. But if the script gets executed past the Location header still everything gets deleted. Thus, it is import to ALWAYS put an exit after a Location header, like this:

<?php
if (!logged_id()) {
    header("Location:login.php");
    exit; // <- don't forget this!
}

delete_everything();
?>

So, to answer your question: to redirect from a php page to another page (not just php, you can redirect to any page this way), use this:

<?php 

header("Location:http://www.example.com/some_page.php"); 
exit; // <- don't forget this!

?>

Small note: the HTTP standard says that you must provide absolute URLs in the Location header (http://... like in my example above) even if you just want to redirect to another file on the same domain. But in practice relative URLs (Location:some_page.php) work in all browsers, though not being standard compliant.

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

How does one get started with procedural generation?

If you want an example of a world generator simulation plates tectonics, erosion, rain-shadow, etc. take a look at: https://github.com/ftomassetti/lands

On top of that there is also a civilizations evolution simulator:

https://github.com/ftomassetti/civs

A blog full on interesting resource is:

dungeonleague.com/

It is abandoned now but you should read all its posts

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Running the script like this (cron case for example): php5 /pathToScript/info.php produces the same error.

The correct way: php5 -cli /pathToScript/info.php

Autoplay an audio with HTML5 embed tag while the player is invisible

<div id="music">
<audio autoplay>
  <source src="kooche.mp3" type="audio/mpeg">
  <p>If you can read this, your browser does not support the audio element.</p>
</audio>
</div>

And the css:

#music {
  display:none;
}

Like suggested above, you probably should have the controls available in some form. Maybe use a toggle link/checkbox that slides the controls in via jquery.

Source: HTML5 Audio Autoplay

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Which characters are valid/invalid in a JSON key name?

Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalid in Unicode because they are reserved for UTF-16 surrogate pairs. Some JSON encoders/decoders will replace them with U+FFFD. See for example how the Go language and its JSON library deals with them.

So avoid "\uD800" to "\uDFFF" alone (not in surrogate pairs).

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

Which ORM should I use for Node.js and MySQL?

First off, please note that I haven't used either of them (but have used Node.js).

Both libraries are documented quite well and have a stable API. However, persistence.js seems to be used in more projects. I don't know if all of them still use it, though.

The developer of sequelize sometimes blogs about it at blog.depold.com. When you'd like to use primary keys as foreign keys, you'll need the patch that's described in this blog post. If you'd like help for persistence.js there is a google group devoted to it.

From the examples I gather that sequelize is a bit more JavaScript-like (more sugar) than persistance.js but has support for fewer datastores (only MySQL, while persistance.js can even use in-browser stores).

I think that sequelize might be the way to go for you, as you only need MySQL support. However, if you need some convenient features (for instance search) or want to use a different database later on you'd need to use persistence.js.

How can I add a volume to an existing Docker container?

Unfortunately the switch option to mount a volume is only found in the run command.

docker run --help

-v, --volume list Bind mount a volume (default [])

There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.

  1. Export your container docker container export -o ./myimage.docker mycontainer
  2. Import as an image docker import ./myimage.docker myimage
  3. Then docker run -i -t -v /somedir --name mycontainer myimage /bin/bash

Jenkins Host key verification failed

SSH

If you are trying it with SSH, then the Host key Verification error can come due to several reasons.Follow these steps to overcome all the reasons.

  1. Set the Environment variable as HOME and provide the address as the root directory of .ssh folder. e.g:- If your .ssh is kept inside Name folder. C:/Users/Name.
  2. Now make sure that the public SSH key is being provided in the repository link also. Either it is github or bitbucket or any other.
  3. Open git bash. And try cloning the project from the repository. This will help in adding your repository URL in the known_host file, which is being auto created in the .ssh folder.
  4. Now open jenkins and create a new job. Then click on configure.
  5. provide the cloning URL in Source code management under Git. The URL should be start with [email protected]/......... or ssh://proje........
  6. Under the Credential you need to add the username and password of your repository form which you are cloning the project. Select that credential.
  7. And now apply and save the configuration.
  8. Bingo! Start building the project. I hope now you will not get any Host Key verification error!

How can I merge two MySQL tables?

You could write a script to update the FK's for you.. check out this blog: http://multunus.com/2011/03/how-to-easily-merge-two-identical-mysql-databases/

They have a clever script to use the information_schema tables to get the "id" columns:

SET @db:='id_new'; 

select @max_id:=max(AUTO_INCREMENT) from information_schema.tables;

select concat('update ',table_name,' set ', column_name,' = ',column_name,'+',@max_id,' ; ') from information_schema.columns where table_schema=@db and column_name like '%id' into outfile 'update_ids.sql';

use id_new
source update_ids.sql;

iOS: Compare two dates

NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Try to add the path to tnsnames.ora to the config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <oracle.manageddataaccess.client>
    <version number="4.112.3.60">
      <settings>
        <setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
      </settings>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

Clear variable in python

Do you want to delete a variable, don't you?

ok, I think I've got a best alternative idea to @bnaul's answer:

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (like import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

Access all Environment properties as a Map or Properties object

Working with Spring Boot 2, I needed to do something similar. Most of the answers above work fine, just beware that at various phases in the app lifecycles the results will be different.

For example, after a ApplicationEnvironmentPreparedEvent any properties inside application.properties are not present. However, after a ApplicationPreparedEvent event they are.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

how do you view macro code in access?

In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.

SQL query: Delete all records from the table except latest N?

To delete all the records except te last N you may use the query reported below.

It's a single query but with many statements so it's actually not a single query the way it was intended in the original question.

Also you need a variable and a built-in (in the query) prepared statement due to a bug in MySQL.

Hope it may be useful anyway...

nnn are the rows to keep and theTable is the table you're working on.

I'm assuming you have an autoincrementing record named id

SELECT @ROWS_TO_DELETE := COUNT(*) - nnn FROM `theTable`;
SELECT @ROWS_TO_DELETE := IF(@ROWS_TO_DELETE<0,0,@ROWS_TO_DELETE);
PREPARE STMT FROM "DELETE FROM `theTable` ORDER BY `id` ASC LIMIT ?";
EXECUTE STMT USING @ROWS_TO_DELETE;

The good thing about this approach is performance: I've tested the query on a local DB with about 13,000 record, keeping the last 1,000. It runs in 0.08 seconds.

The script from the accepted answer...

DELETE FROM `table`
WHERE id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `table`
    ORDER BY id DESC
    LIMIT 42 -- keep this many records
  ) foo
);

Takes 0.55 seconds. About 7 times more.

Test environment: mySQL 5.5.25 on a late 2011 i7 MacBookPro with SSD

Setting Windows PATH for Postgres tools

All you need to do is to change the PATH variable to include the bin directory of your PostgreSQL installation.

An explanation on how to change environment variables is here:

http://support.microsoft.com/kb/310519
http://www.computerhope.com/issues/ch000549.htm

To verify that the path is set correctly, you can use:

echo %PATH%

on the commandline.

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

Is there a timeout for idle PostgreSQL connections?

In PostgreSQL 9.6, there's a new option idle_in_transaction_session_timeout which should accomplish what you describe. You can set it using the SET command, e.g.:

SET SESSION idle_in_transaction_session_timeout = '5min';

Why aren't variable-length arrays part of the C++ standard?

This was considered for inclusion in C++/1x, but was dropped (this is a correction to what I said earlier).

It would be less useful in C++ anyway since we already have std::vector to fill this role.

Replace multiple characters in one replace call

Please try:

  • replace multi string

    var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

  • replace multi chars

    var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";

Good luck!

Can I inject a service into a directive in AngularJS?

You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.

template.html

<div my-directive api-service='ServiceName'></div>

my-directive.directive.coffee

angular.module 'my.module'
  .factory 'myDirective', ($injector) ->
    directive = 
      restrict: 'A'
      link: (scope, element, attributes) ->
        scope.apiService = $injector.get(attributes.apiService)

now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data

For example:

scope.apiService.query((response) ->
  scope.data = response
, (errorResponse) ->
  console.log "ERROR fetching data for service: #{attributes.apiService}"
  console.log errorResponse.data
)

I have found this technique to be very useful when making elements that interact with API endpoints especially.

Adding elements to a collection during iteration

Even though we cannot add items to the same list during iteration, we can use Java 8's flatMap, to add new elements to a stream. This can be done on a condition. After this the added item can be processed.

Here is a Java example which shows how to add to the ongoing stream an object depending on a condition which is then processed with a condition:

List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);

intList = intList.stream().flatMap(i -> {
    if (i == 2) return Stream.of(i, i * 10); // condition for adding the extra items
    return Stream.of(i);
}).map(i -> i + 1)
        .collect(Collectors.toList());

System.out.println(intList);

The output of the toy example is:

[2, 3, 21, 4]

Attach to a processes output for viewing

I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc path. So if you have a program running, whose ID is 1199, cd into it:

$ cd /proc/1199

Then look for the fd directory underneath

$ cd fd

This fd directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f the one you need - in this case, stdout):

$ tail -f 1

How to execute powershell commands from a batch file?

This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.

pros:

  • can be run like standard .cmd file
  • only one file for batch and powershell script
  • powershell script may be multi-line (easy to read script)
  • allows the standard console input (use the Read-Host cmdlet by standard way)

cons:

  • requires powershell version 2.0+

Commented and runable example of batch-ps-script.cmd:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

Snippet for .cmd file:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

How can I run a program from a batch file without leaving the console open after the program starts?

From my own question:

start /b myProgram.exe params...

works if you start the program from an existing DOS session.

If not, call a vb script

wscript.exe invis.vbs myProgram.exe %*

The Windows Script Host Run() method takes:

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

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.