Programs & Examples On #Console.setout

Where does Console.WriteLine go in ASP.NET?

if you happened to use NLog in your ASP.net project, you can add a Debugger target:

<targets>
    <target name="debugger" xsi:type="Debugger"
            layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>

and writes logs to this target for the levels you want:

<rules>
    <logger name="*" minlevel="Trace" writeTo="debugger" />

now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).

Creating random colour in Java?

Here is a method for getting a random color:

private static Random sRandom;

public static synchronized int randomColor() {
    if (sRandom == null) {
        sRandom = new Random();
    }
    return 0xff000000 + 256 * 256 * sRandom.nextInt(256) + 256 * sRandom.nextInt(256)
            + sRandom.nextInt(256);
}

Benefits:

  • Get the integer representation which can be used with java.awt.Color or android.graphics.Color
  • Keep a static reference to Random.

PHP Notice: Undefined offset: 1 with array when reading data

The ideal solution would be as below. You won't miss the values from 0 to n.

$len=count($data);
for($i=0;$i<$len;$i++)
     echo $data[$i]. "<br>";

Load local javascript file in chrome for testing?

Not sure why @user3133050 is voted down, that's all you need to do...

Here's the structure you need, based on your script tag's src, assuming you are trying to load moment.js into index.html:

/js/moment.js
/some-other-directory/index.html

The ../ looks "up" at the "some-other-directory" folder level, finds the js folder next to it, and loads the moment.js inside.

It sounds like your index.html is at root level, or nested even deeper.

If you're still struggling, create a test.js file in the same location as index.html, and add a <script src="test.js"></script> and see if that loads. If that fails, check your syntax. Tested in Chrome 46.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

I think you have 2 separate problems, 1. with restoring and 2. with creating

For 1. you could try checking to see if the file was transferred properly (one easy way would be to check the md5 of the file on the server and again on the local environment to see if they match).

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

How can I pass an argument to a PowerShell script?

# ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

How to extract a floating number from a string

re.findall(r"[-+]?\d*\.?\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")

as described above, works really well! One suggestion though:

re.findall(r"[-+]?\d*\.?\d+|[-+]?\d+", "Current Level: -13.2 db or 14.2 or 3 or -3")

will also return negative int values (like -3 in the end of this string)

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

javascript pushing element at the beginning of an array

For an uglier version of unshift use splice:

TheArray.splice(0, 0, TheNewObject);

Dictionary text file

@Future-searchers: you can use aspell to do the dictionary checks, it has bindings in ruby and python. It would make your job much simpler.

set height of imageview as matchparent programmatically

You can try this incase you would like to match parent. The dimensions arrangement is width and height inorder

web = new WebView(this);
        web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

How to increase Java heap space for a tomcat app

Just set this extra line in catalina.bat file

LINE NO AROUND: 143

set "CATALINA_OPTS=-Xms512m -Xmx512m"

And restart Tomcat service

Iterate all files in a directory using a 'for' loop

I had trouble getting jop's answer to work with an absolute path until I found this reference: https://ss64.com/nt/for_r.html

The following example loops through all files in a directory given by the absolute path.

For /R C:\absoulte\path\ %%G IN (*.*) do (
  Echo %%G
)

How to save .xlsx data to file as a blob

Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.

return fetch(fullUrlEndpoint, options)
  .then((res) => {
    if (!res.ok) {
      const responseStatusText = res.statusText
      const errorMessage = `${responseStatusText}`
      throw new Error(errorMessage);
    }
    return res.arrayBuffer();
  })
    .then((ab) => {
      // BE endpoint sends a readable stream of bytes
      const byteArray = new Uint8Array(ab);
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(
        new Blob([byteArray], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        }),
      );
      a.download = `${fileName}.XLSX`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      throw new Error('Error occurred:' + error);
    });

Difference between "or" and || in Ruby?

and/or are for control flow.

Ruby will not allow this as valid syntax:

false || raise "Error"

However this is valid:

false or raise "Error"

You can make the first work, with () but using or is the correct method.

false || (raise "Error")

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

Why do I need to explicitly push a new branch?

I just experienced a further permutation of this issue.

I had a branch named feat/XYZ-1234-some-description because I was working on Jira issue 1234. During the work I created a new Jira issue to track a smaller piece of work, and when I came to push I decided to push to a branch name with this new issue number in:

git push -u origin feat/XYZ-5678-a-different-description # failed

This gave me the error being discussed in this SO thread. But since I was trying to push to a different branch name from my current branch, my problem was different to the one described here. I ended up renaming my local branch before I could push it:

git branch -m feat/XYZ-1234-some-description feat/XYZ-5678-a-different-description
git push -u origin feat/XYZ-5678-a-different-description # now works

After a bit more reading around I realised that I could have set a src on the git push, either to the current branch name, or just HEAD if appropriate:

git push -u origin feat/XYZ-1234-some-description:feat/XYZ-5678-a-different-description # also works

Listing all extras of an Intent

The Kotlin version of Pratik's utility method which dumps all extras of an Intent:

fun dumpIntent(intent: Intent) {

    val bundle: Bundle = intent.extras ?: return

    val keys = bundle.keySet()
    val it = keys.iterator()

    Log.d(TAG, "Dumping intent start")

    while (it.hasNext()) {
        val key = it.next()
        Log.d(TAG,"[" + key + "=" + bundle.get(key)+"]");
    }

    Log.d(TAG, "Dumping intent finish")

}

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

Android checkbox style

Maybe this will satisfy you -

something.xml

<CheckBox
    android:text="Custom CheckBox"
    android:button="@drawable/checkbox_selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/star_down" />
    <item android:state_checked="false" android:drawable="@drawable/star" />
</selector>

For, the reference just refer here

What is the difference between task and thread?

A Task can be seen as a convenient and easy way to execute something asynchronously and in parallel.

Normally a Task is all you need, I cannot remember if I have ever used a thread for something else than experimentation.

You can accomplish the same with a thread (with lots of effort) as you can with a task.

Thread

int result = 0;
Thread thread = new System.Threading.Thread(() => { 
    result = 1; 
});
thread.Start();
thread.Join();
Console.WriteLine(result); //is 1

Task

int result = await Task.Run(() => {
    return 1; 
});
Console.WriteLine(result); //is 1

A task will by default use the Threadpool, which saves resources as creating threads can be expensive. You can see a Task as a higher level abstraction upon threads.

As this article points out, task provides following powerful features over thread.

  • Tasks are tuned for leveraging multicores processors.

  • If system has multiple tasks then it make use of the CLR thread pool internally, and so do not have the overhead associated with creating a dedicated thread using the Thread. Also reduce the context switching time among multiple threads.

  • Task can return a result.There is no direct mechanism to return the result from thread.
  • Wait on a set of tasks, without a signaling construct.

  • We can chain tasks together to execute one after the other.

  • Establish a parent/child relationship when one task is started from another task.

  • Child task exception can propagate to parent task.

  • Task support cancellation through the use of cancellation tokens.

  • Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.

Launch Bootstrap Modal on page load

In bootstrap 3 you just need to initialise the modal through js and if in the moment of the page load the modal markup is in the page the modal will show up.

In case you want to prevent this, use the option show: false where you initialise the modal. Something like this: $('.modal').modal({ show: false })

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The answer by Leos Literak is correct but now outdated, using one of the troublesome old date-time classes, java.sql.Timestamp.

tl;dr

it is really a DATETIME in the DB

Nope, it is not. No such data type as DATETIME in Oracle database.

I was looking for a getDateTime method.

Use java.time classes in JDBC 4.2 and later rather than troublesome legacy classes seen in your Question. In particular, rather than java.sql.TIMESTAMP, use Instant class for a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE.

Contrived code snippet:

if( 
    JDBCType.valueOf( 
        myResultSetMetaData.getColumnType( … )
    )
    .equals( JDBCType.TIMESTAMP_WITH_TIMEZONE ) 
) {
    Instant instant = myResultSet.getObject( … , Instant.class ) ;
}

Oddly enough, the JDBC 4.2 specification does not require support for the two most commonly used java.time classes, Instant and ZonedDateTime. So if your JDBC does not support the code seen above, use OffsetDateTime instead.

OffsetDateTime offsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;

Details

I would like to get the DATETIME column from an Oracle DB Table with JDBC.

According to this doc, there is no column data type DATETIME in the Oracle database. That terminology seems to be Oracle’s word to refer to all their date-time types as a group.

I do not see the point of your code that detects the type and branches on which data-type. Generally, I think you should be crafting your code explicitly in the context of your particular table and particular business problem. Perhaps this would be useful in some kind of generic framework. If you insist, read on to learn about various types, and to learn about the extremely useful new java.time classes built into Java 8 and later that supplant the classes used in your Question.

Smart objects, not dumb strings

valueToInsert = aDate.toString();

You appear to trying to exchange date-time values with your database as text, as String objects. Don’t.

To exchange date-time values with your database, use date-time objects. Now in Java 8 and later, that means java.time objects, as discussed below.

Various type systems

You may be confusing three sets of date-time related data types:

  • Standard SQL types
  • Proprietary types
  • JDBC types

SQL standard types

The SQL standard defines five types:

  • DATE
  • TIME WITHOUT TIME ZONE
  • TIME WITH TIME ZONE
  • TIMESTAMP WITHOUT TIME ZONE
  • TIMESTAMP WITH TIME ZONE

Date-only

  • DATE
    Date only, no time, no time zone.

Time-Of-Day-only

  • TIME or TIME WITHOUT TIME ZONE
    Time only, no date. Silently ignores any time zone specified as part of input.
  • TIME WITH TIME ZONE (or TIMETZ)
    Time only, no date. Applies time zone and Daylight Saving Time rules if sufficient data is included with input. Of questionable usefulness given the other data types, as discussed in Postgres doc.

Date And Time-Of-Day

  • TIMESTAMP or TIMESTAMP WITHOUT TIME ZONE
    Date and time, but ignores time zone. Any time zone information passed to the database is ignores with no adjustment to UTC. So this does not represent a specific moment on the timeline, but rather a range of possible moments over about 26-27 hours. Use this if the time zone or offset are (a) unknown or (b) irrelevant such as "All our factories around the world close at noon for lunch". If you have any doubts, not likely the right type.
  • TIMESTAMP WITH TIME ZONE (or TIMESTAMPTZ)
    Date and time with respect for time zone. Note that this name is something of a misnomer depending on the implementation. Some systems may store the given time zone info. In other systems such as Postgres the time zone information is not stored, instead the time zone information passed to the database is used to adjust the date-time to UTC.

Proprietary

Many database offer their own date-time related types. The proprietary types vary widely. Some are old, legacy types that should be avoided. Some are believed by the vendor to offer certain benefits; you decide whether to stick with the standard types only or not. Beware: Some proprietary types have a name conflicting with a standard type; I’m looking at you Oracle DATE.

JDBC

The Java platform's handles the internal details of date-time differently than does the SQL standard or specific databases. The job of a JDBC driver is to mediate between these differences, to act as a bridge, translating the types and their actual implemented data values as needed. The java.sql.* package is that bridge.

JDBC legacy classes

Prior to Java 8, the JDBC spec defined 3 types for date-time work. The first two are hacks as before Version 8, Java lacked any classes to represent a date-only or time-only value.

  • java.sql.Date
    Simulates a date-only, pretends to have no time, no time zone. Can be confusing as this class is a wrapper around java.util.Date which tracks both date and time. Internally, the time portion is set to zero (midnight UTC).
  • java.sql.Time
    Time only, pretends to have no date, and no time zone. Can also be confusing as this class too is a thin wrapper around java.util.Date which tracks both date and time. Internally, the date is set to zero (January 1, 1970).
  • java.sql.TimeStamp
    Date and time, but no time zone. This too is a thin wrapper around java.util.Date.

So that answers your question regarding no "getDateTime" method in the ResultSet interface. That interface offers getter methods for the three bridging data types defined in JDBC:

Note that the first lack any concept of time zone or offset-from-UTC. The last one, java.sql.Timestamp is always in UTC despite what its toString method tells you.

JDBC modern classes

You should avoid those poorly-designed JDBC classes listed above. They are supplanted by the java.time types.

  • Instead of java.sql.Date, use LocalDate. Suits SQL-standard DATE type.
  • Instead of java.sql.Time, use LocalTime. Suits SQL-standard TIME WITHOUT TIME ZONE type.
  • Instead of java.sql.Timestamp, use Instant. Suits SQL-standard TIMESTAMP WITH TIME ZONE type.

As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. Use setObject/getObject methods.

Insert/update.

myPreparedStatement.setObject( … , instant ) ;

Retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Adjusting time zone

If you want to see the moment of an Instant as viewed through the wall-clock time used by the people of a particular region (a time zone) rather than as UTC, adjust by applying a ZoneId to get a ZonedDateTime object.

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;

The resulting ZonedDateTime object is the same moment, the same simultaneous point on the timeline. A new day dawns earlier to the east, so the date and time-of-day will differ. For example, a few minutes after midnight in New Zealand is still “yesterday” in UTC.

You can apply yet another time zone to either the Instant or ZonedDateTime to see the same simultaneous moment through yet another wall-clock time used by people in some other region.

ZoneId zMontréal = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = zdtAuckland.withZoneSameInstant( zMontréal ) ;  // Or, for the same effect: instant.atZone( zMontréal ) 

So now we have three objects (instant, zdtAuckland, zMontréal) all representing the same moment, same point on the timeline.

Detecting type

To get back to the code in Question about detecting the data-type of the databases: (a) not my field of expertise, (b) I would avoid this as mentioned up top, and (c) if you insist on this, beware that as of Java 8 and later, the java.sql.Types class is outmoded. That class is now replaced by a proper Java Enum of JDBCType that implements the new interface SQLType. See this Answer to a related Question.

This change is listed in JDBC Maintenance Release 4.2, sections 3 & 4. To quote:

Addition of the java.sql.JDBCType Enum

An Enum used to identify generic SQL Types, called JDBC Types. The intent is to use JDBCType in place of the constants defined in Types.java.

The enum has the same values as the old class, but now provides type-safety.

A note about syntax: In modern Java, you can use a switch on an Enum object. So no need to use cascading if-then statements as seen in your Question. The one catch is that the enum object’s name must be used unqualified when switching for some obscure technical reason, so you must do your switch on TIMESTAMP_WITH_TIMEZONE rather than the qualified JDBCType.TIMESTAMP_WITH_TIMEZONE. Use a static import statement.

So, all that is to say that I guess (I’ve not tried yet) you can do something like the following code example.

final int columnType = myResultSetMetaData.getColumnType( … ) ;
final JDBCType jdbcType = JDBCType.valueOf( columnType ) ;

switch( jdbcType ) {  

    case DATE :  // FYI: Qualified type name `JDBCType.DATE` not allowed in a switch, because of an obscure technical issue. Use a `static import` statement.
        …
        break ;

    case TIMESTAMP_WITH_TIMEZONE :
        …
        break ;

    default :
        … 
        break ;

}

enter image description here


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. This section left intact as history.

Joda-Time

Prior to Java 8 (java.time.* package), the date-time classes bundled with java (java.util.Date & Calendar, java.text.SimpleDateFormat) are notoriously troublesome, confusing, and flawed.

A better practice is to take what your JDBC driver gives you and from that create Joda-Time objects, or in Java 8, java.time.* package. Eventually, you should see new JDBC drivers that automatically use the new java.time.* classes. Until then some methods have been added to classes such as java.sql.Timestamp to interject with java.time such as toInstant and fromInstant.

String

As for the latter part of the question, rendering a String… A formatter object should be used to generate a string value.

The old-fashioned way is with java.text.SimpleDateFormat. Not recommended.

Joda-Time provide various built-in formatters, and you may also define your own. But for writing logs or reports as you mentioned, the best choice may be ISO 8601 format. That format happens to be the default used by Joda-Time and java.time.

Example Code

//java.sql.Timestamp timestamp = resultSet.getTimestamp(i);
// Or, fake it 
// long m = DateTime.now().getMillis();
// java.sql.Timestamp timestamp = new java.sql.Timestamp( m );

//DateTime dateTimeUtc = new DateTime( timestamp.getTime(), DateTimeZone.UTC );
DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC ); // Defaults to now, this moment.

// Convert as needed for presentation to user in local time zone.
DateTimeZone timeZone = DateTimeZone.forID("Europe/Paris");
DateTime dateTimeZoned = dateTimeUtc.toDateTime( timeZone );

Dump to console…

System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeZoned: " + dateTimeZoned );

When run…

dateTimeUtc: 2014-01-16T22:48:46.840Z
dateTimeZoned: 2014-01-16T23:48:46.840+01:00

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

JavaScript pattern for multiple constructors

Answering because this question is returned first in google but the answers are now outdated.

You can use Destructuring objects as constructor parameters in ES6

Here's the pattern:

You can't have multiple constructors, but you can use destructuring and default values to do what you want.

export class myClass {

  constructor({ myArray = [1, 2, 3], myString = 'Hello World' }) {

    // ..
  }
}

And you can do this if you want to support a 'parameterless' constructor.

export class myClass {

      constructor({myArray = [1, 2, 3], myString = 'Hello World'} = {}) {

        // ..
      }
}

How can I find my Apple Developer Team id and Team Agent Apple ID?

You can find your team id here:

https://developer.apple.com/account/#/membership

This will get you to your Membership Details, just scroll down to Team ID

How to simulate "Press any key to continue?"

On Windows:

system("pause");

and on Mac and Linux:

system("read");

will output "Press any key to continue..." and obviously, wait for any key to be pressed. I hope thats what you meant

Java Convert GMT/UTC to Local time doesn't work as expected

tl;dr

Instant.now()                           // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() )       // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant()                            // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) )  // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant()                            // And back to UTC again.

java.time

The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date, Calendar, etc.).

Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.

Get the current system time (local time)

If you want to capture the current moment in UTC, use Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

Adjust into a time zone by applying a ZoneId to get a ZonedDateTime. Same moment, same point on the timeline, different wall-clock time.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

As a shortcut, you can skip the usage of Instant to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Convert Local time to UTC // Works Fine Till here

You can adjust from the zoned date-time to UTC by extracting an Instant from a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;

Reverse the UTC time, back to local time.

As shown above, apply a ZoneId to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).

Instant instant = Instant.now() ;  // Capture current moment in UTC.

ZoneId zDefault = ZoneId.systemDefault() ;  // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;

ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ;  // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;  // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;

Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.

Instant instant = zdtAuckland.toInstant() ;

All of these objects, the Instant and the three ZonedDateTime objects all represent the very same simultaneous moment, the same point in history.

Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.

Forget about trying to fix code using those awful Date, Calendar, and GregorianCalendar classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Bind service to activity in Android

There is a method called unbindService that will take a ServiceConnection which you will have created upon calling bindService. This will allow you to disconnect from the service while still leaving it running.

This may pose a problem when you connect to it again, since you probably don't know whether it's running or not when you start the activity again, so you'll have to consider that in your activity code.

Good luck!

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

CREATE TABLE GUESTS (
      GuestID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
      GuestLogID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestID INT, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

UICollectionView - dynamic cell height?

It worked for me, hope you too.

*Note: I have used auto layout in Nib, remember add top and bottom contraints for subviews in contentView

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
           let cell = YourCollectionViewCell.instantiateFromNib()
           cell.frame.size.width = collectionView.frame.width
           cell.data = viewModel.data[indexPath.item]
           let resizing = cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
           return resizing
    }

How to select all rows which have same value in some column

How about

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL Fiddle DEMO

How to handle invalid SSL certificates with Apache HttpClient?

From http://hc.apache.org/httpclient-3.x/sslguide.html:

Protocol.registerProtocol("https", 
new Protocol("https", new MySSLSocketFactory(), 443));
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.whatever.com/");
try {
  httpclient.executeMethod(httpget);
      System.out.println(httpget.getStatusLine());
} finally {
      httpget.releaseConnection();
}

Where MySSLSocketFactory example can be found here. It references a TrustManager, which you can modify to trust everything (although you must consider this!)

Center Oversized Image in Div

The width and height are only for example:

parentDiv{
    width: 100px;
    height: 100px;
    position:relative; 
}
innerDiv{
    width: 200px;
    height: 200px;
    position:absolute; 
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.

HTML5 Video // Completely Hide Controls

<video width="320" height="240" autoplay="autoplay">
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

iOS Swift - Get the Current Local Time and Date Timestamp

The simple way to create Current TimeStamp. like below,

func generateCurrentTimeStamp () -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
    return (formatter.string(from: Date()) as NSString) as String
}

The default for KeyValuePair

I recommend more understanding way using extension method:

public static class KeyValuePairExtensions
{
    public static bool IsNull<T, TU>(this KeyValuePair<T, TU> pair)
    {
        return pair.Equals(new KeyValuePair<T, TU>());
    }
}

And then just use:

var countries = new Dictionary<string, string>
{
    {"cz", "prague"},
    {"de", "berlin"}
};

var country = countries.FirstOrDefault(x => x.Key == "en");

if(country.IsNull()){

}

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Select N random elements from a List<T> in C#

Selecting N random items from a group shouldn't have anything to do with order! Randomness is about unpredictability and not about shuffling positions in a group. All the answers that deal with some kinda ordering is bound to be less efficient than the ones that do not. Since efficiency is the key here, I will post something that doesn't change the order of items too much.

1) If you need true random values which means there is no restriction on which elements to choose from (ie, once chosen item can be reselected):

public static List<T> GetTrueRandom<T>(this IList<T> source, int count, 
                                       bool throwArgumentOutOfRangeException = true)
{
    if (throwArgumentOutOfRangeException && count > source.Count)
        throw new ArgumentOutOfRangeException();

    var randoms = new List<T>(count);
    randoms.AddRandomly(source, count);
    return randoms;
}

If you set the exception flag off, then you can choose random items any number of times.

If you have { 1, 2, 3, 4 }, then it can give { 1, 4, 4 }, { 1, 4, 3 } etc for 3 items or even { 1, 4, 3, 2, 4 } for 5 items!

This should be pretty fast, as it has nothing to check.

2) If you need individual members from the group with no repetition, then I would rely on a dictionary (as many have pointed out already).

public static List<T> GetDistinctRandom<T>(this IList<T> source, int count)
{
    if (count > source.Count)
        throw new ArgumentOutOfRangeException();

    if (count == source.Count)
        return new List<T>(source);

    var sourceDict = source.ToIndexedDictionary();

    if (count > source.Count / 2)
    {
        while (sourceDict.Count > count)
            sourceDict.Remove(source.GetRandomIndex());

        return sourceDict.Select(kvp => kvp.Value).ToList();
    }

    var randomDict = new Dictionary<int, T>(count);
    while (randomDict.Count < count)
    {
        int key = source.GetRandomIndex();
        if (!randomDict.ContainsKey(key))
            randomDict.Add(key, sourceDict[key]);
    }

    return randomDict.Select(kvp => kvp.Value).ToList();
}

The code is a bit lengthier than other dictionary approaches here because I'm not only adding, but also removing from list, so its kinda two loops. You can see here that I have not reordered anything at all when count becomes equal to source.Count. That's because I believe randomness should be in the returned set as a whole. I mean if you want 5 random items from 1, 2, 3, 4, 5, it shouldn't matter if its 1, 3, 4, 2, 5 or 1, 2, 3, 4, 5, but if you need 4 items from the same set, then it should unpredictably yield in 1, 2, 3, 4, 1, 3, 5, 2, 2, 3, 5, 4 etc. Secondly, when the count of random items to be returned is more than half of the original group, then its easier to remove source.Count - count items from the group than adding count items. For performance reasons I have used source instead of sourceDict to get then random index in the remove method.

So if you have { 1, 2, 3, 4 }, this can end up in { 1, 2, 3 }, { 3, 4, 1 } etc for 3 items.

3) If you need truly distinct random values from your group by taking into account the duplicates in the original group, then you may use the same approach as above, but a HashSet will be lighter than a dictionary.

public static List<T> GetTrueDistinctRandom<T>(this IList<T> source, int count, 
                                               bool throwArgumentOutOfRangeException = true)
{
    if (count > source.Count)
        throw new ArgumentOutOfRangeException();

    var set = new HashSet<T>(source);

    if (throwArgumentOutOfRangeException && count > set.Count)
        throw new ArgumentOutOfRangeException();

    List<T> list = hash.ToList();

    if (count >= set.Count)
        return list;

    if (count > set.Count / 2)
    {
        while (set.Count > count)
            set.Remove(list.GetRandom());

        return set.ToList();
    }

    var randoms = new HashSet<T>();
    randoms.AddRandomly(list, count);
    return randoms.ToList();
}

The randoms variable is made a HashSet to avoid duplicates being added in the rarest of rarest cases where Random.Next can yield the same value, especially when input list is small.

So { 1, 2, 2, 4 } => 3 random items => { 1, 2, 4 } and never { 1, 2, 2}

{ 1, 2, 2, 4 } => 4 random items => exception!! or { 1, 2, 4 } depending on the flag set.

Some of the extension methods I have used:

static Random rnd = new Random();
public static int GetRandomIndex<T>(this ICollection<T> source)
{
    return rnd.Next(source.Count);
}

public static T GetRandom<T>(this IList<T> source)
{
    return source[source.GetRandomIndex()];
}

static void AddRandomly<T>(this ICollection<T> toCol, IList<T> fromList, int count)
{
    while (toCol.Count < count)
        toCol.Add(fromList.GetRandom());
}

public static Dictionary<int, T> ToIndexedDictionary<T>(this IEnumerable<T> lst)
{
    return lst.ToIndexedDictionary(t => t);
}

public static Dictionary<int, T> ToIndexedDictionary<S, T>(this IEnumerable<S> lst, 
                                                           Func<S, T> valueSelector)
{
    int index = -1;
    return lst.ToDictionary(t => ++index, valueSelector);
}

If its all about performance with tens of 1000s of items in the list having to be iterated 10000 times, then you may want to have faster random class than System.Random, but I don't think that's a big deal considering the latter most probably is never a bottleneck, its quite fast enough..

Edit: If you need to re-arrange order of returned items as well, then there's nothing that can beat dhakim's Fisher-Yates approach - short, sweet and simple..

jQuery - What are differences between $(document).ready and $(window).load?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  // executes when HTML-Document is loaded and DOM is ready_x000D_
  console.log("document is ready");_x000D_
});_x000D_
_x000D_
_x000D_
$(window).load(function() {_x000D_
  // executes when complete page is fully loaded, including all frames, objects and images_x000D_
  console.log("window is loaded");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Query 3.0 version

Breaking change: .load(), .unload(), and .error() removed

These methods are shortcuts for event operations, but had several API limitations. The event .load() method conflicted with the ajax .load() method. The .error() method could not be used with window.onerror because of the way the DOM method is defined. If you need to attach events by these names, use the .on() method, e.g. change $("img").load(fn) to $(img).on("load", fn).1

$(window).load(function() {});

Should be changed to

$(window).on('load', function (e) {})

These are all equivalent:

$(function(){
}); 

jQuery(document).ready(function(){
});

$(document).ready(function(){
});

$(document).on('ready', function(){
})

Why does PEP-8 specify a maximum line length of 79 characters?

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Would the use of <caption> be allowed?

<ul>
  <caption> Title of List </caption>
  <li> Item 1 </li>
  <li> Item 2 </li>
</ul>

How to access the request body when POSTing using Node.js and Express?

Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:

app.use(express.json())

Like this:

const express = require('express')

app.use(express.json())    // <==== parse request body as JSON

app.listen(8080)

app.post('/test', (req, res) => {
  res.json({requestBody: req.body})  // <==== req.body will be a parsed JSON object
})

Note - body-parser, on which this depends, is already included with express.

Also don't forget to send the header Content-Type: application/json

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

In scikit version 0.22, you can do it like this

from sklearn.metrics import multilabel_confusion_matrix

y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]

mcm = multilabel_confusion_matrix(y_true, y_pred,labels=["ant", "bird", "cat"])

tn = mcm[:, 0, 0]
tp = mcm[:, 1, 1]
fn = mcm[:, 1, 0]
fp = mcm[:, 0, 1]

No module named 'pymysql'

I had this same problem just now, and found the reason was my editor (Visual Studio Code) was running against the wrong instance of python; I had it set to run again python bundled with tensorflow, I changed it to my Anaconda python and it worked.

Output ("echo") a variable to a text file

Here is an easy one:

$myVar > "c:\myfilepath\myfilename.myextension"

You can also try:

Get-content "c:\someOtherPath\someOtherFile.myextension" > "c:\myfilepath\myfilename.myextension"

REACT - toggle class onclick

You can simply access the element classList which received the click event using event.target then by using toggle method on the classList object to add or remove the intended class

<div onClick={({target}) => target.classList.toggle('active')}>
  ....
  ....
  ....
</div>

Equevelent

<div onClick={e=> e.target.classList.toggle('active')}>
  ....
  ....
  ....
</div>

OR by declaring a function that handle the click and does extra work

function handleClick(el){
    .... Do more stuff
    el.classList.toggle('active');

}
<div onClick={({target})=> handleClick(target)}>
  ....
  ....
  ....
</div>

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

How to sort in mongoose?

This is how I managed to sort and populate:

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Create 3D array using Python

d3 = [[[0 for col in range(4)]for row in range(4)] for x in range(6)]

d3[1][2][1]  = 144

d3[4][3][0]  = 3.12

for x in range(len(d3)):
    print d3[x]



[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 144, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [3.12, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

What do these three dots in React do?

Kudos to Brandon Morelli. He explained perfectly here, but links may die so I am just pasting the content below:

The spread syntax is simply three dots: ... It allows an iterable to expand in places where 0+ arguments are expected. Definitions are tough without context. Let's explore some different use cases to help understand what this means.

Example #1 — Inserting Arrays Take a look at the code below. In this code, we don’t use the spread syntax:

_x000D_
_x000D_
var mid = [3, 4];_x000D_
var arr = [1, 2, mid, 5, 6];_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Above, we’ve created an array named mid. We then create a second array which contains our mid array. Finally, we log out the result. What do you expect arr to print? Click run above to see what happens. Here is the output:

[1, 2, [3, 4], 5, 6]

Is that the result you expected? By inserting the mid array into the arr array, we’ve ended up with an array within an array. That’s fine if that was the goal. But what if you want only a single array with the values of 1 through 6? To accomplish this, we can use the spread syntax! Remember, the spread syntax allows the elements of our array to expand. Lets look at the code below. Everything is the same — except we’re now using the spread syntax to insert the mid array into the arr array:

_x000D_
_x000D_
var mid = [3, 4];_x000D_
var arr = [1, 2, ...mid, 5, 6];_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

And when you hit the run button, here’s the result:

[1, 2, 3, 4, 5, 6]

Awesome! Remember the spread syntax definition you just read above? Here’s where it comes into play. As you can see, when we create the arr array and use the spread operator on the mid array, instead of just being inserted, the mid array expands. This expansion means that each and every element in the mid array is inserted into the arr array. Instead of nested arrays, the result is a single array of numbers ranging from 1 to 6.

Example #2 — Math JavaScript has a built in math object that allows us to do some fun math calculations. In this example we’ll be looking at Math.max(). If you’re unfamiliar, Math.max() returns the largest of zero or more numbers. Here are a few examples:

Math.max();
// -Infinity
Math.max(1, 2, 3);
// 3
Math.max(100, 3, 4);
// 100

As you can see, if you want to find the maximum value of multiple numbers, Math.max() requires multiple parameters. You unfortunately can’t simply use a single array as input. Before the spread syntax, the easiest way to use Math.max() on an array is to use .apply()

_x000D_
_x000D_
var arr = [2, 4, 8, 6, 0];_x000D_
_x000D_
function max(arr) {_x000D_
  return Math.max.apply(null, arr);_x000D_
}_x000D_
_x000D_
console.log(max(arr));
_x000D_
_x000D_
_x000D_

It works, it’s just really annoying. Now take a look at how we do the same exact thing with the spread syntax:

_x000D_
_x000D_
var arr = [2, 4, 8, 6, 0];_x000D_
var max = Math.max(...arr);_x000D_
_x000D_
console.log(max);
_x000D_
_x000D_
_x000D_

Instead of having to create a function and utilize the apply method to return the result of Math.max() , we only need two lines of code! The spread syntax expands our array elements and inputs each element in our array individually into the Math.max() method!

Example #3 — Copy an Array In JavaScript, you can’t just copy an array by setting a new variable equal to already existing array. Consider the following code example:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = arr;_x000D_
_x000D_
console.log(arr2);
_x000D_
_x000D_
_x000D_

When you press run, you’ll get the following output:

['a', 'b', 'c']

Now, at first glance, it looks like it worked — it looks like we’ve copied the values of arr into arr2. But that’s not what has happened. You see, when working with objects in javascript (arrays are a type of object) we assign by reference, not by value. This means that arr2 has been assigned to the same reference as arr. In other words, anything we do to arr2 will also affect the original arr array (and vice versa). Take a look below:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = arr;_x000D_
_x000D_
arr2.push('d');_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Above, we’ve pushed a new element d into arr2. Yet, when we log out the value of arr, you’ll see that the d value was also added to that array:

['a', 'b', 'c', 'd']

No need to fear though! We can use the spread operator! Consider the code below. It’s almost the same as above. Instead though, we’ve used the spread operator within a pair of square brackets:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
console.log(arr2);
_x000D_
_x000D_
_x000D_

Hit run, and you’ll see the expected output:

['a', 'b', 'c']

Above, the array values in arr expanded to become individual elements which were then assigned to arr2. We can now change the arr2 array as much as we’d like with no consequences on the original arr array:

_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
var arr2 = [...arr];_x000D_
_x000D_
arr2.push('d');_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Again, the reason this works is because the value of arr is expanded to fill the brackets of our arr2 array definition. Thus, we are setting arr2 to equal the individual values of arr instead of the reference to arr like we did in the first example.

Bonus Example — String to Array As a fun final example, you can use the spread syntax to convert a string into an array. Simply use the spread syntax within a pair of square brackets:

_x000D_
_x000D_
var str = "hello";_x000D_
var chars = [...str];_x000D_
_x000D_
console.log(chars);
_x000D_
_x000D_
_x000D_

Copy table to a different database on a different SQL Server

Generate the scripts?

Generate a script to create the table then generate a script to insert the data.

check-out SP_ Genereate_Inserts for generating the data insert script.

git visual diff between branches

UPDATE

Mac: I now use SourceTree. Thoroughly recommended. I especially like the way you can stage / unstage hunks.

Linux: I've had success with:

  • smartgit
  • GitKraken
  • meld

E.g. to install smartgit on Ubuntu:


This does the job:

git-diffall with a GUI diff tool like meld. See point 5 here:

http://rubyglazed.com/post/15772234418/git-ify-your-command-line

There's a nice post about git and meld here: http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

Reverse order of foreach list items

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

Error:(1, 0) Plugin with id 'com.android.application' not found

This just happened to me using Android Studio 1.3.2, however, since I had just created the project, I deleted it and created it again.
It seems that it had not been properly created by Android Studio the first time, not even the project folders where as expected.

Removing empty lines in Notepad++

It's very Simple ## No need of any extra plugin

You know what, now Notepad ++ has inbuilt functionality to do so...

  1. Open EDIT Menu by: Alt+E > Press down Arrow > Line Operations > Remove Empty Lines

Remove_Emplty_Lines

  1. Other Option is to use Replace press: ctrl + H

Find : \r\n\r\n

Replcate with : \r\n

Remove_by_Replace

How to use XMLReader in PHP?

Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.

I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?

The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {... - which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.

function parseMyXML ($xml) { //pass in an XML string
    $myXML = new XMLReader();
    $myXML->xml($xml);

    while ($myXML->read()) { //start reading.
        if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
            $tag = $myXML->name; //make $tag contain the name of the tag
            switch ($tag) {
                case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
                    $variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
                    break;

                case 'Tag2': //this tag contains child elements, of which we only want one.
                    while($myXML->read()) { //so we tell it to keep reading
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
                            $variable2 = $myXML->readInnerXML(); //...put it in $variable2. 
                            break;
                        }
                    }
                    break;

                case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
                    while($myXML->read()) {
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
                            $variable3 = $myXML->readInnerXML();
                            break;
                        } else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
                            $variable4 = $myXML->readInnerXML();
                            break;
                        }
                    }
                    break;

            }
        }
    }
$myXML->close();
}

How to convert numbers to words without using num2word library?

Your first statement logic is incorrect. Unless Number is 1 or smaller, that statement is always True; 200 is greater than 1 as well.

Use and instead, and include 1 in the acceptable values:

if (Number >= 1) and (Number <= 19):

You could use chaining as well:

if 1 <= Number <= 19:

For numbers of 20 or larger, use divmod() to get both the number of tens and the remainder:

tens, remainder = divmod(Number, 10)

Demo:

>>> divmod(42, 10)
(4, 2)

then use those values to build your number from the parts:

return num2words2[tens - 2] + '-' + num2words1[below_ten]

Don't forget to account for cases when the number is above 20 and doesn't have a remainder from the divmod operation:

return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]

All put together:

def number(Number):
    if 0 <= Number <= 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, remainder = divmod(Number, 10)
        return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
    else:
        print('Number out of implemented range of numbers.')

Efficient way to rotate a list in python

def solution(A, K):
    if len(A) == 0:
        return A

    K = K % len(A)

    return A[-K:] + A[:-K]

# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))

For example, given

A = [3, 8, 9, 7, 6]
K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

For another example, given

A = [0, 0, 0]
K = 1

the function should return [0, 0, 0]

Given

A = [1, 2, 3, 4]
K = 4

the function should return [1, 2, 3, 4]

Laravel form html with PUT method for PUT routes

You CAN add css clases, and any type of attributes you need to blade template, try this:

{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}

If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:

Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)

<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">

    <!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->

    <input name="_method" type="hidden" value="PUT">

    <div class="form-group">
        <textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
    </div>
</form>

Getting the error "Missing $ inserted" in LaTeX

In my code, when I got the error, I checked the possible source, In a line, I had typed a beginning \[ and an ending \] due to which the error of missing $ appeared though I tried using $ for both the brackets. Removing the brackets or using $[$ instead of $\[$ solved my problem. If you've something like that, try altering.

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Base64 Java encode and decode a string

The following is a good solution -

import android.util.Base64;

String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);

String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));

That's it. A single line encoding and decoding.

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

Permission denied on CopyFile in VBS

for me adding / worked at the end of location of folder. Hence, if you are copying into folder, don't forget to put /

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

test attribute in JSTL <c:if> tag

All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

<c:if test="true">Hello world!</c:if>

The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

How to execute a MySQL command from a shell script?

To "automate" the process of importing the generated .sql file, while avoiding all the traps that can be hidden in trying to pass files through stdin and stdout, just tell MySQL to execute the generated .sql file using the SOURCE command in MySQL.

The syntax in the short, but excellent, answer, from Kshitij Sood, gives the best starting point. In short, modify the OP's command according to Kshitij Sood's syntax and replace the commands in that with the SOURCE command:

#!/bin/bash
mysql -u$user -p$password $dbname -Bse "SOURCE ds_fbids.sql
SOURCE ds_fbidx.sql"

If the database name is included in the generated .sql file, it can be dropped from the command.

The presumption here is that the generated file is valid as an .sql file on its own. By not having the file redirected, piped, or in any other manner handled by the shell, there is no issue with needing to escape any of the characters in the generated output because of the shell. The rules with respect to what needs to be escaped in an .sql file, of course, still apply.

How to deal with the security issues around the password on the command line, or in a my.cnf file, etc., has been well addressed in other answers, with some excellent suggestions. My favorite answer, from Danny, covers that, including how to handle the issue when dealing with cron jobs, or anything else.


To address a comment (question?) on the short answer I mentioned: No, it cannot be used with a HEREDOC syntax, as that shell command is given. HEREDOC can be used in the redirection version syntax, (without the -Bse option), since I/O redirection is what HEREDOC is built around. If you need the functionality of HEREDOC, it would be better to use it in the creation of a .sql file, even if it's a temporary one, and use that file as the "command" to execute with the MySQL batch line.

#!/bin/bash
cat >temp.sql <<SQL_STATEMENTS
...
SELECT \`column_name\` FROM \`table_name\` WHERE \`column_name\`='$shell_variable';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Bear in mind that because of shell expansion you can use shell and environment variables within the HEREDOC. The down-side is that you must escape each and every backtick. MySQL uses them as the delimiters for identifiers but the shell, which gets the string first, uses them as executable command delimiters. Miss the escape on a single backtick of the MySQL commands, and the whole thing explodes with errors. The whole issue can be solved by using a quoted LimitString for the HEREDOC:

#!/bin/bash
cat >temp.sql <<'SQL_STATEMENTS'
...
SELECT `column_name` FROM `table_name` WHERE `column_name`='constant_value';
...
SQL_STATEMENTS
mysql -u $user -p$password $db_name -Be "SOURCE temp.sql"
rm -f temp.sql

Removing shell expansion that way eliminates the need to escape the backticks, and other shell-special characters. It also removes the ability to use shell and environment variables within it. That pretty much removes the benefits of using a HEREDOC inside the shell script to begin with.

The other option is to use the multi-line quoted strings allowed in Bash with the batch syntax version (with the -Bse). I don't know other shells, so I cannot say if they work therein as well. You would need to use this for executing more than one .sql file with the SOURCE command anyway, since that is not terminated by a ; as other MySQL commands are, and only one is allowed per line. The multi-line string can be either single or double quoted, with the normal effects on shell expansion. It also has the same caveats as using the HEREDOC syntax does for backticks, etc.

A potentially better solution would be to use a scripting language, Perl, Python, etc., to create the .sql file, as the OP did, and SOURCE that file using the simple command syntax at the top. The scripting languages are much better at string manipulation than the shell is, and most have in-built procedures to handle the quoting and escaping needed when dealing with MySQL.

Meaning of Choreographer messages in Logcat

I'm late to the party, but hopefully this is a useful addition to the other answers here...

Answering the Question / tl:dr;

I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.

The following are all candidates:

  • IO or expensive processing on the main thread (loading drawables, inflating layouts, and setting Uri's on ImageView's all constitute IO on the main thread)
  • Rendering large/complex/deep View hierarchies
  • Invalidating large portions of a View hierarchy
  • Expensive onDraw methods in custom View's
  • Expensive calculations in animations
  • Running "worker" threads at too high a priority to be considered "background" (AsyncTask's are "background" by default, java.lang.Thread is not)
  • Generating lots of garbage, causing the garbage collector to "stop the world" - including the main thread - while it cleans up

To actually determine the specific cause you'll need to profile your app.

More Detail

I've been trying to understand Choreographer by experimenting and looking at the code.

The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.

The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:

  1. input-handling callbacks (handling user-input such as touch events)
  2. animation callbacks for tweening between frames, supplying a stable frame-start-time to any/all animations that are running. Running these callbacks 2nd means any animation-related calculations (e.g. changing positions of View's) have already been made by the time the third type of callback is invoked...
  3. view traversal callbacks for drawing the view hierarchy.

The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.

The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.

From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View hierarchy or a View with a complicated onDraw method might be enough.

For example this will trigger the warning repeatedly:

public class AnnoyTheChoreographerActivity extends Activity {

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

        setContentView(R.layout.simple_linear_layout);

        ViewGroup root = (ViewGroup) findViewById(R.id.root);

        root.addView(new TextView(this){
            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                long sleep = (long)(Math.random() * 1000L);
                setText("" + sleep);
                try {
                    Thread.sleep(sleep);
                } catch (Exception exc) {}
            }
        });
    }
}

... which produces logging like this:

11-06 09:35:15.865  13721-13721/example I/Choreographer? Skipped 42 frames!  The application may be doing too much work on its main thread.
11-06 09:35:17.395  13721-13721/example I/Choreographer? Skipped 59 frames!  The application may be doing too much work on its main thread.
11-06 09:35:18.030  13721-13721/example I/Choreographer? Skipped 37 frames!  The application may be doing too much work on its main thread.

You can see from the stack during onDraw that the choreographer is involved regardless of whether you are animating:

at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)

... quite a bit of repetition ...

at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)

Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.

In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.

How can I open a popup window with a fixed size using the HREF tag?

Plain HTML does not support this. You'll need to use some JavaScript code.

Also, note that large parts of the world are using a popup blocker nowadays. You may want to reconsider your design!

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Mockito, JUnit and Spring

The difference in whether you have to instantiate your @InjectMocks annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks. In 1.9, which will also handle some constructor injection of your @Mock fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.

This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.

And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.

Running a command in a new Mac OS X Terminal window

You could also invoke the new command feature of Terminal by pressing the Shift + ? + N key combination. The command you put into the box will be run in a new Terminal window.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How to configure nginx to enable kinda 'file browser' mode?

I've tried many times.

And at last I just put autoindex on; in http but outside of server, and it's OK.

List of IP Space used by Facebook

The list from 2020-05-23 is:

31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22

The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

whois -h whois.radb.net -- '-i origin AS32934' | grep ^route

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

Find the version of an installed npm package

I just used

npm list | grep <package name>

and it worked great

On windows run:

npm list | find <package name>

In PowerShell run:

npm list | sls <package name>

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

How do I filter ForeignKey choices in a Django ModelForm?

So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.

I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.

This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...

I've got these classes:

# models.py
class Company(models.Model):
    # ...
class Contract(models.Model):
    company = models.ForeignKey(Company)
    locations = models.ManyToManyField('Location')
class Location(models.Model):
    company = models.ForeignKey(Company)

This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.

In short, I would need some admin option to do something like this:

# admin.py
class LocationInline(admin.TabularInline):
    model = Location
class ContractInline(admin.TabularInline):
    model = Contract
class CompanyAdmin(admin.ModelAdmin):
    inlines = (ContractInline, LocationInline)
    inline_filter = dict(Location__company='self')

Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)

Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

Create an environment.plist file in ~/Library/LaunchAgents/ with this content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>my.startup</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>
    launchctl setenv PRODUCTS_PATH /Users/mortimer/Projects/my_products
    launchctl setenv ANDROID_NDK_HOME /Applications/android-ndk
    launchctl setenv PATH $PATH:/Applications/gradle/bin
    </string>

  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

You can add many launchctl commands inside the <string></string> block.

The plist will activate after system reboot. You can also use launchctl load ~/Library/LaunchAgents/environment.plist to launch it immediately.

[Edit]

The same solution works in El Capitan too.

Xcode 7.0+ doesn't evaluate environment variables by default. The old behaviour can be enabled with this command:

defaults write com.apple.dt.Xcode UseSanitizedBuildSystemEnvironment -bool NO

[Edit]

There a couple of situations where this doesn't quite work. If the computer is restarted and "Reopen windows when logging back in" is selected, the reopened windows may not see the variables (Perhaps they are opened before the agent is run). Also, if you log in via ssh, the variables will not be set (so you'll need to set them in ~/.bash_profile). Finally, this doesn't seem to work for PATH on El Capitan and Sierra. That needs to be set via 'launchctl config user path ...' and in /etc/paths.

Unsupported major.minor version 52.0 in my app

I had two versions of java jdk installed. Once I pointed to right version of java jdk in File->Project Structure -> SDK Location to the latest version which I had in JAVA_HOME environment variable, the issue went away.

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

Convert HH:MM:SS string to seconds only in javascript

Convert hh:mm:ss string to seconds in one line. Also allowed h:m:s format and mm:ss, m:s etc

'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

I had the same problem because I set the following in Catalina.sh of my tomcat:

JAVA_OPTS="$JAVA_OPTS -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999" 

After removing it, my tomcat worked well.

Hope help you.

Force sidebar height 100% using CSS (with a sticky bottom image)?

i guess, today one would probably use flexbox for this. See the holy grail example.

Using CookieContainer with WebClient class

Yes. IMHO, overriding GetWebRequest() is the best solution to WebClient's limited functionalty. Before I knew about this option, I wrote lots of really painful code at the HttpWebRequest layer because WebClient almost, but not quite, did what I needed. Derivation is much easier.

Another option is to use the regular WebClient class, but manually populate the Cookie header before making the request and then pull out the Set-Cookies header on the response. There are helper methods on the CookieContainer class which make creating and parsing these headers easier: CookieContainer.SetCookies() and CookieContainer.GetCookieHeader(), respectively.

I prefer the former approach since it's easier for the caller and requires less repetitive code than the second option. Also, the derivation approach works the same way for multiple extensibility scenarios (e.g. cookies, proxies, etc.).

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

Convert a Pandas DataFrame to a dictionary

Try to use Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

Output:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

How to use FormData for AJAX file upload?

$(document).ready(function () {
    $(".submit_btn").click(function (event) {
        event.preventDefault();
        var form = $('#fileUploadForm')[0];
        var data = new FormData(form);
        data.append("CustomField", "This is some extra data, testing");
        $("#btnSubmit").prop("disabled", true);
        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "upload.php",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {
                console.log();
            },
        });
    });
});

How to find out what character key is pressed?

document.onkeypress = function(event){
    alert(event.key)
}

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

How can I count the rows with data in an Excel sheet?

This is what I finally came up with, which works great!

{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}

Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.

Hiding axis text in matplotlib plots

Instead of hiding each element, you can hide the whole axis:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

Or, you can set the ticks to an empty list:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.

How to return an array from a function?

"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"

template <class X>
  class Array
{
  X     *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(X* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new X [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(X));
            return m_size;
        }
       return 0;
    }
}; 

just for int

class IntArray
{
  int   *m_data;
  int    m_size;
public:
    // there constructor, destructor, some methods
    int Get(int* &_null_pointer)
    {
        if(!_null_pointer)
        {
            _null_pointer = new int [m_size];
            memcpy(_null_pointer, m_data, m_size * sizeof(int));
            return m_size;
        }
       return 0;
    }
}; 

example

Array<float> array;
float  *n_data = NULL;
int     data_size;
if(data_size = array.Get(n_data))
{     // work with array    }

delete [] n_data;

example for int

IntArray   array;
int       *n_data = NULL;
int        data_size;
if(data_size = array.Get(n_data))
{  // work with array  }

delete [] n_data;

Increment a Integer's int value?

AtomicInteger

Maybe this is of some worth also: there is a Java class called AtomicInteger.

This class has some useful methods like addAndGet(int delta) or incrementAndGet() (and their counterparts) which allow you to increment/decrement the value of the same instance. Though the class is designed to be used in the context of concurrency, it's also quite useful in other scenarios and probably fits your need.

final AtomicInteger count = new AtomicInteger( 0 ) ;
…
count.incrementAndGet();  // Ignoring the return value. 

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Valid characters of a hostname?

Checkout this wiki, specifically the section Restrictions on valid host names

Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Excel: last character/string match in a string

In newer versions of Excel (2013 and up) flash fill might be a simple and quick solution see: Using Flash Fill in Excel .

How to access a dictionary key value present inside a list?

You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get 'd'

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present

mylist[1]['d']

"RangeError: Maximum call stack size exceeded" Why?

Browsers can't handle that many arguments. See this snippet for example:

alert.apply(window, new Array(1000000000));

This yields RangeError: Maximum call stack size exceeded which is the same as in your problem.

To solve that, do:

var arr = [];
for(var i = 0; i < 1000000; i++){
    arr.push(Math.random());
}

Maven not found in Mac OSX mavericks

  1. Download Maven from here.
  2. Extract the tar.gz you just downloaded to the location you want (ex:/Users/admin/Maven).
  3. Open the Terminal.
  4. Type " cd " to go to your home folder.
  5. Type "touch .bash_profile".
  6. Type "open -e .bash_profile" to open .bash_profile in TextEdit.
  7. Type the following in the TextEditor

alias mvn='/[Your file location]/apache-maven-x.x.x/bin/mvn'
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdkx.x.x_xx.jdk/Contents/Home/

(Make sure there are no speech marks or apostrophe's) 8. Make sure you fill the required data (ex your file location and version number).

  1. Save your changes
  2. Type ". .bash_profile" to reload .bash_profile and update any functions you add. (*make sure you separate the dots with a single space).
  3. Type mvn -version

If successful you should see the following:

Apache Maven 3.1.1
Maven home: /Users/admin/Maven/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.9.1", arch: "x86_64", family: "mac"

What does asterisk * mean in Python?

See Function Definitions in the Language Reference.

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

Also, see Function Calls.

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

Example 1:

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

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

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

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

Example 2:

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

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

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

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

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

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

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

Prints:

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

And

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

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

Prints:

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

Map enum in JPA with fixed values?

I would do the folowing:

Declare separetly the enum, in it´s own file:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { this.value = value; }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

Declare a new JPA entity named Right

@Entity
public class Right{
    @Id
    private Integer id;
    //FIElDS

    // constructor
    public Right(RightEnum rightEnum){
          this.id = rightEnum.getValue();
    }

    public Right getInstance(RightEnum rightEnum){
          return new Right(rightEnum);
    }


}

You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)

import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 
 * 
 */
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{

    @Override //this method shoudn´t be used, but I implemented anyway, just in case
    public Integer convertToDatabaseColumn(RightEnum attribute) {
        return attribute.getValue();
    }

    @Override
    public RightEnum convertToEntityAttribute(Integer dbData) {
        return RightEnum.valueOf(dbData);
    }

}

The Authority entity:

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;

  // the **Entity** to map : 
  private Right right;

  // the **Enum** to map (not to be persisted or updated) : 
  @Column(name="COLUMN1", insertable = false, updatable = false)
  @Convert(converter = RightEnumConverter.class)
  private RightEnum rightEnum;

}

By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using

autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example

And if you need to compare, you can use:

authority.getRight().equals( RightEnum.READ ); //for example

Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.


However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).

Let´s see.

The RightEnum:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { 
            try {
                  this.value= value;
                  final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
                  field.setAccessible(true);
                  field.set(this, value);
             } catch (Exception e) {//or use more multicatch if you use JDK 1.7+
                  throw new RuntimeException(e);
            }
      }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

and the Authority entity

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;


  // the **Enum** to map (to be persisted or updated) : 
  @Column(name="COLUMN1")
  @Enumerated(EnumType.ORDINAL)
  private RightEnum rightEnum;

}

In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.

I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.

C: socket connection timeout

The answers about using select()/poll() are right and code should be written this way to be portable.

However, since you're on Linux, you can do this:

int synRetries = 2; // Send a total of 3 SYN packets => Timeout ~7s
setsockopt(fd, IPPROTO_TCP, TCP_SYNCNT, &synRetries, sizeof(synRetries));

See man 7 tcp and man setsockopt.

I used this to speed up the connect-timeout in a program I needed to patch quickly. Hacking it to timeout via select()/poll() was not an option.

Should I make HTML Anchors with 'name' or 'id'?

ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.

Center a popup window on screen?

This would work out based on your screen size

<html>
<body>
<button onclick="openfunc()">Click here to open window at center</button>
<script>
function openfunc() {
windowWidth = 800;
windowHeight = 720;
 var left = (screen.width - windowWidth) / 2;
            var top = (screen.height - windowHeight) / 4;
            var myWindow = window.open("https://www.google.com",'_blank','width=' + windowWidth + ', height=' + windowHeight + ', top=' + top + ', left=' + left);
}
</script>
</body>
</html>

Why do people write #!/usr/bin/env python on the first line of a Python script?

It tells the interpreter which version of python to run the program with when you have multiple versions of python.

HTML if image is not found

The best way to solve your problem:

<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.src='Default.jpg'" alt="" width="100" height="120">

onerror is a good thing for you :)

Just change the image file name and try yourself.

strdup() - what does it do in C?

Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it duplicates strings :-)

Keeping in mind it's actually not part of the ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:

char *strdup(const char *src) {
    char *dst = malloc(strlen (src) + 1);  // Space for length plus nul
    if (dst == NULL) return NULL;          // No memory
    strcpy(dst, src);                      // Copy the characters
    return dst;                            // Return the new string
}

In other words:

  1. It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).

  2. If the allocation failed, it sets errno to ENOMEM and returns NULL immediately. Setting of errno to ENOMEM is something malloc does in POSIX so we don't need to explicitly do it in our strdup. If you're not POSIX compliant, ISO C doesn't actually mandate the existence of ENOMEM so I haven't included that here(b).

  3. Otherwise the allocation worked so we copy the old string to the new string(c) and return the new address (which the caller is responsible for freeing at some point).

Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.


(a) However, functions starting with str and a lower case letter are reserved by the standard for future directions. From C11 7.1.3 Reserved identifiers:

Each header declares or defines all identifiers listed in its associated sub-clause, and *optionally declares or defines identifiers listed in its associated future library directions sub-clause.**

The future directions for string.h can be found in C11 7.31.13 String handling <string.h>:

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

So you should probably call it something else if you want to be safe.


(b) The change would basically be replacing if (d == NULL) return NULL; with:

if (d == NULL) {
    errno = ENOMEM;
    return NULL;
}

(c) Note that I use strcpy for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use memcpy, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".

In any case, should you decide to go that route, you would do something like:

char *strdup(const char *src) {
    size_t len = strlen(src) + 1;       // String plus '\0'
    char *dst = malloc(len);            // Allocate space
    if (dst == NULL) return NULL;       // No memory
    memcpy (dst, src, len);             // Copy the block
    return dst;                         // Return the new string
}

Eclipse Java Missing required source folder: 'src'

Go to the Build Path dialog (right-click project > Build Path > Configure Build Path) and make sure you have the correct source folder listed, and make sure it exists.

The source folder is the one that holds your sources, usuglaly in the form: project/src/com/yourpackage/...

ALTER COLUMN in sqlite

There's no ALTER COLUMN in sqlite.

I believe your only option is to:

  • Rename the table to a temporary name
  • Create a new table without the NOT NULL constraint
  • Copy the content of the old table to the new one
  • Remove the old table

This other Stackoverflow answer explains the process in details

How to see JavaDoc in IntelliJ IDEA?

For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I was having the exact same problem. I considered the answer @Snarfblam provided; however, if you read the documentation on MSDN, the ProcessCMDKey method is meant to override key events for menu items in an application.

I recently stumbled across this article from microsoft, which looks quite promising: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx. According to microsoft, the best thing to do is set e.IsInputKey=true; in the PreviewKeyDown event after detecting the arrow keys. Doing so will fire the KeyDown event.

This worked quite well for me and was less hack-ish than overriding the ProcessCMDKey.

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

android.view.InflateException: Binary XML file: Error inflating class fragment

This error is really confusing. In my case I was missing a default empty parameter less constructor for my fragment. After adding empty constructor in my fragment the problem resolved.

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

How to change the height of a <br>?

Css:

br {
   display: block;
   margin: 10px 0;
}

The solution is probably not cross-browser compatible, but it's something at least. Also consider setting line-height:

line-height:22px;

For Google Chrome, consider setting content:

content: " ";

Other than that, I think you're stuck with a JavaScript solution.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

How to create a remote Git repository from a local one?

I think you make a bare repository on the remote side, git init --bare, add the remote side as the push/pull tracker for your local repository (git remote add origin URL), and then locally you just say git push origin master. Now any other repository can pull from the remote repository.

Capturing image from webcam in java?

http://grack.com/downloads/school/enel619.10/report/java_media_framework.html

Using the Player with Swing

The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:

import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.event.*;

public class JMFTest extends JFrame {
    Player _player;
    JMFTest() {
        addWindowListener( new WindowAdapter() {
            public void windowClosing( WindowEvent e ) {
                _player.stop();
                _player.deallocate();
                _player.close();
                System.exit( 0 );
            }
        });
          setExtent( 0, 0, 320, 260 );
        JPanel panel = (JPanel)getContentPane();
        panel.setLayout( new BorderLayout() );
        String mediaFile = "vfw://1";
        try {
            MediaLocator mlr = new MediaLocator( mediaFile );
            _player = Manager.createRealizedPlayer( mlr );
            if (_player.getVisualComponent() != null)
            panel.add("Center", _player.getVisualComponent());
            if (_player.getControlPanelComponent() != null)
            panel.add("South", _player.getControlPanelComponent());
        }
        catch (Exception e) {
            System.err.println( "Got exception " + e );
        }
    }

    public static void main(String[] args) {
        JMFTest jmfTest = new JMFTest();
        jmfTest.show();
    }
}

SQL Server : Transpose rows to columns

I had a slightly different requirement, whereby I had to selectively transpose columns into rows.

The table had columns:

create table tbl (ID, PreviousX, PreviousY, CurrentX, CurrentY)

I needed columns for Previous and Current, and rows for X and Y. A Cartesian product generated on a static table worked nicely, eg:

select 
    ID,
    max(case when metric='X' then PreviousX
        case when metric='Y' then PreviousY end) as Previous,
    max(case when metric='X' then CurrentX
        case when metric='Y' then CurrentY end) as Current
from tbl inner join
    /* Cartesian product - transpose by repeating row and 
    picking appropriate metric column for period */
    ( VALUES (1, 'X'), (2, 'Y')) AS x (sort, metric) ON 1=1
group by ID
order by ID, sort

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

Android SDK installation doesn't find JDK

Actual SETUP:

  • OS: Windows 8.1
  • JDK file: jdk-8u11-windows-x64.exe
  • ADT file: installer_r23.0.2-windows.exe

Install the x64 JDK, and try the back-next option first, and then try setting JAVA_HOME like the error message says, but if that doesn't work for you either, then try this:

Do as it says, set JAVA_HOME in your environment variables, but in the path use forward slashes instead of backslashes.

Seriously.

For me it failed when JAVA_HOME was C:\Program Files\Java\jdk1.6.0_31 but worked fine when it was C:/Program Files/Java/jdk1.6.0_31 - drove me nuts!

If this is not enough, also add to the beginning of the Environment Variable Path %JAVA_HOME%;

Updated values in System Environment Variables:

  • JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11
  • JRE_HOME=C:/Program Files/Java/jre8
  • Path=%JAVA_HOME%;C:...

How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

Private WithEvents Items As Outlook.Items 
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub
Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 
  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' do something here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

After pasting the code in ThisOutlookSession module, you must restart Outlook.

How to use Select2 with JSON via Ajax request?

This is how I fixed my issue, I am getting data in data variable and by using above solutions I was getting error could not load results. I had to parse the results differently in processResults.

searchBar.select2({
            ajax: {
                url: "/search/live/results/",
                dataType: 'json',
                headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                delay: 250,
                type: 'GET',
                data: function (params) {
                    return {
                        q: params.term, // search term
                    };
                },
                processResults: function (data) {
                    var arr = []
                    $.each(data, function (index, value) {
                        arr.push({
                            id: index,
                            text: value
                        })
                    })
                    return {
                        results: arr
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; },
            minimumInputLength: 1
        });

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Breaking/exit nested for in vb.net

If I want to exit a for-to loop, I just set the index beyond the limit:

    For i = 1 To max
        some code
        if this(i) = 25 Then i = max + 1
        some more code...
    Next`

Poppa.

Simple example of threading in C++

It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:

class RThread : public wxThread {

public:
    RThread()
        : wxThread(wxTHREAD_JOINABLE){
    }
private:
    RThread(const RThread &copy);

public:
    void *Entry(void){
        //Do...

        return 0;
    }

};

wxThread *CreateThread() {
    //Create thread
    wxThread *_hThread = new RThread();

    //Start thread
    _hThread->Create();
    _hThread->Run();

    return _hThread;
}

If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it. More info here: wxThread documentation

Adding elements to object

push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below

var lastIndex = Object.keys(element)[Object.keys(element).length-1];

then add object to the new index of element

element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ ]] has more features - I suggest you take a look at the Advanced Bash Scripting Guide for more info, specifically the extended test command section in Chapter 7. Tests.

Incidentally, as the guide notes, [[ ]] was introduced in ksh88 (the 1988 version of the Korn shell).

What does MVW stand for?

I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.

It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.

In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.

I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

The answer is above by Ross.

Firstly, putting session_start() as the first line of code will mean that you cannot deserialise any objects correctly into session variables.

The reason for getting this issue is 99% likely to be trailing spaces at the end of your include files (yes - I know it sounds unlikely but just try it). The offending file is in the error message. I wanted to back up Ross answer which worked for me but this site is counter intuitive.

IGNORE the nonsense answers. Remove the trailing spaces, newlines etc... and all will be well. ROSS knows what he is talking about. Putting session_start() at the top of your file DOES work but it isnt the correct solution.

Count number of rows by group using dplyr

Another option, not necesarily more elegant, but does not require to refer to a specific column:

mtcars %>% 
  group_by(cyl, gear) %>%
  do(data.frame(nrow=nrow(.)))

Representing Directory & File Structure in Markdown Syntax

If you're using Atom editor, you can accomplish this by the ascii-tree package.

You can write the following tree:

root
+-- dir1
    +--file1
+-- dir2
    +-- file2

and convert it to the following by selecting it and pressing ctrl-alt-t:

root
+-- dir1
¦   +-- file1
+-- dir2
    +-- file2

Best practice for using assert?

The only thing that's really wrong with this approach is that it's hard to make a very descriptive exception using assert statements. If you're looking for the simpler syntax, remember you can also do something like this:

class XLessThanZeroException(Exception):
    pass

def CheckX(x):
    if x < 0:
        raise XLessThanZeroException()

def foo(x):
    CheckX(x)
    #do stuff here

Another problem is that using assert for normal condition-checking is that it makes it difficult to disable the debugging asserts using the -O flag.

Taking multiple inputs from user in python

List_of_input=list(map(int,input (). split ()))
print(List_of_input)

It's for Python3.

How to add elements of a Java8 stream into an existing List

Lets say we have existing list, and gonna use java 8 for this activity `

import java.util.*;
import java.util.stream.Collectors;

public class AddingArray {

    public void addArrayInList(){
        List<Integer> list = Arrays.asList(3, 7, 9);

   // And we have an array of Integer type 

        int nums[] = {4, 6, 7};

   //Now lets add them all in list
   // converting array to a list through stream and adding that list to previous list
        list.addAll(Arrays.stream(nums).map(num -> 
                                       num).boxed().collect(Collectors.toList()));
     }
}

`

How to show current time in JavaScript in the format HH:MM:SS?

Use this way:

var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });

Result: 18:56:31

How to get full REST request body using Jersey?

You could use the @Consumes annotation to get the full body:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

@Path("doc")
public class BodyResource
{
  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public void post(Document doc) throws TransformerConfigurationException, TransformerException
  {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult(System.out));
  }
}

Note: Don't forget the "Content-Type: application/xml" header by the request.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

How do I wait for an asynchronously dispatched block to finish?

- (void)performAndWait:(void (^)(dispatch_semaphore_t semaphore))perform;
{
  NSParameterAssert(perform);
  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  perform(semaphore);
  dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  dispatch_release(semaphore);
}

Example usage:

[self performAndWait:^(dispatch_semaphore_t semaphore) {
  [self someLongOperationWithSuccess:^{
    dispatch_semaphore_signal(semaphore);
  }];
}];

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

MVC Return Partial View as JSON

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}

how to set radio button checked in edit mode in MVC razor view

Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:

Controller:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
        user.user_gender = collection["rdbtnGender"];
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        throw e;
    }
}

public ActionResult Edit(int id)
{
    CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
    ViewBag.UserObj = user;
    return View();
}

VIEW:

Create:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label  for="rdbtnGender2">FEMALE</label>

Edit:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>

<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>

Show div when radio button selected

 $('input[type="radio"]').change(function(){
      if($("input[name='group']:checked")){
      $(div).show();
    }
  });

Using onBackPressed() in Android Fragments

You can try to override onCreateAnimation, parameter and catch enter==false. This will fire before every back press.

@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {            
        if(!enter){
            //leaving fragment
            Log.d(TAG,"leaving fragment");
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

Set value for particular cell in pandas DataFrame using index

I too was searching for this topic and I put together a way to iterate through a DataFrame and update it with lookup values from a second DataFrame. Here is my code.

src_df = pd.read_sql_query(src_sql,src_connection)
for index1, row1 in src_df.iterrows():
    for index, row in vertical_df.iterrows():
        src_df.set_value(index=index1,col=u'etl_load_key',value=etl_load_key)
        if (row1[u'src_id'] == row['SRC_ID']) is True:
            src_df.set_value(index=index1,col=u'vertical',value=row['VERTICAL'])

VB.NET Empty String Array

VB is 0-indexed in array declarations, so seomthing like Dim myArray(10) as String gives you 11 elements. It's a common mistake when translating from C languages.

So, for an empty array, either of the following would work:

Dim str(-1) as String ' -1 + 1 = 0, so this has 0 elements
Dim str() as String = New String() { } ' implicit size, initialized to empty

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

Detect click outside React component

This is the method that suits me the best to make a dropdown menu:

handleClick = () => {
    document.getElementById("myDrop").classList.toggle("showing");
}

render() {

    return (
        <div className="courses">
            <div class="dropdownBody">
                <button onClick={this.handleClick} onBlur={this.handleClick} class="dropbtn">Dropdown</button>
                <div id="myDrop" class="dropdown-content">
                    <a href="#home">Home</a>
                    <a href="#about">About</a>
                    <a href="#contact">Contact</a>
                </div>
            </div>
        </div>
    )
}

Copying a HashMap in Java

If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.

The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.

This question is the perfect definition for the application of the deep copy approach.

First, if you have a simple HashMap<Integer, List<T>> map then we just create a workaround like this. Creating a new instance of the List<T>.

public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
    HashMap<Integer, List<T>> copy = new HashMap<>();
    for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
        copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    return copy;
}

This one uses Stream.collect() method to create the clone map, but uses the same idea as the previous method.

public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
    return original
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}   

But, if the instances inside T are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.

To solve that this deep copy implementations will do the work.

public class DeepClone
{
    public static void main(String[] args)
    {
        Map<Long, Item> itemMap = Stream.of(
                entry(0L, new Item(2558584)),
                entry(1L, new Item(254243232)),
                entry(2L, new Item(986786)),
                entry(3L, new Item(672542)),
                entry(4L, new Item(4846)),
                entry(5L, new Item(76867467)),
                entry(6L, new Item(986786)),
                entry(7L, new Item(7969768)),
                entry(8L, new Item(68868486)),
                entry(9L, new Item(923)),
                entry(10L, new Item(986786)),
                entry(11L, new Item(549768)),
                entry(12L, new Item(796168)),
                entry(13L, new Item(868421)),
                entry(14L, new Item(923)),
                entry(15L, new Item(986786)),
                entry(16L, new Item(549768)),
                entry(17L, new Item(4846)),
                entry(18L, new Item(4846)),
                entry(19L, new Item(76867467)),
                entry(20L, new Item(986786)),
                entry(21L, new Item(7969768)),
                entry(22L, new Item(923)),
                entry(23L, new Item(4846)),
                entry(24L, new Item(986786)),
                entry(25L, new Item(549768))
        ).collect(entriesToMap());


        Map<Long, Item> clone = DeepClone.deepClone(itemMap);
        clone.remove(1L);
        clone.remove(2L);

        System.out.println(itemMap);
        System.out.println(clone);
    }

    private DeepClone() {}

    public static <T> T deepClone(final T input)
    {
        if (input == null) return null;

        if (input instanceof Map<?, ?>) {
            return (T) deepCloneMap((Map<?, ?>) input);
        } else if (input instanceof Collection<?>) {
            return (T) deepCloneCollection((Collection<?>) input);
        } else if (input instanceof Object[]) {
            return (T) deepCloneObjectArray((Object[]) input);
        } else if (input.getClass().isArray()) {
            return (T) clonePrimitiveArray((Object) input);
        }

        return input;
    }

    private static Object clonePrimitiveArray(final Object input)
    {
        final int length = Array.getLength(input);
        final Object output = Array.newInstance(input.getClass().getComponentType(), length);
        System.arraycopy(input, 0, output, 0, length);
        return output;
    }

    private static <E> E[] deepCloneObjectArray(final E[] input)
    {
        final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
        for (int i = 0; i < input.length; i++) {
            clone[i] = deepClone(input[i]);
        }

        return clone;
    }

    private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
    {
        Collection<E> clone;
        if (input instanceof LinkedList<?>) {
            clone = new LinkedList<>();
        } else if (input instanceof SortedSet<?>) {
            clone = new TreeSet<>();
        } else if (input instanceof Set) {
            clone = new HashSet<>();
        } else {
            clone = new ArrayList<>();
        }

        for (E item : input) {
            clone.add(deepClone(item));
        }

        return clone;
    }

    private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
    {
        Map<K, V> clone;
        if (map instanceof LinkedHashMap<?, ?>) {
            clone = new LinkedHashMap<>();
        } else if (map instanceof TreeMap<?, ?>) {
            clone = new TreeMap<>();
        } else {
            clone = new HashMap<>();
        }

        for (Map.Entry<K, V> entry : map.entrySet()) {
            clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
        }

        return clone;
    }
}

Mailx send html message

Well, the "-a" mail and mailx in Centos7 is "attach file" not "append header." My shortest path to a solution on Centos7 from here: stackexchange.com

Basically:

yum install mutt
mutt -e 'set content_type=text/html' -s 'My subject' [email protected] < msg.html

Setting the default page for ASP.NET (Visual Studio) server configuration

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.AbsolutePath.EndsWith("/"))
        {
             Server.Transfer("~/index.aspx");
        }
    }
}

Stretch background image css?

.style1 {
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Works in:

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

In addition you can try this for an IE solution

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;

Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/

Python date string to date object

import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

Show which git tag you are on?

git log --decorate

This will tell you what refs are pointing to the currently checked out commit.

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Mime type for WOFF fonts?

I have had the same problem, font/opentype worked for me

How to pass object with NSNotificationCenter

Building on the solution provided I thought it might be helpful to show an example passing your own custom data object (which I've referenced here as 'message' as per question).

Class A (sender):

YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];

Class B (receiver):

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}

#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
    NSDictionary *dict = notification.userInfo;
    YourDataObject *message = [dict valueForKey:@"message"];
    if (message != nil) {
        // do stuff here with your message data
    }
}

Hiding a password in a python script (insecure obfuscation only)

More homegrown appraoch rather than converting authentication / passwords / username to encrytpted details. FTPLIB is just the example. "pass.csv" is the csv file name

Save password in CSV like below :

user_name

user_password

(With no column heading)

Reading the CSV and saving it to a list.

Using List elelments as authetntication details.

Full code.

import os
import ftplib
import csv 
cred_detail = []
os.chdir("Folder where the csv file is stored")
for row in csv.reader(open("pass.csv","rb")):       
        cred_detail.append(row)
ftp = ftplib.FTP('server_name',cred_detail[0][0],cred_detail[1][0])

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

To my knowledge, StackOverflow has lots of people asking this question in various ways, but nobody has answered it completely yet.

My spec called for the user to be able to choose email, twitter, facebook, or SMS, with custom text for each one. Here is how I accomplished that:

public void onShareClick(View v) {
    Resources resources = getResources();

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.share_email_subject));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);     
    sendIntent.setType("text/plain");


    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();        
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if(packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if(packageName.contains("twitter") || packageName.contains("facebook") || packageName.contains("mms") || packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if(packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_twitter));
            } else if(packageName.contains("facebook")) {
                // Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
                // One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
                // will show the <meta content ="..."> text from that page with our link in Facebook.
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_facebook));
            } else if(packageName.contains("mms")) {
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_sms));
            } else if(packageName.contains("android.gm")) { // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.share_email_subject));               
                intent.setType("message/rfc822");
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray( new LabeledIntent[ intentList.size() ]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);       
}

I found bits of how to do this in various places, but I haven't seen all of it in one place anywhere else.

Note that this method also hides all the silly options that I don't want, like sharing over wifi and bluetooth.

Hope this helps someone.

Edit: In a comment, I was asked to explain what this code is doing. Basically, it's creating an ACTION_SEND intent for the native email client ONLY, then tacking other intents onto the chooser. Making the original intent email-specific gets rid of all the extra junk like wifi and bluetooth, then I grab the other intents I want from a generic ACTION_SEND of type plain-text, and tack them on before showing the chooser.

When I grab the additional intents, I set custom text for each one.

Edit2: It's been awhile since I posted this, and things have changed a bit. If you are seeing gmail twice in the list of options, try removing the special handling for "android.gm" as suggested in a comment by @h_k below.

Since this one answer is the source of nearly all my stackoverflow reputation points, I have to at least try to keep it up to date.

Reading a file character by character in C

the file is being opened and not closed for each call to the function also

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.

In Jelly Bean it is: Settings > Data Usage > mobile data

Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.

For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.

It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

In any flow where you retrieved an authorization code on the client side, such as the GoogleAuth.grantOfflineAccess() API, and now you want to pass the code to your server, redeem it, and store the access and refresh tokens, then you have to use the literal string postmessage instead of the redirect_uri.

For example, building on the snippet in the Ruby doc:

client_secrets = Google::APIClient::ClientSecrets.load('client_secrets.json')
auth_client = client_secrets.to_authorization
auth_client.update!(
  :scope => 'profile https://www.googleapis.com/auth/drive.metadata.readonly',
  :redirect_uri => 'postmessage' # <---- HERE
)

# Inject user's auth_code here:
auth_client.code = "4/lRCuOXzLMIzqrG4XU9RmWw8k1n3jvUgsI790Hk1s3FI"
tokens = auth_client.fetch_access_token!
# { "access_token"=>..., "expires_in"=>3587, "id_token"=>..., "refresh_token"=>..., "token_type"=>"Bearer"}

The only Google documentation to even mention postmessage is this old Google+ sign-in doc. Here's a screenshot and archive link since G+ is closing and this link will likely go away:

Legacy Google+ API DOC

It is absolutely unforgivable that the doc page for Offline Access doesn't mention this. #FacePalm

Does hosts file exist on the iPhone? How to change it?

Not programming related, but I'll answer anyway. It's in /etc/hosts.

You can change it with a simple text editor such as nano.

(Obviously you would need a jailbroken iphone for this)

How to show the last queries executed on MySQL?

You can enable a general query log for that sort of diagnostic. Generally you don't log all SELECT queries on a production server though, it's a performance killer.

Edit your MySQL config, e.g. /etc/mysql/my.cnf - look for, or add, a line like this

[mysqld]
log = /var/log/mysql/mysql.log

Restart mysql to pick up that change, now you can

tail -f /var/log/mysql/mysql.log

Hey presto, you can watch the queries as they come in.

Defining arrays in Google Scripts

I think that maybe it is because you are declaring a variable that you already declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- Here's the issue: 'var'

I think this should be like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Tell me if it works! ;)

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

Does Eclipse have line-wrap

Ctrl+Shift+F will format a file in Eclipse, breaking long lines into multiple lines and nicely word-wrapping comments. You can also highlight just a section of text and format that.

I realize this is not an automatic soft/hard word wrap like the other answers, but I don't think the question was asking for anything fancy.

Cross domain POST request is not sending cookie Ajax Jquery

I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.

Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.

I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

jQuery trigger event when click outside the element

$(document).click((e) => {
  if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
  } else {
    this.onClose();
  }
}); 

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

http://example.com

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Unable to Resolve Module in React Native App

If your file path is correct then check any one file contains

import React from './node_modules/react';

replace it with

import React, { Component } from 'react';

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

What is the difference between ( for... in ) and ( for... of ) statements?

A see a lot of good answers, but I decide to put my 5 cents just to have good example:

For in loop

iterates over all enumerable props

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
  console.log( key );_x000D_
}
_x000D_
_x000D_
_x000D_

For of loop

iterates over all iterable values

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
  console.log( node.toString() );_x000D_
}
_x000D_
_x000D_
_x000D_

Java - sending HTTP parameters via POST method easily

I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:

public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : postsData.entrySet()) {
        if (postData.length() != 0) postData.append('&');

        Object value = param.getValue();
        String key = param.getKey();

        if(value instanceof Object[] || value instanceof List<?>)
        {
            int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
            for(int i = 0; i < size; i++)
            {
                Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
                if(i>0) postData.append('&');
                postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
                postData.append('=');            
                postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
            }
        }
        else
        {
            postData.append(URLEncoder.encode(key, "UTF-8"));
            postData.append('=');            
            postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
        }
    }
    return postData.toString().getBytes("UTF-8");
}