Programs & Examples On #Launchdagent

Can I make a phone call from HTML on Android?

Yes you can; it works on Android too:

tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:

* tel:2125551212
* tel: (212) 555 1212

The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:

<a href="tel:2125551212">2125551212</a>

on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.

Have a look to RFC3966

Wordpress plugin install: Could not create directory

I was on XAMPP for linux localhost and this worked for me:

sudo chown -R my-linux-username wp-content

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Div width 100% minus fixed amount of pixels

what if your wrapping div was 100% and you used padding for a pixel amount, then if the padding # needs to be dynamic, you can easily use jQuery to modify your padding amount when your events fire.

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

What is the difference between an Instance and an Object?

Quick and Simple Answer

  • Class : a specification, blueprint for an object
  • Object : physical presence of the class in memory
  • Instance : an unique copy of the object (same structure, different data)

The difference between sys.stdout.write and print?

Are there situations in which sys.stdout.write() is preferable to print?

For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.

import sys

def printstars(count):

    if count >= 1:
        i = 1
        while (i <= count):
            x=0
            while(x<i):
                sys.stdout.write('*')
                x = x+1
            print('')
            i=i+1

printstars(5)

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

Unix shell script find out which directory the script file resides?

This one-liner tells where the shell script is, does not matter if you ran it or if you sourced it. Also, it resolves any symbolic links involved, if that is the case:

dir=$(dirname $(test -L "$BASH_SOURCE" && readlink -f "$BASH_SOURCE" || echo "$BASH_SOURCE"))

By the way, I suppose you are using /bin/bash.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Unsupported major.minor version 52.0 when rendering in Android Studio

This occur due to incompatible java version you are using in android studio and the java version that was used with your imported project. Go to File->Project structure->Change jdk 1.7 to jdk 1.8 .After that Go to File->click on Invalidate cache and Restart. Hope this helps..

And change the dependency classpath in gradle file

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

Simultaneously merge multiple data.frames in a list

I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values. The dataframes were produced using table function. The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim. My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.

Therefore, I made the following function. Maybe this function can help someone.

##########################################################
####             Dependencies                        #####
##########################################################

# Depends on Base R only

##########################################################
####             Example DF                          #####
##########################################################

# Example df
ex_df           <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ), 
                         c( seq(1, 7, 1),  rep("NA", 3), seq(1, 12, 1) ), 
                         c( seq(1, 3, 1),  rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))

# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]

# Making an unequal list of dfs, 
# without a common id column
list_of_df      <- apply(ex_df=="NA", 2, ( table) )

it is following the function

##########################################################
####             The function                        #####
##########################################################


# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
  length_df     <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
  max_no        <- max(length_df[,1])
  max_df        <- length_df[max(length_df),]
  name_df       <- names(length_df[length_df== max_no,][1])
  names_list    <- names(list_of_dfs[ name_df][[1]])

  df_dfs <- list()
  for (i in 1:max_no ) {

    df_dfs[[i]]            <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))

  }

  df_cbind               <- do.call( cbind, df_dfs )
  rownames( df_cbind )   <- rownames (length_df)
  colnames( df_cbind )   <- names_list

  df_cbind

}

Running the example

##########################################################
####             Running the example                 #####
##########################################################

rbind_null_df_lists ( list_of_df )

How to add an extra column to a NumPy array

For me, the next way looks pretty intuitive and simple.

zeros = np.zeros((2,1)) #2 is a number of rows in your array.   
b = np.hstack((a, zeros))

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

Replacing objects in array

Here a transparent approach, instead of an unreadable and undebuggable oneliner:

export class List {
    static replace = (object, list) => {
        let newList = [];
        list.forEach(function (item) {
            if (item.id === object.id) {
                newList.push(object);
            } else {
                newList.push(item);
            }
        });
        return newList;
    }
}

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

Clear History and Reload Page on Login/Logout Using Ionic Framework

Welcome to the framework! Actually the routing in Ionic is powered by ui-router. You should probably check out this previous SO question to find a couple of different ways to accomplish this.

If you just want to reload the state you can use:

$state.go($state.current, {}, {reload: true});

If you actually want to reload the page (as in, you want to re-bootstrap everything) then you can use:

$window.location.reload(true)

Good luck!

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Difference between del, remove, and pop on lists

Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

Format Date time in AngularJS

Have you seen the Writing directives (short version) section of the documentation?

HTML

<div ng-controller="Ctrl2">
      Date format: <input ng-model="format"> <hr/>
      Current time is: <span my-current-time="format"></span>
</div> 

JS

function Ctrl2($scope) {
  $scope.format = 'M/d/yy h:mm:ss a';
}

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

or

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

Recover SVN password from local cache

For those interested in the OS X solution for apps like Intelli-J where authorizations are stored by OSX:

  1. Hit CMD+SPACE
  2. Type "keychain"
  3. Open keychain access
  4. Under "Keychains" on the left, choose "login"
  5. Under "Category" on the right, choose "All items"
  6. At the top right in the search box, type in the the host URL (e.g. svn.mycompany.com)
  7. Your keychain item will show if you chose to have your Mac remember your login credentials.
  8. Double click the item and check the "Show password" checkbox at the bottom of the dialog that pops up. You will have to enter your Mac login to reveal the password.

Much easier than having to try to decrypt a password :-)

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

HTML:

?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????

CSS:

?.header
{
    height:50px;
}
.content
{
    position:absolute;
    top: 50px;
    left:0px;
    right:0px;
    bottom:0px;
    overflow-y:scroll;        
}?

Convert comma separated string to array in PL/SQL

Using a pipelined table function:

SQL> CREATE OR REPLACE TYPE test_type
  2  AS
  3    TABLE OF VARCHAR2(100)
  4  /

Type created.

SQL> CREATE OR REPLACE FUNCTION comma_to_table(
  2      p_list IN VARCHAR2)
  3    RETURN test_type PIPELINED
  4  AS
  5    l_string LONG := p_list || ',';
  6    l_comma_index PLS_INTEGER;
  7    l_index PLS_INTEGER := 1;
  8  BEGIN
  9    LOOP
 10      l_comma_index := INSTR(l_string, ',', l_index);
 11      EXIT
 12    WHEN l_comma_index = 0;
 13      PIPE ROW ( TRIM(SUBSTR(l_string, l_index, l_comma_index - l_index)));
 14      l_index := l_comma_index                                + 1;
 15    END LOOP;
 16  RETURN;
 17  END comma_to_table;
 18  /

Function created.

Let's see the output:

SQL> SELECT *
  2  FROM TABLE(comma_to_table('12 3,456,,,,,abc,def'))
  3  /

COLUMN_VALUE
------------------------------------------------------------------------------
12 3
456




abc
def

8 rows selected.

SQL>

What to gitignore from the .idea folder?

You can simply ignore all of them by adding .idea/* to the .gitignore file.

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

Database corruption with MariaDB : Table doesn't exist in engine

This theme required awhile to find results and reasons:

using MaiaDB 5.4. via SuSE-LINUX tumblweed

  1. some files in the appointed directory havn't been necessary in any direct relation with mariadb. I.e: I placed some hints, a text-file, some bakup-copys somewhere in the same appointed directory for mysql mariadb and this caused endless error-messages and blocking the server from starting. Mariadb appears to be very sensible and hostile with the presence of other files not beeing database files(comments,backups,experimantal files etc) .

  2. using libreoffice as client then there already this generated much problems with the creation and working on a database and caused some crashes.The crashes eventually produced bad tables.

  3. May be because of that or may be because of the presence of not yet deleted but unusable tables !! the mysql mariadb server crashed and didn't want to do it' job not even start.

Error message always same : "Table 'some.table' doesn't exist in engine"

But when it started then tables appeared as normal, but it was unpossible to work on them.

So what to do without a more precise Error Message ?? The unusable tables showed up with: "CHECK TABLE" or on the command line of the system with "mysqlcheck " So I deleted by filemanager or on the system-level as root or as allowed user all the questionable files and then problem was solved.

Proposal: the Error Message could be a bit more precisely for example: "corrupted tables" (which can be found by CHECK TABLE, but only if the server is running) or by mysqlcheck even whe server is not running - but here are other disturbing files like hints/bakups a.s.o not visible.

ANYWAY it helped a lot to have backup-copies of the original database-files on a backup volume. This helped to check out and test it again and again until solution was found.

Good luck all - Herbert

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

For Linux users who don't have root access and hence can't use sudo command as suggested in other answers...

First, activate your conda virtual-environment (if you want to use one) by:

source activate virtual-env-name

Then install graphviz, even if you have already done it using pip:

conda install graphviz

then copy the result of the following command:

whereis dot

In my case, its output is:

/home/nader/anaconda2/bin/dot

and add it to your PATH variable. Just run the command below

nano ~/.bashrc

and add these lines to the end of the opened file:

PATH="/home/username/anaconda2/bin/dot:$PATH"
export PATH

now press Ctrl+O and then Ctrl+X to save and exit.

Problem should be solved by now.

Pycharm users, please note: Pycharm does not always see the PATH variable the same as your terminal. This solution does not work for Pycharm, and maybe other IDEs. But you can fix this by adding this line of code:

os.environ["PATH"] += os.pathsep + '/home/nader/anaconda2/bin'

to your python program. Do not forget to

import os

first :)

Edit: If you don't want to use conda, you can still install graphviz from here without any root permissions and add the bin folder to your PATH variable. I didn't test this.

Why are static variables considered evil?

There are two main questions in your post.

First, about static variables. Static variables are completelly unnecesary and it's use can be avoided easily. In OOP languajes in general, and in Java particularlly, function parameters are pased by reference, this is to say, if you pass an object to a funciont, you are passing a pointer to the object, so you dont need to define static variables since you can pass a pointer to the object to any scope that needs this information. Even if this implies that yo will fill your memory with pointers, this will not necesary represent a poor performance because actual memory pagging systems are optimized to handle with this, and they will maintain in memory the pages referenced by the pointers you passed to the new scope; usage of static variables may cause the system to load the memory page where they are stored when they need to be accessed (this will happen if the page has not been accesed in a long time). A good practice is to put all that static stuf together in some little "configuration clases", this will ensure the system puts it all in the same memory page.

Second, about static methods. Static methods are not so bad, but they can quickly reduce performance. For example, think about a method that compares two objects of a class and returns a value indicating which of the objects is bigger (tipical comparison method) this method can be static or not, but when invoking it the non static form will be more eficient since it will have to solve only two references (one for each object) face to the three references that will have to solve the static version of the same method (one for the class plus two, one for each object). But as I say, this is not so bad, if we take a look at the Math class, we can find a lot of math functions defined as static methods. This is really more eficient than putting all these methods in the class defining the numbers, because most of them are rarelly used and including all of them in the number class will cause the class to be very complex and consume a lot of resources unnecesarilly.

In concluson: Avoid the use of static variables and find the correct performance equilibrium when dealing with static or non static methods.

PS: Sorry for my english.

How do I find the location of Python module sources?

For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as "csv" in "import csv") and select "go to definition" - this will open the file, but also on the top you can see the exact file location ("C:....csv.py")

How to assign a heredoc value to a variable in Bash?

Branching off Neil's answer, you often don't need a var at all, you can use a function in much the same way as a variable and it's much easier to read than the inline or read-based solutions.

$ complex_message() {
  cat <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
}

$ echo "This is a $(complex_message)"
This is a abc'asdf"
$(dont-execute-this)
foo"bar"''

Remove all subviews?

If you're using Swift, it's as simple as:

subviews.map { $0.removeFromSuperview }

It's similar in philosophy to the makeObjectsPerformSelector approach, however with a little more type safety.

Angular2 Material Dialog css, dialog size

For the most recent version of Angular as of this post, it seems you must first create a MatDialogConfig object and pass it as a second parameter to dialog.open() because Typescript expects the second parameter to be of type MatDialogConfig.

const matDialogConfig = new MatDialogConfig();
matDialogConfig.width = "600px";
matDialogConfig.height = "480px";
this.dialog.open(MyDialogComponent, matDialogConfig);

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

Checking for NULL pointer in C/C++

This is one of the fundamentals of both languages that pointers evaluate to a type and value that can be used as a control expression, bool in C++ and int in C. Just use it.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

Error: Cannot pull with rebase: You have unstaged changes

If you want to keep your working changes while performing a rebase, you can use --autostash. From the documentation:

Before starting rebase, stash local modifications away (see git-stash[1]) if needed, and apply the stash when done.

For example:

git pull --rebase --autostash

How do I read configuration settings from Symfony2 config.yml?

Like it was saying previously - you can access any parameters by using injection container and use its parameter property.

"Symfony - Working with Container Service Definitions" is a good article about it.

jQuery iframe load() event?

If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.

In the main document:

function iframeLoaded() {
    alert("Iframe loaded!");
}

In the iframe document:

window.onload = function() {
    parent.iframeLoaded();
}

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

How do I write a bash script to restart a process if it dies?

if ! test -f $PIDFILE || ! psgrep `cat $PIDFILE`; then
    restart_process
    # Write PIDFILE
    echo $! >$PIDFILE
fi

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function(){
       $("#dropdown").slideToggle();
});

JsFiddle

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

Random number generator only generating one random number

My answer from here:

Just reiterating the right solution:

namespace mySpace
{
    public static class Util
    {
        private static rnd = new Random();
        public static int GetRandom()
        {
            return rnd.Next();
        }
    }
}

So you can call:

var i = Util.GetRandom();

all throughout.

If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.

public static class Util
{
    public static int GetRandom()
    {
        return Guid.NewGuid().GetHashCode();
    }
}

It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.

But not:

new Random(Guid.NewGuid().GetHashCode()).Next();

The unnecessary object creation is going to make it slower especially under a loop.

And never:

new Random().Next();

Not only it's slower (inside a loop), its randomness is... well not really good according to me..

Passing data to a jQuery UI Dialog

Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:

        buttons: {
            "Ja": function() {
                $.post(a.href);
                $(a). // code to remove the table row
                $("#dialog").dialog("close");
            },
            "Nej": function() { $(this).dialog("close"); }
        },

The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.

How to make a progress bar

Though one can build a progress bar using setInterval and animating its width

For best performance while animating a progress bar one has to take into account compositor only properties and manage layer count.

Here is an example:

_x000D_
_x000D_
function update(e){_x000D_
  var left = e.currentTarget.offsetLeft;_x000D_
  var width = e.currentTarget.offsetWidth_x000D_
  var position = Math.floor((e.pageX - left) / width * 100) + 1;_x000D_
  var bar = e.currentTarget.querySelector(".progress-bar__bar");_x000D_
  bar.style.transform = 'translateX(' + position + '%)';_x000D_
}
_x000D_
body {_x000D_
  padding: 2em;_x000D_
}_x000D_
_x000D_
.progress-bar {_x000D_
  cursor: pointer;_x000D_
  margin-bottom: 10px;_x000D_
  user-select: none;_x000D_
}_x000D_
_x000D_
.progress-bar {_x000D_
  background-color: #669900;_x000D_
  border-radius: 4px;_x000D_
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);_x000D_
  height: 20px;_x000D_
  margin: 10px;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  transform: translateZ(0);_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.progress-bar__bar {_x000D_
  background-color: #ececec;_x000D_
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  transition: all 500ms ease-out;_x000D_
}
_x000D_
Click on progress bar to update value_x000D_
_x000D_
<div class="progress-bar" onclick="update(event)">_x000D_
  <div class="progress-bar__bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Flask-SQLAlchemy how to delete all rows in a single table

Try delete:

models.User.query.delete()

From the docs: Returns the number of rows deleted, excluding any cascades.

Calling one Activity from another in Android

The following code demonstrates how you can start another activity via an intent.

Start the activity with an intent connected to the specified class

Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);

Activities which are started by other Android activities are called sub-activities. This wording makes it easier to describe which activity is meant.

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

DBNull if statement

This should work.

if (rsData["usr.ursrdaystime"] != System.DBNull.Value))
{
    strLevel = rsData["usr.ursrdaystime"].ToString();
}

also need to add using statement, like bellow:

using (var objConn = new SqlConnection(strConnection))
     {
        objConn.Open();
        using (var objCmd = new SqlCommand(strSQL, objConn))
        {
           using (var rsData = objCmd.ExecuteReader())
           {
              while (rsData.Read())
              {
                 if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
                 {
                    strLevel = rsData["usr.ursrdaystime"].ToString();
                 }
              }
           }
        }
     }

this'll automaticly dispose (close) resources outside of block { .. }.

Svn switch from trunk to branch

You don't need to --relocate since the branch is within the same repository URL. Just do:

svn switch https://www.example.com/svn/branches/v1p2p3

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

How to re import an updated package while in Python Interpreter?

dragonfly's answer worked for me (python 3.4.3).

import sys
del sys.modules['module_name']

Here is a lower level solution :

exec(open("MyClass.py").read(), globals())

Get the position of a div/span tag

This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

However, if you just wanted the x,y position of the element relative to its container, then all you need is:

var x = el.offsetLeft, y = el.offsetTop;

To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.

var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;

Marker in leaflet, click event

Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.

It seems that when we do:

marker.on('click', function(e) {...

The e points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this object which strangely, requires us to use this.options to get to the options object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid then within the function above, we can get the value by invoking: this.options.objid

jquery find element by specific class when element has multiple classes

You can select elements with multiple classes like so:

$("element.firstClass.anotherClass");

Simply chain the next class onto the first one, without a space (spaces mean "children of").

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

How can I pad a value with leading zeros?

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

_x000D_
_x000D_
console.log(("00000000" + 5).substr(-6));
_x000D_
_x000D_
_x000D_

Generalizing we'll get:

_x000D_
_x000D_
function pad(num, len) { return ("00000000" + num).substr(-len) };_x000D_
_x000D_
console.log(pad(5, 6));_x000D_
console.log(pad(45, 6));_x000D_
console.log(pad(345, 6));_x000D_
console.log(pad(2345, 6));_x000D_
console.log(pad(12345, 6));
_x000D_
_x000D_
_x000D_

How to Write text file Java

Using java 8 LocalDateTime and java 7 try-with statement:

public class WriteFile {

    public static void main(String[] args) {

        String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
        File logFile = new File(timeLog);

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile))) 
        {
            System.out.println("File was written to: "  + logFile.getCanonicalPath());
            bw.write("Hello world!");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

How to escape the % (percent) sign in C's printf?

You can simply use % twice, that is "%%"

Example:

printf("You gave me 12.3 %% of profit");

What is the list of supported languages/locales on Android?

Just FYI, if you are unable to set any locale, the problem might be below attribute in your app level gradle file:

resConfigs "en", "hi" //to specify allowed locales for your app

So, if you want to support any locale other than English and Hindi, specify your locale here or just remove above line. By default your app will support all the locales.

Thanks :)

Django, creating a custom 500/404 error page

As one single line (for 404 generic page):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

node.js execute system command synchronously

I actually had a situation where I needed to run multiple commands one after another from a package.json preinstall script in a way that would work on both Windows and Linux/OSX, so I couldn't rely on a non-core module.

So this is what I came up with:

#cmds.coffee
childproc = require 'child_process'

exports.exec = (cmds) ->
  next = ->
    if cmds.length > 0
      cmd = cmds.shift()
      console.log "Running command: #{cmd}"
      childproc.exec cmd, (err, stdout, stderr) ->
        if err? then console.log err
        if stdout? then console.log stdout
        if stderr? then console.log stderr
        next()
    else
      console.log "Done executing commands."

  console.log "Running the follows commands:"
  console.log cmds
  next()

You can use it like this:

require('./cmds').exec ['grunt coffee', 'nodeunit test/tls-config.js']

EDIT: as pointed out, this doesn't actually return the output or allow you to use the result of the commands in a Node program. One other idea for that is to use LiveScript backcalls. http://livescript.net/

How to restart ADB manually from Android Studio

When I had this problem, I wrote adb kill-server and adb restart-server in terminal, but the problem appeared again the next day. Then I updated GPU debugging tools in the Android SDK manager and restarted the computer, which worked for me.

Bootstrap Modal Backdrop Remaining

Be carful adding {data-dismiss="modal"} as mentioned in the second answer. When working with Angulars ng-commit using a controller-scope-defined function the data-dismiss will be executed first and controller-scope-defined function is never called. I spend an hour to figure this out.

How to disable button in React.js

very simple solution for this is by using useRef hook

const buttonRef = useRef();

const disableButton = () =>{
  buttonRef.current.disabled = true; // this disables the button
 }

<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
    Add
</button>

Similarly you can enable the button by using buttonRef.current.disabled = false

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How do I hide javascript code in a webpage?

I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).

If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

Built in Python hash() function

Polynomial hash for strings. 1000000009 and 239 are arbitrary prime numbers. Unlikely to have collisions by accident. Modular arithmetic is not very fast, but for preventing collisions this is more reliable than taking it modulo a power of 2. Of course, it is easy to find a collision on purpose.

mod=1000000009
def hash(s):
    result=0
    for c in s:
        result = (result * 239 + ord(c)) % mod
    return result % mod

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.

String [] separado = line.split("\\*");

Postgres user does not exist?

psql: Logs me in with my default username

psql -U postgres: Logs me in as the postgres user

Sudo doesn't seem to be required for me.

I use Postgres.app for my OS X postgres database. It removed the headache of making sure the installation was working and the database server was launched properly. Check it out here: http://postgresapp.com

Edit: Credit to @Erwin Brandstetter for correcting my use of the arguments.

How can I nullify css property?

An initial keyword is being added in CSS3 to allow authors to explicitly specify this initial value.

How to uninstall with msiexec using product id guid without .msi file present

msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q 

Read a XML (from a string) and get some fields - Problems reading XML

I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

        string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
        XElement xmlroot = XElement.Parse(textXml);
        string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

Show / hide div on click with CSS

Although a bit unstandard, a possible solution is to contain the content you want to show/hide inside the <a> so it can be reachable through CSS:

http://jsfiddle.net/Jdrdh/2/

_x000D_
_x000D_
a .hidden {_x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
a:visited .hidden {_x000D_
  visibility: visible;_x000D_
}
_x000D_
<div id="container">_x000D_
  <a href="#">_x000D_
        A_x000D_
        <div class="hidden">hidden content</div>_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

res.sendFile absolute path

Another way to do this by writing less code.

app.use(express.static('public'));

app.get('/', function(req, res) {
   res.sendFile('index.html');
});

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

How to print Two-Dimensional Array like table

For traversing through a 2D array, I think the following for loop can be used.

        for(int a[]: twoDm)
        {
            System.out.println(Arrays.toString(a));
        }
if you don't want the commas you can string replace
if you want this to be performant you should loop through a[] and then print it.

Maven2: Best practice for Enterprise Project (EAR file)

This is a good example of the maven-ear-plugin part.

You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is

maven-archetype-j2ee-simple

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

Below are the commands for Ubuntu user to authorise devices once developer option is ON.

sudo ~/Android/Sdk/platform-tools/adb kill-server

sudo ~/Android/Sdk/platform-tools/adb start-server

On Device:

  • Developer option activated
  • USB debugging checked

Connect your device now and you must only accept request, on your phone.

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

Watch multiple $scope attributes

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Here function will get called when both age and name value get changed.

val() doesn't trigger change() in jQuery

You can very easily override the val function to trigger change by replacing it with a proxy to the original val function.

just add This code somewhere in your document (after loading jQuery)

(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0)
            $(this).change(); // OR with custom event $(this).trigger('value-changed');
        return result;
    };
})(jQuery);

A working example: here

(Note that this will always trigger change when val(new_val) is called even if the value didn't actually changed.)

If you want to trigger change ONLY when the value actually changed, use this one:

//This will trigger "change" event when "val(new_val)" called 
//with value different than the current one
(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var prev;
        if(arguments.length>0){
            prev = originalVal.apply(this,[]);
        }
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0 && prev!=originalVal.apply(this,[]))
            $(this).change();  // OR with custom event $(this).trigger('value-changed')
        return result;
    };
})(jQuery);

Live example for that: http://jsfiddle.net/5fSmx/1/

How to get the URL of the current page in C#

if you just want the part between http:// and the first slash

string url = Request.Url.Host;

would return stackoverflow.com if called from this page

Here's the complete breakdown

Best approach to converting Boolean object to string in java

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

Disable html5 video autoplay

just put the autoplay="false" on source tag.. :)

Is module __file__ attribute absolute or relative?

With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path the result is absolute, but if it is located in a relative path in sys.path the result is relative.

Now the site.py startup file takes care of delivering only absolute path in sys.path, except the initial '', so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path), you will get always an absolute path, but when the module is accessed through the current directory.

Now if you trick sys.path in a funny way you can get anything.

As example if you have a sample module foo.py in /tmp/ with the code:

import sys
print(sys.path)
print (__file__)

If you go in /tmp you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py

When in in /home/user, if you add /tmp your PYTHONPATH you get:

>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py

Even if you add ../../tmp, it will be normalized and the result is the same.

But if instead of using PYTHONPATH you use directly some funny path you get a result as funny as the cause.

>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py

Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:

we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,

So your path is used as it is.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

After changing https to http within gitbox app, it worked for me.

MongoDB or CouchDB - fit for production?

I have been using CouchDB in production for almost 2 years now. There's no migration work as the project started of directly with CouchDB implementation. It serves as a database that stores the data of a single electronic product from beginning till packaging.

Since we are selling sensor with a demand on high accuracy, we do a lot of test at different stage and all these will be stored into one document on CouchDB.

There's some learning curve that I learnt from my experience, which is to make full use of the views (or also known as permanent views). Views should be "small filter" of a fraction of the Database that will be called often.

My CouchDB databse is not as crazy as other gigantic company. But so far, I'm still doing fine. Currently I'm having 24000 documents at 700MB.

Feature from CouchDB that I like is 'replication', 'store revisions of a document'.

I'd read a lot of good reviews on MongoDB and I will want to try it if there's a chance.

Writing sqlplus output to a file

You may use the SPOOL command to write the information to a file.

Before executing any command type the following:

SPOOL <output file path>

All commands output following will be written to the output file.

To stop command output writing type

SPOOL OFF

What are the options for (keyup) in Angular2?

If your keyup event is outside the CTRL, SHIFT, ENTER and ESC bracket, just use @Md Ayub Ali Sarker's guide. The only keyup pseudo-event mentioned here in angular docs https://angular.io/docs/ts/latest/guide/user-input.html is ENTER key. There are no keyup pseudo-events for number keys and alphabets yet.

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Flatten List in LINQ

Like this?

var iList = Method().SelectMany(n => n);

To the power of in C?

Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header

#include <math.h>

then you can use pow().

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

Okay, this worked for me. Open the old solution/project as an administrator in Visual Studio 2010 and open the new or copied solution/project. As an administrator, remove the copied pfk file in the new Visual Studio 2010 solution/project and go to project properties and unselect it.

With both projects open, copy paste to the new one. Go to project properties and select Build. I opened and closed Visual Studio and also after removing from the new project built it before copying it from the old project and selecting it. I received the error at the start of this post first up when I copied the project and tried to build it.

Uploading multiple files using formData()

To upload multiple files with angular form data, make sure you have this in your component.html

Upload Documents

                <div class="row">


                  <div class="col-md-4">
                     &nbsp; <small class="text-center">  Driver  Photo</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'profilepic')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                     &nbsp; <small> Driver ID</small>
                    <div class="form-group">
                      <input  (change)="onFileSelected($event, 'id')"  type="file" class="form-control" >
                    </div>
                  </div>

                  <div class="col-md-4">
                    &nbsp; <small>Driving Permit</small>
                    <div class="form-group">
                      <input type="file"  (change)="onFileSelected($event, 'drivingpermit')" class="form-control"  />
                    </div>
                  </div>
                </div>



                <div class="row">
                    <div class="col-md-6">
                       &nbsp; <small>Car Registration</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                            <input class="form-control" 
                (change)="onFileSelected($event, 'carregistration')" type="file"> <br>
                        </div>
                      </div>
                    </div>

                    <div class="col-md-6">
                        <small id="li"> Car Insurance</small>
                      <div class="form-group">
                        <div class="input-group mb-4">
                          <input class="form-control" (change)="onFileSelected($event, 

                         'insurancedocs')"   type="file">
                        </div>
                      </div>
                    </div>

                  </div>


                <div style="align-items:c" class="modal-footer">
                    <button type="button" class="btn btn-secondary" data- 
                  dismiss="modal">Close</button>
                    <button class="btn btn-primary"  (click)="uploadFiles()">Upload 
                  Files</button>
                  </div>
              </form>

In your componenet.ts file declare array selected files like this

selectedFiles = [];

// array of selected files

onFileSelected(event, type) {
    this.selectedFiles.push({ type, file: event.target.files[0] });
  }

//in the upload files method, append your form data like this

uploadFiles() {
    const formData = new FormData(); 

    this.selectedFiles.forEach(file => {
      formData.append(file.type, file.file, file.file.name); 
    });
    formData.append("driverid", this.driverid);

    this.driverService.uploadDriverDetails(formData).subscribe(
      res => {
        console.log(res); 

      },
      error => console.log(error.message)
    );
  }

NOTE: I hope this solution works for you friends

CSS to line break before/after a particular `inline-block` item

I accomplished this by creating a ::before selector for the first inline element in the row, and making that selector a block with a top or bottom margin to separate rows a little bit.

.1st_item::before
{
  content:"";
  display:block;
  margin-top: 5px;
}

.1st_item
{
  color:orange;
  font-weight: bold;
  margin-right: 1em;
}

.2nd_item
{
  color: blue;
}

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Google Maps API v3 adding an InfoWindow to each marker

I had a similar problem. If all you want is for some info to be displayed when you hover over a marker, instead of clicking it, then I found that a good alternative to using an info Window was to set a title on the marker. That way whenever you hover the mouse over the marker the title displays like an ALT tag. 'marker.setTitle('Marker '+id);' It removes the need to create a listener for the marker too

JavaScript: clone a function

function cloneFunction(Func, ...args) {
  function newThat(...args2) {
    return new Func(...args2);
  }
  function clone() {
    if (this instanceof clone) {
      return newThat(...args);
    }
    return Func.apply(this, args);
  }
  for (const key in Func) {
    if (Func.hasOwnProperty(key)) {
      clone[key] = Func[key];
    }
  }
  Object.defineProperty(clone, 'name', { value: Func.name, configurable: true })
  return clone
};

function myFunction() {
  console.log('Called Function')
}

myFunction.value = 'something';

const newFunction = cloneFunction(myFunction);

newFunction.another = 'somethingelse';

console.log('Equal? ', newFunction === myFunction);
console.log('Names: ', myFunction.name, newFunction.name);
console.log(myFunction);
console.log(newFunction);
console.log('InstanceOf? ', newFunction instanceof myFunction);

myFunction();
newFunction();

While I would never recommend using this, I thought it would be an interesting little challenge to come up with a more precise clone by taking some of the practices that seemed to be the best and fixing it up a bit. Heres the result of the logs:

Equal?  false
Names:  myFunction myFunction
{ [Function: myFunction] value: 'something' }
{ [Function: myFunction] value: 'something', another: 'somethingelse' }
InstanceOf?  false
Called Function
Called Function

What does "Changes not staged for commit" mean

You have to use git add to stage them, or they won't commit. Take it that it informs git which are the changes you want to commit.

git add -u :/ adds all modified file changes to the stage git add * :/ adds modified and any new files (that's not gitignore'ed) to the stage

Jenkins: Is there any way to cleanup Jenkins workspace?

You can run the below script in the Manage Jenkins ? Scripts Console for deleting the workspaces of all the jobs at one shot. We did this to clean up space on the file system.

import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding()) {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}

Removing border from table cells

<style type="text/css">
table {
  border:1px solid black;
}
</style>

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

How can I set response header on express.js assets

There is at least one middleware on npm for handling CORS in Express: cors.

Change <br> height using CSS

The line height of the br tag can be different from the line height of the rest of the text inside a paragraph text by setting font-size for br tag.

Example: br { font-size: 200%; }

Python3 project remove __pycache__ folders and .pyc files

From the project directory type the following:

Deleting all .pyc files

find . -path "*/*.pyc" -delete

Deleting all .pyo files:

find . -path "*/*.pyo" -delete

Finally, to delete all '__pycache__', type:

find . -path "*/__pycache__" -type d -exec rm -r {} ';'

If you encounter permission denied error, add sudo at the begining of all the above command.

How to hide 'Back' button on navigation bar on iPhone?

Objective-C:
self.navigationItem.hidesBackButton = YES;

Swift:
navigationItem.hidesBackButton = true

Python: Continuing to next iteration in outer loop

I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

This is really not that different from breaking the code out into a function, but I thought that using the "any" operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.

Why am I getting error for apple-touch-icon-precomposed.png

If you don't care about the icon looking pretty on all sort of Apple devices, just add

get '/:apple_touch_icon' => redirect('/icon.png'), constraints: { apple_touch_icon: /apple-touch-icon(-\d+x\d+)?(-precomposed)?\.png/ }

to your config/routes.rb file and some icon.png to your public directory. Redirecting to 404.html instead of icon.png works too.

What is the difference between char * const and const char *?

Rule of thumb: read the definition from right to left!


const int *foo;

Means "foo points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; is allowed.

int *const foo;

Means "foo cannot change (const) and points (*) to an int".
To the programmer this means "I will not change the memory address that foo refers to".

  • *foo = 123; or foo[0] = 123; is allowed.
  • foo = &bar; would be invalid.

const int *const foo;

Means "foo cannot change (const) and points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to, nor will I change the address that foo refers to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; would be invalid.

casting Object array to Integer array error

Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);

Here the reason to hitting an ClassCastException is you can't treat an array of Integer as an array of Object. Integer[] is a subtype of Object[] but Object[] is not a Integer[].

And the following also will not give an ClassCastException.

Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;

Angularjs prevent form submission when input validation fails

Change the submit button to:

<button type="submit" ng-disabled="loginform.$invalid">Login</button>

Git Clone - Repository not found

On github you can have the main repository and subfolders. Make sure that the URL that you are using is that of the main repository and not that of a folder. The former will succeed and the latter will produce the repository not found error. If you have a doubt you are in a subfolder, navigate up the repository chain till you find a page which actually specified the https URL and use that.

SQL Joins Vs SQL Subqueries (Performance)?

You can use an Explain Plan to get an objective answer.

For your problem, an Exists filter would probably perform the fastest.

What is difference between sleep() method and yield() method of multi threading?

Both methods are used to prevent thread execution. But specifically, sleep(): purpose:if a thread don't want to perform any operation for particular amount of time then we should go for sleep().for e.x. slide show . yield(): purpose:if a thread wants to pause it's execution to give chance of execution to another waiting threads of same priority.thread which requires more execution time should call yield() in between execution.

Note:some platform may not provide proper support for yield() . because underlying system may not provide support for preemptive scheduling.moreover yield() is native method.

Allow user to select camera or gallery for image

I found this. Using:

galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

for one of the intents shows the user the option of selecting 'documents' in Android 4, which I found very confusing. Using this instead shows the 'gallery' option:

Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

Rename master branch for both local and remote Git repositories

git checkout -b new-branch-name
git push remote-name new-branch-name :old-branch-name

You may have to manually switch to new-branch-name before deleting old-branch-name

Vue.js: Conditional class style binding

Why not pass an object to v-bind:class to dynamically toggle the class:

<div v-bind:class="{ disabled: order.cancelled_at }"></div>

This is what is recommended by the Vue docs.

How to solve npm error "npm ERR! code ELIFECYCLE"

Cleaning Cache and Node_module are not enough. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

It works for me like this.

How to remove specific elements in a numpy array

Remove specific index(i removed 16 and 21 from matrix)

import numpy as np
mat = np.arange(12,26)
a = [4,9]
del_map = np.delete(mat, a)
del_map.reshape(3,4)

Output:

array([[12, 13, 14, 15],
      [17, 18, 19, 20],
      [22, 23, 24, 25]])

Chart.js v2 - hiding grid lines

I found a solution that works for hiding the grid lines in a Line chart.

Set the gridLines color to be the same as the div's background color.

var options = {
    scales: {
        xAxes: [{
            gridLines: {
                color: "rgba(0, 0, 0, 0)",
            }
        }],
        yAxes: [{
            gridLines: {
                color: "rgba(0, 0, 0, 0)",
            }   
        }]
    }
}

or use

var options = {
    scales: {
        xAxes: [{
            gridLines: {
                display:false
            }
        }],
        yAxes: [{
            gridLines: {
                display:false
            }   
        }]
    }
}

Use grep --exclude/--include syntax to not grep through certain files

Use the shell globbing syntax:

grep pattern -r --include=\*.{cpp,h} rootdir

The syntax for --exclude is identical.

Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as --include="*.{cpp,h}", would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like grep pattern -r --include=foo.cpp --include=bar.h rootdir, which would only search files named foo.cpp and bar.h, which is quite likely not what you wanted.

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

How to increment a datetime by one day?

This was a straightforward solution for me:

from datetime import timedelta, datetime

today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):

If Double.IsNaN(MyVariableName) Then
    MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If

If you try to use a variable that has a NaN value you will get the following error:

Value was either too large or too small for a Decimal.

Getting an Embedded YouTube Video to Auto Play and Loop

YouTubes HTML5 embed code:

<iframe width="560" height="315" src="http://www.youtube.com/embed/GRonxog5mbw?autoplay=1&loop=1&playlist=GRonxog5mbw" frameborder="0" allowfullscreen></iframe>?

You can read about it here: ... (EDIT Link died.) ... View original content on Internet Archive project.

http://web.archive.org/web/20121016180134/http://brianwong.com/blog/2012-youtube-embed-code-autoplay-on-and-all-other-parameters/

How to find MAC address of an Android device programmatically

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress(); 

Also, add below permission in your manifest file

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

How to filter files when using scp to copy dir recursively?

There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

rsync -av --exclude '*.svn' user@server:/my/dir .

(this line copy rsync from distant folder to current one)

Recent versions of rsync tunnel over an ssh connection automatically by default.

Help with packages in java - import does not work

Okay, just to clarify things that have already been posted.

You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.

From the folder containing com, run:

$ javac com\company\example\MyClass.java

Then:

$ java com.company.example.MyClass
Hello from MyClass!

These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).

A short example

I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:

package testpackage;

import testpackage2.MyClass;

public class TestPackageClass {
    public static void main(String[] args) {
        System.out.println("Hello from testpackage.TestPackageClass!");
        System.out.println("Now accessing " + MyClass.NAME);
    }
}

Inside testpackage2, I created MyClass.java containing the following code:

package testpackage2;
public class MyClass {
    public static String NAME = "testpackage2.MyClass";
}

From the directory containing the two new folders, I ran:

C:\examples>javac testpackage\*.java

C:\examples>javac testpackage2\*.java

Then:

C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass

Does that make things any clearer?

Finding an item in a List<> using C#

What is wrong with List.Find ??

I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

How to convert a Drawable to a Bitmap?

if you are using kotlin the use below code. it'll work

// for using image path

val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap

text box input height

If you want to increase the height of the input field, you can specify line-height css property for the input field.

input {
    line-height: 2em; // 2em is (2 * default line height)
}

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

How to change the order of DataFrame columns?

I think this is a slightly neater solution:

df.insert(0, 'mean', df.pop("mean"))

This solution is somewhat similar to @JoeHeffer 's solution but this is one liner.

Here we remove the column "mean" from the dataframe and attach it to index 0 with the same column name.

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
  MessageBox.show(i);
--Here i want to get the index or current row from the list                   

}
 ++i;
}

JavaScript get element by name

Method document.getElementsByName returns an array of elements. You should select first, for example.

document.getElementsByName('acc')[0].value

Relation between CommonJS, AMD and RequireJS?

Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

Eclipse not recognizing JVM 1.8

For some weird reason "Java SE Development Kit 8u151" gives this trouble. Just install, "Java SE Development Kit 8u152" from the following link-

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

It should work then.

Regular expression for extracting tag attributes

If you want to be general, you have to look at the precise specification of the a tag, like here. But even with that, if you do your perfect regexp, what if you have malformed html?

I would suggest to go for a library to parse html, depending on the language you work with: e.g. like python's Beautiful Soup.

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

For Docker users - When trying to connect local sql using mysql -u root -h 127.0.0.1 -p and your database is running on Docker container, make sure the mysql service is up and running (verify using docker ps and also check that you are in the right port as well) , if the container is down you'll get connection error.

Best practice is to set the ip's in /etc/hosts on your machine:

127.0.0.1 db.local

and running it by mysql -u root -h db.local -p

Get MAC address using shell script

None of the above worked for me because my devices are in a balance-rr bond. Querying either would say the same MAC address with ip l l, ifconfig, or /sys/class/net/${device}/address, so one of them is correct, and one is unknown.

But this works if you haven't renamed the device (any tips on what I missed?):

udevadm info -q all --path "/sys/class/net/${device}"

And this works even if you rename it (eg. ip l set name x0 dev p4p1):

cat /proc/net/bonding/bond0

or my ugly script that makes it more parsable (untested driver/os/whatever compatibility):

awk -F ': ' '
         $0 == "" && interface != "" {
            printf "%s %s %s\n", interface, mac, status;
            interface="";
            mac=""
         }; 
         $1 == "Slave Interface" {
            interface=$2
         }; 
         $1 == "Permanent HW addr" {
            mac=$2
         };
         $1 == "MII Status" {
            status=$2
         };
         END {
            printf "%s %s %s\n", interface, mac, status
         }' /proc/net/bonding/bond0

How do I find the maximum of 2 numbers?

You could also achieve the same result by using a Conditional Expression:

maxnum = run if run > value else value

a bit more flexible than max but admittedly longer to type.

Cannot set property 'innerHTML' of null

I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.

If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.

I hope this was useful to you.

How to use the priority queue STL for objects?

A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.

The C++ standard library defines a class template priority_queue, with the following operations:

push: Insert an element into the prioity queue.

top: Return (without removing it) a highest priority element from the priority queue.

pop: Remove a highest priority element from the priority queue.

size: Return the number of elements in the priority queue.

empty: Return true or false according to whether the priority queue is empty or not.

The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

The following is an example of priority queue usage:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
{
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("fox");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << pq.top() << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string
    }

    return 0;
}

The output of this program is:

the quick
the lazy dog
jumped over
fox

Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.

Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:

struct Time {
    int h; 
    int m; 
    int s;
};

class CompareTime {
    public:
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
}

A priority queue to store times according the the above comparison criterion would be defined as follows:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59
};

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2)
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
};

int main()
{
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)
       pq.push(t[i]);

    while (! pq.empty()) {
       Time t2 = pq.top();
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;
       pq.pop();
    }

    return 0;
}

The program prints the times from latest to earliest:

5  16  13
5  14  20
3   2  40
3   2  26

If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
    {
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;
    }
};

Remove all html tags from php string

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

Or if you have a content coming from the database;

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

Cannot call getSupportFragmentManager() from activity

Your activity doesn't extend FragmentActivity from the support library, therefore the method is not present in the superclass

If you are targeting api 11 or above, you could use Activity.getFragmentManager instead.

How to embed a SWF file in an HTML page?

This one will work, I am sure!

<embed src="application.swf" quality="high" pluginspage="http://www.macromedia.com/go/getfashplayer" type="application/x-shockwave-flash" width="690" height="430">

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

in HQL query, Don't write the Table name, write your Entity class name in your query like

String s = "from Entity_class name";
query qry = session.createUqery(s);

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

How do I list / export private keys from a keystore?

Here is a shorter version of the above code, in Groovy. Also has built-in base64 encoding:

import java.security.Key
import java.security.KeyStore

if (args.length < 3)
        throw new IllegalArgumentException('Expected args: <Keystore file> <Keystore format> <Keystore password> <alias> <key password>')

def keystoreName = args[0]
def keystoreFormat = args[1]
def keystorePassword = args[2]
def alias = args[3]
def keyPassword = args[4]

def keystore = KeyStore.getInstance(keystoreFormat)
keystore.load(new FileInputStream(keystoreName), keystorePassword.toCharArray())
def key = keystore.getKey(alias, keyPassword.toCharArray())

println "-----BEGIN PRIVATE KEY-----"
println key.getEncoded().encodeBase64()
println "-----END PRIVATE KEY-----"

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

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

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

How to do relative imports in Python?

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

apache redirect from non www to www

Redirect domain.tld to www.

The following lines can be added either in Apache directives or in .htaccess file:

RewriteEngine on    
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  • Other sudomains are still working.
  • No need to adjust the lines. just copy/paste them at the right place.

Don't forget to apply the apache changes if you modify the vhost.

(based on the default Drupal7 .htaccess but should work in many cases)

How to call a parent method from child class in javascript?

Here's a nice way for child objects to have access to parent properties and methods using JavaScript's prototype chain, and it's compatible with Internet Explorer. JavaScript searches the prototype chain for methods and we want the child’s prototype chain to looks like this:

Child instance -> Child’s prototype (with Child methods) -> Parent’s prototype (with Parent methods) -> Object prototype -> null

The child methods can also call shadowed parent methods, as shown at the three asterisks *** below.

Here’s how:

_x000D_
_x000D_
//Parent constructor_x000D_
function ParentConstructor(firstName){_x000D_
    //add parent properties:_x000D_
    this.parentProperty = firstName;_x000D_
}_x000D_
_x000D_
//add 2 Parent methods:_x000D_
ParentConstructor.prototype.parentMethod = function(argument){_x000D_
    console.log(_x000D_
            "Parent says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ParentConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Parent! argument=" + argument);_x000D_
};_x000D_
_x000D_
//Child constructor    _x000D_
function ChildConstructor(firstName, lastName){_x000D_
    //first add parent's properties_x000D_
    ParentConstructor.call(this, firstName);_x000D_
_x000D_
    //now add child's properties:_x000D_
    this.childProperty = lastName;_x000D_
}_x000D_
_x000D_
//insert Parent's methods into Child's prototype chain_x000D_
var rCopyParentProto = Object.create(ParentConstructor.prototype);_x000D_
rCopyParentProto.constructor = ChildConstructor;_x000D_
ChildConstructor.prototype = rCopyParentProto;_x000D_
_x000D_
//add 2 Child methods:_x000D_
ChildConstructor.prototype.childMethod = function(argument){_x000D_
    console.log(_x000D_
            "Child says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ChildConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Child! argument=" + argument);_x000D_
_x000D_
    // *** call Parent's version of common method_x000D_
    ParentConstructor.prototype.commonMethod(argument);_x000D_
};_x000D_
_x000D_
//create an instance of Child_x000D_
var child_1 = new ChildConstructor('Albert', 'Einstein');_x000D_
_x000D_
//call Child method_x000D_
child_1.childMethod('do child method');_x000D_
_x000D_
//call Parent method_x000D_
child_1.parentMethod('do parent method');_x000D_
_x000D_
//call common method_x000D_
child_1.commonMethod('do common method');
_x000D_
_x000D_
_x000D_

How to disable Django's CSRF validation?

CSRF can be enforced at the view level, which can't be disabled globally.

In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.

https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps

Android notification is not showing

The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:

.setSmallIcon(R.drawable.icon)

Android Oreo (8.0) and above

Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.

private NotificationManager mNotificationManager;

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");

mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);

mNotificationManager =
    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
    String channelId = "Your_channel_id";
    NotificationChannel channel = new NotificationChannel(
                                        channelId,
                                        "Channel human readable title",
                                        NotificationManager.IMPORTANCE_HIGH);
   mNotificationManager.createNotificationChannel(channel);
  mBuilder.setChannelId(channelId);
}

mNotificationManager.notify(0, mBuilder.build());

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In Python there is a method for doing this: driver.refresh(). It may not be the same in Java.

Alternatively, you could driver.get("http://foo.bar");, although I think the refresh method should work just fine.

How do I convert a Python 3 byte-string variable into a regular string?

UPDATED:

TO NOT HAVE ANY b and quotes at first and end

How to convert bytes as seen to strings, even in weird situations.

As your code may have unrecognizable characters to 'utf-8' encoding, it's better to use just str without any additional parameters:

some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]

print(text)
Output: \x02-\xdfI

if you add 'utf-8' parameter, to these specific bytes, you should receive error.

As PYTHON 3 standard says, text would be in utf-8 now with no concern.

How can I get a vertical scrollbar in my ListBox?

The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.

If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.

<ListBox 
    ItemsSource="{Binding}" 
    ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>

Setting this value to Auto will popup the scrollbar on an as needed basis.

How to get the excel file name / path in VBA

There is a universal way to get this:

Function FileName() As String
    FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function

How to copy static files to build directory with Webpack?

You can write bash in your package.json:

# package.json
{
  "name": ...,
  "version": ...,
  "scripts": {
    "build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
    ...
  }
}

Anaconda-Navigator - Ubuntu16.04

Use the following command on your terminal (Ctrl + Alt + T):-

$ conda activate
$ anaconda-navigator

No String-argument constructor/factory method to deserialize from String value ('')

Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)

or

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

depending on your Jackson version.

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

How do you run a SQL Server query from PowerShell?

To avoid SQL Injection with varchar parameters you could use

function sqlExecuteRead($connectionString, $sqlCommand, $pars) {

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $connection.Open()
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand, $connection)

    if ($pars -and $pars.Keys) {
        foreach($key in $pars.keys) {
            # avoid injection in varchar parameters
            $par = $command.Parameters.Add("@$key", [system.data.SqlDbType]::VarChar, 512);
            $par.Value = $pars[$key];
        }
    }

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataset) | Out-Null
    $connection.Close()
    return $dataset.tables[0].rows

}

$connectionString = "connectionstringHere"
$sql = "select top 10 Message, TimeStamp, Level from dbo.log " +
    "where Message = @MSG and Level like @LEVEL"
$pars = @{
    MSG = 'this is a test from powershell'
    LEVEL = 'aaa%'
};
sqlExecuteRead $connectionString $sql $pars

Symfony2 Setting a default choice field selection

You can use "preferred_choices" and "push" the name you want to select to the top of the list. Then it will be selected by default.

'preferred_choices' => array(1), //1 is item number

entity Field Type

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How to update the constant height constraint of a UIView programmatically?

You can update your constraint with a smooth animation if you want, see the chunk of code below:

heightOrWidthConstraint.constant = 100
UIView.animate(withDuration: animateTime, animations:{
self.view.layoutIfNeeded()
})

When should we use mutex and when should we use semaphore

Binary semaphore and Mutex are different. From OS perspective, a binary semaphore and counting semaphore are implemented in the same way and a binary semaphore can have a value 0 or 1.

Mutex -> Can only be used for one and only purpose of mutual exclusion for a critical section of code.

Semaphore -> Can be used to solve variety of problems. A binary semaphore can be used for signalling and also solve mutual exclusion problem. When initialized to 0, it solves signalling problem and when initialized to 1, it solves mutual exclusion problem.

When the number of resources are more and needs to be synchronized, we can use counting semaphore.

In my blog, I have discussed these topics in detail.

https://designpatterns-oo-cplusplus.blogspot.com/2015/07/synchronization-primitives-mutex-and.html

CSS table td width - fixed, not flexible

Put a div inside td and give following style width:50px;overflow: hidden; to the div
Jsfiddle link

<td>
  <div style="width:50px;overflow: hidden;"> 
    <span>A long string more than 50px wide</span>
  </div>
</td>

How do I find out what version of WordPress is running?

From Dashboard At a Glance box

or at the bottom right corner of any admin page.

enter image description here

If that Glance box is hidden - click on screen options at top-right corner and check At a Glance option.

Php header location redirect not working

For me also it was not working. Then i try with javascript inside php like

echo "<script type='text/javascript'>  window.location='index.php'; </script>";

This will definitely working.

What is the most effective way for float and double comparison?

In terms of the scale of quantities:

If epsilon is the small fraction of the magnitude of quantity (i.e. relative value) in some certain physical sense and A and B types is comparable in the same sense, than I think, that the following is quite correct:

#include <limits>
#include <iomanip>
#include <iostream>

#include <cmath>
#include <cstdlib>
#include <cassert>

template< typename A, typename B >
inline
bool close_enough(A const & a, B const & b,
                  typename std::common_type< A, B >::type const & epsilon)
{
    using std::isless;
    assert(isless(0, epsilon)); // epsilon is a part of the whole quantity
    assert(isless(epsilon, 1));
    using std::abs;
    auto const delta = abs(a - b);
    auto const x = abs(a);
    auto const y = abs(b);
    // comparable generally and |a - b| < eps * (|a| + |b|) / 2
    return isless(epsilon * y, x) && isless(epsilon * x, y) && isless((delta + delta) / (x + y), epsilon);
}

int main()
{
    std::cout << std::boolalpha << close_enough(0.9, 1.0, 0.1) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0, 1.1, 0.1) << std::endl;
    std::cout << std::boolalpha << close_enough(1.1,    1.2,    0.01) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0001, 1.0002, 0.01) << std::endl;
    std::cout << std::boolalpha << close_enough(1.0, 0.01, 0.1) << std::endl;
    return EXIT_SUCCESS;
}

Difference between DTO, VO, POJO, JavaBeans?

JavaBeans

A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:

JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are:

  • The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
  • The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.

Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.

POJO

A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:

POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:

"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."

The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.

The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).

As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.

Value Object

A Value Object or VO is an object such as java.lang.Integer that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:

In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.

You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.

A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.

Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.

You can find some more good material on value objects on the wiki and by Dirk Riehle.

Data Transfer Object

Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).

In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.


So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

How do I increase modal width in Angular UI Bootstrap?

Use max-width on modal-dialog for angular 5

.mod-class .modal-dialog {
    max-width: 1000px;
}

and use windowClass as others recommended, TS eg:

this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
        (result) => {
            // this.closeResult = `Closed with: ${result}`;
         }, (reason) => {
            // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});

Also, I had to put the css code in global styles > styles.css.

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Invoke-WebRequest, POST with parameters

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams

The system cannot find the file specified. in Visual Studio

This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.

form serialize javascript (no framework)

A refactored version of @SimonSteinberger's code using less variables and taking advantage of the speed of forEach loops (which are a bit faster than fors)

function serialize(form) {
    var result = [];
    if (typeof form === 'object' && form.nodeName === 'FORM')
        Array.prototype.slice.call(form.elements).forEach(function(control) {
            if (
                control.name && 
                !control.disabled && 
                ['file', 'reset', 'submit', 'button'].indexOf(control.type) === -1
            )
                if (control.type === 'select-multiple')
                    Array.prototype.slice.call(control.options).forEach(function(option) {
                        if (option.selected) 
                            result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(option.value));
                    });
                else if (
                    ['checkbox', 'radio'].indexOf(control.type) === -1 || 
                    control.checked
                ) result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(control.value));
        });
        return result.join('&').replace(/%20/g, '+');
}

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How to program a delay in Swift 3

//Runs function after x seconds

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

//Use:-

runThisAfterDelay(seconds: x){
  //write your code here
}

Spring: @Component versus @Bean

Additional Points from above answers

Let’s say we got a module which is shared in multiple apps and it contains a few services. Not all are needed for each app.

If use @Component on those service classes and the component scan in the application,

we might end up detecting more beans than necessary

In this case, you either had to adjust the filtering of the component scan or provide the configuration that even the unused beans can run. Otherwise, the application context won’t start.

In this case, it is better to work with @Bean annotation and only instantiate those beans,

which are required individually in each app

So, essentially, use @Bean for adding third-party classes to the context. And @Component if it is just inside your single application.