Programs & Examples On #Siteminder

siteminder is an application sold by Computer Associates that allows web assets to require authentication before access is given.

Read lines from a file into a Bash array

The simplest way to read each line of a file into a bash array is this:

IFS=$'\n' read -d '' -r -a lines < /etc/passwd

Now just index in to the array lines to retrieve each line, e.g.

printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"

# all lines
echo "${lines[@]}"

Update row with data from another row in the same table

Try this:

UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
                        FROM data_table
                       WHERE VALUE IS NOT NULL AND VALUE != '') t1
   SET t.VALUE = t1.VALUE
 WHERE t.ID = t1.ID
   AND t.NAME = t1.NAME

How to find the path of Flutter SDK

All you need to do is to find a folder called "flutter" (lowecase), which is located inside a folder called "Flutter" (uppercase), select it, and browse it.

In my case it is located at:

C:\Users\Administrator\Flutter\flutter_windows_v1.12.13+hotfix.5-stable\flutter

enter image description here

Also make sure that your Flutter and Dart are of the latest version. If they are not, upgrade them and re-start the IDE.

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

$("#myImg").one("load",function(){
  //do something, like getting image width/height
}).each(function(){
  if(this.complete) $(this).trigger("load");
});

From Chris' comment: http://api.jquery.com/load-event/

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Create table (structure) from existing table

I use the following stored proc for copying a table's schema, including PK, indexes, partition status. It's not very swift, but seems to do the job. I I welcome any ideas how to speed it up:

    /*
        Clones a table's schema from an existing table (without data)
        if target table exists, it will be dropped first.
        The following schema elements are cloned:
            * Structure
            * Primary key
            * Indexes
            * Constraints
    DOES NOT copy:
        * Triggers
        * File groups

    ASSUMPTION: constraints are uniquely named with the table name, so that we dont end up with duplicate constraint names
*/
CREATE PROCEDURE [dbo].[spCloneTableStructure]

@SourceTable            nvarchar(255),
@DestinationTable       nvarchar(255),
@PartionField           nvarchar(255),
@SourceSchema           nvarchar(255) = 'dbo',  
@DestinationSchema      nvarchar(255) = 'dbo',    
@RecreateIfExists       bit = 1

AS
BEGIN

DECLARE @msg  nvarchar(200), @PartionScript nvarchar(255), @sql NVARCHAR(MAX)

    IF EXISTS(Select s.name As SchemaName, t.name As TableName
                        From sys.tables t
                        Inner Join sys.schemas s On t.schema_id = s.schema_id
                        Inner Join sys.partitions p on p.object_id = t.object_id
                        Where p.index_id In (0, 1) and t.name = @SourceTable
                        Group By s.name, t.name
                        Having Count(*) > 1)

        SET @PartionScript = ' ON [PS_PartitionByCompanyId]([' + @PartionField + '])'
    else
        SET @PartionScript = ''

SET NOCOUNT ON;
BEGIN TRY   
    SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 1, Drop table if exists. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
     RAISERROR( @msg,0,1) WITH NOWAIT
    --drop the table
    if EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @DestinationTable)
    BEGIN
        if @RecreateIfExists = 1
            BEGIN
                exec('DROP TABLE [' + @DestinationSchema + '].[' + @DestinationTable + ']')
            END
        ELSE
            RETURN
    END

    SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 2, Create table. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
    RAISERROR( @msg,0,1) WITH NOWAIT
    --create the table
    exec('SELECT TOP (0) * INTO [' + @DestinationTable + '] FROM [' + @SourceTable + ']')       

    --create primary key
    SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 3, Create primary key. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
    RAISERROR( @msg,0,1) WITH NOWAIT
    DECLARE @PKSchema nvarchar(255), @PKName nvarchar(255),@count   INT
    SELECT TOP 1 @PKSchema = CONSTRAINT_SCHEMA, @PKName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = @SourceSchema AND TABLE_NAME = @SourceTable AND CONSTRAINT_TYPE = 'PRIMARY KEY'
    IF NOT @PKSchema IS NULL AND NOT @PKName IS NULL
    BEGIN
        DECLARE @PKColumns nvarchar(MAX)
        SET @PKColumns = ''

        SELECT @PKColumns = @PKColumns + '[' + COLUMN_NAME + '],'
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
            where TABLE_NAME = @SourceTable and TABLE_SCHEMA = @SourceSchema AND CONSTRAINT_SCHEMA = @PKSchema AND CONSTRAINT_NAME= @PKName
            ORDER BY ORDINAL_POSITION

        SET @PKColumns = LEFT(@PKColumns, LEN(@PKColumns) - 1)

        exec('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD  CONSTRAINT [PK_' + @DestinationTable + '] PRIMARY KEY CLUSTERED (' + @PKColumns + ')' + @PartionScript);
    END

    --create other indexes
    SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 4, Create Indexes. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
    RAISERROR( @msg,0,1) WITH NOWAIT
    DECLARE @IndexId int, @IndexName nvarchar(255), @IsUnique bit, @IsUniqueConstraint bit, @FilterDefinition nvarchar(max), @type int

    set @count=0
    DECLARE indexcursor CURSOR FOR
    SELECT index_id, name, is_unique, is_unique_constraint, filter_definition, type FROM sys.indexes WHERE is_primary_key = 0 and object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']')
    OPEN indexcursor;
    FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition, @type
    WHILE @@FETCH_STATUS = 0
       BEGIN
            set @count =@count +1
            DECLARE @Unique nvarchar(255)
            SET @Unique = CASE WHEN @IsUnique = 1 THEN ' UNIQUE ' ELSE '' END

            DECLARE @KeyColumns nvarchar(max), @IncludedColumns nvarchar(max)
            SET @KeyColumns = ''
            SET @IncludedColumns = ''

            select @KeyColumns = @KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' from sys.index_columns ic
            inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
            where index_id = @IndexId and ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') and key_ordinal > 0
            order by index_column_id

            select @IncludedColumns = @IncludedColumns + '[' + c.name + '],' from sys.index_columns ic
            inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
            where index_id = @IndexId and ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') and key_ordinal = 0
            order by index_column_id

            IF LEN(@KeyColumns) > 0
                SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1)

            IF LEN(@IncludedColumns) > 0
            BEGIN
                SET @IncludedColumns = ' INCLUDE (' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + ')'
            END

            IF @FilterDefinition IS NULL
                SET @FilterDefinition = ''
            ELSE
                SET @FilterDefinition = 'WHERE ' + @FilterDefinition + ' '

            SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 4.' + CONVERT(NVARCHAR(5),@count) + ', Create Index ' + @IndexName + '. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
            RAISERROR( @msg,0,1) WITH NOWAIT

            if @type = 2
                SET @sql = 'CREATE ' + @Unique + ' NONCLUSTERED INDEX [' + @IndexName + '] ON [' + @DestinationSchema + '].[' + @DestinationTable + '] (' + @KeyColumns + ')' + @IncludedColumns + @FilterDefinition  + @PartionScript
            ELSE
                BEGIN
                    SET @sql = 'CREATE ' + @Unique + ' CLUSTERED INDEX [' + @IndexName + '] ON [' + @DestinationSchema + '].[' + @DestinationTable + '] (' + @KeyColumns + ')' + @IncludedColumns + @FilterDefinition + @PartionScript
                END
            EXEC (@sql)
            FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition, @type
       END
    CLOSE indexcursor
    DEALLOCATE indexcursor

    --create constraints
    SET @msg ='  CloneTable  ' + @DestinationTable + ' - Step 5, Create constraints. Timestamp: '  + CONVERT(NVARCHAR(50),GETDATE(),108)
    RAISERROR( @msg,0,1) WITH NOWAIT
    DECLARE @ConstraintName nvarchar(max), @CheckClause nvarchar(max), @ColumnName NVARCHAR(255)
    DECLARE const_cursor CURSOR FOR
        SELECT
            REPLACE(dc.name, @SourceTable, @DestinationTable),[definition], c.name
        FROM sys.default_constraints dc
            INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
        WHERE OBJECT_NAME(parent_object_id) =@SourceTable               
    OPEN const_cursor
    FETCH NEXT FROM const_cursor INTO @ConstraintName, @CheckClause, @ColumnName
    WHILE @@FETCH_STATUS = 0
       BEGIN
            exec('ALTER TABLE [' + @DestinationTable + '] ADD CONSTRAINT [' + @ConstraintName + '] DEFAULT ' + @CheckClause + ' FOR ' + @ColumnName)
            FETCH NEXT FROM const_cursor INTO @ConstraintName, @CheckClause, @ColumnName
       END;
    CLOSE const_cursor
    DEALLOCATE const_cursor                 


END TRY
    BEGIN CATCH
        IF (SELECT CURSOR_STATUS('global','indexcursor')) >= -1
        BEGIN
         DEALLOCATE indexcursor
        END

        IF (SELECT CURSOR_STATUS('global','const_cursor')) >= -1
        BEGIN
         DEALLOCATE const_cursor
        END


        PRINT 'Error Message: ' + ERROR_MESSAGE(); 
    END CATCH

END

GO

How to loop an object in React?

you could also just have a return div like the one below and use the built in template literals of Javascript :

const tifs = {1: 'Joe', 2: 'Jane'};

return(

        <div>
            {Object.keys(tifOptions).map((key)=>(
                <p>{paragraphs[`${key}`]}</p>
            ))}
        </div>
    )

How to create a drop shadow only on one side of an element?

You could also just do a gradient on the bottom - this was helpful for me because the shadow I wanted was on an element that was already semi-transparent, so I didn't have to worry about any clipping:

&:after {
      content:"";
      width:100%;
      height: 8px;
      position: absolute;
      bottom: -8px;
      left: 0;
      background: linear-gradient(to bottom, rgba(0,0,0,0.65) 0%,rgba(0,0,0,0) 100%);
    }

Just make the "bottom" and "height" properties match and set your rgba values to whatever you want them to be at the top / bottom of the shadow

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I use chrome's build in developer console tools to debug javascript so the answer marked solution works great for me.
This is the weird error message i was getting from VS Community 2017 when trying to debug asp.net app:

"An error occurred that usually indicates a corrupt installation (code 0x80040154). If the problem persists, repair your Visual Studio installation via 'Add or Remove Programs' in Control Panel." and it's fixed now.

What datatype should be used for storing phone numbers in SQL Server 2005?

Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.

How to delete only the content of file in python

I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat contains:

"This is the original content"

Then you can simply write:

f = open('myfile.dat', 'w')
f.close()

This would erase all the content. Then you can write the new content to the file:

f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()

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

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

Xcode 9 error: "iPhone has denied the launch request"

The many answers to the original question are a testament to Apple's messiness when it comes to code signing and provisioning.

Short answer: I could launch successfully again on device by simply deploying to another device, then going back to the device where it first failed: same AppleId, same OS (iOS 12.4.1 on both devices, macOS Mojave 10.14.3 on macBook), same project, same Xcode 10.1. No need to uncheck "debug executable" in the project scheme.

Long answer: The problem is hard to catch basically because the error is non-descriptive. Judging by the answers posted, it looks like there might be different causes, probably related to some configuration for the AppleId being used for the signing.

One way to narrow down the search is to use Apple Configurator (as hinted by @notytony here) or simply in the console under Window -> Devices and simulators -> Open Console, then choose the device (previously attached via USB cable). Like so I could catch the error message:

does not pass CT evaluation; Unrecoverable CT signature issue

which pointed me to this answer, which suggests to go over several certificates (most notably "Apple Worldwide Developer Relations Certification Authority") making sure the trust level is set to "Use System Defaults". Still I couldn't launch on device, but the previous message was no longer present in the logs. No other meaningful error was shown.

I was stuck here. Nothing listed here worked: rebooting device, revoking certificates and provisioning profiles and recreating new ones, clean build, restart Xcode, signing out and in again from AppleID,... the only workaround at this point (and only after fixing the trust issue from the certificates) was to uncheck the "debug executable" in the project scheme, which is not ideal.

I then tested on another device and it worked, even with "debug executable" enabled. After that, launching on the original device worked again as well. Something must have been reset on that AppleId account that it can successfully sign and provision apps again on the original device.

jQuery: Check if div with certain class name exists

It's quite simple...

if ($('.mydivclass').length > 0) {
  //do something
}

ls command: how can I get a recursive full-path listing, one line per file?

ls -lR is what you were looking for, or atleast I was. cheers

How to use "raise" keyword in Python

Besides raise Exception("message") and raise Python 3 introduced a new form, raise Exception("message") from e. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.

It's very similar to inner exceptions from C#.

More info: https://www.python.org/dev/peps/pep-3134/

Make a table fill the entire window

This works fine for me:

_x000D_
_x000D_
<style type="text/css">_x000D_
#table {_x000D_
 position: absolute;_x000D_
 top: 0;_x000D_
 bottom: 0;_x000D_
 left: 0;_x000D_
 right: 0;_x000D_
 height: 100%;_x000D_
 width: 100%;_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

For me, just changing Height and Width to 100% doesn’t do it for me, and neither do setting left, right, top and bottom to 0, but using them both together will do the trick.

Programmatically go back to previous ViewController in Swift

If Segue is Kind of 'Show' or 'Push' then You can invoke "popViewController(animated: Bool)" on Instance of UINavigationController. Or if segue is kind of "present" then call "dismiss(animated: Bool, completion: (() -> Void)?)" with instance of UIViewController

Java ArrayList how to add elements at the beginning

I had a similar problem, trying to add an element at the beginning of an existing array, shift the existing elements to the right and discard the oldest one (array[length-1]). My solution might not be very performant but it works for my purposes.

 Method:

   updateArray (Element to insert)

     - for all the elements of the Array
       - start from the end and replace with the one on the left; 
     - Array [0] <- Element

Good luck

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

Run all SQL files in a directory

Create a .BAT file with the following command:

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -E -i"%%G"
pause

If you need to provide username and passsword

for %%G in (*.sql) do sqlcmd /S servername /d databaseName -U username -P 
password -i"%%G"

Note that the "-E" is not needed when user/password is provided

Place this .BAT file in the directory from which you want the .SQL files to be executed, double click the .BAT file and you are done!

Using ffmpeg to change framerate

In general, to set a video's FPS to 24, almost always you can do:

With Audio and without re-encoding:

# Extract video stream
ffmpeg -y -i input_video.mp4 -c copy -f h264 output_raw_bitstream.h264
# Extract audio stream
ffmpeg -y -i input_video.mp4 -vn -acodec copy output_audio.aac
# Remux with new FPS 
ffmpeg -y -r 24 -i output_raw_bitstream.h264 -i output-audio.aac -c copy output.mp4

If you want to find the video format (H264 in this case), you can use FFprobe, like this

ffprobe -loglevel error -select_streams v -show_entries stream=codec_name -of default=nw=1:nk=1 input_video.mp4

which will output:

h264

Read more in How can I analyze file and detect if the file is in H.264 video format?


With re-encoding:

ffmpeg -y -i input_video.mp4 -vf -r 24 output.mp4

Element-wise addition of 2 lists?

Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).

Replace \n with actual new line in Sublime Text

For Windows line endings:

(Turn on regex - Alt+R)

Find: \\r\\n

Replace: \r\n

illustration

How do I create delegates in Objective-C?

Swift version

A delegate is just a class that does some work for another class. Read the following code for a somewhat silly (but hopefully enlightening) Playground example that shows how this is done in Swift.

// A protocol is just a list of methods (and/or properties) that must
// be used by any class that adopts the protocol.
protocol OlderSiblingDelegate: class {
    // This protocol only defines one required method
    func getYourNiceOlderSiblingAGlassOfWater() -> String
}

class BossyBigBrother {
    
    // The delegate is the BossyBigBrother's slave. This position can 
    // be assigned later to whoever is available (and conforms to the 
    // protocol).
    weak var delegate: OlderSiblingDelegate?
    
    func tellSomebodyToGetMeSomeWater() -> String? {
        // The delegate is optional because there might not be anyone
        // nearby to boss around.
        return delegate?.getYourNiceOlderSiblingAGlassOfWater()
    }
}

// PoorLittleSister conforms to the OlderSiblingDelegate protocol
class PoorLittleSister: OlderSiblingDelegate {

    // This method is repquired by the protocol, but the protocol said
    // nothing about how it needs to be implemented.
    func getYourNiceOlderSiblingAGlassOfWater() -> String {
        return "Go get it yourself!"
    }
    
}

// initialize the classes
let bigBro = BossyBigBrother()
let lilSis = PoorLittleSister()

// Set the delegate 
// bigBro could boss around anyone who conforms to the 
// OlderSiblingDelegate protocol, but since lilSis is here, 
// she is the unlucky choice.
bigBro.delegate = lilSis

// Because the delegate is set, there is a class to do bigBro's work for him.
// bigBro tells lilSis to get him some water.
if let replyFromLilSis = bigBro.tellSomebodyToGetMeSomeWater() {
    print(replyFromLilSis) // "Go get it yourself!"
}

In actual practice, delegates are often used in the following situations

  1. When a class needs to communicate some information to another class
  2. When a class wants to allow another class to customize it

The classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.

I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

Get the Query Executed in Laravel 3/4

Laravel 3

Another way to do this is:

#config/database.php

'profiler' => true

For all Queries result:

print_r(DB::profiler());

For last Result:

print_r(DB::last_query());

MongoDB vs. Cassandra

I'm probably going to be an odd man out, but I think you need to stay with MySQL. You haven't described a real problem you need to solve, and MySQL/InnoDB is an excellent storage back-end even for blob/json data.

There is a common trick among Web engineers to try to use more NoSQL as soon as realization comes that not all features of an RDBMS are used. This alone is not a good reason, since most often NoSQL databases have rather poor data engines (what MySQL calls a storage engine).

Now, if you're not of that kind, then please specify what is missing in MySQL and you're looking for in a different database (like, auto-sharding, automatic failover, multi-master replication, a weaker data consistency guarantee in cluster paying off in higher write throughput, etc).

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I was facing this issue in ionic and tried many solutions but solved this by running this.

For MAC: node --max-old-space-size=4096 /usr/local/bin/ionic cordova build android --prod

For Windows: node --max-old-space-size=4096 /Users/{your user}/AppData/Roaming/npm/node_modules/ionic/bin/ionic cordova build windows --prod

Do subclasses inherit private fields?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass

reference: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html#:~:text=Private%20Members%20in%20a%20Superclass,be%20used%20by%20the%20subclass.

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

Logical operators ("and", "or") in DOS batch

De Morgan's laws allow us to convert disjunctions ("OR") into logical equivalents using only conjunctions ("AND") and negations ("NOT"). This means we can chain disjunctions ("OR") on to one line.

This means if name is "Yakko" or "Wakko" or "Dot", then echo "Warner brother or sister".

set warner=true
if not "%name%"=="Yakko" if not "%name%"=="Wakko" if not "%name%"=="Dot" set warner=false
if "%warner%"=="true" echo Warner brother or sister

This is another version of paxdiablo's "OR" example, but the conditions are chained on to one line. (Note that the opposite of leq is gtr, and the opposite of geq is lss.)

set res=true
if %hour% gtr 6 if %hour% lss 22 set res=false
if "%res%"=="true" set state=asleep

Datetime BETWEEN statement not working in SQL Server

Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN CONVERT(datetime,'2013-10-17') AND CONVERT(datetime,'2013-10-18 23:59:59:999')

if you want to search the entire day of the 18th.

SQL DATETIME fields have milliseconds. So I added 999 to the field.

Text File Parsing in Java

If you have a 200,000,000 character files and split that every five characters, you have 40,000,000 String objects. Assume they are sharing actual character data with the original 400 MB String (char is 2 bytes). A String is say 32 bytes, so that is 1,280,000,000 bytes of String objects.

(It's probably worth noting that this is very implementation dependent. split could create entirely strings with entirely new backing char[] or, OTOH, share some common String values. Some Java implementations to not use the slicing of char[]. Some may use a UTF-8-like compact form and give very poor random access times.)

Even assuming longer strings, that's a lot of objects. With that much data, you probably want to work with most of it in compact form like the original (only with indexes). Only convert to objects that which you need. The implementation should be database like (although they traditionally don't handle variable length strings efficiently).

ASP.NET MVC Global Variables

public static class GlobalVariables
{
    // readonly variable
    public static string Foo
    {
        get
        {
            return "foo";
        }
    }

    // read-write variable
    public static string Bar
    {
        get
        {
            return HttpContext.Current.Application["Bar"] as string;
        }
        set
        {
            HttpContext.Current.Application["Bar"] = value;
        }
    }
}

Get the date (a day before current time) in Bash

Advanced Bash-scripting Guide

date +%Y:%m:%d -d "yesterday"

For details about the date format see the man page for date

date --date='-1 day'

Get URL query string parameters

This code and notation is not mine. Evan K solves a multi value same name query with a custom function ;) is taken from:

http://php.net/manual/en/function.parse-str.php#76792 Credits go to Evan K.

It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);
    
    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>

How to convert unix timestamp to calendar date moment.js

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment(value, 'MM/DD/YYYY', false).calendar(); 
    alert(dateString);
});

There is a strict mode and a Forgiving mode.

While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.

In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.

A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.

In strict mode, the following code results in 'Invalid Date' being displayed:

moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"

In forgiving mode using a format string, you get a wrong date:

moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"

another way would be

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment.unix(value).calendar(); 
    alert(dateString);
});

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

Another way to solve this problem is to install the missing libs that you need.

You can download the libs and see how to install here.

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

What's the difference between lists and tuples?

This is an example of Python lists:

my_list = [0,1,2,3,4]
top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]

This is an example of Python tuple:

my_tuple = (a,b,c,d,e)
celebrity_tuple = ("John", "Wayne", 90210, "Actor", "Male", "Dead")

Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "( ... , ... )", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable (...so only tuples are hashable and can be used as dictionary/hash keys!). This gives rise to differences in how they can or can't be used (enforced a priori by syntax) and differences in how people choose to use them (encouraged as 'best practices,' a posteriori, this is what smart programers do). The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what meaning people give to the order of elements.

For tuples, 'order' signifies nothing more than just a specific 'structure' for holding information. What values are found in the first field can easily be switched into the second field as each provides values across two different dimensions or scales. They provide answers to different types of questions and are typically of the form: for a given object/subject, what are its attributes? The object/subject stays constant, the attributes differ.

For lists, 'order' signifies a sequence or a directionality. The second element MUST come after the first element because it's positioned in the 2nd place based on a particular and common scale or dimension. The elements are taken as a whole and mostly provide answers to a single question typically of the form, for a given attribute, how do these objects/subjects compare? The attribute stays constant, the object/subject differs.

There are countless examples of people in popular culture and programmers who don't conform to these differences and there are countless people who might use a salad fork for their main course. At the end of the day, it's fine and both can usually get the job done.

To summarize some of the finer details

Similarities:

  1. Duplicates - Both tuples and lists allow for duplicates
  2. Indexing, Selecting, & Slicing - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same:

    >>> my_list[0:3]
    [0,1,2]
    >>> my_tuple[0:3]
    [a,b,c]
    
  3. Comparing & Sorting - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference.

    >>> [0,2,0,0,0,0]>[0,0,0,0,0,500]
    True
    >>> (0,2,0,0,0,0)>(0,0,0,0,0,500)
    True
    

Differences: - A priori, by definition

  1. Syntax - Lists use [], tuples use ()

  2. Mutability - Elements in a given list are mutable, elements in a given tuple are NOT mutable.

    # Lists are mutable:
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son']
    >>> top_rock_list[1]
    'Kashmir'
    >>> top_rock_list[1] = "Stairway to Heaven"
    >>> top_rock_list
    ['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son']
    
    # Tuples are NOT mutable:       
    >>> celebrity_tuple
    ('John', 'Wayne', 90210, 'Actor', 'Male', 'Dead')
    >>> celebrity_tuple[5]
    'Dead'
    >>> celebrity_tuple[5]="Alive"
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    
  3. Hashtables (Dictionaries) - As hashtables (dictionaries) require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists.

    #Lists CAN'T act as keys for hashtables(dictionaries)
    >>> my_dict = {[a,b,c]:"some value"}
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    
    #Tuples CAN act as keys for hashtables(dictionaries)
    >>> my_dict = {("John","Wayne"): 90210}
    >>> my_dict
    {('John', 'Wayne'): 90210}
    

Differences - A posteriori, in usage

  1. Homo vs. Heterogeneity of Elements - Generally list objects are homogenous and tuple objects are heterogeneous. That is, lists are used for objects/subjects of the same type (like all presidential candidates, or all songs, or all runners) whereas although it's not forced by), whereas tuples are more for heterogenous objects.

  2. Looping vs. Structures - Although both allow for looping (for x in my_list...), it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information (%s %s residing in %s is an %s and presently %s % ("John","Wayne",90210, "Actor","Dead"))

Android studio- "SDK tools directory is missing"

The same problem observed on my side while looking for uiautomatorviewer.bat. After installing Android studio 3.6.2 (at Win10) I was looking for Android SDK Tools section at SDK Manager. Currently, this section is Hidden as Obsolete. enter image description here Fix: uncheck Hide Obsolete Packages, then check the mentioned package and install it - C:\Users..\AppData\Local\Android\Sdk\tools\bin is created.

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

Hello here is a simple solution,

Just go to File -> Convert to a C/C++ Autotools Project Select your project files appropriately.

Inclusions will be added to your project file

Is there a way to create multiline comments in Python?

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

Insert, on duplicate update in PostgreSQL?

I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

 #This is pseudo-code - within the application:
 BEGIN TRANSACTION - get transaction lock
 SELECT all current name value pairs where id = $id into a hash record
 create a merge record from the current and update record
  (set intersection where shared keys in new win, and empty values in new are deleted).
 DELETE all name value pairs where id = $id
 COPY/INSERT merged records 
 END TRANSACTION

Find full path of the Python interpreter?

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $ 

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I also faced the same issue today in my running code. Well, I found a lot of answers here. But the important thing I want to mention is that this error message is quite ambiguous and doesn't explicitly point out the exact error.

Some faced it due to browser extensions, some due to incorrect URL patterns and I faced this due to an error in my formGroup instance used in a pop-up in that screen. So, I would suggest everyone that before making any new changes in your code, please debug your code and verify that you don't have any such errors. You will certainly find the actual reason by debugging.

If nothing else works then check your URL as that is the most common reason for this issue.

Why can't Python import Image from PIL?

I had the same issue, and did this to fix it:

  1. In command prompt

    pip install Pillow ##
    
  2. Ensure that you use

    from PIL import Image
    

I in Image has to be capital. That was the issue in my case.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Tim Lentine's answer works IF you have yours specs saved. Your question did not specify that, it only stated you had imported the data. His method would not save your specs that way.

The way to save the spec of that current import is to re-open the import, hit "apend" and that will allow you to use your current import settings that MS Access picked up. (This is useful if your want to keep the import specs from an Excel format you worked on prior to importing into MS ACCESS.)

Once you're in the apend option, use Tim's instructions, which is using the advanced option and "Save As." From there, simply click cancel, and you can now import any other similar data to various tables, etc.

Open a folder using Process.Start

Ive just had this issue, and i found out why. my reason isnt listed here so anyone else who gets this issue and none of these fix it.

If you run Visual Studio as another user and attempt to use Process.Start it will run in that users context and you will not see it on your screen.

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

What to do with branch after merge

After the merge, it's safe to delete the branch:

git branch -d branch1

Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

If you also want to delete the branch on a remote host, you can do:

git push origin :branch1

This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).


git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

Multiple parameters in a List. How to create without a class?

If you are using .NET 4.0 you can use a Tuple.

List<Tuple<T1, T2>> list;

For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

Copy file from source directory to binary directory using CMake

both option are valid and targeting two different steps of your build:

  1. file(COPY ... copies the file in configuration step and only in this step. When you rebuild your project without having changed your cmake configuration, this command won't be executed.
  2. add_custom_command is the preferred choice when you want to copy the file around on each build step.

The right version for your task would be:

add_custom_command(
        TARGET foo POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy
                ${CMAKE_SOURCE_DIR}/test/input.txt
                ${CMAKE_CURRENT_BINARY_DIR}/input.txt)

you can choose between PRE_BUILD, PRE_LINK, POST_BUILD best is you read the documentation of add_custom_command

an example on how to use the first version can be found here: Use CMake add_custom_command to generate source for another target

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

Saving image to file

You can try with this code

Image.Save("myfile.png", ImageFormat.Png)

Link : http://msdn.microsoft.com/en-us/library/ms142147.aspx

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

How to format date and time in Android?

Shortest way:

// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())

%tR is short for %tH:%tM, < means to reuse last parameter(1$).

It is equivalent to String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())

https://developer.android.com/reference/java/util/Formatter.html

Input type number "only numeric value" validation

The easiest way would be to use a library like this one and specifically you want noStrings to be true

    export class CustomValidator{   // Number only validation   
      static numeric(control: AbstractControl) {
        let val = control.value;

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }

How to publish a website made by Node.js to Github Pages?

No, You cannot publish on Github pages. Try Heroku or something like that. You can only deploy static sites on github pages. You can't deploy a server on github pages.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For 'Bad' red:

  • The Font Is: (156,0,6)
  • The Background Is: (255,199,206)

For 'Good' green:

  • The Font Is: (0,97,0)
  • The Background Is: (198,239,206)

For 'Neutral' yellow:

  • The Font Is: (156,101,0)
  • The Background Is: (255,235,156)

Passing null arguments to C# methods

Yes. There are two kinds of types in .NET: reference types and value types.

References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.

Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.

The usage is slightly different, though.

// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
    if (arg1.HasValue)
        DoSomething();

    arg1 = null; // Valid.
    arg1 = 123;  // Also valid.

    DoSomethingWithInt(arg1); // NOT valid!
    DoSomethingWithInt(arg1.Value); // Valid.
}

Exporting result of select statement to CSV format in DB2

You can run this command from the DB2 command line processor (CLP) or from inside a SQL application by calling the ADMIN_CMD stored procedure

EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL 
SELECT col1, col2, coln FROM testtable;

There are lots of options for IMPORT and EXPORT that you can use to create a data file that meets your needs. The NOCHARDEL qualifier will suppress double quote characters that would otherwise appear around each character column.

Keep in mind that any SELECT statement can be used as the source for your export, including joins or even recursive SQL. The export utility will also honor the sort order if you specify an ORDER BY in your SELECT statement.

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Example use of "continue" statement in Python?

Let's say we want to print all numbers which are not multiples of 3 and 5

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x

Predict() - Maybe I'm not understanding it

To avoid error, an important point about the new dataset is the name of independent variable. It must be the same as reported in the model. Another way is to nest the two function without creating a new dataset

model <- lm(Coupon ~ Total, data=df)
predict(model, data.frame(Total=c(79037022, 83100656, 104299800)))

Pay attention on the model. The next two commands are similar, but for predict function, the first work the second don't work.

model <- lm(Coupon ~ Total, data=df) #Ok
model <- lm(df$Coupon ~ df$Total) #Ko

Form submit with AJAX passing form data to PHP without page refresh

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {
        $('form').bind('click', function (event) {
        // using this page stop being refreshing 
        event.preventDefault();

          $.ajax({
            type: 'POST',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

PHP

<?php

if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}

echo $time."<br>";
echo $date;
}
?>

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

How to run multiple Python versions on Windows

I thought this answer might be helpful to others having multiple versions of python and wants to use pipenv to create virtual environment.

  1. navigate to the project directory, and run py -[python version] pip install pipenv, example: py -3.6 pip install pipenv
  2. run pipenv --python [version] to create the virtual environment in the version of the python you desire. example: pipenv --python 3.6
  3. run pipenv shell to activate your virtual environment.

jQuery ajax success error

You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

Add json_encdoe in validate.php in last

mail($to, $subject, $message, $headers); 
echo json_encode(array('success'=>'true'));

JS Code

success: function(data){ 
     if(data.success == true){ 
       alert('success'); 
    } 

Hope it works

Easy way to concatenate two byte arrays

Here's a nice solution using Guava's com.google.common.primitives.Bytes:

byte[] c = Bytes.concat(a, b);

The great thing about this method is that it has a varargs signature:

public static byte[] concat(byte[]... arrays)

which means that you can concatenate an arbitrary number of arrays in a single method call.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

You can store orther disk or path (not C) EX : D\

C:\Program Files\Java\jre1.8.0_101\bin>keytool -genkey -alias server -keyalg RSA -keysize 2048 -keystore D:\myserver.jks -dname "CN=myserver,OU=IT-WebDev, O=TIACHOP, L=HCM, ST=0753, C=VN" && keytool -certreq -alias server -file D:\myserver.csr -keystore D:\myserver.jks

enter image description here

get original element from ng-click

You need $event.currentTarget instead of $event.target.

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

Vue js error: Component template should contain exactly one root element

if, for any reasons, you don't want to add a wrapper (in my first case it was for <tr/> components), you can use a functionnal component.

Instead of having a single components/MyCompo.vue you will have few files in a components/MyCompo folder :

  • components/MyCompo/index.js
  • components/MyCompo/File.vue
  • components/MyCompo/Avatar.vue

With this structure, the way you call your component won't change.

components/MyCompo/index.js file content :

import File from './File';
import Avatar from './Avatar';   

const commonSort=(a,b)=>b-a;

export default {
  functional: true,
  name: 'MyCompo',
  props: [ 'someProp', 'plopProp' ],
  render(createElement, context) {
    return [
        createElement( File, { props: Object.assign({light: true, sort: commonSort},context.props) } ),
        createElement( Avatar, { props: Object.assign({light: false, sort: commonSort},context.props) } )
    ]; 
  }
};

And if you have some function or data used in both templates, passed them as properties and that's it !

I let you imagine building list of components and so much features with this pattern.

How do I find the date a video (.AVI .MP4) was actually recorded?

For me the mtime (modification time) is also earlier than the create date in a lot of (most) cases since, as you say, any reorganisation modifies the create time. However, the mtime AFAIUI is an accurate reflection of when the file contents were actually changed so should be an accurate record of video capture date.

After discovering this metadata failure for movie files, I am going to be renaming my videos based on their mtime so I have this stored in a more robust way!

How can I update NodeJS and NPM to the next versions?

First check your NPM version

npm -v

1) Update NPM to current version:

View curent NPM version:

npm view npm version

Update npm to current version:

npm i -g npm


2) List all available NPM versions and make a custom install/update/roll-back

View all versions including "alpha", "beta" and "rc" (release candidate)

npm view npm versions --json

Reinstall NPM to a specific version chosen from the versions list - for example to 5.0.3

npm i -g [email protected]
  • Installing one version will automatically remove the one currently installed.

  • For Linux and iOS prepend commands with sudo

How to deal with certificates using Selenium?

Creating a profile and then a driver helps us get around the certificate issue in Firefox:

var profile = new FirefoxProfile();
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris","DESIREDURL");
driver = new FirefoxDriver(profile);

How to find tag with particular text with Beautiful Soup?

You could solve this with some simple gazpacho parsing:

from gazpacho import Soup

soup = Soup(html)
tds = soup.find("td", {"class": "pos"})
tds[1].find("strong").text

Which will output:

text I am looking for

Multiple Inheritance in C#

In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.

Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.

Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.

Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.

how to know status of currently running jobs

Given a job (I assume you know its name) you can use:

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

as suggested in MSDN Job Help Procedure. It returns a lot of informations about the job (owner, server, status and so on).

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Algorithm to return all combinations of k elements from n

In Python like Andrea Ambu, but not hardcoded for choosing three.

def combinations(list, k):
    """Choose combinations of list, choosing k elements(no repeats)"""
    if len(list) < k:
        return []
    else:
        seq = [i for i in range(k)]
        while seq:
            print [list[index] for index in seq]
            seq = get_next_combination(len(list), k, seq)

def get_next_combination(num_elements, k, seq):
        index_to_move = find_index_to_move(num_elements, seq)
        if index_to_move == None:
            return None
        else:
            seq[index_to_move] += 1

            #for every element past this sequence, move it down
            for i, elem in enumerate(seq[(index_to_move+1):]):
                seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1

            return seq

def find_index_to_move(num_elements, seq):
        """Tells which index should be moved"""
        for rev_index, elem in enumerate(reversed(seq)):
            if elem < (num_elements - rev_index - 1):
                return len(seq) - rev_index - 1
        return None   

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

How to hide a div with jQuery?

$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.

The way I got around this was to get the html content of myDiv using .html().

I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.

After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.

var Content = $('myDiv').html(); 
        $('myDiv').empty();
        var hiddenField = $("<input type='hidden' id='myDiv2'>");
        $('body').append(hiddenField);
        HiddenField.val(Content);

and then when I wanted to SHOW the content again.

        var Content = $('myDiv');
        Content.html($('#myDiv2').val());
        $('#myDiv2').remove();

This was more reliable that the .hide() & .show() methods.

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

How to include "zero" / "0" results in COUNT aggregate?

if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)

Ex:

select P.person_id, nvl(A.nb_apptmts, 0) from 
(SELECT person.person_id
FROM person) P
LEFT JOIN 
(select person_id, count(*) as nb_apptmts
from appointment 
group by person_id) A
ON P.person_id = A.person_id

Xcode 9 Swift Language Version (SWIFT_VERSION)

Answer to your question:
You can download Xcode 8.x from Apple Download Portal or Download Xcode 8.3.3 (or see: Where to download older version of Xcode), if you've premium developer account (apple id). You can install & work with both Xcode 9 and Xcode 8.x in single (mac) system. (Make sure you've Command Line Tools supporting both version of Xcode, to work with terminal (see: How to install 'Command Line Tool'))


Hint: How to migrate your code Xcode 9 compatible Swift versions (Swift 3.2 or 4)
Xcode 9 allows conversion/migration from Swift 3.0 to Swift 3.2/4.0 only. So if current version of Swift language of your project is below 3.0 then you must migrate your code in Swift 3 compatible version Using Xcode 8.x.

This is common error message that Xcode 9 shows if it identifies Swift language below 3.0, during migration.

enter image description here


Swift 3.2 is supported by Xcode 9 & Xcode 8 both.

Project ? (Select Your Project Target) ? Build Settings ? (Type 'swift' in Searchbar) Swift Compiler Language ? Swift Language Version ? Click on Language list to open it.

enter image description here



Convert your source code from Swift 2.0 to 3.2 using Xcode 8 and then continue with Xcode 9 (Swift 3.2 or 4).


For easier migration of your code, follow these steps: (it will help you to convert into latest version of swift supported by your Xcode Tool)

Xcode: Menus: Edit ? Covert ? To Current Swift Syntax

enter image description here

Git Bash doesn't see my PATH

In my case It happened while installing heroku cli and git bash, Here is what i did to work.

got to this location

C:\Users\<username here>\AppData\Local

and delete the file in my case heroku folder. So I deleded folder and run cmd. It is working

Execute a PHP script from another PHP script

<?php
$output = file_get_contents('http://host/path/another.php?param=value ');
echo $output;
?>

How do I compare two string variables in an 'if' statement in Bash?

Use:

#!/bin/bash

s1="hi"
s2="hi"

if [ "x$s1" == "x$s2" ]
then
  echo match
fi

Adding an additional string inside makes it more safe.

You could also use another notation for single-line commands:

[ "x$s1" == "x$s2" ] && echo match

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Ways to circumvent the same-origin policy

Here are some workarounds and explanation of same-origin-policy:
Thiru's Blog - Browser same origin policy workaround

Convert a row of a data frame to vector

Note that you have to be careful if your row contains a factor. Here is an example:

df_1 = data.frame(V1 = factor(11:15),
                  V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns 
[1] 1 21

Here is another example (by default data.frame() converts characters to factors)

df_2 = data.frame(V1 = letters[1:5],
                  V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"

To prevent this behavior, you need to take care of the factor, before extracting it:

df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11  21
df_2[3,] %>% as.character()
[1] "c" "3"

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Read Excel File in Python

Here is the code to read an excel file and and print all the cells present in column 1 (except the first cell i.e the header):

import xlrd

file_location="C:\pythonprog\xxx.xlsv"
workbook=xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
print(sheet.cell_value(0,0))

for row in range(1,sheet.nrows):
     print(sheet.cell_value(row,0))

Insert line at middle of file with Python?

location_of_line = 0
with open(filename, 'r') as file_you_want_to_read:
     #readlines in file and put in a list
     contents = file_you_want_to_read.readlines()

     #find location of what line you want to insert after
     for index, line in enumerate(contents):
            if line.startswith('whatever you are looking for')
                   location_of_line = index

#now you have a list of every line in that file
context.insert(location_of_line, "whatever you want to append to middle of file")
with open(filename, 'w') as file_to_write_to:
        file_to_write_to.writelines(contents)

That is how I ended up getting whatever data I want to insert to the middle of the file.

this is just pseudo code, as I was having a hard time finding clear understanding of what is going on.

essentially you read in the file to its entirety and add it into a list, then you insert your lines that you want to that list, and then re-write to the same file.

i am sure there are better ways to do this, may not be efficient, but it makes more sense to me at least, I hope it makes sense to someone else.

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

Pentaho Data Integration SQL connection

You need to download mysql-connector-java-5.1.46.tar.gz, not the latest version. The Driver class that Pentaho uses is not included in mysql-connector-java-8.xx.yy versions.

Setting a JPA timestamp column to be generated by the database?

I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).

The "timestamp" column in this example is like a "last-touched" column.x`

The code below uses a separate column "version" for optimistic locking.

private long version;
private Date timeStamp

@Version
public long getVersion() {
    return version;
}

public void setVersion(long version) {
    this.version = version;
}

// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
    return timeStamp;
}

public void setTimeStamp(Date timeStamp) {
    this.timeStamp = timeStamp;
}

(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)

From the MySQL manual regarding TIMESTAMP :

With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.

no module named zlib

After you install the missing zlib dev package you can also use pythonbrew to uninstall and then reinstall the version of python you wanted and it seems like it picks up the new package to compile to correct abilities. This way you can keep using pythonbrew and don't have to do the compilation yourself (though it isn't that difficult)

How can I ssh directly to a particular directory?

You can do the following:

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted ; bash --login"

This way, you will get a login shell right on the directory_wanted.


Explanation

-t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.

Multiple -t options force tty allocation, even if ssh has no local tty.

  • If you don't use -t then no prompt will appear.
  • If you don't add ; bash then the connection will get closed and return control to your local machine
  • If you don't add bash --login then it will not use your configs because its not a login shell

How do I center align horizontal <UL> menu?

I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)

/*ul wrapper*/
.gallery_wrapper{
        width:          958px;
        margin:         0 auto;
  }
/*ul list*/
ul.gallery_carrousel{
        display:        inline-block;
        margin:         0 auto;
}
.contenido_secundario li{
        float:          left;
}

Adding text to ImageView in Android

To draw text directly on canvas do the following:

  1. Create a member Paint object in myImageView constructor

    Paint mTextPaint = new Paint();
    
  2. Use canvas.drawText in your myImageView.onDraw() method:

    canvas.drawText("My fancy text", xpos, ypos, mTextPaint);
    

Explore Paint and Canvas class documentation to add fancy effects.

String.contains in Java

no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:

calling stack:

String.indexOf(char[], int, int, char[], int, int, int) line: 1591  
String.indexOf(String, int) line: 1564  
String.indexOf(String) line: 1546   
String.contains(CharSequence) line: 1934    

code:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
  if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
  }
      if (fromIndex < 0) {
        fromIndex = 0;
      }
  if (targetCount == 0) {//my comment: this is where it returns, the size of the 
    return fromIndex;    // incoming string is 0,  which is passed in as targetCount
  }                      // fromIndex is 0 as well, as the search starts from the 
                         // start of the source string
    ...//the rest of the method 

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Take these two scenarios:

Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );

If opt doesn't contain a value, the two are indeed equivalent. But if opt does contain a value, how many Foo objects will be created?

P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.

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

This issue might also be caused by a broken Maven repository.

I observe the SEVERE: A child container failed during start message from time to time when working with Eclipse. My Eclipse workspace has several projects. Some of the projects have common external dependencies. If Maven repository is empty (or I add new dependencies into pom.xml files), Eclipse starts downloading libraries specified in pom.xml into Maven repository. And Eclipse does that in parallel for several projects in the workspace. It might happen that several Eclipse threads would be downloading the same file simultaneously into the same place in Maven repository. As a result, this file becomes corrupted.

So, this is how you could resolve the issue.

  1. Close your Eclipse.
  2. If you know which specific jar-file is broken in Maven repository, then delete that file.
  3. If you do not know which file is broken in Maven repository, then delete the whole repository (rm -rf $HOME/.m2).
  4. For each project, run mvn package in the command line. It is important to run the command for each project one-by-one, not in parallel; thus, you ensure that only one instance of Maven runs each time.
  5. Open your Eclipse.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Changing file permission in Python

Simply include permissions integer in octal (works for both python 2 and python3):

os.chmod(path, 0o444)

How can I git stash a specific file?

To add to svick's answer, the -m option simply adds a message to your stash, and is entirely optional. Thus, the command

git stash push [paths you wish to stash]

is perfectly valid. So for instance, if I want to only stash changes in the src/ directory, I can just run

git stash push src/

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

Border color on default input style

You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update: You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

error: use of deleted function

The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.

class X {
    const int x;
};

Since X::x is const, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x). You can get the same kind of situation with a member that's a reference:

class X { 
    whatever &x;
};

It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.

This is why a const member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.

It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.

Annotation @Transactional. How to rollback?

Just throw any RuntimeException from a method marked as @Transactional.

By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

@Transactional(rollbackFor=Exception.class)

This will rollback transaction after throwing any exception.

Checking if a worksheet-based checkbox is checked

Is this what you are trying?

Sub Sample()
    Dim cb As Shape

    Set cb = ActiveSheet.Shapes("Check Box 1")

    If cb.OLEFormat.Object.Value = 1 Then
        MsgBox "Checkbox is Checked"
    Else
        MsgBox "Checkbox is not Checked"
    End If
End Sub

Replace Activesheet with the relevant sheetname. Also replace Check Box 1 with the relevant checkbox name.

What's the scope of a variable initialized in an if statement?

Yes. It is also true for for scope. But not functions of course.

In your example: if the condition in the if statement is false, x will not be defined though.

LinearLayout not expanding inside a ScrollView

All the answers here didn't work (completely) for me. Just to recap what we wanna do for a complete answer: We have a ScrollView, supposedly filling the device's viewport, thus we set fillViewport to "true" in the layout xml. Then, inside the ScrollView, we have a LinearLayout containing everything else, and that LinearLayout should be at least as high as its parent ScrollView, so stuff that's supposed to be on the bottom (of the LinearLayout) is actually, as we want it, at the bottom of the screen (or at the bottom of the ScrollView, in case the LinearLayout's content has more hight than the screen.

Example activity_main.xml layout:

<ScrollView
    android:id="@+id/layout_scrollwrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:layout_alignParentTop="true"
    android:layout_above="@+id/layout_footer"
    >
<LinearLayout
    android:id="@+id/layout_scrollwrapper_inner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
...content which might or might not be higher than screen height...
</LinearLayout>
</ScrollView>

Then, in the activity's onCreate, we "wait" for the LinearLayout's layouting to be done (implying it's parent's layouting is also already done) and then set it's minimum height to the ScrollView's height. Thus it also works in case the ScrollView does not occupy the whole screen height. Whether you call .post(...) on the ScrollView or the inner LinearLayout should not make that much of a difference, if one doesn't work for you, try the other.

public class MainActivity extends AppCompatActivity {

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

    LinearLayout linearLayoutWrapper = findViewById(R.id.layout_scrollwrapper_inner);

    ...

    linearLayoutWrapper.post(() -> {
        linearLayoutWrapper.setMinimumHeight(((ScrollView)linearLayoutWrapper.getParent()).getHeight());
    });
}
...
}

Sadly, it's not an xml-only solution, but it works well enough for me, hope it also helps some other tortured android dev scouring the interwebs in search for a solution to this problem ;D

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

XSD - how to allow elements in any order any number of times?

This is what finally worked for me:

<xsd:element name="bar">
  <xsd:complexType>
    <xsd:sequence>
      <!--  Permit any of these tags in any order in any number     -->
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element name="child1" type="xsd:string" />
        <xsd:element name="child2" type="xsd:string" />
        <xsd:element name="child3" type="xsd:string" />
      </xsd:choice>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

Java Refuses to Start - Could not reserve enough space for object heap

Steps to be execute .... to resolve the Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine.

Step 1: Reduce the memory what earlier you used.. java -Xms128m -Xmx512m -cp simple.jar

step 2: Remove the RAM some time from the mother board and plug it and restart * may it will release the blocking heap area memory.. java -Xms512m -Xmx1024m -cp simple.jar

Hope it will work well now... :-)

jQuery select2 get value of select tag?

$("#first").select2('data') will return all data as map

Why is "except: pass" a bad programming practice?

You should use at least except Exception: to avoid catching system exceptions like SystemExit or KeyboardInterrupt. Here's link to docs.

In general you should define explicitly exceptions you want to catch, to avoid catching unwanted exceptions. You should know what exceptions you ignore.

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

Calculate average in java

Just some minor modification to your code will do (with some var renaming for clarity) :

double sum = 0; //average will have decimal point

for(int i=0; i < args.length; i++){
   //parse string to double, note that this might fail if you encounter a non-numeric string
   //Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
   sum += Double.valueOf( args[i] ); 
}

double average = sum/args.length;

System.out.println(average );

Note that the loop can also be simplified:

for(String arg : args){
   sum += Double.valueOf( arg );
}

Edit: the OP seems to want to use the args array. This seems to be a String array, thus updated the answer accordingly.

Update:

As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:

BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
  sum = sum.add( new BigDecimal( arg ) );
}

This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):

  • Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)
  • The probability of overflow is practically eliminated. Note however, that a BigDecimal might be bigger than what fits into a double or long.

Sorting A ListView By Column

Made minor changes to the article here to accommodate sorting of both string and numeric values in ListView.

Form1.cs contains

using System;
using System.Windows.Forms;

namespace ListView
{
    public partial class Form1 : Form
    {
        Random rnd = new Random();
        private ListViewColumnSorter lvwColumnSorter;

        public Form1()
        {
            InitializeComponent();
            // Create an instance of a ListView column sorter and assign it to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;

            InitListView();
        }

        private void InitListView()
        {
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.FullRowSelect = true;

            //Add column header
            listView1.Columns.Add("Name", 100);
            listView1.Columns.Add("Price", 70);
            listView1.Columns.Add("Trend", 70);

            for (int i = 0; i < 10; i++)
            {
                listView1.Items.Add(AddToList("Name" + i.ToString(), rnd.Next(1, 100).ToString(), rnd.Next(1, 100).ToString()));
            }
        }

        private ListViewItem AddToList(string name, string price, string trend)
        {
            string[] array = new string[3];
            array[0] = name;
            array[1] = price;
            array[2] = trend;

            return (new ListViewItem(array));
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.listView1.Sort();
        }

    }
}

ListViewColumnSorter.cs contains

using System;
using System.Collections;
using System.Windows.Forms;

/// <summary>
/// This class is an implementation of the 'IComparer' interface.
/// </summary>
public class ListViewColumnSorter : IComparer
{
    /// <summary>
    /// Specifies the column to be sorted
    /// </summary>
    private int ColumnToSort;
    /// <summary>
    /// Specifies the order in which to sort (i.e. 'Ascending').
    /// </summary>
    private SortOrder OrderOfSort;
    /// <summary>
    /// Case insensitive comparer object
    /// </summary>
    private CaseInsensitiveComparer ObjectCompare;

    /// <summary>
    /// Class constructor.  Initializes various elements
    /// </summary>
    public ListViewColumnSorter()
    {
        // Initialize the column to '0'
        ColumnToSort = 0;

        // Initialize the sort order to 'none'
        OrderOfSort = SortOrder.None;

        // Initialize the CaseInsensitiveComparer object
        ObjectCompare = new CaseInsensitiveComparer();
    }

    /// <summary>
    /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
    /// </summary>
    /// <param name="x">First object to be compared</param>
    /// <param name="y">Second object to be compared</param>
    /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
    public int Compare(object x, object y)
    {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // Cast the objects to be compared to ListViewItem objects
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        decimal num = 0;
        if (decimal.TryParse(listviewX.SubItems[ColumnToSort].Text, out num))
        {
            compareResult = decimal.Compare(num, Convert.ToDecimal(listviewY.SubItems[ColumnToSort].Text));
        }
        else 
        {
            // Compare the two items
            compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
        }

        // Calculate correct return value based on object comparison
        if (OrderOfSort == SortOrder.Ascending)
        {
            // Ascending sort is selected, return normal result of compare operation
            return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending)
        {
            // Descending sort is selected, return negative result of compare operation
            return (-compareResult);
        }
        else
        {
            // Return '0' to indicate they are equal
            return 0;
        }
    }

    /// <summary>
    /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
    /// </summary>
    public int SortColumn
    {
        set
        {
            ColumnToSort = value;
        }
        get
        {
            return ColumnToSort;
        }
    }

    /// <summary>
    /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
    /// </summary>
    public SortOrder Order
    {
        set
        {
            OrderOfSort = value;
        }
        get
        {
            return OrderOfSort;
        }
    }

}

JavaScript push to array

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

How to configure the web.config to allow requests of any length

Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;

$mysqladmin -u root -p[your root password here] version Which outputs:

    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Server version      5.5.49-0ubuntu0.14.04.1
    Protocol version    10
    Connection      Localhost via UNIX socket
    UNIX socket     /var/run/mysqld/mysqld.sock
    Uptime:         1 hour 54 min 3 sec

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

    $cfg['Servers'][$i]['host'] = 'localhost';
    $cfg['Servers'][$i]['connect_type'] = 'socket';
    $cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';

All credit goes to this person: This is the correct solution

docker unauthorized: authentication required - upon push with successful login

I had the same problem but i fixed it with push with specified url. as: docker login -u https://index.docker.io/v1/

console output:

The push refers to a repository [docker.io/<username>/richcity]
adc9144127c1: Preparing 
4db5654f7a64: Preparing 
ce71ae73bc60: Preparing 
e8e980243ee4: Preparing 
d773e991f7d2: Preparing 
bae23f4bbe95: Waiting 
5f70bf18a086: Waiting 
3d3e4e34386e: Waiting 
e72d5d9d5d30: Waiting 
8d1d75696199: Waiting 
bdf5b19f60a4: Waiting 
c8bd8922fbb7: Waiting 
unauthorized: authentication required

1010deiMac:dockerspace whoami$ docker login -u <username> https://index.docker.io/v1/
Password: 
Login Succeeded
1010deiMac:dockerspace whoami$ docker push <username>/richcity 
The push refers to a repository [docker.io/<username>/richcity]
adc9144127c1: Pushed 
4db5654f7a64: Pushed 
ce71ae73bc60: Pushed 
e8e980243ee4: Pushed 
d773e991f7d2: Pushed 
bae23f4bbe95: Pushed 
5f70bf18a086: Pushed 
3d3e4e34386e: Pushing [=============>                                     ] 45.07 MB/165.4 MB
e72d5d9d5d30: Pushed 
8d1d75696199: Pushing [>                                                  ] 1.641 MB/118.1 MB
bdf5b19f60a4: Pushing [============>                                      ]   142 MB/568.4 MB
c8bd8922fbb7: Pushing [========================>                          ] 59.44 MB/121.8 MB

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Can I add color to bootstrap icons only using CSS?

The accepted answer (using font awesome) is the right one. But since I just wanted the red variant to show on validation errors, I ended using an addon package, kindly offered on this site.

Just edited the url paths in css files since they are absolute (start with /) and I prefer to be relative. Like this:

.icon-red {background-image: url("../img/glyphicons-halflings-red.png") !important;}
.icon-purple {background-image: url("../img/glyphicons-halflings-purple.png") !important;}
.icon-blue {background-image: url("../img/glyphicons-halflings-blue.png") !important;}
.icon-lightblue {background-image: url("../img/glyphicons-halflings-lightblue.png") !important;}
.icon-green {background-image: url("../img/glyphicons-halflings-green.png") !important;}
.icon-yellow {background-image: url("../img/glyphicons-halflings-yellow.png") !important;}
.icon-orange {background-image: url("../img/glyphicons-halflings-orange.png") !important;}

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Rename a file in C#

NOTE: In this example code we open a directory and search for PDF files with open and closed parenthesis in the name of the file. You can check and replace any character in the name you like or just specify a whole new name using replace functions.

There are other ways to work from this code to do more elaborate renames but my main intention was to show how to use File.Move to do a batch rename. This worked against 335 PDF files in 180 directories when I ran it on my laptop. This is spur of the moment code and there are more elaborate ways to do it.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenamer
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");

            int i = 0;

            try
            {
                foreach (var dir in dirnames)
                {
                    var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);

                    DirectoryInfo d = new DirectoryInfo(dir);
                    FileInfo[] finfo = d.GetFiles("*.pdf");

                    foreach (var f in fnames)
                    {
                        i++;
                        Console.WriteLine("The number of the file being renamed is: {0}", i);

                        if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
                        {
                            File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
                        }
                        else
                        {
                            Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
                            foreach (FileInfo fi in finfo)
                            {
                                Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}

Regex Email validation

   public bool VailidateEntriesForAccount()
    {
       if (!(txtMailId.Text.Trim() == string.Empty))
        {
            if (!IsEmail(txtMailId.Text))
            {
                Logger.Debug("Entered invalid Email ID's");
                MessageBox.Show("Please enter valid Email Id's" );
                txtMailId.Focus();
                return false;
            }
        }
     }
   private bool IsEmail(string strEmail)
    {
        Regex validateEmail = new Regex("^[\\W]*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z] {2,4}[\\W]*,{1}[\\W]*)*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z]{2,4})[\\W]*$");
        return validateEmail.IsMatch(strEmail);
    }

SQL Query for Selecting Multiple Records

If you know the list of ids try this query:

SELECT * FROM `Buses` WHERE BusId IN (`list of busIds`)

or if you pull them from another table list of busIds could be another subquery:

SELECT * FROM `Buses` WHERE BusId IN (SELECT SomeId from OtherTable WHERE something = somethingElse)

If you need to compare to another table you need a join:

SELECT * FROM `Buses` JOIN OtheTable on Buses.BusesId = OtehrTable.BusesId

creating an array of structs in c++

Some compilers support compound literals as an extention, allowing this construct:

Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};

But it's rather unportable.

How to retrieve images from MySQL database and display in an html tag

You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:

<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>

Then getImage.php is

<?php

  $id = $_GET['id'];
  // do some validation here to ensure id is safe

  $link = mysql_connect("localhost", "root", "");
  mysql_select_db("dvddb");
  $sql = "SELECT dvdimage FROM dvd WHERE id=$id";
  $result = mysql_query("$sql");
  $row = mysql_fetch_assoc($result);
  mysql_close($link);

  header("Content-type: image/jpeg");
  echo $row['dvdimage'];
?>

Unity 2d jumping script

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

This worked for me

scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();

where filter is following function and scan is the input string:

public String filter(String scan, String regex, String replace) {
    StringBuffer sb = new StringBuffer();

    Pattern pt = Pattern.compile(regex);
    Matcher m = pt.matcher(scan);

    while (m.find()) {
        m.appendReplacement(sb, replace);
    }

    m.appendTail(sb);

    return sb.toString();
}

SQL Server Group By Month

SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]

You could also try:

SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month

How to always show the vertical scrollbar in a browser?

Just use CSS.

body {
  overflow-y: scroll;
}

How to get PID of process by specifying process name and store it in a variable to use further?

use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.

ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?

How to create a directory if it doesn't exist using Node.js?

var dir = 'path/to/dir';
try {
  fs.mkdirSync(dir);
} catch(e) {
  if (e.code != 'EEXIST') throw e;
}

Why do I need to do `--set-upstream` all the time?

By the way, the shortcut to pushing the current branch to a remote with the same name:

$ git push -u origin HEAD

In Javascript, how to conditionally add a member to an object?

This is probably the shortest solution with ES6

console.log({
   ...true && {foo: 'bar'}
})
// Output: {foo:'bar'}
console.log({
   ...false && {foo: 'bar'}
})
// Output: {}

How do I mock an autowired @Value field in Spring with Mockito?

Also note that I have no explicit "setter" methods (e.g. setDefaultUrl) in my class and I don't want to create any just for the purposes of testing.

One way to resolve this is change your class to use Constructor Injection, that is used for testing and Spring injection. No more reflection :)

So, you can pass any String using the constructor:

class MySpringClass {

    private final String defaultUrl;
    private final String defaultrPassword;

    public MySpringClass (
         @Value("#{myProps['default.url']}") String defaultUrl, 
         @Value("#{myProps['default.password']}") String defaultrPassword) {
        this.defaultUrl = defaultUrl;
        this.defaultrPassword= defaultrPassword;
    }

}

And in your test, just use it:

MySpringClass MySpringClass  = new MySpringClass("anyUrl", "anyPassword");

Xcode 8 shows error that provisioning profile doesn't include signing certificate

If your trying to upload your app to iTunes Connect (your Provisioning Profiles are set to Distribution), Go to Project Settings -> Build Settings -> Code Signing. Make sure to set all of Debug and Release Options to your Distribution Provisioning Provisioning Profile.

How to use HTML to print header and footer on every printed page of a document?

Is this something you want to print-only? You could add it to every page on your site and use CSS to define the tag as a print-only media.

As an example, this could be an example header:

<span class="printspan">UNCLASSIFIED</span>

And in your CSS, do something like this:

<style type="text/css" media="screen">
    .printspan
    {
        display: none;
    }
</style>
<style type="text/css" media="print">
    .printspan
    {
        display: inline;
        font-family: Arial, sans-serif;
        font-size: 16 pt;
        color: red;
    }
</style>

Finally, to include the header/footer on every page you might use server-side includes or if you have any pages being generated with PHP or ASP you could simply code it in to a common file.

Edit:

This answer is intended to provide a way to show something on the physical printed version of a document while not showing it otherwise. However just as comments suggest, it doesn't solve the issue of having a footer on multiple printed pages when content overflows.

I'm leaving it here in case it's helpful nevertheless.

Remote debugging a Java application

For JDK 1.3 or earlier :

-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For JDK 1.4

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For newer JDK :

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006

Please change the port number based on your needs.

From java technotes

From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)

One more thing to note, from JVM Tool interface documentation:

JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.

process.env.NODE_ENV is undefined

tips

in package.json:

"scripts": {
  "start": "set NODE_ENV=dev && node app.js"
 }

in app.js:

console.log(process.env.NODE_ENV) // dev
console.log(process.env.NODE_ENV === 'dev') // false
console.log(process.env.NODE_ENV.length) // 4 (including a space at the end) 

so, this may better:

"start": "set NODE_ENV=dev&& node app.js"

or

console.log(process.env.NODE_ENV.trim() === 'dev') // true

jQuery DataTable overflow and text-wrapping issues

You can just use render and wrap your own div or span around it. TD`s are hard to style when it comes to max-width, max-height, etc. Div and span is easy..

See: https://datatables.net/examples/advanced_init/column_render.html

I think a nicer solution then working with CSS hacks which are not supported cross browser.

Create a custom View by inflating a layout?

Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

http://developer.android.com/guide/topics/ui/custom-components.html

Get full path without filename from path that includes filename

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

NuGet auto package restore does not work with MSBuild

In Visual Studio 2017 - When you compile using IDE - It will download all the missing nuget packages and save in the folder "packages".

But on the build machine compilation was done using msbuild.exe. In that case, I downloaded nuget.exe and kept in path.

During each build process before executing msbuild.exe. It will execute -> nuget.exe restore NAME_OF_SLN_File (if there is only one .SLN file then you can ignore that parameter)

Best practice for partial updates in a RESTful service

It doesn't matter. In terms of REST, you can't do a GET, because it's not cacheable, but it doesn't matter if you use POST or PATCH or PUT or whatever, and it doesn't matter what the URL looks like. If you're doing REST, what matters is that when you get a representation of your resource from the server, that representation is able give the client state transition options.

If your GET response had state transitions, the client just needs to know how to read them, and the server can change them if needed. Here an update is done using POST, but if it was changed to PATCH, or if the URL changes, the client still knows how to make an update:

{
  "customer" :
  {
  },
  "operations":
  [
    "update" : 
    {
      "method": "POST",
      "href": "https://server/customer/123/"
    }]
}

You could go as far as to list required/optional parameters for the client to give back to you. It depends on the application.

As far as business operations, that might be a different resource linked to from the customer resource. If you want to send an email to the customer, maybe that service is it's own resource that you can POST to, so you might include the following operation in the customer resource:

"email":
{
  "method": "POST",
  "href": "http://server/emailservice/send?customer=1234"
}

Some good videos, and example of the presenter's REST architecture are these. Stormpath only uses GET/POST/DELETE, which is fine since REST has nothing to do with what operations you use or how URLs should look (except GETs should be cacheable):

https://www.youtube.com/watch?v=pspy1H6A3FM,
https://www.youtube.com/watch?v=5WXYw4J4QOU,
http://docs.stormpath.com/rest/quickstart/

How is CountDownLatch used in Java Multithreading?

Best real time Example for countDownLatch explained in this link CountDownLatchExample

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

How to create a RelativeLayout programmatically with two buttons one on top of the other?

I have written a quick example to demonstrate how to create a layout programmatically.

public class CodeLayout extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Creating a new RelativeLayout
        RelativeLayout relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

        // Creating a new TextView
        TextView tv = new TextView(this);
        tv.setText("Test");

        // Defining the layout parameters of the TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);

        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(tv);

        // Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
    }
}

In theory everything should be clear as it is commented. If you don't understand something just tell me.

How to save image in database using C#

Try this method. It should work when field when you want to store image is of type byte. First it creates byte[] for image. Then it saves it to the DB using IDataParameter of type binary.

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

    public static void PerisitImage(string path, IDbConnection connection)
    {
        using (var command = connection.CreateCommand ())
        {
            Image img = Image.FromFile (path);
            MemoryStream tmpStream = new MemoryStream();
            img.Save (tmpStream, ImageFormat.Png); // change to other format
            tmpStream.Seek (0, SeekOrigin.Begin);
            byte[] imgBytes = new byte[MAX_IMG_SIZE];
            tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

            command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
            IDataParameter par = command.CreateParameter();
            par.ParameterName = "payload";
            par.DbType = DbType.Binary;
            par.Value = imgBytes;
            command.Parameters.Add(par);
            command.ExecuteNonQuery ();
        }
    }

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

Matching an empty input box using CSS

If supporting legacy browsers is not needed, you could use a combination of required, valid, and invalid.

The good thing about using this is the valid and invalid pseudo-elements work well with the type attributes of input fields. For example:

_x000D_
_x000D_
input:invalid, textarea:invalid { _x000D_
    box-shadow: 0 0 5px #d45252;_x000D_
    border-color: #b03535_x000D_
}_x000D_
_x000D_
input:valid, textarea:valid {_x000D_
    box-shadow: 0 0 5px #5cd053;_x000D_
    border-color: #28921f;_x000D_
}
_x000D_
<input type="email" name="email" placeholder="[email protected]" required />_x000D_
<input type="url" name="website" placeholder="http://johndoe.com"/>_x000D_
<input type="text" name="name" placeholder="John Doe" required/>
_x000D_
_x000D_
_x000D_

For reference, JSFiddle here: http://jsfiddle.net/0sf6m46j/

Apply style to only first level of td tags

This style:

table tr td { border: 1px solid red; }
td table tr td { border: none; }

gives me:

this http://img12.imageshack.us/img12/4477/borders.png

However, using a class is probably the right approach here.

What's a good way to extend Error in JavaScript?

Custom Error Decorator

This is based on George Bailey's answer, but extends and simplifies the original idea. It is written in CoffeeScript, but is easy to convert to JavaScript. The idea is extend Bailey's custom error with a decorator that wraps it, allowing you to create new custom errors easily.

Note: This will only work in V8. There is no support for Error.captureStackTrace in other environments.

Define

The decorator takes a name for the error type, and returns a function that takes an error message, and encloses the error name.

CoreError = (@message) ->

    @constructor.prototype.__proto__ = Error.prototype
    Error.captureStackTrace @, @constructor
    @name = @constructor.name

BaseError = (type) ->

    (message) -> new CoreError "#{ type }Error: #{ message }"

Use

Now it is simple to create new error types.

StorageError   = BaseError "Storage"
SignatureError = BaseError "Signature"

For fun, you could now define a function that throws a SignatureError if it is called with too many args.

f = -> throw SignatureError "too many args" if arguments.length

This has been tested pretty well and seems to work perfectly on V8, maintaing the traceback, position etc.

Note: Using new is optional when constructing a custom error.

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

Display string as html in asp.net mvc view

I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"

The resolution was to put the variable in quotes in the value statement as follows:

<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
       onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">

What Are Some Good .NET Profilers?

ANTS Profiler. I haven't used many, but I don't really have any complaints about ANTS. The visualization is really helpful.

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

How to vertically align an image inside a div

If you can live with pixel-sized margins, just add font-size: 1px; to the .frame. But remember, that now on the .frame 1em = 1px, which means, you need to set the margin in pixels too.

http://jsfiddle.net/feeela/4RPFa/96/

Now it's not centered any more in Opera…

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

Overloading and overriding

Method overloading and Method overriding are 2 different concepts completely different. Method overloading is having the same method name but with different signatures. Method overriding is changing the default implementation of base class method in the derived class. Below you can find 2 excellent video tutorials explaining these concepts.

Method overriding Vs hiding

Method overloading

What is the difference between active and passive FTP?

Active mode: -server initiates the connection.

Passive mode: -client initiates the connection.

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

You are missing a field annotated with @Id. Each @Entity needs an @Id - this is the primary key in the database.

If you don't want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable instead of @Entity.

If you want simply a data transfer object to hold some data from the hibernate entity, use no annotations on it whatsoever - leave it a simple pojo.

Update: In regards to SQL views, Hibernate docs write:

There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

It's actually quite easy to implement as a helper:

Handlebars.registerHelper('eachProperty', function(context, options) {
    var ret = "";
    for(var prop in context)
    {
        ret = ret + options.fn({property:prop,value:context[prop]});
    }
    return ret;
});

Then using it like so:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

How to specify jackson to only use fields - preferably globally

for jackson 1.9.10 I use

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(JsonMethod.ALL, Visibility.NONE);
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

to turn of auto dedection.

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

Using Git, show all commits that are in one branch, but not the other(s)

If it is one (single) branch that you need to check, for example if you want that branch 'B' is fully merged into branch 'A', you can simply do the following:

$ git checkout A
$ git branch -d B

git branch -d <branchname> has the safety that "The branch must be fully merged in HEAD."

Caution: this actually deletes the branch B if it is merged into A.

load jquery after the page is fully loaded

You can either use .onload function. It runs a function when the page is fully loaded including graphics.

window.onload=function(){
      // Run code
    };

Or another way is : Include scripts at the bottom of your page.

Right query to get the current number of connections in a PostgreSQL DB

The following query is very helpful

select  * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;